fix(clients/go): counter-based fallback when crypto/rand fails in newCorrelationID (mxaccessgw#201)
This commit is contained in:
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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[:])
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user