diff --git a/clients/go/mxgateway/correlation_test.go b/clients/go/mxgateway/correlation_test.go new file mode 100644 index 00000000..4253ec75 --- /dev/null +++ b/clients/go/mxgateway/correlation_test.go @@ -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) + } +} diff --git a/clients/go/mxgateway/session.go b/clients/go/mxgateway/session.go index 639a38cc..89f1fb2e 100644 --- a/clients/go/mxgateway/session.go +++ b/clients/go/mxgateway/session.go @@ -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--") 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[:]) }