diff --git a/.github/workflows/BuildAndTest.yml b/.github/workflows/BuildAndTest.yml index d61f6dc6..eb22877b 100644 --- a/.github/workflows/BuildAndTest.yml +++ b/.github/workflows/BuildAndTest.yml @@ -182,7 +182,7 @@ jobs: wget -O - https://apt.llvm.org/llvm-snapshot.gpg.key | gpg --dearmor | sudo tee /usr/share/keyrings/llvm-archive-keyring.gpg > /dev/null echo "deb [signed-by=/usr/share/keyrings/llvm-archive-keyring.gpg] https://apt.llvm.org/noble/ llvm-toolchain-noble-23 main" | sudo tee /etc/apt/sources.list.d/llvm.list sudo apt-get update - sudo apt-get install -y clang-23 libclang-rt-23-dev libc++-23-dev libc++abi-23-dev + sudo apt-get install -y clang-23 libclang-rt-23-dev libc++-23-dev libc++abi-23-dev zlib1g-dev - name: Restrict address-space randomization for ThreadSanitizer if: matrix.sanitizer == 'thread' run: sudo sysctl vm.mmap_rnd_bits=28 @@ -191,13 +191,19 @@ jobs: run: >- cmake -S . -B build-sanitizers -DCMAKE_BUILD_TYPE=RelWithDebInfo -DWEBFRONT_EMBED_CEF=OFF -DWEBFRONT_BUILD_EXAMPLES=OFF -DENABLE_TESTING=ON -DENABLE_CACHE=OFF - ${{ matrix.sanitizer == 'thread' && '-DCMAKE_CXX_FLAGS=-stdlib=libc++ -DENABLE_SANITIZER_THREAD=ON' || '-DENABLE_SANITIZER_ADDRESS=ON -DENABLE_SANITIZER_UNDEFINED_BEHAVIOR=ON -DENABLE_FUZZING=ON' }} + ${{ matrix.sanitizer == 'thread' && '-DCMAKE_CXX_FLAGS=-stdlib=libc++ -DENABLE_SANITIZER_THREAD=ON' || '-DENABLE_SANITIZER_ADDRESS=ON -DENABLE_SANITIZER_UNDEFINED_BEHAVIOR=ON -DENABLE_FUZZING=ON -DWEBFRONT_GZIP_DIFFERENTIAL=ON' }} - name: Build run: cmake --build build-sanitizers --parallel 2 - name: Run full CEF-off suite run: >- ctest --test-dir build-sanitizers --output-on-failure --no-tests=error --parallel 4 --output-junit "${{ github.workspace }}/build-sanitizers/test-results.xml" + - name: Compare generated gzip streams against zlib + timeout-minutes: 5 + if: matrix.sanitizer == 'address-undefined' + run: | + python3 test/fuzz/GenerateGzipCorpus.py build-sanitizers/gzip-corpus + build-sanitizers/test/unit/gzip_differential build-sanitizers/gzip-corpus - name: Retain test timings and diagnostics if: always() uses: actions/upload-artifact@v4 @@ -218,6 +224,9 @@ jobs: -max_total_time=30 -timeout=5 -max_len=65536 -rss_limit_mb=1024 \ -artifact_prefix=build-sanitizers/test/fuzz/artifacts/$decoder- done + build-sanitizers/test/fuzz/fuzz_gzip_differential build-sanitizers/test/fuzz/corpus/gzip \ + -max_total_time=30 -timeout=5 -max_len=65536 -rss_limit_mb=1024 \ + -artifact_prefix=build-sanitizers/test/fuzz/artifacts/gzip-differential- - name: Upload fuzz findings if: failure() && matrix.sanitizer == 'address-undefined' uses: actions/upload-artifact@v4 diff --git a/CMakeLists.txt b/CMakeLists.txt index 5f3c361d..ae123f08 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -12,6 +12,7 @@ option(ENABLE_TESTING "Enable Test Builds" OFF) option(WEBFRONT_BUILD_EXAMPLES "Build the example applications" ${WEBFRONT_IS_TOP_LEVEL}) option(ENABLE_COVERAGE "Enable test coverage instrumentation" OFF) option(ENABLE_FUZZING "Enable Fuzzing Builds" OFF) +option(WEBFRONT_GZIP_DIFFERENTIAL "Build test-only gzip/zlib differential checks" OFF) option(WEBFRONT_USE_MDDLOG "Use the compiled mddlog diagnostic adapter" OFF) # The experimental gate must be selected before project() probes the compiler. if(WEBFRONT_USE_MDDLOG) diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 173ae300..30615a00 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -2,6 +2,13 @@ ## Unreleased +## 0.5.0 - 2026-10-26 + +- Gzip identity fallback reuses a bounded validated-representation cache for GET and HEAD (#281). + Cold decoding uses buffered bit reads and a small Huffman lookup (#282), with unchanged + allocation behavior, strict stream validation and output budgets. Release benchmarks and + test-only zlib differential/sanitizer validation are recorded in `docs/GZIP_DECODER_MEASUREMENTS.md`. + - `WebFrontLifeDeveloper` starts without argument on `./life-project` (created when missing, reused untouched otherwise) and the pinned environment; the explicit ` [ ]` form remains. At configuration, the native window engine of the platform is enabled automatically when its dependencies are found (top-level builds with examples, diff --git a/docs/GZIP_DECODER_MEASUREMENTS.md b/docs/GZIP_DECODER_MEASUREMENTS.md new file mode 100644 index 00000000..584e0d12 --- /dev/null +++ b/docs/GZIP_DECODER_MEASUREMENTS.md @@ -0,0 +1,151 @@ +# Gzip decoder measurements (#282) + +Measured on macOS 27.0.1, Apple M2 arm64, Homebrew Clang 21.1.8/libc++, Release +(`-std=c++23 -O3 -DNDEBUG`), 2026-10-25. Both versions use libc++ extensive hardening +and `-ftrivial-auto-var-init=pattern`. Timings are informational; no CI timing threshold. + +The baseline is `Gzip.hpp` at `d27e4fc`, after the cache (#281) and bounded worker (#283). +The same `GzipDecoderBenchmark.cpp` runs against both headers. It measures decoding, +CRC/header/trailer validation and byte-for-byte output verification, excluding provider reads, +HTTP, cache lookup, scheduling and network I/O. Every iteration decodes a cold representation. +`fresh` destroys the output string each iteration; `reserved` reserves the exact decoded size +before timing, representing the worker's preallocated output. The actual worker reserves its +configured limit. The benchmark does not simulate worker admission or response copying. + +The [cache measurements](GZIP_CACHE_MEASUREMENTS.md) show that cache hits remove repeat decoding; +this change reduces the remaining cold CPU work. Warm cache hits and gzip pass-through do not +invoke the decoder and receive no algorithmic benefit. The worker still runs one active decode, +with the same output, admission and shutdown contracts. + +## Corpus and results + +`GenerateGzipCorpus.py` uses Python 3.14.7/zlib 1.2.12, seed 282, gzip level 6 unless +specified. Compressed hashes depend on the Python zlib version; CI regenerates its own +corpus and does not require byte-identical compression across versions. The core bridge/bootstrap +sources are compressed **test inputs**; their production representations remain identity. The application is the generated developer compiler bundle +(78,508 decoded bytes, SHA-256 `5f36728943433f1b88eadcdc0db910133257b4502c8faec3357168b6739f70bc`). +No removed core provider is restored. Near-budget cases decode to 4,194,303 bytes, one byte +below the default limit: stored uses level 0 and deterministic random bytes; fixed/dynamic +use repeating JavaScript text; Huffman-only uses a deterministic sixteen-symbol alphabet; +incompressible uses random bytes and zlib's default strategy (predominantly stored blocks). +Some near-budget inputs exceed the server's separate 4 MiB compressed-input cap; these are +codec benchmarks, not claims that the default server admits those representations. + +Median of three runs, alternating order. Throughput uses preallocated output; fresh-output +times and allocation totals are shown separately. Allocation totals match the baseline. + +| Asset | gzip / decoded bytes | Reserved µs before / after | MiB/s before / after | Fresh µs before / after | Fresh allocations / bytes | +| --- | ---: | ---: | ---: | ---: | ---: | +| fixed | 499 / 23768 | 86.48 / 87.28 | 262.1 / 259.7 | 93.65 / 94.78 | 9 / 73,488 | +| dynamic | 453 / 23768 | 93.14 / 87.52 | 243.4 / 259.0 | 100.26 / 90.93 | 9 / 73,488 | +| optional | 476 / 23768 | 92.25 / 89.59 | 245.7 / 253.0 | 89.34 / 91.54 | 9 / 73,488 | +| bridge | 5739 / 25527 | 207.21 / 170.62 | 117.5 / 142.7 | 226.52 / 159.51 | 11 / 98,256 | +| bootstrap | 2824 / 6534 | 78.32 / 48.77 | 79.6 / 127.8 | 73.57 / 58.28 | 9 / 24,528 | +| application | 22974 / 78508 | 827.14 / 568.52 | 90.5 / 131.7 | 809.29 / 587.63 | 12 / 196,560 | +| near-stored | 4194651 / 4194303 | 12525.22 / 11135.83 | 319.4 / 359.2 | 12826.86 / 11119.19 | 7 / 8,323,072 | +| near-fixed | 36667 / 4194303 | 16501.30 / 14886.27 | 242.4 / 268.7 | 17698.25 / 14966.84 | 17 / 11,009,856 | +| near-dynamic | 14330 / 4194303 | 14807.34 / 15056.99 | 270.1 / 265.7 | 17463.25 / 14797.25 | 17 / 11,009,856 | +| near-incompressible | 4195601 / 4194303 | 11036.32 / 11085.55 | 362.4 / 360.8 | 11213.95 / 11048.08 | 9 / 8,378,352 | +| near-huffman | 2132022 / 4194303 | 48956.38 / 30807.26 | 81.7 / 129.8 | 47336.47 / 31237.99 | 18 / 12,582,864 | + +The application improves by about 31% and the Huffman-only case by 37% in these runs. +Small fixed decoding is within 1%; near-budget dynamic decoding is about 2% slower. +Stored-block copying and CRC are unchanged, so their variable timing is not evidence of a +new bulk-copy optimization. These observations support the small lookup for application +code and literal-heavy inputs, without claiming universal improvement. + +Allocation counts and bytes are **identical before and after**. They count scalar `operator new` +requests during the loop, including string growth, rather than allocator bookkeeping or peak RSS. +Input, reference output and pre-reservation allocations are excluded. The decoder has no aligned +or array allocation path. Every `reserved` case makes **zero allocations** during decoding. +The fresh case reports cumulative allocated bytes, not simultaneously live or retained memory. + +## Algorithm choice + +A byte-bounded 64-bit reservoir replaces per-bit input indexing. It holds at most 39 bits for +reads of up to 32 bits, checks each byte before fetching it and tracks logical offsets separately +from prefetched bytes. Alignment discards only the fractional byte; bulk reads return complete +prefetched bytes to the input view. This preserves header CRC ranges, stored blocks, member +trailers, concatenation and strict trailing-byte rejection without reading past the supplied span. + +A buffered-reader-only prototype gave a modest gain on the compiler bundle. The 128-entry +Huffman prototype reduced its fresh decode from approximately 743 to 613 µs; 256 entries reduced +it to approximately 534 µs in the exploratory run. The 256-entry table is retained: each tree +adds 512 stack bytes and no heap allocations. Codes longer than eight bits and short final input +use the validated canonical decoder. No large secondary tables or new tree acceptance rules are +introduced. Repeating-match and stored workloads remain dominated by copying and CRC validation. + +## Reproduction + +Configure the ordinary CEF-off Release build, then build the optional benchmark (not in CTest): + +```bash +cmake -S . -B build -DCMAKE_BUILD_TYPE=Release -DWEBFRONT_EMBED_CEF=OFF -DENABLE_TESTING=ON +cmake --build build --target gzip_decoder_benchmark --parallel 2 +python3 test/fuzz/GenerateGzipCorpus.py build/gzip-corpus path/to/build-distribution/compiler.mjs +build/test/unit/gzip_decoder_benchmark build/gzip-corpus/*.gz +``` + +The corpus directory must not already exist. Omit the optional bundle argument to use only +repository sources and generated neutral fixtures. The generator prints compressed/decoded +sizes and SHA-256 checksums. The benchmark also always runs the three small checked-in fixtures. +CSV reports time, decoded MiB/s, allocations and requested bytes per decode, for both output modes; +2,000 iterations per small input and 40 per input above 1 MiB. No timing assertion runs in CI. + +For an exact historical comparison, copy only the two standalone headers into a build directory +and compile the same harness with that directory first in the include path: + +```bash +mkdir -p build/gzip-baseline/webfront/http +git show d27e4fc:include/webfront/http/Gzip.hpp > build/gzip-baseline/webfront/http/Gzip.hpp +git show d27e4fc:include/webfront/http/BuffersPolicy.hpp > build/gzip-baseline/webfront/http/BuffersPolicy.hpp +clang++ -std=c++23 -O3 -DNDEBUG -D_LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_EXTENSIVE \ + -ftrivial-auto-var-init=pattern -Ibuild/gzip-baseline -Itest/unit \ + test/unit/GzipDecoderBenchmark.cpp -o build/gzip-before +clang++ -std=c++23 -O3 -DNDEBUG -D_LIBCPP_HARDENING_MODE=_LIBCPP_HARDENING_MODE_EXTENSIVE \ + -ftrivial-auto-var-init=pattern -Iinclude test/unit/GzipDecoderBenchmark.cpp -o build/gzip-after +build/gzip-before build/gzip-corpus/*.gz +build/gzip-after build/gzip-corpus/*.gz +``` + +Use the same compiler for both; adapt the standard-library hardening macro on other platforms. +Repeat three times, alternating before/after order. Desktop background activity makes these +local observations noisy; compare the corpus as a whole rather than treating a small timing +difference as a guaranteed gain. + +## Differential and sanitizer validation + +`WEBFRONT_GZIP_DIFFERENTIAL=ON` opts into test-only zlib linkage. Production remains header-only +and does not depend on zlib. `GzipZlibDifferential` checks the neutral fixtures in ordinary CTest; +`gzip_differential ` also compares generated stored/fixed/dynamic/Huffman-only, +flush boundaries and size-boundary cases, exact budgets, sampled truncations/mutations, optional +headers, concatenation, CRC and trailing bytes. Comparisons require matching acceptance and +byte-for-byte content. The oracle explicitly loops over members and requires full consumption. + +Intentional differences from permissive gzip consumers: WebFront rejects all trailing padding, +including zeros, and dynamic declarations of 31/32 distance symbols. The zlib oracle normalizes +strict consumption; arbitrary-input differential fuzzing compares every WebFront-accepted stream +with zlib, while the generated supported corpus checks acceptance in both directions. Reserved +or otherwise unsupported declarations are covered by WebFront's malformed-input unit fixtures. + +```bash +cmake -S . -B build -DWEBFRONT_GZIP_DIFFERENTIAL=ON +cmake --build build --target gzip_differential --parallel 2 +build/test/unit/gzip_differential build/gzip-corpus +ctest --test-dir build --output-on-failure --parallel 4 +``` + +For Clang/compiler-rt sanitizer fuzzing, configure with `ENABLE_FUZZING=ON` and +`WEBFRONT_GZIP_DIFFERENTIAL=ON`. See [fuzzing](../test/fuzz/README.md) for commands. +The extended CI ASan/UBSan job runs the generated corpus and both gzip fuzzers; CodeScene +quality gates remain unchanged. The generated-corpus comparison step has a five-minute timeout. + +On this macOS host, Homebrew's ASan runtime stalled in its allocator initialization before main. +Validation instead used Apple Clang 21.0.0's ASan/UBSan runtime; libFuzzer came from Homebrew LLVM +21.1.8 because Apple does not ship its archive. Both fuzzers ran for 30 seconds with a 1 MiB output +cap, 65,536-byte maximum mutation size and a five-second per-input timeout. Standalone differential +validation used the 4 MiB output limit with the complete generated corpus. + +Local validation: 293 CEF-off CTest cases passed; 12,571 generated/fixture comparisons passed +under ASan/UBSan; bounded fuzzing completed 53,370 runs and differential fuzzing 44,065 runs +without a finding. The 264 bit-width/alignment combinations are covered by the unit tests. diff --git a/docs/HTTP_ASSETS.md b/docs/HTTP_ASSETS.md index c3794878..aa551b1a 100644 --- a/docs/HTTP_ASSETS.md +++ b/docs/HTTP_ASSETS.md @@ -62,8 +62,11 @@ the decoded output budget is read for every fallback request. Zero retention dis caching, including HEAD metadata. Policies without this member inherit 8 MiB. For the synchronous API, `RequestHandler::fallbackCacheStatistics()` exposes decode attempts, hits (including budget-rejected hits), entries and accounted retained bytes; read it on the server context. The LRU lookup compares compressed bytes linearly across retained -entries; gzip pass-through remains independent of this cost. Decoder throughput and buffered -bit reads remain [#282](https://github.com/ambroise-leclerc/WebFront/issues/282). +entries; gzip pass-through remains independent of this cost. Cold decoding uses bounded buffered +bit reads and a 256-entry short-code Huffman lookup, with the canonical decoder for longer codes. +See [decoder measurements and differential validation](GZIP_DECODER_MEASUREMENTS.md) for the +Release comparison, allocation accounting and test-only zlib tools. Validation, budgets and +strict member/trailer boundaries are unchanged. See [gzip cache measurements](GZIP_CACHE_MEASUREMENTS.md) for cold/repeated GET and HEAD data and the optional benchmark target. @@ -142,7 +145,8 @@ never closes a socket from its thread. An active non-interruptible decode can de queued jobs are stopped without decoding. `fallbackDecodeStatistics()` exposes atomic counters for jobs, response leases, charged bytes, decode attempts and whether a worker has been created. `Server::fallbackCacheStatistics()` combines I/O-context cache counters with worker decode attempts; -read cache statistics on the I/O context. Decoder throughput remains #282. +read cache statistics on the I/O context. Buffered decoding reduces cold CPU work; see +[decoder measurements](GZIP_DECODER_MEASUREMENTS.md). ## Fallback budget diff --git a/docs/PROJECT_STATUS.md b/docs/PROJECT_STATUS.md index c2d1b983..ece6f321 100644 --- a/docs/PROJECT_STATUS.md +++ b/docs/PROJECT_STATUS.md @@ -178,6 +178,16 @@ be checked on the corrected head before merging. See the +## Release 0.5.0 (2026-10-26) + +`webfront::version` and the CMake project version are 0.5.0. This version integrates the +manifest-driven, self-building developer environment, the reduced identity-only embedded core, +and bounded cached/worker gzip fallback with buffered decoding. Includes move to +``; removed terminal/tool-manager APIs migrate to the developer terminal and +`webfront::Commands`. See `docs/CHANGELOG.md` and `docs/UI_COMPONENTS.md` for migration details. +The published developer environment pin is 0.6.2; environment sources at 0.6.3 are not yet +published. Library APIs and packaging remain experimental. + ## Release 0.4.0 (#200, 2026-10-21) `webfront::version` and the CMake project version are 0.4.0. The release presents the repository @@ -521,8 +531,13 @@ The minimum demonstration milestone is deliberately narrower than the long-term across keys and decoded storage. Each hit rechecks the active output budget; oversized entries are served without retention. Cold fallback runs on a lazy, owned CPU worker (#283), with bounded jobs, consumer slots and buffer reservations; results return to the I/O context. - Job, consumer and buffer saturation returns 503; the compressed-input cap (4 MiB by default) returns 500 before cache lookup. Active decoding finishes before shutdown joins; decoder throughput remains #282. See [HTTP asset encoding](HTTP_ASSETS.md) - for negotiation rules, errors, strict stream validation and budget configuration. + Job, consumer and buffer saturation returns 503; the compressed-input cap (4 MiB by default) + returns 500 before cache lookup. Active decoding finishes before shutdown joins. Bounded + buffered bit reads and a 256-entry + short-code Huffman table reduce cold decoding work (#282); allocation counts are unchanged. + See [Release decoder measurements and zlib differential validation](GZIP_DECODER_MEASUREMENTS.md) + and [HTTP asset encoding](HTTP_ASSETS.md) for negotiation rules, errors, strict stream validation + and budget configuration. Regression tests and gzip/HTTP fuzzers cover decoding and encoding preferences. Verified 2026-10-25 on Linux for #281: 275 CEF-off CTest cases and all 64 CEF/Xvfb web-integration cases passed; cold/repeated GET/HEAD measurements are recorded in diff --git a/include/webfront/WebFront.hpp b/include/webfront/WebFront.hpp index 8aef5f1b..b2f6cd53 100644 --- a/include/webfront/WebFront.hpp +++ b/include/webfront/WebFront.hpp @@ -34,7 +34,7 @@ namespace webfront { -inline constexpr std::string_view version = "0.4.0"; +inline constexpr std::string_view version = "0.5.0"; using NetProvider = networking::TCPStdnet; using ConnectionError = std::runtime_error; diff --git a/include/webfront/http/Gzip.hpp b/include/webfront/http/Gzip.hpp index 94094f03..5b66a162 100644 --- a/include/webfront/http/Gzip.hpp +++ b/include/webfront/http/Gzip.hpp @@ -21,48 +21,65 @@ class GzipReader { public: explicit GzipReader(std::string_view bytes) : input(bytes) {} - unsigned bits(unsigned count) { - unsigned value = 0; - for (unsigned index = 0; index < count; ++index) { - if (position == input.size()) - throw InvalidGzip{}; - value |= ((static_cast(input[position]) >> bit) & 1u) << index; - if (++bit == 8) { - bit = 0; - ++position; - } + // The reservoir contains at most 39 bits (a 32-bit read plus seven unused bits). + // Refill is byte-bounded even when a lookup probes the final short code. + bool peek(unsigned count, unsigned& value) { + if (count > 32) + throw InvalidGzip{}; + while (available < count && position < input.size()) { + buffer |= static_cast(static_cast(input[position++])) << available; + available += 8; } + if (available < count) + return false; + value = static_cast(buffer & ((std::uint64_t{1} << count) - 1)); + return true; + } + + void consume(unsigned count) { + if (count > available) + throw InvalidGzip{}; + buffer >>= count; + available -= count; + } + + unsigned bits(unsigned count) { + unsigned value; + if (!peek(count, value)) + throw InvalidGzip{}; + consume(count); return value; } std::string_view readBytes(std::size_t count) { - if (bit != 0) + if (available % 8 != 0) throw InvalidGzip{}; - if (count > input.size() - position) + // Return any whole prefetched bytes to the byte-oriented view. + const auto start = offset(); + if (count > input.size() - start) throw InvalidGzip{}; - const auto bytes = input.substr(position, count); - position += count; - return bytes; + position = start + count; + buffer = 0; + available = 0; + return input.substr(start, count); } void align() { - if (bit != 0) { - bit = 0; - ++position; - } + consume(available % 8); } std::size_t offset() const { - return position; + return position - (available + 7) / 8; } bool done() const { - return position == input.size(); + return offset() == input.size(); } private: std::string_view input; - std::size_t position = 0; - unsigned bit = 0; + std::size_t position = 0; + std::uint64_t buffer = 0; + unsigned available = 0; }; class DeflateTree { @@ -71,9 +88,18 @@ class DeflateTree { countLengths(lengths); validate(lengths.size(), requireComplete); buildTable(lengths); + buildLookup(); } unsigned decode(GzipReader& input) const { + unsigned prefix; + if (input.peek(lookupBits, prefix)) { + const auto entry = lookup[prefix]; + if (entry != 0) { + input.consume(entry & 15); + return entry >> 4; + } + } unsigned code = 0, first = 0, index = 0; for (unsigned length = 1; length <= 15; ++length) { code |= input.bits(1); @@ -135,8 +161,31 @@ class DeflateTree { sorted[offsets[lengths[symbol]]++] = symbol; } - std::array counts{}; - std::array sorted{}; + void buildLookup() { + unsigned code = 0, index = 0; + for (unsigned length = 1; length <= lookupBits; ++length) { + for (unsigned symbol = 0; symbol < counts[length]; ++symbol) { + addLookup(code + symbol, length, sorted[index + symbol]); + } + index += counts[length]; + code = (code + counts[length]) << 1; + } + } + + void addLookup(unsigned code, unsigned length, unsigned symbol) { + unsigned reversed = 0; + for (unsigned bit = 0; bit < length; ++bit) + reversed = (reversed << 1) | ((code >> bit) & 1u); + const auto entry = static_cast((symbol << 4) | length); + for (unsigned prefix = reversed; prefix < lookup.size(); prefix += 1u << length) + lookup[prefix] = entry; + } + + // Short codes use a small direct table; longer codes retain the canonical decoder. + static constexpr unsigned lookupBits = 8; + std::array lookup{}; + std::array counts{}; + std::array sorted{}; }; inline std::uint32_t gzipCrc(std::string_view bytes) { diff --git a/test/fuzz/CMakeLists.txt b/test/fuzz/CMakeLists.txt index 810ebfc4..0acafed7 100644 --- a/test/fuzz/CMakeLists.txt +++ b/test/fuzz/CMakeLists.txt @@ -28,3 +28,12 @@ foreach(_decoder IN ITEMS Messages HTTP WebSocket Gzip) # A writable copy lets libFuzzer evolve its corpus without touching the checkout. file(COPY "${CMAKE_CURRENT_SOURCE_DIR}/corpus/${_corpus}" DESTINATION "${CMAKE_CURRENT_BINARY_DIR}/corpus") endforeach() + +if(WEBFRONT_GZIP_DIFFERENTIAL) + find_package(ZLIB REQUIRED) + add_executable(fuzz_gzip_differential GzipDifferentialFuzz.cpp) + target_link_libraries(fuzz_gzip_differential PRIVATE WebFront WebFront_test_hardening ZLIB::ZLIB) + target_compile_options(fuzz_gzip_differential PRIVATE -g -fno-omit-frame-pointer + -fsanitize=fuzzer,address,undefined -fno-sanitize-recover=all) + target_link_options(fuzz_gzip_differential PRIVATE -fsanitize=fuzzer,address,undefined) +endif() diff --git a/test/fuzz/GenerateGzipCorpus.py b/test/fuzz/GenerateGzipCorpus.py new file mode 100644 index 00000000..c0a9b211 --- /dev/null +++ b/test/fuzz/GenerateGzipCorpus.py @@ -0,0 +1,44 @@ +"""Reproducible gzip benchmark/differential corpus; writes only to a new directory.""" +import hashlib +import pathlib +import random +import sys +import zlib + +root = pathlib.Path(__file__).resolve().parents[2] +out = pathlib.Path(sys.argv[1]) +out.mkdir(parents=True, exist_ok=False) + + +def write(name, data, level=6, strategy=zlib.Z_DEFAULT_STRATEGY): + compressor = zlib.compressobj(level, zlib.DEFLATED, 31, 8, strategy) + compressed = compressor.compress(data) + compressor.flush() + (out / (name + ".gz")).write_bytes(compressed) + print(name, len(compressed), len(data), hashlib.sha256(compressed).hexdigest()) + + +for name, path in [("bridge", root / "js/core/WebFront.js"), + ("bootstrap", root / "js/core/bootstrap/bootstrap.bundle.mjs")]: + write(name, path.read_bytes()) +# Representative application bundle supplied separately, e.g. the pinned developer compiler.mjs. +if len(sys.argv) > 2: + write("application", pathlib.Path(sys.argv[2]).read_bytes()) +size = 4 * 1024 * 1024 - 1 +rng = random.Random(282) +noise = rng.randbytes(size) +pattern = b"const state = {value: 42}; export function render() { return state.value; }\n" +text = (pattern * (size // len(pattern) + 1))[:size] +write("near-stored", noise, 0) +write("near-fixed", text, strategy=zlib.Z_FIXED) +write("near-dynamic", text) +write("near-incompressible", noise) +write("near-huffman", bytes(random.Random(282).choices(range(16), k=size)), + strategy=zlib.Z_HUFFMAN_ONLY) +compressor = zlib.compressobj(wbits=31) +mixed = compressor.compress(text[:4096]) + compressor.flush(zlib.Z_SYNC_FLUSH) +mixed += compressor.compress(noise[:513]) + compressor.flush() +(out / "mixed-blocks.gz").write_bytes(mixed) +print("mixed-blocks", len(mixed), 4096 + 513, hashlib.sha256(mixed).hexdigest()) +for length in [0, 1, 2, 7, 8, 15, 16, 31, 32, 255, 256, 257, 258, 32767, 32768, 65535, 65536]: + for level, strategy, name in [(0, 0, "stored"), (6, zlib.Z_FIXED, "fixed"), (6, 0, "dynamic")]: + write(f"boundary-{length}-{name}", noise[:length], level, strategy) diff --git a/test/fuzz/GzipDifferential.cpp b/test/fuzz/GzipDifferential.cpp new file mode 100644 index 00000000..09b3383c --- /dev/null +++ b/test/fuzz/GzipDifferential.cpp @@ -0,0 +1,61 @@ +#include "../unit/GzipFixtures.hpp" +#include "GzipZlib.hpp" + +#include +#include +#include +#include + +namespace { +std::size_t comparisons{}; +void check(std::string_view bytes, std::size_t limit = 4 * 1024 * 1024) { + gziptest::compare(bytes, limit); + ++comparisons; +} +void exercise(std::string_view bytes) { + const auto expected = gziptest::reference(bytes, 4 * 1024 * 1024); + if (!expected) + throw std::runtime_error("expected a valid corpus member"); + check(bytes); + check(bytes, expected->size()); + if (!expected->empty()) + check(bytes, expected->size() - 1); + // Exhaust short streams; sample large stored/literal streams and every trailer byte. + const auto stride = std::max(1, bytes.size() / 128); + for (std::size_t size = 0; size < bytes.size(); size += stride) + check(bytes.substr(0, size)); + for (std::size_t size = bytes.size() - 8; size < bytes.size(); ++size) + check(bytes.substr(0, size)); + for (std::size_t index = 0; index < bytes.size(); index += stride) { + auto corrupt = std::string(bytes); + corrupt[index] ^= static_cast(0x80); + check(corrupt); + } + for (const auto suffix : {std::string("\0", 1), std::string("garbage"), std::string(gzipfixtures::empty)}) + check(std::string(bytes) + suffix); +} +} // namespace + +int main(int argc, char** argv) { + try { + for (const auto bytes : {gzipfixtures::fixed, gzipfixtures::dynamic, gzipfixtures::optional, gzipfixtures::empty}) + exercise(bytes); + check(std::string(gzipfixtures::dynamic) + std::string(gzipfixtures::optional)); + for (int index = 1; index < argc; ++index) { + for (const auto& entry : std::filesystem::directory_iterator(argv[index])) { + if (entry.path().extension() != ".gz") + continue; + std::ifstream file(entry.path(), std::ios::binary); + if (!file) + throw std::runtime_error("cannot read corpus"); + const std::string bytes(std::istreambuf_iterator(file), {}); + std::cout << entry.path().filename().string() << '\n'; + exercise(bytes); + } + } + std::cout << comparisons << " differential comparisons passed (zlib " << zlibVersion() << ")\n"; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/test/fuzz/GzipDifferentialFuzz.cpp b/test/fuzz/GzipDifferentialFuzz.cpp new file mode 100644 index 00000000..0ec39f77 --- /dev/null +++ b/test/fuzz/GzipDifferentialFuzz.cpp @@ -0,0 +1,14 @@ +#include "GzipZlib.hpp" + +#include + +extern "C" int LLVMFuzzerTestOneInput(const std::uint8_t* data, std::size_t size) { + const std::string_view bytes(reinterpret_cast(data), size); + constexpr std::size_t limit = 1024 * 1024; + const auto actual = webfront::http::gzip::decodeGzip(bytes, limit); + // Arbitrary zlib-accepted inputs may use unsupported reserved distance declarations. + // Generated supported streams are checked in both directions by gzip_differential. + if (actual && actual != gziptest::reference(bytes, limit)) + std::abort(); + return 0; +} diff --git a/test/fuzz/GzipZlib.hpp b/test/fuzz/GzipZlib.hpp new file mode 100644 index 00000000..6f8f3bb9 --- /dev/null +++ b/test/fuzz/GzipZlib.hpp @@ -0,0 +1,53 @@ +#pragma once + +#include + +#include +#include +#include + +#include + +namespace gziptest { +// Test-only zlib oracle. Require complete consumption, concatenation and the same total budget. +inline std::optional reference(std::string_view bytes, std::size_t limit) { + if (bytes.size() > std::numeric_limits::max()) + throw std::runtime_error("zlib oracle input exceeds uInt"); + z_stream stream{}; + if (inflateInit2(&stream, 31) != Z_OK) + throw std::runtime_error("inflateInit2 failed"); + struct Cleanup { + z_stream& stream; + ~Cleanup() { + inflateEnd(&stream); + } + } cleanup{stream}; + stream.next_in = reinterpret_cast(const_cast(bytes.data())); + stream.avail_in = static_cast(bytes.size()); + std::string output; + std::array block{}; + for (;;) { + stream.next_out = reinterpret_cast(block.data()); + stream.avail_out = block.size(); + const auto before = stream.avail_in; + const auto status = inflate(&stream, Z_NO_FLUSH); + const auto produced = block.size() - stream.avail_out; + if (produced > limit - output.size()) + return std::nullopt; + output.append(block.data(), produced); + if (status == Z_STREAM_END) { + if (stream.avail_in == 0) + return output; + if (inflateReset(&stream) != Z_OK) + throw std::runtime_error("inflateReset failed"); + } else if (status != Z_OK || (before == stream.avail_in && produced == 0)) { + return std::nullopt; + } + } +} + +inline void compare(std::string_view bytes, std::size_t limit) { + if (webfront::http::gzip::decodeGzip(bytes, limit) != reference(bytes, limit)) + throw std::runtime_error("gzip/zlib acceptance or content mismatch"); +} +} // namespace gziptest diff --git a/test/fuzz/README.md b/test/fuzz/README.md index 4a9a73cb..b347198b 100644 --- a/test/fuzz/README.md +++ b/test/fuzz/README.md @@ -24,9 +24,44 @@ Run against that copy, since libFuzzer adds and minimizes inputs in its corpus: Repeat for `http`, `websocket` and `gzip`. Gzip seeds cover stored, fixed/dynamic Huffman blocks, optional header fields, empty members, corruption and truncation. The gzip harness -caps total decoded output at 1 MiB; the HTTP server uses 64 MiB. Input errors caught by the harness are limited +caps total decoded output at 1 MiB; the HTTP server defaults to 4 MiB. Input errors caught by the harness are limited to the decoder's documented rejection exceptions; allocation failures, sanitizer findings and hardening assertion failures must stop the process. WebSocket payload budgets exercise rejection before allocation of attacker-supplied lengths. CI retains reproducer artifacts on failure. Reproduce a finding by passing its file to the same executable, then add a unit regression before fixing it. + + +## Gzip/zlib differential checks + +Opt in with `-DWEBFRONT_GZIP_DIFFERENTIAL=ON`: tests link zlib, production headers do not. +With `ENABLE_TESTING=ON`, `gzip_differential` compares the neutral fixtures in CTest; +with `ENABLE_FUZZING=ON`, `fuzz_gzip_differential` additionally checks arbitrary accepted +streams against zlib under ASan/UBSan: + +```sh +python3 test/fuzz/GenerateGzipCorpus.py build-test/gzip-corpus +build-test/test/unit/gzip_differential build-test/gzip-corpus +build-test/test/fuzz/fuzz_gzip_differential build-test/test/fuzz/corpus/gzip \ + -max_total_time=30 -timeout=5 -max_len=65536 -rss_limit_mb=1024 +``` + +The corpus directory must be new. An optional second generator argument supplies an application +bundle to compress. Generated supported streams check acceptance and content in both directions; +the fuzz target checks every WebFront-accepted stream, allowing intentional rejections of +unsupported declarations. The oracle handles concatenated members and requires exact consumption, +normalizing zlib consumers' permissive treatment of trailing padding. See +[decoder measurements](../../docs/GZIP_DECODER_MEASUREMENTS.md) for sizes, limits and reproduction. + +On macOS with Apple Clang and an external libFuzzer archive, the standalone equivalent is: + +```sh +clang++ -std=c++23 -O1 -g -fsanitize=fuzzer-no-link,address,undefined \ + -fno-sanitize-recover=all -Iinclude test/fuzz/GzipDifferentialFuzz.cpp \ + /path/to/libclang_rt.fuzzer_osx.a -lz -o build-test/fuzz_gzip_differential +``` + +Use `GzipFuzz.cpp` in the same command without `-lz` for the bounded non-differential harness. +This allows the compiler and its ASan runtime to remain paired when a different toolchain supplies +libFuzzer. A standalone differential runner uses `GzipDifferential.cpp` with +`-fsanitize=address,undefined -lz` and no libFuzzer archive. diff --git a/test/unit/CMakeLists.txt b/test/unit/CMakeLists.txt index 107b1e28..63f2e0f8 100644 --- a/test/unit/CMakeLists.txt +++ b/test/unit/CMakeLists.txt @@ -162,3 +162,16 @@ target_link_libraries(gzip_cache_benchmark PRIVATE WebFront_test_hardening WebFr add_test(NAME TransportBenchmarksAreManual COMMAND ${CMAKE_COMMAND} -DROOT=${PROJECT_SOURCE_DIR} -P ${PROJECT_SOURCE_DIR}/test/cmake/CheckManualTransportBenchmarks.cmake) + +if(NOT ENABLE_SANITIZER_THREAD) + add_executable(gzip_decoder_benchmark EXCLUDE_FROM_ALL GzipDecoderBenchmark.cpp) + target_link_libraries(gzip_decoder_benchmark PRIVATE WebFront_test_hardening WebFront_warnings WebFront_options WebFront) +endif() + +if(WEBFRONT_GZIP_DIFFERENTIAL) + find_package(ZLIB REQUIRED) + add_executable(gzip_differential ../fuzz/GzipDifferential.cpp) + target_link_libraries(gzip_differential PRIVATE WebFront_test_hardening WebFront_options WebFront ZLIB::ZLIB) + add_test(NAME GzipZlibDifferential COMMAND gzip_differential) + set_tests_properties(GzipZlibDifferential PROPERTIES TIMEOUT 60) +endif() diff --git a/test/unit/GzipDecoderBenchmark.cpp b/test/unit/GzipDecoderBenchmark.cpp new file mode 100644 index 00000000..119d1fb1 --- /dev/null +++ b/test/unit/GzipDecoderBenchmark.cpp @@ -0,0 +1,81 @@ +// Manual Release benchmark; global allocation counters are isolated from the test runtime. +#include "GzipFixtures.hpp" +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +std::size_t allocations{}, allocatedBytes{}; +} + +void* operator new(std::size_t size) { + if (auto* memory = std::malloc(size ? size : 1)) { + ++allocations; + allocatedBytes += size; + return memory; + } + throw std::bad_alloc(); +} +void operator delete(void* memory) noexcept { + std::free(memory); +} +void operator delete(void* memory, std::size_t) noexcept { + std::free(memory); +} + +namespace { +void measure(std::string_view name, std::string_view bytes, bool reserved) { + const auto expected = webfront::http::gzip::decodeGzip(bytes); + if (!expected) + throw std::runtime_error("invalid or over-budget benchmark input"); + const unsigned iterations = expected->size() > 1024 * 1024 ? 40 : 2000; + std::string output; + if (reserved) + output.reserve(expected->size()); + const auto initialCount = allocations, initialBytes = allocatedBytes; + const auto start = std::chrono::steady_clock::now(); + for (unsigned index = 0; index < iterations; ++index) { + if (!reserved) + std::string{}.swap(output); + if (!webfront::http::gzip::decodeGzipInto(bytes, output, expected->size()) || output != *expected) + throw std::runtime_error("benchmark decode mismatch"); + } + const auto elapsed = std::chrono::duration(std::chrono::steady_clock::now() - start).count(); + const auto count = allocations - initialCount, size = allocatedBytes - initialBytes; + std::cout << name << ',' << (reserved ? "reserved" : "fresh") << ',' << bytes.size() << ',' << expected->size() << ',' << iterations << ',' + << elapsed * 1e6 / iterations << ',' << static_cast(expected->size()) * iterations / elapsed / (1024 * 1024) << ',' + << static_cast(count) / iterations << ',' << static_cast(size) / iterations << '\n'; +} +} // namespace + +int main(int argc, char** argv) { + try { + std::cout << std::setprecision(12); + std::cout << "asset,output,compressed_bytes,decoded_bytes,iterations,us_per_decode,MiB_per_s,allocations,allocated_bytes\n"; + for (const auto& [name, bytes] : { + std::pair{ "fixed", gzipfixtures::fixed}, + { "dynamic", gzipfixtures::dynamic}, + {"optional", gzipfixtures::optional} + }) + for (const bool reserved : {false, true}) + measure(name, bytes, reserved); + for (int index = 1; index < argc; ++index) { + std::ifstream file(argv[index], std::ios::binary); + if (!file) + throw std::runtime_error("cannot open benchmark input"); + const std::string bytes(std::istreambuf_iterator(file), {}); + for (const bool reserved : {false, true}) + measure(argv[index], bytes, reserved); + } + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/test/unit/GzipTests.cpp b/test/unit/GzipTests.cpp index e589510f..1551e21c 100644 --- a/test/unit/GzipTests.cpp +++ b/test/unit/GzipTests.cpp @@ -362,3 +362,118 @@ SCENARIO("Gzip decoding fills a preallocated bounded worker buffer without growi REQUIRE(output.empty()); } } + +SCENARIO("Gzip buffered reads preserve logical byte offsets and exact member boundaries") { + using webfront::http::gzip::GzipReader; + using webfront::http::gzip::InvalidGzip; + GIVEN("a binary stream read with every supported width and initial bit alignment") { + const std::string bytes("\x81\x72\xe3\x54\xa5\x96", 6); + THEN("every value and offset counts consumed bits without consuming later bytes") { + for (unsigned alignment = 0; alignment < 8; ++alignment) { + for (unsigned width = 0; width <= 32; ++width) { + GzipReader reader(bytes); + reader.bits(alignment); + std::uint32_t expected = 0; + for (unsigned bit = 0; bit < width; ++bit) { + const auto offset = alignment + bit; + expected |= ((static_cast(bytes[offset / 8]) >> (offset % 8)) & 1u) << bit; + } + INFO(alignment << ", " << width); + REQUIRE(reader.bits(width) == expected); + REQUIRE(reader.offset() == (alignment + width) / 8); + REQUIRE_FALSE(reader.done()); + reader.align(); + const auto consumed = (alignment + width + 7) / 8; + REQUIRE(reader.offset() == consumed); + REQUIRE(reader.readBytes(bytes.size() - consumed) == std::string_view(bytes).substr(consumed)); + REQUIRE(reader.done()); + REQUIRE(reader.bits(0) == 0); + REQUIRE_THROWS_AS(reader.bits(1), InvalidGzip); + } + } + } + } + GIVEN("a one-byte input and a partially consumed final byte") { + GzipReader reader(std::string_view("\xff", 1)); + REQUIRE(reader.bits(1) == 1); + REQUIRE(reader.offset() == 0); + REQUIRE_FALSE(reader.done()); + REQUIRE(reader.bits(7) == 127); + REQUIRE(reader.offset() == 1); + REQUIRE(reader.done()); + REQUIRE_THROWS_AS(reader.bits(1), InvalidGzip); + REQUIRE_THROWS_AS(reader.bits(33), InvalidGzip); + } + GIVEN("optional header checksums and empty members between Huffman members") { + const auto bytes = std::string(gzipfixtures::optional) + std::string(gzipfixtures::empty) + std::string(gzipfixtures::fixed); + THEN("header CRC ranges and every member trailer stay exact") { + REQUIRE(decodeGzip(bytes) == payload() + payload()); + for (std::size_t size = bytes.size() - 8; size < bytes.size(); ++size) + REQUIRE_FALSE(decodeGzip(std::string_view(bytes).substr(0, size))); + REQUIRE_FALSE(decodeGzip(bytes + std::string(1, '\0'))); + } + } +} + +SCENARIO("Gzip lookahead retains prefetched bytes through alignment and bulk reads") { + using webfront::http::gzip::GzipReader; + using webfront::http::gzip::InvalidGzip; + GzipReader reader("abcdef"); + unsigned prefix; + GIVEN("lookahead across four bytes without consuming them") { + REQUIRE(reader.peek(32, prefix)); + REQUIRE(prefix == 0x64636261u); + REQUIRE(reader.offset() == 0); + REQUIRE(reader.readBytes(2) == "ab"); + REQUIRE(reader.bits(8) == 'c'); + REQUIRE(reader.peek(16, prefix)); + REQUIRE(prefix == 0x6564u); + THEN("alignment keeps complete prefetched bytes") { + reader.bits(1); + reader.align(); + REQUIRE(reader.offset() == 4); + REQUIRE(reader.readBytes(2) == "ef"); + REQUIRE(reader.done()); + } + } + GIVEN("lookahead beyond the end of an exact input span") { + REQUIRE(reader.readBytes(5) == "abcde"); + REQUIRE_FALSE(reader.peek(16, prefix)); + THEN("a failed probe preserves the last byte for a shorter code") { + REQUIRE(reader.offset() == 5); + REQUIRE(reader.bits(8) == 'f'); + REQUIRE(reader.done()); + REQUIRE_THROWS_AS(reader.consume(1), InvalidGzip); + } + } +} + +SCENARIO("Gzip Huffman lookup preserves short tails, long codes and empty distance trees") { + using namespace webfront::http::gzip; + GIVEN("a single-symbol incomplete alphabet at the very last input bit") { + const std::array lengths{1}; + DeflateTree tree(lengths); + GzipReader reader(std::string_view("\x7f", 1)); + reader.bits(7); + REQUIRE(tree.decode(reader) == 0); + REQUIRE(reader.done()); + } + GIVEN("a complete tree with codes longer than the direct table") { + std::array tooMany{}; + REQUIRE_THROWS_AS(DeflateTree(tooMany), InvalidGzip); + // One code at each length 1..8 and two at length 9 make a complete alphabet. + const std::array lengths{1, 2, 3, 4, 5, 6, 7, 8, 9, 9}; + DeflateTree tree(lengths); + GzipReader reader(std::string_view("\xff\x01", 2)); + REQUIRE(tree.decode(reader) == 9); + REQUIRE(reader.offset() == 1); + REQUIRE(reader.bits(7) == 0); + REQUIRE(reader.done()); + } + GIVEN("an empty distance alphabet and a full input byte") { + const std::array lengths{0}; + DeflateTree tree(lengths); + GzipReader reader(std::string_view("\0\0", 2)); + REQUIRE_THROWS_AS(tree.decode(reader), InvalidGzip); + } +}