Repository navigation
Reject RESP lengths and counts the parser cannot represent - #832
Conversation
A bulk length of LONG_MAX or LONG_MAX - 1 (strtol clamps an out-of-range length to LONG_MAX) made m_bulk_len + 2 overflow long in rs_read_bulk. A RESP3 map or attribute count above INT_MAX / 2 overflowed int when doubled. Under per-element miss tracking, nested counts adding up past INT_MAX overflowed m_nested_remaining. Counts above INT_MAX were also silently truncated when stored in int. Reject a bulk length above LONG_MAX - 2. Also reject an aggregate whose elements, together with the ones still outstanding, exceed INT_MAX. Both go through the existing parse_response() == -1 error path. Valid lengths and counts parse as before. The RESP fuzzer missed this because UBSan with halt_on_error=1 and no abort_on_error exits 1 and prints only "runtime error:". Treat that string, and LeakSanitizer reports, as crash needles. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🤖 Automated first-pass review. A human maintainer still needs to review this before merge. Thanks for this. I went through the bounds and they look right to me. One question, not blocking and probably a follow-up rather than something for this PR: with miss tracking on, a top-level Thanks also for the The core fix looks solid to me. |
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.
❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.
Reviewed by Cursor Bugbot for commit 22c6282. Configure here.
…G_MAX long is 32-bit on Windows, so strtol clamped counts above INT_MAX to LONG_MAX == INT_MAX. That let them pass the new bound, and the unit test hardcoded 64-bit LONG_MAX boundaries (MSYS2 UCRT64 make check failed). Parse aggregate counts as long long, and build the bulk length boundaries from LONG_MAX at run time. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Thanks for the review (version updated 2026-10-24T11:43:15Z).
|
… branch The sanitized next cell's UBSan abort found the bulk-length overflow; carry the fix so the cell can go green before either PR lands. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Re the review updated 2026-10-24T11:54:05Z, about a nested map near the bound: I checked this locally in an ASan+UBSan build (
The bot marked this as optional, and #545 currently carries this branch merged in, so I haven't pushed these cases. I can add them if a maintainer wants them in-tree. |
A nested RESP3 attribute takes a slot of its parent but is not tracked for per-element misses. That leaves m_nested_remaining larger than the outstanding element count, so *1 *2 |0 *2147483647 with miss tracking on still overflowed m_nested_remaining. When a tracked nested element is being recorded, include m_nested_remaining - 1 in the bound as well. Also parse the bulk length into a local, so a rejected length leaves m_bulk_len unchanged. Add unit cases for maps nested under outstanding elements and for the nested-attribute case. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Re the review updated 2026-10-24T13:49:29Z:
|
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Re the review updated 2026-10-24T14:02:40Z:
|
…ent CI branch Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Re the review updated 2026-10-24T14:41:28Z: thanks. On the |
|
CI note for a92655a. The only failure is |
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…-222-opt-in Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Thanks. Pushed 15ef8ad, which moves the
|
…-222-opt-in Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Thanks. The |
… 2.2.2-alpha (#545) **Depends on #822 and #832.** This branch merges both PR branches unchanged, so either can land first and the other merges cleanly: - #822 (`fix/libevent22-tls-error-access`, at cba1fcc) brings the `shard_connection.cpp` TLS error guard and `tests/test_connection_error_types.py`. Please review those in #822. - #832 (`fix/resp-bulk-length-overflow`, at 300da45) brings the RESP length/count bounds in `protocol.cpp`, the `check_length_limits()` unit test and the fuzzer's sanitizer-output checks. This PR's UBSan-aborting sanitized cell found that overflow. Please review those in #832. Intended order: land #822 and #832 first, then merge master here (no rebase or force push), so this diff becomes CI, tooling and docs only. Refs #535. #823 also adds a "Supported libevent versions" table and a #535 read-size note to DEVELOPMENT.md. Whichever of #823 and this PR lands second merges the two tables into one and keeps a single #535 paragraph. ## Problem memtier's integration suites (including ASan/UBSan/TSan) run only on the distro's libevent 2.1.12. Nothing in CI builds the current security release 2.1.13-stable or the 2.2 series, and libevent itself is never instrumented. Because of that, the 2.2.2-alpha regression fixed in #822 (an out-of-bounds access inside libevent on every plaintext connection error in a TLS-enabled build) could only be found by hand. The earlier version of this workflow used `paths:` filters, so it could not be a required check (a skipped required check never reports), put versions in job names, and installed Redis from a different source than `ci.yml`. ## Root cause libevent behaviour differs by series: 2.2.2-alpha asserts, or with `NDEBUG` reads and writes out of bounds, when `bufferevent_get_openssl_error()` is called on a plain bufferevent, and it returns no error for TLS bufferevents. 2.1 reads at most 4 KiB per socket read, 2.2 up to 16 KiB (#535). None of this is visible without building those libevent versions, instrumenting them, and checking which library memtier actually loads. ## Fix - **`scripts/build-libevent.sh`**: one helper for Linux and macOS. It pins 2.1.12-stable, 2.1.13-stable and 2.2.2-alpha by release-asset sha256 (never `/archive/`) and libevent `master` by commit (`d82464a2`, canary only). It rejects a non-empty or non-directory prefix before creating it, builds with CMake (Release), and with `LIBEVENT_FLAVOUR=sanitize` also builds libevent with ASan+UBSan. `--source-id` feeds the CI cache key. The macOS jobs in `ci.yml` keep using it for 2.1.13 (clean prefix as in #674, debug mode off). The macOS OpenSSL 1.0.2 cell keeps master's autotools build of 2.1.12, unchanged. Because the existing `ci.yml` macOS jobs now go through the helper, a helper regression also breaks those jobs. `build-macos-libevent.sh` and the helper are in the harness pattern, so any change to them runs the full libevent grid. - **`scripts/check-libevent-linkage.sh`** (Linux; on macOS it delegates to `check-macos-tls-links.sh`). It fails unless the `--version` `libevent=` field equals the expected string from the matrix (e.g. `2.2.2-alpha-dev`), the prefix's pkg-config files for every component are the same release, every libevent library loaded (directly or transitively, per `ldd`/`readelf`) comes from the prefix, the process loads exactly one libssl and one libcrypto (so `libevent_openssl` and memtier share one OpenSSL; checked on memtier's transitive `ldd` set, so a private OpenSSL found through RUNPATH is handled), and the `openssl=`/`prometheus=` fields are as intended. - **`.github/workflows/libevent-compat.yml`** redesign: - No path filters. Triggers match `ci.yml` (`pull_request` and `push` on `master`, `main`, `2.*`), plus a nightly schedule, a weekly schedule and `workflow_dispatch`. - Stable job names `libevent-compat (<track>, <cell>)` with no versions in them. The track is `legacy` 2.1.12, `stable` 2.1.13, `next` 2.2.2-alpha or `canary` master. - Aggregate **`libevent-compat-gate`** (`if: always()`). It fails unless planning and every non-canary cell succeeded. This is the only check to mark required. - **Every PR/push**: - `stable` and `next` TLS full suites, standalone and cluster. - `next` plaintext full suites with **memtier and libevent both under ASan+UBSan**. This is the cell that catches the #822 regression. - `next` `--disable-tls` build (Prometheus on) with `make check`. - **Nightly**, and PRs that change this harness: adds 2.1.12 source builds (TLS and plaintext), the remaining plaintext and no-TLS cells, and macOS builds with OpenSSL 3 and 4. - **Weekly and on dispatch**: a libevent `master` canary with `continue-on-error`. It is not required and not part of the gate. A failing canary writes a warning and a step-summary line, and a small `canary-alert` job (`issues: write`, canary runs only) opens or updates one "libevent master canary is failing" issue. - Sanitized cells run with `ASAN_OPTIONS=detect_leaks=1:abort_on_error=1` and `UBSAN_OPTIONS=halt_on_error=1:abort_on_error=1:print_stacktrace=1`. Concurrency groups include the event name, so pushes never cancel scheduled or dispatched runs. The nightly skips Sunday, when the weekly run covers the same grid. - Built libevent is cached with `actions/cache`, keyed on version, sha256/commit, flavour, OpenSSL version, compiler version, and the hashes of the helper and the workflow. - Redis is installed from packages.redis.io, the same way as `ci.yml`. - Wall time: each test cell runs one topology, and the cluster suites are split into two file shards (`utils/select_test_shard.py`, coverage checked by `utils/check_test_shards.py`, as in the sanitizer workflows). On 658fed4 an unsharded cluster cell took 35–41 min, as long as `ci.yml`'s slowest cell (`OSS-CLUSTER API: TCP TLS`, 37 min); standalone cells take about 25 min. - **`tests/test_reconnections.py`**: when memtier dies from a signal, the test prints its stderr, starting at the first sanitizer report or assertion. This makes an abort in `test_reconnect_cluster_mode_no_assertion` diagnosable from the CI log. On the previous head it failed with rc −6 in the sanitized alpha cell, and no stderr was printed. - **`DEVELOPMENT.md`**: the tested libevent matrix, how to evaluate another libevent locally, the 2.1 (4 KiB) vs 2.2 (16 KiB) read size (Refs #535), and the TLS messages memtier prints on 2.2 after #822. ## Tests - CI on 8e8b3a6: Libevent compatibility, all 28 jobs green (full grid, because this PR changes the harness), and all other workflows green. On 658fed4 it showed harness-side failures that are fixed: a test-time `PKG_CONFIG_PATH`, and absolute macOS install names for 2.2. - The cell that was red before (`test_reconnect_cluster_mode_no_assertion`, rc −6 under ASan+UBSan on b3c67f1) passed on x86_64 on 658fed4 and 8e8b3a6. The earlier failure ran on a source 167 commits behind master, before several cluster-reconnect fixes landed (e.g. 019d658, #777, #797, #799). The test now prints memtier's stderr whenever memtier dies from a signal. - Local (Ubuntu 24.04 container, OpenSSL 3.0.13): - The helper built 2.1.12, 2.1.13, 2.2.2-alpha, master and sanitized 2.2.2. - memtier built against each, plus `--disable-tls` and ASan+UBSan builds, and the linkage checker accepted every one. - The checker rejected each negative case: wrong expected version, prefix/runtime mismatch, a TLS expectation on a no-TLS build, a wrong Prometheus flag, and a build that loads the system libevent. - The helper rejected a non-empty prefix, a file used as prefix, an unknown version or flavour, and a missing argument. - Before/after: unguarded `master` built against sanitized 2.2.2-alpha aborts on a refused plaintext connection with `AddressSanitizer: heap-buffer-overflow` in `bufferevent_get_ssl_error` (`bufferevent_ssl.c:1108`), called from `shard_connection.cpp`. This branch exits normally in the same setup. - macOS (CI, nightly cells): with 2.2 the helper now sets absolute install names (`CMAKE_INSTALL_NAME_DIR`), because 2.2's CMake otherwise installs `@rpath/` dylibs, which `check-macos-tls-links.sh` rejects. - `actionlint` (with shellcheck) is clean on the new workflow, `shellcheck` is clean on the scripts, and the C++ passes `clang-format-18 --dry-run --Werror`. ## Per-PR cost, sanitizers, and the required check - **PR scope**: 10 Linux jobs. On 8e8b3a6 (full grid, 28 jobs, all green) the longest cell took 27 min (`next, plaintext-asan, standalone`) and the cluster shards 18–23 min. `ci.yml`'s slowest cell took about 37 min on the same push, so libevent-compat is not on the PR critical path. - **Measured cost**: on 8e8b3a6 the 10 PR-scope jobs used about 203 runner-min (all existing workflows together use about 818 per PR run). Of that, `stable` (2.1.13) TLS is 3 jobs and about 68 runner-min. - **Why `stable` runs per PR**: the goal is full coverage of the libevent users actually run. 2.1.13 is the current security release and ships in RHEL 9/10, Debian 13, Fedora, Alpine ≥ 3.21, Homebrew and MSYS2, while `ci.yml` runs integration suites only on Ubuntu's 2.1.12 and only builds and unit-tests 2.1.13. If CI budget ever requires it, the plan step makes moving it to nightly a one-line change. - **ASan/LSan with an instrumented libevent**: `abort_on_error=1` stays on purpose. Without it, a leak exits with 23, and tests that only check `!= -6` pass over it. Full runs came back clean with no suppressions file: on 658fed4 the sanitized cluster cell passed 858/858, and on 8e8b3a6 all three sanitized cells passed. If an alpha-internal leak ever appears, the fix is a narrow LSan suppression with an upstream link, not a waiver. - **Required check**: after merge, someone with admin rights must mark `libevent-compat-gate` (only that job) as required. Suggested timing: after three consecutive green nightlies, given that `next` is an alpha. - **Canary pin**: the expected `2.2.2-alpha-dev` string is tied to the helper's `master_commit`. Both are commented to be bumped together. ## Affected versions CI and tooling only. No memtier runtime change beyond what #822 (TLS error guard) and #832 (RESP length bounds) carry. The runtime failure that #822 fixes affects TLS-enabled builds running on libevent ≥ 2.2.2-alpha (2.1.x tolerates the call). <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Medium Risk** > Changes touch connection error handling, RESP parser bounds, and a large new required CI surface; misconfiguration of the gate or parser rejections could affect TLS diagnostics or malformed-server behavior. > > **Overview** > Adds **libevent compatibility CI** and build/link tooling so memtier is exercised against pinned **2.1.12**, **2.1.13**, and **2.2.2-alpha** (plus a non-blocking **master** canary). New `scripts/build-libevent.sh` and `check-libevent-linkage.sh` install verified libevent into a private prefix; macOS CI gains **cmake** and routes `build-macos-libevent.sh` through the shared helper. The **`libevent-compat.yml`** workflow runs a scoped PR matrix (TLS on stable/next, ASan+UBSan plaintext on 2.2) with nightly/weekly expansion, cluster sharding, caching, and a single required **`libevent-compat-gate`**. > > **Runtime and test changes** in the same branch: **TLS connection errors** only call OpenSSL/libevent accessors on real TLS bufferevents, with certificate-verify fallback when libevent 2.2 reports no OpenSSL reason (`shard_connection.cpp` + new `test_connection_error_types.py`, wired into ASan/TSan/UBSan misc cells). **RESP parsing** rejects aggregate counts and bulk lengths that would overflow `int`/`long` bookkeeping (`protocol.cpp` + `check_length_limits()`). Fuzzer/reconnect tests broaden sanitizer failure detection and stderr logging on signal death. **DEVELOPMENT.md** documents the libevent matrix and local evaluation; **`.gitignore`** ignores local libevent build dirs. > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit cd86f27. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup> <!-- /CURSOR_SUMMARY --> Co-Authored-By: Claude Opus 5.5 <[email protected]>
) ## Problem `--connection-stage-timeout=N` can abort after just over N − 1 seconds. The supervisor stamps the run start and the first setup failure with `tv_sec` only, and compares whole seconds. The main loop polls it once per second (`sleep(1)`). Suppose the run starts at 10.99 s and a poll lands at 12.01 s: the supervisor sees 12 − 10 = 2 seconds after 1.02 s, so a 2 s timeout trips. This makes `test_cluster_unowned_slots:test_unowned_keys_survive_repeated_redial` (from #799) flaky. It has a 2 s budget against about 1.1 s of injected server delays and backoffs. It failed in #545's `libevent-compat (legacy, plaintext, standalone)` cell: ``` Connection dropped, attempting reconnection 2/3 in 0.50 seconds... memtier_benchmark: aborting after 2 seconds of connection-stage failures (last error: no response from server during setup). Wall time: 1.010s ``` Locally it failed 3 times in 180 runs: 2 of 70 on #545, 1 of 40 on #832, and 0 of 70 on master. Every failure was this abort after about one second. Neither #545 nor #832 touches this code; the failure depends on where in the second the run starts. Deterministic reproduction (from review): start memtier at set points late in a wall-clock second, against a server that accepts and never replies, with `--connection-stage-timeout=2`. Master aborted early in 4 of 25 runs, after 1.016 s, still saying "2 seconds". With this PR none did; the fastest abort was 2.008 s. ## Fix - Stamp the run start and the failure streak in wall-clock microseconds, and compare them with the timeout in microseconds. - The comparison moves to `connection_stage_clock.h` (`connection_stage_timed_out()`), so it can be unit-tested. - The abort message still reports whole seconds. - With the once-per-second poll, an abort now lands between N and N + 1 seconds instead of between N − 1 and N. ## Tests - **New unit test** `tests/unit/connection_stage_clock_test` (`make check`): a phase that started late in a second has not timed out 1.02 s later. It times out at exactly 2 s and reports whole elapsed seconds, has no start time before the first failure, and uses timestamps far from the epoch. A mutant that compares whole seconds fails it, and so does one that converts the timeout to microseconds in 32 bits (a 5000 s case). - **Integration tests on libevent 2.1.12, ASan + UBSan.** I ran the 17 test files that use `--connection-stage-timeout` (connection setup rejection, cluster slots, unowned slots, reconnects, retries, CLI validation and others). Results are the same with and without the fix: 236 pass, and the one failure is the same pre-existing `test_memcache_meta_protocol:test_meta_unsupported_options_fail_before_connection` on both. <!-- CURSOR_SUMMARY --> --- > [!NOTE] > <sup>[Cursor Bugbot](https://cursor.com/bugbot) is generating a summary for commit e1a6c84. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup> <!-- /CURSOR_SUMMARY --> Co-Authored-By: Claude Opus 5.5 <[email protected]>
#832's bound comment and unit-test comment said a nested attribute takes a parent slot; with this PR an attribute is drained in its own scope and takes none. Keep #832's bound and say so. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Fixes #458. `redis_protocol::parse_response()` treated a RESP3 attribute (`|N`) like an ordinary aggregate. Its key/value pairs became part of the reply. With `set_keep_value(true)` that crashes. The three forms in the issue comments all reproduce on master under ASan + UBSan: - `|0\r\n*1\r\n+a\r\n`: the attribute becomes the root of the kept tree, and the next aggregate calls `add_new_element()` on a NULL cursor (`protocol.cpp:764`). - An attribute inside an attribute hits `assert(!m_attribute)`. - An attribute on an array element, `*2\r\n|1\r\n+k\r\n+v\r\n+a\r\n*1\r\n+b\r\n`: it takes one of the parent's slots, so the reply ends early, and the following aggregate dereferences NULL. Without keep_value, the attribute's elements were counted as hits and as ArrayPerElementNulls elements, which is the miscount the issue describes. An error inside an attribute also marked the whole reply as an error; it no longer does. **Fix (`protocol.cpp` only).** An attribute is now drained in its own scope, the same way a nested push (`>`) already is. It takes no slot from its parent, and anything inside it (another attribute, or a push) is drained with it. When it ends, parsing continues as if it weren't there; at top level, the reply goes on. Nothing from an attribute is ever added to the reply tree, so there is nothing to free. **Tests.** A new `check_attribute_frames()` in `tests/unit/redis_protocol_test.cpp` covers: - the three crash forms - an attribute before `*0` (still empty for EmptyCollection, with and without keep_value) - an attribute inside a map - an attribute on an array element (gives [miss, hit] for ArrayPerElementNulls) - attribute bulks not counted as hits Against master's `protocol.cpp`, each crash form aborts under ASan (null member call, or the assertion) and the counting cases give wrong results. With the fix every case passes. **Results** (Ubuntu 24.04 container, ASan + UBSan): - `make check` passes, and clang-format is clean. - `test_resp_response_fuzzer.py`, `test_read_preference_resp3.py`, `test_arbitrary_command_misses.py` and `test_collection_scan.py` pass 47/47. **#832** (also in `protocol.cpp` / `redis_protocol_test.cpp`) merges cleanly with this, and the merged tree's sanitized unit test passes, including #832's nested-attribute bound checks. Once both land, a comment in #832 saying a nested attribute "takes a parent slot" will be out of date. ## Release notes (proposed) > Fixes crashes and miscounts when a RESP3 server sends attribute frames (`|`): attribute contents are no longer counted in Hits/Misses or per-element miss tracking, and no longer reach the kept reply (#458). <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Medium Risk** > Changes core RESP3 reply parsing and completion logic; incorrect draining could mis-frame replies or miscount hits, though behavior is narrowly scoped to attribute frames with extensive unit tests. > > **Overview** > Fixes **#458** by treating RESP3 **attribute** frames (`|N`) like out-of-band drain scopes (same pattern as nested push `>`), instead of merging their key/value pairs into the command reply. > > **`protocol.cpp`:** On `|`, the parser enters nested drain mode (`m_push` / `m_push_nested`), skips consuming a parent aggregate slot, and does not record attributes as the top-level reply body, kept mbulk tree, hits, or per-element miss tracking. When the attribute ends, parsing resumes on the following element; errors inside an attribute no longer mark the whole reply as failed. **`m_push_outer_attribute`** is removed in favor of this unified nested-scope handling. > > **Tests:** New **`check_attribute_frames()`** covers prior crash shapes (top-level and nested attributes with `keep_value`), maps, empty arrays, push/attribute interaction, and ArrayPerElementNulls alignment. > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit a173343. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup> <!-- /CURSOR_SUMMARY --> Co-Authored-By: Claude Opus 5.5 <[email protected]>

