diff --git a/formal/catalogs/go-parity.json b/formal/catalogs/go-parity.json index 4e876fa2..08f7b2ae 100644 --- a/formal/catalogs/go-parity.json +++ b/formal/catalogs/go-parity.json @@ -3680,14 +3680,14 @@ "symbols": [ "Identity" ], - "sha256": "d12b6b8c8c91f40e93cd44d97644ea1824b57ff0641d07a0e16ffe9a25ffde4a" + "sha256": "27cd94fd9d5e3b5b101d9dd4db810706b35811c8f5ebece23d89aae439669267" }, { "path": "go/codec.go", "symbols": [ "JSONCodec" ], - "sha256": "f0494637d5f1c5d5b16172c83545224468898543bbf862dcee86a3ffe226284c" + "sha256": "ddec51c29141c29c6c76e74cb2b25f20235519a8d26e32bc0e73fd04ab6882a0" } ] } @@ -3714,7 +3714,7 @@ "RawReadResult", "NormalizeReadResult" ], - "sha256": "d12b6b8c8c91f40e93cd44d97644ea1824b57ff0641d07a0e16ffe9a25ffde4a" + "sha256": "27cd94fd9d5e3b5b101d9dd4db810706b35811c8f5ebece23d89aae439669267" }, { "path": "go/engine.go", @@ -3751,7 +3751,7 @@ "EscapeRawPayload", "firstZstdFrame" ], - "sha256": "f0494637d5f1c5d5b16172c83545224468898543bbf862dcee86a3ffe226284c" + "sha256": "ddec51c29141c29c6c76e74cb2b25f20235519a8d26e32bc0e73fd04ab6882a0" } ] } @@ -3818,7 +3818,7 @@ "CeilSupportedCacheTTLMS", "ValidateTimestampMS" ], - "sha256": "d12b6b8c8c91f40e93cd44d97644ea1824b57ff0641d07a0e16ffe9a25ffde4a" + "sha256": "27cd94fd9d5e3b5b101d9dd4db810706b35811c8f5ebece23d89aae439669267" }, { "path": "go/policy.go", @@ -3904,7 +3904,7 @@ "symbols": [ "Cohort" ], - "sha256": "d12b6b8c8c91f40e93cd44d97644ea1824b57ff0641d07a0e16ffe9a25ffde4a" + "sha256": "27cd94fd9d5e3b5b101d9dd4db810706b35811c8f5ebece23d89aae439669267" }, { "path": "go/policy.go", @@ -3959,7 +3959,7 @@ "CompressPayload", "DecompressPayload" ], - "sha256": "f0494637d5f1c5d5b16172c83545224468898543bbf862dcee86a3ffe226284c" + "sha256": "ddec51c29141c29c6c76e74cb2b25f20235519a8d26e32bc0e73fd04ab6882a0" }, { "path": "go/redis_adapter.go", @@ -4028,7 +4028,7 @@ "parseWatermark", "replacementUTF8" ], - "sha256": "d12b6b8c8c91f40e93cd44d97644ea1824b57ff0641d07a0e16ffe9a25ffde4a" + "sha256": "27cd94fd9d5e3b5b101d9dd4db810706b35811c8f5ebece23d89aae439669267" } ] } @@ -4143,7 +4143,7 @@ "symbols": [ "appendJSON" ], - "sha256": "f0494637d5f1c5d5b16172c83545224468898543bbf862dcee86a3ffe226284c" + "sha256": "ddec51c29141c29c6c76e74cb2b25f20235519a8d26e32bc0e73fd04ab6882a0" }, { "path": "go/shadow_log.go", @@ -4211,7 +4211,7 @@ "escape", "utf16Less" ], - "sha256": "d12b6b8c8c91f40e93cd44d97644ea1824b57ff0641d07a0e16ffe9a25ffde4a" + "sha256": "27cd94fd9d5e3b5b101d9dd4db810706b35811c8f5ebece23d89aae439669267" } ] } @@ -4361,7 +4361,7 @@ "ReadResult", "NormalizeReadResult" ], - "sha256": "d12b6b8c8c91f40e93cd44d97644ea1824b57ff0641d07a0e16ffe9a25ffde4a" + "sha256": "27cd94fd9d5e3b5b101d9dd4db810706b35811c8f5ebece23d89aae439669267" }, { "path": "go/redis_adapter.go", @@ -4394,7 +4394,7 @@ "EncodeFrame", "DecodeFrame" ], - "sha256": "d12b6b8c8c91f40e93cd44d97644ea1824b57ff0641d07a0e16ffe9a25ffde4a" + "sha256": "27cd94fd9d5e3b5b101d9dd4db810706b35811c8f5ebece23d89aae439669267" }, { "path": "go/redis_adapter.go", @@ -4440,7 +4440,7 @@ "SemanticEqual", "validateJSONScalarStrings" ], - "sha256": "f0494637d5f1c5d5b16172c83545224468898543bbf862dcee86a3ffe226284c" + "sha256": "ddec51c29141c29c6c76e74cb2b25f20235519a8d26e32bc0e73fd04ab6882a0" } ] } diff --git a/go/codec.go b/go/codec.go index 2e78b275..2faa3e46 100644 --- a/go/codec.go +++ b/go/codec.go @@ -527,6 +527,12 @@ const MaxDecompressedBytes = 512 * 1024 * 1024 const DefaultCompressionThresholdBytes = 4096 const DefaultZstdLevel = 3 +// The decoder allocates a frame's window before it reads any block, so a tiny +// stored frame could otherwise force a 512 MiB allocation. libzstd's default +// reader limit, which the TypeScript, Rust and Python readers keep, is +// (1<<27)+1 bytes; a single-segment frame's window is its content size. +const maxZstdWindowBytes = 1<<27 + 1 + type CompressionConfig struct { ThresholdBytes int Level int @@ -653,7 +659,7 @@ func DecompressPayload(payload Payload, limit ...int) CompressionReadResult { result.Outcome = "fallback_raw" return result } - reader, err := zstd.NewReader(bytes.NewReader(body), zstd.WithDecoderConcurrency(1), zstd.WithDecoderMaxMemory(MaxDecompressedBytes)) + reader, err := zstd.NewReader(bytes.NewReader(body), zstd.WithDecoderConcurrency(1), zstd.WithDecoderMaxMemory(MaxDecompressedBytes), zstd.WithDecoderMaxWindow(maxZstdWindowBytes)) if err != nil { result.Outcome = "fallback_raw" return result @@ -672,7 +678,13 @@ func DecompressPayload(payload Payload, limit ...int) CompressionReadResult { return result } if marker == 1 { - decoded = replacementUTF8(decoded) + var within bool + // The limit counts decoded bytes (portable vectors), but each ill-formed + // byte can grow to a 3-byte U+FFFD; keep the replaced text under the cap. + if decoded, within = replacementUTF8Within(decoded, MaxDecompressedBytes); !within { + result.Outcome = "read_over_limit" + return result + } } return CompressionReadResult{Payload{Bytes: decoded, Binary: marker == 2}, "decompressed"} } diff --git a/go/internal/testsuite/compression_test.go b/go/internal/testsuite/compression_test.go index 2bfc917c..867f6059 100644 --- a/go/internal/testsuite/compression_test.go +++ b/go/internal/testsuite/compression_test.go @@ -3,7 +3,9 @@ package dialcache_test import ( "bytes" "context" + "encoding/binary" "math/rand/v2" + "runtime" "slices" "strings" "testing" @@ -36,8 +38,8 @@ type frameRemote struct { writes int } -func (r *frameRemote) Read(context.Context, string, string) (ReadResult, error) { - result := DecodeFrame(r.raw, false, nil) +func (r *frameRemote) Read(_ context.Context, _, watermarkKey string) (ReadResult, error) { + result := DecodeFrame(r.raw, watermarkKey != "", nil) return result, result.Error() } func (r *frameRemote) Write(_ context.Context, _ string, frame Frame, _ time.Duration) error { @@ -118,3 +120,120 @@ func TestCompressPayloadRoundTripsAcrossBlockSizes(t *testing.T) { } } } + +// rleZstdFrame returns a zstd frame with the given frame header descriptor and +// window or content size fields, holding n copies of b in RLE blocks of at most +// 128 KiB. +func rleZstdFrame(header []byte, b byte, n int) []byte { + frame := append([]byte{0x28, 0xb5, 0x2f, 0xfd}, header...) + for { + size := min(n, 128<<10) + n -= size + block := uint32(1)<<1 | uint32(size)<<3 + if n == 0 { + block |= 1 + } + frame = append(frame, byte(block), byte(block>>8), byte(block>>16), b) + if n == 0 { + return frame + } + } +} + +// declaredWindow is a frame header that declares a 2^windowLog window and no +// content size, so the decoder sizes its history from the window. +func declaredWindow(windowLog int) []byte { return []byte{0x00, byte((windowLog - 10) << 3)} } + +// singleSegment is a frame header with an 8-byte content size and no window +// descriptor, which bounds the window by the content size. +func singleSegment(size int) []byte { + return binary.LittleEndian.AppendUint64([]byte{0xe0}, uint64(size)) +} + +func measure(f func()) (allocated uint64, elapsed time.Duration) { + var before, after runtime.MemStats + runtime.GC() + runtime.ReadMemStats(&before) + start := time.Now() + f() + elapsed = time.Since(start) + runtime.ReadMemStats(&after) + return after.TotalAlloc - before.TotalAlloc, elapsed +} + +// The decoder allocates a frame's declared window before it reads a block, so +// a stored value of a few bytes could force a 512 MiB allocation on every read. +// Reads accept the largest window the TypeScript reader accepts and reject a +// larger one without allocating it. +func TestDecompressPayloadRejectsWindowsLargerThanTheTypeScriptReader(t *testing.T) { + for _, marker := range []byte{1, 2} { + accepted := DecompressPayload(Payload{Binary: true, Bytes: append([]byte{marker}, rleZstdFrame(declaredWindow(27), 'x', 1)...)}) + if accepted.Outcome != "decompressed" || string(accepted.Payload.Bytes) != "x" { + t.Fatalf("marker %d, 128 MiB window: outcome %q, payload %q", marker, accepted.Outcome, accepted.Payload.Bytes) + } + for _, windowLog := range []int{28, 29} { + stored := append([]byte{marker}, rleZstdFrame(declaredWindow(windowLog), 'x', 1)...) + var read CompressionReadResult + allocated, elapsed := measure(func() { read = DecompressPayload(Payload{Binary: true, Bytes: stored}) }) + if read.Outcome != "read_over_limit" || !bytes.Equal(read.Payload.Bytes, stored) || allocated > 1<<20 || elapsed > 100*time.Millisecond { + t.Fatalf("marker %d, %d MiB window: outcome %q, %d bytes allocated in %v", marker, 1<<(windowLog-20), read.Outcome, allocated, elapsed) + } + } + } +} + +// A single-segment frame's window is its content size. Reads accept the same +// sizes as libzstd's default reader limit, (1<<27)+1 bytes; libzstd and +// klauspost write a single-segment frame only when the content fits the window. +func TestDecompressPayloadMatchesLibzstdSingleSegmentLimit(t *testing.T) { + const size = 128<<20 + 1 + read := DecompressPayload(Payload{Binary: true, Bytes: append([]byte{2}, rleZstdFrame(singleSegment(size), 'x', size)...)}) + if read.Outcome != "decompressed" || len(read.Payload.Bytes) != size { + t.Fatalf("%d bytes: outcome %q, %d bytes", size, read.Outcome, len(read.Payload.Bytes)) + } + stored := append([]byte{2}, rleZstdFrame(singleSegment(size+1), 'x', size+1)...) + if read := DecompressPayload(Payload{Binary: true, Bytes: stored}); read.Outcome != "read_over_limit" || !bytes.Equal(read.Payload.Bytes, stored) { + t.Fatalf("%d bytes: outcome %q", size+1, read.Outcome) + } +} + +// Writers that store uncompressed values still read frames marked as zstd, so +// the window bound holds on a tracked, remote-only read too. +func TestOversizedZstdWindowFailsOpenWithoutAllocating(t *testing.T) { + raw, err := EncodeFrame(Frame{CreatedAtMS: uint64(time.Now().UnixMilli()), Binary: true, Payload: append([]byte{2}, rleZstdFrame(declaredWindow(29), 'x', 1)...)}) + if err != nil { + t.Fatal(err) + } + remote := &frameRemote{raw: raw} + var errors []any + cache := MustNew(WithRemote(remote), WithoutCompression(), WithLocalCapacity(0), WithObserver(func(event Event) { + if event.Kind == "error" { + errors = append(errors, event.Data["error"]) + } + })) + coalesce := false + ctx, done := cache.Enable(context.Background()) + var value string + allocated, _ := measure(func() { + value, err = GetOrLoad(ctx, cache, Operation[string]{ + Identity: Identity{Namespace: "test", KeyType: "entity", ID: "1", UseCase: "read", Tracked: true}, + Policy: Policy{RemoteTTL: time.Minute, Coalesce: &coalesce}, + }, func(context.Context) (string, error) { return "source", nil }) + }) + done() + if value != "source" || err != nil || remote.writes != 1 || !slices.Equal(errors, []any{"serialization_load"}) || allocated > 16<<20 { + t.Fatalf("value=%q err=%v writes=%d errors=%v allocated=%d", value, err, remote.writes, errors, allocated) + } +} + +// The read limit counts decoded bytes, and each ill-formed UTF-8 byte then +// becomes a 3-byte U+FFFD. A 16 KiB frame of 512 MiB of 0xFF would otherwise +// return 1.5 GiB of text, so the replaced text must also fit the 512 MiB cap. +func TestDecompressPayloadBoundsReplacedText(t *testing.T) { + stored := append([]byte{1}, rleZstdFrame(declaredWindow(17), 0xff, MaxDecompressedBytes)...) + var read CompressionReadResult + allocated, elapsed := measure(func() { read = DecompressPayload(Payload{Binary: true, Bytes: stored}) }) + if read.Outcome != "read_over_limit" || !bytes.Equal(read.Payload.Bytes, stored) || allocated > 5<<30 { + t.Fatalf("outcome %q, %d bytes returned, %d bytes allocated in %v", read.Outcome, len(read.Payload.Bytes), allocated, elapsed) + } +} diff --git a/go/protocol.go b/go/protocol.go index a468a059..61699a94 100644 --- a/go/protocol.go +++ b/go/protocol.go @@ -323,8 +323,18 @@ func DecodeFrame(raw []byte, tracked bool, watermark *string) ReadResult { // A valid incomplete prefix (E2 82) is one subpart; forbidden continuation bytes // (ED A0 80, an encoded surrogate) are not swallowed into that prefix. func replacementUTF8(raw []byte) []byte { + out, _ := replacementUTF8Within(raw, -1) + return out +} + +// replacementUTF8Within stops with false once the output exceeds limit bytes; a +// negative limit means no limit. +func replacementUTF8Within(raw []byte, limit int) ([]byte, bool) { out := make([]byte, 0, len(raw)) for len(raw) > 0 { + if limit >= 0 && len(out) > limit { + return nil, false + } r, size := utf8.DecodeRune(raw) if r != utf8.RuneError || size != 1 { out = append(out, raw[:size]...) @@ -355,7 +365,7 @@ func replacementUTF8(raw []byte) []byte { out = utf8.AppendRune(out, utf8.RuneError) raw = raw[consumed:] } - return out + return out, limit < 0 || len(out) <= limit } // UnmarshalJSON rejects isolated UTF-16 escapes before encoding/json replaces diff --git a/go/protocol_test.go b/go/protocol_test.go index 4ed40500..893a2884 100644 --- a/go/protocol_test.go +++ b/go/protocol_test.go @@ -528,3 +528,24 @@ func protocolNumber(value float64, special string) float64 { return value } } + +func TestReplacementUTF8Within(t *testing.T) { + for _, test := range []struct { + raw string + limit int + want string + ok bool + }{ + {"\xff\xff", -1, "\ufffd\ufffd", true}, + {"\xff\xff", 6, "\ufffd\ufffd", true}, + {"\xff\xff", 5, "", false}, + {"abc", 3, "abc", true}, + {"abc", 2, "", false}, + {"", 0, "", true}, + } { + got, ok := replacementUTF8Within([]byte(test.raw), test.limit) + if ok != test.ok || ok && string(got) != test.want { + t.Errorf("%q within %d: got %q, %v", test.raw, test.limit, got, ok) + } + } +}