diff --git a/pkgs/mcpx/internal/artifacts/artifacts.go b/pkgs/mcpx/internal/artifacts/artifacts.go index e0d857481c..8ef2b4f1b3 100644 --- a/pkgs/mcpx/internal/artifacts/artifacts.go +++ b/pkgs/mcpx/internal/artifacts/artifacts.go @@ -28,7 +28,6 @@ package artifacts import ( - "crypto/rand" "crypto/sha256" "database/sql" "encoding/hex" @@ -291,7 +290,7 @@ func (s *Store) blobPath(hash string) string { // anything that can reach the daemon. func NewID() string { b := make([]byte, defaults.ArtifactIDBytes) - _, _ = rand.Read(b) + _, _ = RandSource.Read(b) return "art-" + hex.EncodeToString(b) } diff --git a/pkgs/mcpx/internal/artifacts/randsrc.go b/pkgs/mcpx/internal/artifacts/randsrc.go new file mode 100644 index 0000000000..d9ddcfab1d --- /dev/null +++ b/pkgs/mcpx/internal/artifacts/randsrc.go @@ -0,0 +1,15 @@ +package artifacts + +import ( + "io" + + "github.com/developing-today/code/pkgs/mcpx/internal/randsrc" +) + +// RandSource is the source NewID mints from (#2640). +// +// The production value is randsrc.Crypto -- crypto/rand -- and must +// stay that: an artifact id is the whole of the artifact's access control until OAuth scopes land, so it has to stay unguessable. Tests swap in randsrc.Seeded so a run seed +// reproduces the ids a run minted; restore the old value when the +// test ends. +var RandSource io.Reader = randsrc.Crypto diff --git a/pkgs/mcpx/internal/artifacts/randsrc_test.go b/pkgs/mcpx/internal/artifacts/randsrc_test.go new file mode 100644 index 0000000000..2c1822335d --- /dev/null +++ b/pkgs/mcpx/internal/artifacts/randsrc_test.go @@ -0,0 +1,40 @@ +package artifacts + +import ( + "crypto/rand" + "io" + "testing" + + "github.com/developing-today/code/pkgs/mcpx/internal/randsrc" +) + +func swapRandSource(t *testing.T, s io.Reader) { + t.Helper() + old := RandSource + RandSource = s + t.Cleanup(func() { RandSource = old }) +} + +// The production default must stay crypto/rand: these ids are +// access control, and a silent swap of the default would make them +// guessable (#2640). +func TestRandSourceDefaultIsCryptoRand(t *testing.T) { + if RandSource != rand.Reader { + t.Fatal("production default RandSource is not crypto/rand") + } +} + +// Two runs seeded identically mint identical ids: the #2640 +// acceptance test at the package level. +func TestNewIDSeededReproducesIDs(t *testing.T) { + swapRandSource(t, randsrc.Seeded([]byte("run-seed"), "artifacts")) + first := NewID() + swapRandSource(t, randsrc.Seeded([]byte("run-seed"), "artifacts")) + if second := NewID(); second != first { + t.Fatalf("same seed minted different ids: %q vs %q", first, second) + } + swapRandSource(t, randsrc.Seeded([]byte("other-seed"), "artifacts")) + if third := NewID(); third == first { + t.Fatalf("different seed minted the same id %q", first) + } +} diff --git a/pkgs/mcpx/internal/cli/randsrc.go b/pkgs/mcpx/internal/cli/randsrc.go new file mode 100644 index 0000000000..97c4545d26 --- /dev/null +++ b/pkgs/mcpx/internal/cli/randsrc.go @@ -0,0 +1,15 @@ +package cli + +import ( + "io" + + "github.com/developing-today/code/pkgs/mcpx/internal/randsrc" +) + +// RandSource is the source InstanceID mints from (#2640). +// +// The production value is randsrc.Crypto -- crypto/rand -- and must +// stay that: the instance id distinguishes this daemon from any other for the self-connection guard, so it has to stay unguessable. Tests swap in randsrc.Seeded so a run seed +// reproduces the ids a run minted; restore the old value when the +// test ends. +var RandSource io.Reader = randsrc.Crypto diff --git a/pkgs/mcpx/internal/cli/randsrc_test.go b/pkgs/mcpx/internal/cli/randsrc_test.go new file mode 100644 index 0000000000..bdd652985c --- /dev/null +++ b/pkgs/mcpx/internal/cli/randsrc_test.go @@ -0,0 +1,15 @@ +package cli + +import ( + "crypto/rand" + "testing" +) + +// The production default must stay crypto/rand (#2640): the +// instance id distinguishes this daemon from any other for the +// self-connection guard. +func TestRandSourceDefaultIsCryptoRand(t *testing.T) { + if RandSource != rand.Reader { + t.Fatal("production default RandSource is not crypto/rand") + } +} diff --git a/pkgs/mcpx/internal/cli/root.go b/pkgs/mcpx/internal/cli/root.go index e6c9321167..4854aff882 100644 --- a/pkgs/mcpx/internal/cli/root.go +++ b/pkgs/mcpx/internal/cli/root.go @@ -2,7 +2,6 @@ package cli import ( "context" - "crypto/rand" "encoding/hex" "encoding/json" "errors" @@ -268,7 +267,7 @@ var processInstance struct { func (a *App) InstanceID() string { processInstance.once.Do(func() { b := make([]byte, 16) - if _, err := rand.Read(b); err == nil { + if _, err := RandSource.Read(b); err == nil { processInstance.id = hex.EncodeToString(b) } else { processInstance.id = fmt.Sprintf("pid-%d-%d", os.Getpid(), time.Now().UnixNano()) diff --git a/pkgs/mcpx/internal/daemon/randsrc.go b/pkgs/mcpx/internal/daemon/randsrc.go new file mode 100644 index 0000000000..4f839354a2 --- /dev/null +++ b/pkgs/mcpx/internal/daemon/randsrc.go @@ -0,0 +1,15 @@ +package daemon + +import ( + "io" + + "github.com/developing-today/code/pkgs/mcpx/internal/randsrc" +) + +// RandSource is the source randomHex mints from (#2640). +// +// The production value is randsrc.Crypto -- crypto/rand -- and must +// stay that: these tokens name proxied sessions, so they have to stay unguessable. Tests swap in randsrc.Seeded so a run seed +// reproduces the ids a run minted; restore the old value when the +// test ends. +var RandSource io.Reader = randsrc.Crypto diff --git a/pkgs/mcpx/internal/daemon/randsrc_test.go b/pkgs/mcpx/internal/daemon/randsrc_test.go new file mode 100644 index 0000000000..39fd5621a3 --- /dev/null +++ b/pkgs/mcpx/internal/daemon/randsrc_test.go @@ -0,0 +1,40 @@ +package daemon + +import ( + "crypto/rand" + "io" + "testing" + + "github.com/developing-today/code/pkgs/mcpx/internal/randsrc" +) + +func swapRandSource(t *testing.T, s io.Reader) { + t.Helper() + old := RandSource + RandSource = s + t.Cleanup(func() { RandSource = old }) +} + +// The production default must stay crypto/rand: these ids are +// access control, and a silent swap of the default would make them +// guessable (#2640). +func TestRandSourceDefaultIsCryptoRand(t *testing.T) { + if RandSource != rand.Reader { + t.Fatal("production default RandSource is not crypto/rand") + } +} + +// Two runs seeded identically mint identical ids: the #2640 +// acceptance test at the package level. +func TestRandomHexSeededReproducesIDs(t *testing.T) { + swapRandSource(t, randsrc.Seeded([]byte("run-seed"), "daemon")) + first := randomHex(16) + swapRandSource(t, randsrc.Seeded([]byte("run-seed"), "daemon")) + if second := randomHex(16); second != first { + t.Fatalf("same seed minted different ids: %q vs %q", first, second) + } + swapRandSource(t, randsrc.Seeded([]byte("other-seed"), "daemon")) + if third := randomHex(16); third == first { + t.Fatalf("different seed minted the same id %q", first) + } +} diff --git a/pkgs/mcpx/internal/daemon/routes_proxy.go b/pkgs/mcpx/internal/daemon/routes_proxy.go index 373e8625f9..875be26dab 100644 --- a/pkgs/mcpx/internal/daemon/routes_proxy.go +++ b/pkgs/mcpx/internal/daemon/routes_proxy.go @@ -2,7 +2,6 @@ package daemon import ( "bytes" - "crypto/rand" "encoding/hex" "encoding/json" "fmt" @@ -300,6 +299,6 @@ func extractUserQuery(msgs []chatMessage) string { func randomHex(n int) string { b := make([]byte, n) - _, _ = rand.Read(b) + _, _ = RandSource.Read(b) return hex.EncodeToString(b) } diff --git a/pkgs/mcpx/internal/elicit/elicit.go b/pkgs/mcpx/internal/elicit/elicit.go index 7112a2e382..052fe39555 100644 --- a/pkgs/mcpx/internal/elicit/elicit.go +++ b/pkgs/mcpx/internal/elicit/elicit.go @@ -14,7 +14,6 @@ package elicit import ( "bytes" "context" - "crypto/rand" "database/sql" "encoding/hex" "encoding/json" @@ -359,7 +358,7 @@ CREATE TABLE IF NOT EXISTS elicitation_answers ( // NewID mints an identifier. func NewID() string { var b [8]byte - _, _ = rand.Read(b[:]) + _, _ = RandSource.Read(b[:]) return "elc-" + hex.EncodeToString(b[:]) } diff --git a/pkgs/mcpx/internal/elicit/randsrc.go b/pkgs/mcpx/internal/elicit/randsrc.go new file mode 100644 index 0000000000..b00d27c12b --- /dev/null +++ b/pkgs/mcpx/internal/elicit/randsrc.go @@ -0,0 +1,15 @@ +package elicit + +import ( + "io" + + "github.com/developing-today/code/pkgs/mcpx/internal/randsrc" +) + +// RandSource is the source NewID mints from (#2640). +// +// The production value is randsrc.Crypto -- crypto/rand -- and must +// stay that: an elicitation id names a pending question to its session, so it has to stay unguessable. Tests swap in randsrc.Seeded so a run seed +// reproduces the ids a run minted; restore the old value when the +// test ends. +var RandSource io.Reader = randsrc.Crypto diff --git a/pkgs/mcpx/internal/elicit/randsrc_test.go b/pkgs/mcpx/internal/elicit/randsrc_test.go new file mode 100644 index 0000000000..3e7d3a2ae9 --- /dev/null +++ b/pkgs/mcpx/internal/elicit/randsrc_test.go @@ -0,0 +1,40 @@ +package elicit + +import ( + "crypto/rand" + "io" + "testing" + + "github.com/developing-today/code/pkgs/mcpx/internal/randsrc" +) + +func swapRandSource(t *testing.T, s io.Reader) { + t.Helper() + old := RandSource + RandSource = s + t.Cleanup(func() { RandSource = old }) +} + +// The production default must stay crypto/rand: these ids are +// access control, and a silent swap of the default would make them +// guessable (#2640). +func TestRandSourceDefaultIsCryptoRand(t *testing.T) { + if RandSource != rand.Reader { + t.Fatal("production default RandSource is not crypto/rand") + } +} + +// Two runs seeded identically mint identical ids: the #2640 +// acceptance test at the package level. +func TestNewIDSeededReproducesIDs(t *testing.T) { + swapRandSource(t, randsrc.Seeded([]byte("run-seed"), "elicit")) + first := NewID() + swapRandSource(t, randsrc.Seeded([]byte("run-seed"), "elicit")) + if second := NewID(); second != first { + t.Fatalf("same seed minted different ids: %q vs %q", first, second) + } + swapRandSource(t, randsrc.Seeded([]byte("other-seed"), "elicit")) + if third := NewID(); third == first { + t.Fatalf("different seed minted the same id %q", first) + } +} diff --git a/pkgs/mcpx/internal/logging/randsrc.go b/pkgs/mcpx/internal/logging/randsrc.go new file mode 100644 index 0000000000..0a11835a11 --- /dev/null +++ b/pkgs/mcpx/internal/logging/randsrc.go @@ -0,0 +1,15 @@ +package logging + +import ( + "io" + + "github.com/developing-today/code/pkgs/mcpx/internal/randsrc" +) + +// RandSource is the source NewTraceID mints from (#2640). +// +// The production value is randsrc.Crypto -- crypto/rand -- and must +// stay that: a trace id is only a correlation handle, but production ids stay unguessable for the same reason. Tests swap in randsrc.Seeded so a run seed +// reproduces the ids a run minted; restore the old value when the +// test ends. +var RandSource io.Reader = randsrc.Crypto diff --git a/pkgs/mcpx/internal/logging/randsrc_test.go b/pkgs/mcpx/internal/logging/randsrc_test.go new file mode 100644 index 0000000000..ecf0f4cc7b --- /dev/null +++ b/pkgs/mcpx/internal/logging/randsrc_test.go @@ -0,0 +1,51 @@ +package logging + +import ( + "crypto/rand" + "errors" + "io" + "testing" + + "github.com/developing-today/code/pkgs/mcpx/internal/randsrc" +) + +func swapRandSource(t *testing.T, s io.Reader) { + t.Helper() + old := RandSource + RandSource = s + t.Cleanup(func() { RandSource = old }) +} + +func TestRandSourceDefaultIsCryptoRand(t *testing.T) { + if RandSource != rand.Reader { + t.Fatal("production default RandSource is not crypto/rand") + } +} + +type errReader struct{} + +func (errReader) Read([]byte) (int, error) { return 0, errors.New("no randomness") } + +// Two runs seeded identically mint identical ids: the #2640 +// acceptance test at the package level. +func TestNewTraceIDSeededReproducesIDs(t *testing.T) { + swapRandSource(t, randsrc.Seeded([]byte("run-seed"), "logging")) + first := NewTraceID("trc") + swapRandSource(t, randsrc.Seeded([]byte("run-seed"), "logging")) + if second := NewTraceID("trc"); second != first { + t.Fatalf("same seed minted different ids: %q vs %q", first, second) + } + swapRandSource(t, randsrc.Seeded([]byte("other-seed"), "logging")) + if third := NewTraceID("trc"); third == first { + t.Fatalf("different seed minted the same id %q", first) + } +} + +// A failing source keeps the documented fallback: logging must not +// stop because randomness did. +func TestNewTraceIDFailingSourceFallsBack(t *testing.T) { + swapRandSource(t, errReader{}) + if got := NewTraceID("trc"); got != "trc-0000000000000000" { + t.Fatalf("failing source: got %q, want the zero fallback", got) + } +} diff --git a/pkgs/mcpx/internal/logging/trace.go b/pkgs/mcpx/internal/logging/trace.go index 730fd26705..20614de146 100644 --- a/pkgs/mcpx/internal/logging/trace.go +++ b/pkgs/mcpx/internal/logging/trace.go @@ -1,7 +1,6 @@ package logging import ( - "crypto/rand" "encoding/hex" "encoding/json" "net" @@ -29,7 +28,7 @@ type TraceID string // NewTraceID mints an identifier with a short readable prefix. func NewTraceID(prefix string) TraceID { var b [8]byte - if _, err := rand.Read(b[:]); err != nil { + if _, err := RandSource.Read(b[:]); err != nil { // Randomness failing is not a reason to stop logging. return TraceID(prefix + "-0000000000000000") } diff --git a/pkgs/mcpx/internal/mcpserver/randsrc.go b/pkgs/mcpx/internal/mcpserver/randsrc.go new file mode 100644 index 0000000000..1eb29a0085 --- /dev/null +++ b/pkgs/mcpx/internal/mcpserver/randsrc.go @@ -0,0 +1,15 @@ +package mcpserver + +import ( + "io" + + "github.com/developing-today/code/pkgs/mcpx/internal/randsrc" +) + +// RandSource is the source newSessionID, newStateSigner and the requestState nonce mints from (#2640). +// +// The production value is randsrc.Crypto -- crypto/rand -- and must +// stay that: a session id is a bearer handle and the state signer key is secret material, so both have to stay unguessable and unreproducible in production. Tests swap in randsrc.Seeded so a run seed +// reproduces the ids a run minted; restore the old value when the +// test ends. +var RandSource io.Reader = randsrc.Crypto diff --git a/pkgs/mcpx/internal/mcpserver/randsrc_test.go b/pkgs/mcpx/internal/mcpserver/randsrc_test.go new file mode 100644 index 0000000000..30453ff2a5 --- /dev/null +++ b/pkgs/mcpx/internal/mcpserver/randsrc_test.go @@ -0,0 +1,71 @@ +package mcpserver + +import ( + "bytes" + "crypto/rand" + "errors" + "io" + "testing" + + "github.com/developing-today/code/pkgs/mcpx/internal/randsrc" +) + +func swapRandSource(t *testing.T, s io.Reader) { + t.Helper() + old := RandSource + RandSource = s + t.Cleanup(func() { RandSource = old }) +} + +type errReader struct{} + +func (errReader) Read([]byte) (int, error) { return 0, errors.New("no randomness") } + +func TestRandSourceDefaultIsCryptoRand(t *testing.T) { + if RandSource != rand.Reader { + t.Fatal("production default RandSource is not crypto/rand") + } +} + +func TestNewSessionIDSeededReproducesIDs(t *testing.T) { + swapRandSource(t, randsrc.Seeded([]byte("run-seed"), "mcpserver")) + first := newSessionID() + swapRandSource(t, randsrc.Seeded([]byte("run-seed"), "mcpserver")) + if second := newSessionID(); second != first { + t.Fatalf("same seed minted different session ids: %q vs %q", first, second) + } + swapRandSource(t, randsrc.Seeded([]byte("other-seed"), "mcpserver")) + if third := newSessionID(); third == first { + t.Fatalf("different seed minted the same session id %q", first) + } +} + +// A deterministic source never fails, so the sess-0 fallback needs +// its own injected failing reader (#2640 review brief). +func TestNewSessionIDFailingSourceFallsBack(t *testing.T) { + swapRandSource(t, errReader{}) + if got := newSessionID(); got != "sess-0" { + t.Fatalf("failing source: got %q, want sess-0", got) + } +} + +func TestStateSignerSeededKeyReproduces(t *testing.T) { + swapRandSource(t, randsrc.Seeded([]byte("run-seed"), "mcpserver")) + a := newStateSigner() + swapRandSource(t, randsrc.Seeded([]byte("run-seed"), "mcpserver")) + b := newStateSigner() + if len(a.key) == 0 { + t.Fatal("seeded signer has no key") + } + if !bytes.Equal(a.key, b.key) { + t.Fatal("same seed produced different signer keys") + } +} + +func TestStateSignerFailingSourceHasNoKey(t *testing.T) { + swapRandSource(t, errReader{}) + s := newStateSigner() + if _, err := s.mint("call", "binding"); !errors.Is(err, ErrNoStateKey) { + t.Fatalf("mint with no key: err = %v, want ErrNoStateKey", err) + } +} diff --git a/pkgs/mcpx/internal/mcpserver/server.go b/pkgs/mcpx/internal/mcpserver/server.go index eca84f1a8c..22aae109b9 100644 --- a/pkgs/mcpx/internal/mcpserver/server.go +++ b/pkgs/mcpx/internal/mcpserver/server.go @@ -17,7 +17,6 @@ import ( "bufio" "bytes" "context" - "crypto/rand" "encoding/base64" "encoding/hex" "encoding/json" @@ -2378,7 +2377,7 @@ func (s *Server) reapSessionsLocked() { func newSessionID() string { var b [16]byte - if _, err := rand.Read(b[:]); err != nil { + if _, err := RandSource.Read(b[:]); err != nil { return "sess-0" } return "sess-" + hex.EncodeToString(b[:]) diff --git a/pkgs/mcpx/internal/mcpserver/state.go b/pkgs/mcpx/internal/mcpserver/state.go index 0363c7c651..6ab3c05feb 100644 --- a/pkgs/mcpx/internal/mcpserver/state.go +++ b/pkgs/mcpx/internal/mcpserver/state.go @@ -2,7 +2,6 @@ package mcpserver import ( "crypto/hmac" - "crypto/rand" "crypto/sha256" "encoding/base64" "encoding/json" @@ -36,7 +35,7 @@ type stateSigner struct { func newStateSigner() *stateSigner { key := make([]byte, 32) - if _, err := rand.Read(key); err != nil { + if _, err := RandSource.Read(key); err != nil { // Without a key nothing can be verified, and issuing tokens that // cannot be checked is worse than not issuing them: every mint // fails below instead. @@ -81,7 +80,7 @@ func (s *stateSigner) mintRound(callID, binding string, rounds int) (string, err return "", errors.New("a requestState must be bound to something") } nonce := make([]byte, 8) - if _, err := rand.Read(nonce); err != nil { + if _, err := RandSource.Read(nonce); err != nil { return "", err } b, err := json.Marshal(statePayload{Call: callID, Binding: binding, diff --git a/pkgs/mcpx/internal/pool/pool.go b/pkgs/mcpx/internal/pool/pool.go index 517a9790dc..2d44e7fd05 100644 --- a/pkgs/mcpx/internal/pool/pool.go +++ b/pkgs/mcpx/internal/pool/pool.go @@ -18,7 +18,6 @@ package pool import ( "context" - "crypto/rand" "encoding/hex" "encoding/json" "errors" @@ -1868,7 +1867,7 @@ func (p *Pool) closeDrained(drain time.Duration, stopReason, callErr string) { // does not depend on the logging package. func newTraceID(prefix string) string { var b [8]byte - if _, err := rand.Read(b[:]); err != nil { + if _, err := RandSource.Read(b[:]); err != nil { return prefix + "-0000000000000000" } return prefix + "-" + hex.EncodeToString(b[:]) diff --git a/pkgs/mcpx/internal/pool/randsrc.go b/pkgs/mcpx/internal/pool/randsrc.go new file mode 100644 index 0000000000..ab5517ee95 --- /dev/null +++ b/pkgs/mcpx/internal/pool/randsrc.go @@ -0,0 +1,15 @@ +package pool + +import ( + "io" + + "github.com/developing-today/code/pkgs/mcpx/internal/randsrc" +) + +// RandSource is the source newTraceID mints from (#2640). +// +// The production value is randsrc.Crypto -- crypto/rand -- and must +// stay that: a trace id is only a correlation handle, but production ids stay unguessable for the same reason. Tests swap in randsrc.Seeded so a run seed +// reproduces the ids a run minted; restore the old value when the +// test ends. +var RandSource io.Reader = randsrc.Crypto diff --git a/pkgs/mcpx/internal/pool/randsrc_test.go b/pkgs/mcpx/internal/pool/randsrc_test.go new file mode 100644 index 0000000000..20b5b95a4c --- /dev/null +++ b/pkgs/mcpx/internal/pool/randsrc_test.go @@ -0,0 +1,40 @@ +package pool + +import ( + "crypto/rand" + "io" + "testing" + + "github.com/developing-today/code/pkgs/mcpx/internal/randsrc" +) + +func swapRandSource(t *testing.T, s io.Reader) { + t.Helper() + old := RandSource + RandSource = s + t.Cleanup(func() { RandSource = old }) +} + +// The production default must stay crypto/rand: these ids are +// access control, and a silent swap of the default would make them +// guessable (#2640). +func TestRandSourceDefaultIsCryptoRand(t *testing.T) { + if RandSource != rand.Reader { + t.Fatal("production default RandSource is not crypto/rand") + } +} + +// Two runs seeded identically mint identical ids: the #2640 +// acceptance test at the package level. +func TestNewTraceIDSeededReproducesIDs(t *testing.T) { + swapRandSource(t, randsrc.Seeded([]byte("run-seed"), "pool")) + first := newTraceID("srv") + swapRandSource(t, randsrc.Seeded([]byte("run-seed"), "pool")) + if second := newTraceID("srv"); second != first { + t.Fatalf("same seed minted different ids: %q vs %q", first, second) + } + swapRandSource(t, randsrc.Seeded([]byte("other-seed"), "pool")) + if third := newTraceID("srv"); third == first { + t.Fatalf("different seed minted the same id %q", first) + } +} diff --git a/pkgs/mcpx/internal/randsrc/randsrc.go b/pkgs/mcpx/internal/randsrc/randsrc.go new file mode 100644 index 0000000000..9ab657ee9f --- /dev/null +++ b/pkgs/mcpx/internal/randsrc/randsrc.go @@ -0,0 +1,84 @@ +// Package randsrc is mcpx's injectable randomness seam (#2640). +// +// Production id minting reads from crypto/rand, and must keep doing +// so: artifact handles, task handles and session ids are access +// control, and a guessable id is a broken one. But a hard-wired +// crypto/rand means no test seed (#1949) can ever reproduce an id a +// run minted, so seeded inputs cannot compose with execution. +// Packages that mint ids therefore read from a package-level source +// variable whose production value is Crypto (this package), and a +// test swaps in Seeded to make the run reproducible. +// +// Seeded is a test source only. Its output is a pure function of the +// seed, so anyone who knows the seed knows every byte it will ever +// produce: never wire it into a production path, and never derive +// secret material from it (internal/secrets does not use this +// package at all, on purpose). +package randsrc + +import ( + "crypto/rand" + "crypto/sha256" + "encoding/binary" + "io" +) + +// Source is a source of random bytes: the part of io.Reader the +// minting call sites use. crypto/rand.Reader is one; Seeded returns +// another. +type Source = io.Reader + +// Crypto is the production source: crypto/rand itself. +var Crypto Source = rand.Reader + +// Seeded returns a deterministic Source expanding an opaque seed. +// +// The seed is deliberately opaque bytes: #1949 decides the run +// seed's format, and this expansion must not hard-code one, so any +// seed string or byte string drops in. The label separates streams +// that share a seed -- one per minting package, say -- so two +// packages seeded alike do not mint the same ids. +// +// Expansion is SHA-256 in counter mode: +// +// block(i) = SHA-256(seed || 0x00 || label || 0x00 || uint64be(i)) +// +// and the stream is block(0) || block(1) || ... . Reads of any size +// slice the same stream: reading 8 then 8 yields the bytes reading +// 16 yields. +func Seeded(seed []byte, label string) Source { + return &seeded{seed: append([]byte(nil), seed...), label: label} +} + +type seeded struct { + seed []byte + label string + counter uint64 + block [sha256.Size]byte + off int + filled bool +} + +func (s *seeded) Read(p []byte) (int, error) { + n := 0 + for n < len(p) { + if !s.filled || s.off == len(s.block) { + h := sha256.New() + h.Write(s.seed) + h.Write([]byte{0}) + h.Write([]byte(s.label)) + h.Write([]byte{0}) + var c [8]byte + binary.BigEndian.PutUint64(c[:], s.counter) + h.Write(c[:]) + copy(s.block[:], h.Sum(nil)) + s.counter++ + s.off = 0 + s.filled = true + } + m := copy(p[n:], s.block[s.off:]) + s.off += m + n += m + } + return n, nil +} diff --git a/pkgs/mcpx/internal/randsrc/randsrc_test.go b/pkgs/mcpx/internal/randsrc/randsrc_test.go new file mode 100644 index 0000000000..a7f9ddd5a4 --- /dev/null +++ b/pkgs/mcpx/internal/randsrc/randsrc_test.go @@ -0,0 +1,59 @@ +package randsrc_test + +import ( + "bytes" + "crypto/rand" + "io" + "testing" + + "github.com/developing-today/code/pkgs/mcpx/internal/randsrc" +) + +func readN(t *testing.T, s randsrc.Source, n int) []byte { + t.Helper() + b := make([]byte, n) + if _, err := io.ReadFull(s, b); err != nil { + t.Fatalf("read: %v", err) + } + return b +} + +// The acceptance test for #2640 at the source level: two sources +// built from the same seed produce the same stream. +func TestSeededSameSeedSameStream(t *testing.T) { + a := readN(t, randsrc.Seeded([]byte("run-seed"), "pkg"), 64) + b := readN(t, randsrc.Seeded([]byte("run-seed"), "pkg"), 64) + if !bytes.Equal(a, b) { + t.Fatalf("same seed+label streams differ:\n%x\n%x", a, b) + } +} + +func TestSeededSeedAndLabelSeparateStreams(t *testing.T) { + base := readN(t, randsrc.Seeded([]byte("run-seed"), "pkg"), 32) + otherSeed := readN(t, randsrc.Seeded([]byte("other-seed"), "pkg"), 32) + otherLabel := readN(t, randsrc.Seeded([]byte("run-seed"), "other"), 32) + if bytes.Equal(base, otherSeed) { + t.Fatal("different seeds produced the same stream") + } + if bytes.Equal(base, otherLabel) { + t.Fatal("different labels produced the same stream") + } +} + +func TestSeededReadSizesSliceOneStream(t *testing.T) { + whole := readN(t, randsrc.Seeded([]byte("run-seed"), "pkg"), 48) + s := randsrc.Seeded([]byte("run-seed"), "pkg") + var chunked []byte + for _, n := range []int{1, 7, 8, 31, 1} { + chunked = append(chunked, readN(t, s, n)...) + } + if !bytes.Equal(whole, chunked) { + t.Fatalf("chunked reads diverged from one read:\n%x\n%x", whole, chunked) + } +} + +func TestCryptoIsCryptoRand(t *testing.T) { + if randsrc.Crypto != rand.Reader { + t.Fatal("the production source is not crypto/rand") + } +} diff --git a/pkgs/mcpx/internal/tasks/randsrc.go b/pkgs/mcpx/internal/tasks/randsrc.go new file mode 100644 index 0000000000..acc1bb132d --- /dev/null +++ b/pkgs/mcpx/internal/tasks/randsrc.go @@ -0,0 +1,15 @@ +package tasks + +import ( + "io" + + "github.com/developing-today/code/pkgs/mcpx/internal/randsrc" +) + +// RandSource is the source NewID mints from (#2640). +// +// The production value is randsrc.Crypto -- crypto/rand -- and must +// stay that: a task id is the handle a caller holds a task by, so it has to stay unguessable. Tests swap in randsrc.Seeded so a run seed +// reproduces the ids a run minted; restore the old value when the +// test ends. +var RandSource io.Reader = randsrc.Crypto diff --git a/pkgs/mcpx/internal/tasks/randsrc_test.go b/pkgs/mcpx/internal/tasks/randsrc_test.go new file mode 100644 index 0000000000..2ed2d65a80 --- /dev/null +++ b/pkgs/mcpx/internal/tasks/randsrc_test.go @@ -0,0 +1,40 @@ +package tasks + +import ( + "crypto/rand" + "io" + "testing" + + "github.com/developing-today/code/pkgs/mcpx/internal/randsrc" +) + +func swapRandSource(t *testing.T, s io.Reader) { + t.Helper() + old := RandSource + RandSource = s + t.Cleanup(func() { RandSource = old }) +} + +// The production default must stay crypto/rand: these ids are +// access control, and a silent swap of the default would make them +// guessable (#2640). +func TestRandSourceDefaultIsCryptoRand(t *testing.T) { + if RandSource != rand.Reader { + t.Fatal("production default RandSource is not crypto/rand") + } +} + +// Two runs seeded identically mint identical ids: the #2640 +// acceptance test at the package level. +func TestNewIDSeededReproducesIDs(t *testing.T) { + swapRandSource(t, randsrc.Seeded([]byte("run-seed"), "tasks")) + first := NewID() + swapRandSource(t, randsrc.Seeded([]byte("run-seed"), "tasks")) + if second := NewID(); second != first { + t.Fatalf("same seed minted different ids: %q vs %q", first, second) + } + swapRandSource(t, randsrc.Seeded([]byte("other-seed"), "tasks")) + if third := NewID(); third == first { + t.Fatalf("different seed minted the same id %q", first) + } +} diff --git a/pkgs/mcpx/internal/tasks/tasks.go b/pkgs/mcpx/internal/tasks/tasks.go index 82696d8208..9715f2daf9 100644 --- a/pkgs/mcpx/internal/tasks/tasks.go +++ b/pkgs/mcpx/internal/tasks/tasks.go @@ -14,7 +14,6 @@ package tasks import ( "context" - "crypto/rand" "database/sql" "encoding/hex" "encoding/json" @@ -411,7 +410,7 @@ func (s *Store) ensure() { // now let the store grow to. func NewID() string { var b [16]byte - _, _ = rand.Read(b[:]) + _, _ = RandSource.Read(b[:]) return "tsk-" + hex.EncodeToString(b[:]) }