Problem
redis_protocol::parse_response()does signed arithmetic on lengths and counts that come from the server. An oversized value makes that arithmetic overflow, which is undefined behaviour (#831):$9223372036854775807(and$99999999999999999999, whichstrtolclamps toLONG_MAX):m_bulk_len + 2overflowslonginrs_read_bulk(protocol.cpp:864). The same happens for RESP3!and=.%1073741824/|1073741824:count *= 2overflowsint(protocol.cpp:723).*2\r\n*2147483646\r\n*3\r\noverflowm_nested_remaining(protocol.cpp:747). So does a nested RESP3 attribute followed by a large count, e.g.*1\r\n*2\r\n|0\r\n*2147483647\r\n: the|takes a parent slot without being tracked.INT_MAXis truncated when stored inint, so*2147483648is read as a null array.The existing fixture
bulk_int_overflow.binreaches the first case.test_bulk_int_overflowstill passed underubsan.ymlbecausehalt_on_error=1withoutabort_on_errormakes UBSan exit 1 after printing onlyruntime error:. The harness checks only for negative exit codes and a set of stderr needles that did not include that string. #545's libevent CI aborts on UBSan and failed on it withexit_code=-6.Root cause
m_bulk_lenfromunsigned intto alongread withstrtol. Nothing bounds it, som_bulk_len + 2can overflow.int.intnested-element bookkeeping.Fix
LONG_MAX - 2, the parser returns the existing protocol error (-1, "error: response parsing failed.") without changing any parser state, andlineis freed. Wherelongis 32 bits (LLP64, e.g. MSYS2/Windows), lengths above 2^31 - 3 are now rejected; before, they overflowed (UB) or waited forever.strtoll, becauselongis 32 bits on Windows. Negative values are clamped as before. The parser then rejects the aggregate if its elements (doubled for%/|), plus the elements still outstanding, would exceedINT_MAX. A nested aggregate counts as one outstanding slot of its parent. When miss tracking is recording a nested element, the bound also usesm_nested_remaining - 1, because a nested attribute can leavem_nested_remaininglarger than the outstanding count. This keepsm_total_bulks_count,m_nested_remainingand the doubling withinint.$-1,$0, other negative lengths,*-1, and counts up toINT_MAX.tests/test_resp_response_fuzzer.py: addruntime error:andLeakSanitizerto the crash needles. UBSan is now caught whateverabort_on_erroris set to. The fixture README is updated to match.Tests
check_length_limits()intests/unit/redis_protocol_test.cpp. It covers the boundaries (LONG_MAX, LONG_MAX-1 and out-of-range bulk lengths are rejected, LONG_MAX-2 waits for data; INT_MAX vs INT_MAX+1 arrays; INT_MAX/2 vs INT_MAX/2+1 maps and attributes; maps nested under outstanding elements; nested outstanding at INT_MAX vs above it; the nested-attribute tracking case at and above the bound). It also checks that ordinary bulk, empty, null, map and nested replies still parse.protocol.cppwith the new tests), Ubuntu 24.04 / GCC 13 / system libevent:redis_protocol_testreports 14FAILlines.runtime erroratprotocol.cpp:864:80(9223372036854775807 + 2),:723:27(1073741824 * 2) and:747:48(2147483646 + 2).test_resp_response_fuzzer.pywith the CIUBSAN_OPTIONS:test_bulk_int_overflowFAIL,needle 'runtime error:' exit_code=1. Withabort_on_error=1: FAIL,exit_code=-6.make check: 18/18 in both the normal and the ASan+UBSan (detect_leaks=1,abort_on_error=1) builds.test_resp_response_fuzzer.py: 12/12 in the normal build, in ASan+UBSan with the CI UBSan options, and in ASan+UBSan withabort_on_error=1(ASAN_OPTIONS=detect_leaks=1:abort_on_error=1throughout).LONG_MAXat run time, so the test also holds wherelongis 32 bits (MSYS2 UCRT64).clang-format18--dry-run --Werroris clean.Unrelated CI failure:
TSAN OSS-CLUSTER API: TCP TLS (misc)fails on 3b65721 and on the current head a92655a intest_crash_handler_integration:test_crash_handler_time_zone_lock_held(watchdog exit -14, missing BUG REPORT END). This is the known TSan crash-tail failure, tracked by #412 and targeted by #828. This PR does not touch the crash handler.Release notes
Behaviour change: an aggregate count above what the parser can represent (e.g.
*2147483648, which used to be truncated and read as a null array) and a bulk length aboveLONG_MAX - 2are now protocol errors (response parsing failed). No real server sends these.Affected versions
Fixes #831
🤖 Generated with Claude Code
Note
Medium Risk
Changes core RESP parsing on every connection; malformed oversized frames now error out instead of UB, but legitimate traffic within prior limits is unchanged.
Overview
Hardens the Redis RESP parser in
parse_responseso malicious or oversized wire values cannot trigger integer overflow (UB) or silent truncation.Bulk/blob lengths (
$,!,=) are validated before updating parser state: ifstrtolyields a length aboveLONG_MAX - 2, parsing fails with-1instead of overflowingm_bulk_len + 2in the bulk-read path.Aggregate counts (
*,%,|, etc.) are read withstrtoll(for 32-bitlongon Windows), negative counts are still treated as zero, and counts are rejected when declared elements (×2 for maps/attributes) plus outstanding/nested miss-tracking slots would exceedINT_MAX. Valid replies behave as before.Tests/docs: adds
check_length_limits()unit coverage for boundary cases; extends the RESP fuzz harness crash needles (runtime error:,LeakSanitizer) and updates fixture README expectations.Reviewed by Cursor Bugbot for commit a7fe64f. Bugbot is set up for automated code reviews on this repo. Configure here.