Reject undersized data chunks in framed stream decompression

Merged
BR
17d ago
+85-14

What changed

  • SnappyStreamDecompressor throws InvalidDataException("Chunk too small to contain a CRC.") when a compressed or uncompressed chunk header declares fewer than 4 bytes. The check runs once, when the header is read, and covers both branches.
  • ReadChunkHeader is replaced by TryReadChunkHeader(ref input, out uint header). The old method returned 0 to mean "insufficient data", so an all-zero header (a compressed chunk declaring 0 bytes) was treated as missing data and the stream ended without an error.
  • When part of a chunk header is already in scratch, the copy of the remaining bytes is bounded by the input length.
  • New tests: UndersizedDataChunk_ThrowsInvalidDataException (both chunk types, sizes 0–3) and Decompress_OneByteReads_RoundTrips (a valid stream read one byte at a time).

Why

An uncompressed chunk declaring 0–3 bytes threw ArgumentOutOfRangeException from input.Slice, because ReadChunkCrc consumes 4 bytes without checking the declared size. Every other malformed-input path throws InvalidDataException, and the compressed branch already guarded this case after #147. A caller that catches only InvalidDataException around decompression could let the exception escape. In a BackgroundService on the default generic host, that stops the application.

The split-header fix affects valid input: a chunk header arriving over three or more reads, as from a slow network stream, threw ArgumentOutOfRangeException.

Reviewer notes

  • Against the previous decompressor, 6 of the new test cases fail: all four undersized uncompressed sizes, the all-zero compressed header, and the one-byte-read round trip.
  • All 1268 tests pass on net8.0, net10.0, net11.0 and net481.
  • The new throw uses an inline message, matching the other throws in SnappyStreamDecompressor, which #158 did not move into helpers.

šŸ¤– Generated with Claude Code