fix(clients/go): counter-based fallback when crypto/rand fails in newCorrelationID (mxaccessgw#201)

This commit is contained in:
Joseph Doherty
2026-11-09 12:03:29 -05:00
parent 0ec247e88c
commit 9007966292
2 changed files with 45 additions and 2 deletions
+31
View File
@@ -0,0 +1,31 @@
package mxgateway
import (
"errors"
"strings"
"testing"
)
type failingReader struct{}
func (failingReader) Read([]byte) (int, error) { return 0, errors.New("entropy unavailable") }
func TestNewCorrelationIDFallsBackWhenRandFails(t *testing.T) {
a := newCorrelationIDFrom(failingReader{})
b := newCorrelationIDFrom(failingReader{})
if a == "" || b == "" {
t.Fatal("fallback id must not be empty")
}
if a == b {
t.Fatalf("fallback ids must be unique, got %q twice", a)
}
if !strings.HasPrefix(a, "fallback-") {
t.Fatalf("unexpected fallback shape %q", a)
}
}
func TestNewCorrelationIDRandomIsHex32(t *testing.T) {
if id := newCorrelationID(); len(id) != 32 {
t.Fatalf("expected 32 hex chars, got %q", id)
}
}
+14 -2
View File
@@ -9,6 +9,7 @@ import (
"io"
"sort"
"sync"
"sync/atomic"
"time"
pb "gitea.dohertylan.com/dohertj2/mxaccessgw/clients/go/internal/generated"
@@ -1241,10 +1242,21 @@ func (s *Session) invokeCommand(ctx context.Context, command *MxCommand) (*MxCom
})
}
// correlationFallbackCounter backs correlation ids when crypto/rand fails, so a
// request never goes out with an empty ClientCorrelationId.
var correlationFallbackCounter atomic.Uint64
// newCorrelationID returns a random 128-bit hex id, falling back to a
// process-unique counter-based id ("fallback-<unixnano>-<n>") if crypto/rand
// fails.
func newCorrelationID() string {
return newCorrelationIDFrom(rand.Reader)
}
func newCorrelationIDFrom(reader io.Reader) string {
var buffer [16]byte
if _, err := rand.Read(buffer[:]); err != nil {
return ""
if _, err := io.ReadFull(reader, buffer[:]); err != nil {
return fmt.Sprintf("fallback-%d-%d", time.Now().UnixNano(), correlationFallbackCounter.Add(1))
}
return hex.EncodeToString(buffer[:])
}