From 2651e287aed1efdd6cf2c6fee573fff9322e943a Mon Sep 17 00:00:00 2001 From: Dean Sheather Date: Wed, 20 Aug 2025 23:10:54 +0000 Subject: [PATCH] fix: use int64 in publisher delay --- cryptorand/numbers.go | 6 ++++++ cryptorand/numbers_test.go | 21 +++++++++++++++++++++ enterprise/coderd/usage/publisher.go | 4 ++-- 3 files changed, 29 insertions(+), 2 deletions(-) diff --git a/cryptorand/numbers.go b/cryptorand/numbers.go index d6a4889b80562..ea1e522a37b0a 100644 --- a/cryptorand/numbers.go +++ b/cryptorand/numbers.go @@ -47,6 +47,12 @@ func Int63() (int64, error) { return rng.Int63(), cs.err } +// Int63n returns a non-negative integer in [0,maxVal) as an int64. +func Int63n(maxVal int64) (int64, error) { + rng, cs := secureRand() + return rng.Int63n(maxVal), cs.err +} + // Intn returns a non-negative integer in [0,maxVal) as an int. func Intn(maxVal int) (int, error) { rng, cs := secureRand() diff --git a/cryptorand/numbers_test.go b/cryptorand/numbers_test.go index aec9c89a7476c..dd47d942dc4e4 100644 --- a/cryptorand/numbers_test.go +++ b/cryptorand/numbers_test.go @@ -19,6 +19,27 @@ func TestInt63(t *testing.T) { } } +func TestInt63n(t *testing.T) { + t.Parallel() + + for i := 0; i < 20; i++ { + v, err := cryptorand.Int63n(100) + require.NoError(t, err, "unexpected error from Int63n") + t.Logf("value: %v <- random?", v) + require.GreaterOrEqual(t, v, int64(0), "values must be positive") + require.Less(t, v, int64(100), "values must be less than 100") + } + + // Ensure Int63n works for int larger than 32 bits + _, err := cryptorand.Int63n(1 << 35) + require.NoError(t, err, "expected Int63n to work for 64-bit int") + + // Expect a panic if max is negative + require.PanicsWithValue(t, "invalid argument to Int63n", func() { + cryptorand.Int63n(0) + }) +} + func TestIntn(t *testing.T) { t.Parallel() diff --git a/enterprise/coderd/usage/publisher.go b/enterprise/coderd/usage/publisher.go index 5c205ecd8c3b8..16cc5564d0c08 100644 --- a/enterprise/coderd/usage/publisher.go +++ b/enterprise/coderd/usage/publisher.go @@ -136,8 +136,8 @@ func (p *tallymanPublisher) Start() error { if p.initialDelay <= 0 { // Pick a random time between tallymanPublishInitialMinimumDelay and // tallymanPublishInterval. - maxPlusDelay := int(tallymanPublishInterval - tallymanPublishInitialMinimumDelay) - plusDelay, err := cryptorand.Intn(maxPlusDelay) + maxPlusDelay := tallymanPublishInterval - tallymanPublishInitialMinimumDelay + plusDelay, err := cryptorand.Int63n(int64(maxPlusDelay)) if err != nil { return xerrors.Errorf("could not generate random start delay: %w", err) }