Skip to content

Fix libevent TLS error reporting on 2.1 and 2.2 - #822

Merged
fcostaoliveira merged 4 commits into
masterfrom
fix/libevent22-tls-error-access
Oct 26, 2026
Merged

fcostaoliveira merged 4 commits into
masterfrom
fix/libevent22-tls-error-access

Conversation

@fcostaoliveira

@fcostaoliveira fcostaoliveira commented Oct 24, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

With libevent 2.2.2-alpha (released 2026-07-01, the current 2.2 release), a TLS-enabled memtier:

  1. Corrupts memory on a plaintext connection error. Any BEV_EVENT_ERROR, for example a refused connection, calls bufferevent_get_openssl_error() on the plain socket bufferevent. With an instrumented libevent:
    ERROR: AddressSanitizer: heap-buffer-overflow ... READ of size 1
      #0 bufferevent_get_ssl_error  bufferevent_ssl.c:1108
      #1 shard_connection::handle_event(short)  shard_connection.cpp:2073
    0x... is located 68 bytes after 616-byte region ... allocated by bufferevent_socket_new
    
    A libevent built without NDEBUG aborts in EVUTIL_ASSERT instead.
  2. Fails TLS connections silently. A rejected handshake or an untrusted server certificate prints only Connection error, attempting reconnection…, with no reason.

With libevent 2.1 (what distributions ship), the same error loop prints TLS connection error: (null). It passes NULL to %s, which glibc renders and other C libraries need not. On a refused --tls connection that line replaces Connection error: Connection refused.

Root cause

  • Upstream 2f27523e ("bufferevent_ssl: do not return NULL from upcast") made bufferevent_ssl_upcast() only assert the type, and bufferevent_get_ssl_error() gained an inverted check (if (BEV_IS_SSL(bev)) return err;). The check is still on libevent master d82464a2.
    • For a plain bufferevent, the accessor reads and decrements past the object.
    • For a TLS bufferevent, it always returns 0. libevent has already drained the thread's OpenSSL queue into its own per-connection array, so ERR_get_error() cannot recover the reasons either.
  • memtier called the accessor unconditionally in TLS builds, ever since TLS support (53353b8).
  • libevent queues the SSL_get_error() result of the failed call (SSL_ERROR_SYSCALL, SSL_ERROR_SSL) next to the real OpenSSL error codes (conn_closed() in 2.1 and 2.2). memtier printed those as OpenSSL errors; they have no reason string, which is the (null).

Fix

  • Query the accessor only when m_config->openssl_ctx is set. That is the same condition setup_event() uses before creating the OpenSSL bufferevent.
  • Skip the queued SSL_get_error() codes (ERR_GET_LIB() == 0). If a real code has no reason string, use ERR_error_string_n().
  • When a TLS connection reports no OpenSSL reason:
    • If the certificate check ran (that is, without --tls-skip-verify) and failed, report certificate verify failed: <X509 reason> from SSL_get_verify_result().
    • Otherwise, if there is no socket error either, print TLS connection error: no OpenSSL reason reported (libevent <version>).
    • Otherwise, print the existing Connection error: <socket error>.
  • Read the socket error before logging anything; the Windows deferred-refusal path sets it.

Output on libevent 2.1:

Case Before After
Real OpenSSL reasons (handshake failure, certificate rejected) the reasons, plus a trailing TLS connection error: (null) the same reasons, no (null) line
Refused or reset --tls connection TLS connection error: (null) Connection error: Connection refused (or reset, broken pipe…)
Peer closes during the handshake (no socket error) TLS connection error: (null) the OpenSSL reason if any (e.g. unexpected eof while reading), else no OpenSSL reason reported
Plaintext connections unchanged unchanged

Tests

New tests/test_connection_error_types.py. The first and third cases are based on #545.

Test Asserts
test_plaintext_connection_refused A TLS-enabled binary handles a refused plain connection, with no TLS error and no sanitizer report
test_tls_connection_refused A refused --tls connection reports Connection error: Connection refused: no (null) and no no OpenSSL reason reported line
test_tls_handshake_failure An HTTP reply to the ClientHello is reported as TLS connection error: and reconnected
test_tls_certificate_verify_failure The suite's CA-signed certificate without --cacert is reported as certificate verify failed
test_tls_skip_verify_failure_not_blamed_on_certificate With --tls-skip-verify, a handshake rejected for a missing client certificate is not blamed on the certificate

The file is also added to the TLS "misc" lists in the ASan, UBSan and TSan workflows.

Ubuntu 24.04, OpenSSL 3.0.13, TLS=1 standalone:

libevent master d8d4e9f this PR
2.1.12 (distro) test_tls_connection_refused fails ((null), no Connection refused) 5/5 pass
2.2.2-alpha Release handshake, certificate and skip-verify tests fail (no reason printed) 5/5 pass
2.2.2-alpha, libevent and memtier ASan+UBSan heap-buffer-overflow above 5/5 pass, no sanitizer output

Affected versions

  • Introduced in 53353b8 ("Initial TLS support", 2019-08-16), present from 1.3.0 through 2.5.2 and on master.
  • The memory error and the silent TLS failures need libevent ≥ 2.2.2-alpha (upstream 2f27523e; 2.2.1-alpha still returned NULL).
  • The (null) line and the missing Connection refused affect every libevent version before 2.2.2 (2.1.x, 2.2.1-alpha).

Refs #545, #535

🤖 Generated with Claude Code


Note

Medium Risk
Changes core reconnect/error logging on every failed connection in TLS builds; behavior is well-covered by new integration tests and sanitizer CI, but mistakes could misclassify errors or skip reporting.

Overview
Fixes connection error reporting on BEV_EVENT_ERROR so TLS builds no longer call libevent’s OpenSSL error APIs on plain socket bufferevents (avoids ASan heap overflows / asserts on libevent 2.2.2) and produce clearer logs across libevent 2.1 and 2.2.

In shard_connection.cpp, the handler now snapshots the socket errno first, only drains OpenSSL errors when openssl_ctx is set (real TLS connections), skips queued SSL_get_error pseudo-codes, falls back to SSL_get_verify_result() for certificate failures when libevent returns no reason, and prefers Connection error: … for transport failures such as connection refused.

Adds tests/test_connection_error_types.py (plaintext refused, TLS refused, bad handshake, cert verify, --tls-skip-verify behavior) and wires it into the ASan/TSan/UBSan TLS “misc” matrix jobs. test_reconnections.py docstring is updated to match the new TLS vs socket error logging.

Reviewed by Cursor Bugbot for commit cba1fcc. Bugbot is set up for automated code reviews on this repo. Configure here.

A TLS-enabled build called bufferevent_get_openssl_error() on every
connection error, including plaintext connections. libevent 2.2.2-alpha
only asserts the bufferevent type there (upstream 2f27523e): a debug build
aborts and a release build reads and writes past the plain socket
bufferevent. Query it only when the connection was created with the
OpenSSL context, the same predicate setup_event() uses.

The same libevent release drains the OpenSSL queue into the bufferevent
but its accessor returns nothing for a TLS bufferevent, so TLS failures
were silent. When no reason is returned, report a failed certificate
verification from the SSL object, and otherwise say that libevent >= 2.2
reported no OpenSSL reason. libevent 2.1 still returns the queued reasons,
so its output is unchanged.

Add regressions for a refused plaintext connection, a rejected handshake
and an untrusted server certificate.

Refs #545

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@github-actions

github-actions Bot commented Oct 24, 2026 •

Copy link
Copy Markdown

🤖 Automated first-pass review — a human maintainer's review is still required before merge.

Thanks for this. The description makes the upstream libevent change easy to follow. I went through the handle_event() change and the new test file and have only a couple of small points.

The guard looks right to me. m_config->openssl_ctx != NULL is the same check setup_event() uses to choose bufferevent_openssl_socket_new() over bufferevent_socket_new(), so the accessor can no longer see a plain bufferevent. Capturing EVUTIL_SOCKET_ERROR() once, before any logging, also seems correct.

A few questions:

  • The ERR_GET_LIB(sslerr) == 0 skip: I think this is right for the SSL_get_error() values libevent pushes (SSL_ERROR_SYSCALL is 5, so its lib is 0). On OpenSSL 3, system errors carry ERR_SYSTEM_FLAG and report ERR_LIB_SYS, so they still get printed, and if their reason string is NULL you now fall back to ERR_error_string_n(). Was that path seen on 3.0.13 for the reset/refused cases? If not, I'd expect a doubled "TLS connection error: ..." plus "Connection error: ..." pair there. The tests suggest it doesn't happen, so I'm just checking.
  • As I read it, test_plaintext_connection_refused only fails on master against an instrumented libevent ≥ 2.2.2. With the distro 2.1 in CI today it would pass with or without the fix, so the heap-buffer-overflow regression isn't actually pinned until the 2.2 cells from Add libevent build helper and compatibility CI for 2.1.12, 2.1.13 and 2.2.2-alpha #545 land. That's fine if Add libevent build helper and compatibility CI for 2.1.12, 2.1.13 and 2.2.2-alpha #545 is close behind. It might be worth a sentence in the test's comment so nobody later assumes CI covers it.
  • Nitpicking: the stderr wording changes (no more (null), and Connection error: Connection refused instead of the TLS line on a refused --tls connect). This is log output, not JSON/CSV, and I think it's strictly better, so I'm not worried about compatibility. Anyone who greps stderr for "TLS connection error" on a refused connect will see different text, though, so it may be worth a line in the release notes.

None of this blocks the PR. The core fix looks solid to me, and the fails-on-master table across 2.1.12 and 2.2.2 is the kind of evidence I'd want for this.

(would file this as a comment, not a formal block)

fcostaoliveira added a commit that referenced this pull request Oct 24, 2026
Take #822's shard_connection.cpp and tests/test_connection_error_types.py
verbatim so whichever PR lands first, the other merges cleanly.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
fcostaoliveira added a commit that referenced this pull request Oct 24, 2026
scripts/build-libevent.sh now pins 2.1.12-stable, 2.1.13-stable and
2.2.2-alpha by release-asset sha256 and libevent master by commit,
rejects a non-empty prefix before creating it, and can build libevent
with ASan+UBSan (LIBEVENT_FLAVOUR=sanitize). --source-id feeds the
cache key.

scripts/check-libevent-linkage.sh proves what a Linux build runs with:
the --version libevent field equals the expected string, the prefix's
pkg-config files are the same release, every libevent library loaded
(directly or transitively) comes from the prefix, libevent_openssl and
memtier share one libssl, and the openssl=/prometheus= fields are as
intended. macOS delegates to check-macos-tls-links.sh.

libevent-compat.yml drops its path filters, which made it unusable as
a required check, and uses ci.yml's triggers plus a nightly and weekly
schedule. A plan job picks the cells: every PR runs 2.1.13 and 2.2.2
TLS standalone/cluster suites, 2.2.2 plaintext suites with memtier and
libevent both under ASan+UBSan (the cell that catches the #822
regression), and a 2.2.2 --disable-tls build with make check. Nightly,
and PRs that change this harness, add 2.1.12, the remaining plaintext
and no-TLS cells and macOS with OpenSSL 3 and 4. A weekly canary
builds libevent master and may fail. Job names carry the track, not
the version; libevent-compat-gate is the one check to require. Built
libevent is cached by version, checksum, flavour, OpenSSL, compiler
and helper hash. Redis comes from packages.redis.io as in ci.yml.

tests/test_reconnections.py prints memtier's stderr (from the first
sanitizer report) whenever memtier dies from a signal, so an abort in
the cluster reconnect test is diagnosable from the CI log.

DEVELOPMENT.md documents the tested matrix, local evaluation, the 4 KiB
(2.1) vs 16 KiB (2.2) read size (Refs #535) and the TLS error messages
memtier prints on 2.2.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review follow-ups to the libevent 2.2 guard:

- libevent also queues the SSL_get_error() code of the failed call, e.g.
  SSL_ERROR_SYSCALL. It is not an OpenSSL error code, has no reason string,
  and was printed as "TLS connection error: (null)" (passing NULL to %s).
  On a refused TLS connection it also suppressed "Connection refused".
  Skip these codes; the socket error and the queued OpenSSL errors report
  the failure. Fall back to ERR_error_string_n() for a reason-less code.
- Print "reported no OpenSSL reason" only when there is no socket error
  either, so refused, reset and closed TLS connections are reported as the
  socket errors they are. This also removes the libevent version check.
- Read the socket error before logging anything.
- Test --tls-skip-verify failures, refused TLS connections, and run the
  file in the sanitizer TLS cells.

Refs #545

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- The "no OpenSSL reason" line can appear on libevent 2.1 too, e.g. when
  the peer closes during the handshake; drop the 2.2 framing.
- Say what the early socket error read protects against.
- The skip-verify test server now reads the client's remaining flight
  before closing. Closing with unread data sent an RST, which memtier
  correctly reports as a socket error, failing ~2% of runs on 2.2.2.
- Update the test_reconnections docstring for the new error lines.

Refs #545

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@fcostaoliveira fcostaoliveira changed the title Guard libevent TLS error access and keep TLS diagnostics on libevent 2.2 Fix libevent TLS error reporting on 2.1 and 2.2 Oct 24, 2026
fcostaoliveira added a commit that referenced this pull request Oct 24, 2026
Keep #822's shard_connection.cpp, tests/test_connection_error_types.py
and sanitizer workflow test lists exactly.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
fcostaoliveira added a commit that referenced this pull request Oct 24, 2026
@fcostaoliveira

fcostaoliveira commented Oct 24, 2026 •

Copy link
Copy Markdown
Collaborator Author

Thanks for the review. Replies to the latest pass, on 4a8b556:

  • Authorship of 24579b5. That's right, and it wasn't intended. A local tool set a placeholder git identity in that checkout. It has been removed, and the history has been rewritten: the commit is now 6c72fa9, authored by fcostaoliveira, with a byte-identical tree. The PR head is now 5cab6f6. A squash merge adds a Co-authored-by: trailer for every commit author, so this did need fixing rather than being left to the merger.
  • Upstream libevent. Not filed yet. It will be reported against libevent/libevent (the inverted BEV_IS_SSL check from 2f27523e, still present on master d82464a2), and the code comment will get the link once it exists. About keeping the SSL_get_verify_result() fallback: it doesn't depend on the libevent version. On 2.1 the queued OpenSSL reasons are printed first, so the fallback never runs. If upstream fixes the accessor, the fallback stays dormant again. So it's safe to keep, and it costs nothing.
  • Description wording. It was updated after that review pass and now says no OpenSSL reason reported (libevent <version>), which matches the code.
  • "Connection error" in _run_failure(). Agreed, it matches the attempt_reconnect() line on every path. It stays as a cheap shared check that each failure went through the reconnect path. The per-test assertions do the discriminating, as you say.

@fcostaoliveira
fcostaoliveira force-pushed the fix/libevent22-tls-error-access branch from 4a8b556 to 5cab6f6 Compare October 24, 2026 09:23
fcostaoliveira added a commit that referenced this pull request Oct 24, 2026
Keep #822's shard_connection.cpp, tests/test_connection_error_types.py
and sanitizer workflow test lists exactly.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
fcostaoliveira added a commit that referenced this pull request Oct 24, 2026
@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Rewrote the branch history to fix the placeholder probe <x@x> authorship of the shared commit "Report TLS connection errors accurately on libevent 2.1 and 2.2" (now 6c72fa9, authored by fcostaoliveira). Only author and committer identity changed, and the head tree is byte-identical to the previous head (#822: 4a8b556 → 5cab6f6; #545: 62a2c4e → d32dd38). Pushed with --force-with-lease.

fcostaoliveira added a commit that referenced this pull request Oct 24, 2026
@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Replies to the review of cba1fcc:

  • ERR_LIB_SYS on OpenSSL 3.0.13. I didn't see it for refused or reset connections. In those cases libevent queues only the SSL_get_error() code (SSL_ERROR_SYSCALL), which is now skipped. The output is the single line Connection error: Connection refused (or …reset by peer). test_tls_connection_refused asserts exactly that on 2.1.12 + OpenSSL 3.0.13, and an output comparison over 22 failure scenarios found no doubled TLS/socket pair. An ERR_LIB_SYS entry, when OpenSSL queues one, is kept and printed through the ERR_error_string_n() fallback. That's intentional: it is a real OpenSSL-reported reason.
  • What CI covers today. Correct. On the 2.1 that CI builds against today, test_plaintext_connection_refused passes with or without the guard, so the heap-buffer-overflow is only covered once Add libevent build helper and compatibility CI for 2.1.12, 2.1.13 and 2.2.2-alpha #545's sanitized 2.2.2 cell lands. The PR description says so. test_tls_connection_refused does fail on master under 2.1, so part of the change is covered in CI now. I've left the test comment as is to avoid another full CI cycle just for a comment. If a maintainer wants the sentence, it's a one-line follow-up.
  • Release notes. Agreed. Noted for the release notes: on a refused or reset --tls connection, stderr now shows the socket error instead of TLS connection error: (null).

fcostaoliveira added a commit that referenced this pull request Oct 24, 2026
…he full grid

- #822's TLS fallback depends most on libevent 2.2 internals; run it
  against an ASan+UBSan libevent in a nightly 'next, tls-asan,
  standalone' cell.
- The cluster cells depend on utils/select_test_shard.py and
  utils/check_test_shards.py, so a PR changing them runs the full grid.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@fcostaoliveira
fcostaoliveira merged commit 4904880 into master Oct 26, 2026
150 checks passed
fcostaoliveira added a commit that referenced this pull request Oct 26, 2026
… 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]>
fcostaoliveira added a commit that referenced this pull request Oct 26, 2026
… failures (#823)

## Problem

Part of the libevent support work (Refs #545). memtier did not check or record which libevent and OpenSSL it was built against and which it runs with, and a few libevent failures were not handled:

- A binary built with one libevent's headers can load another series' library, for example headers from one prefix and the library from another, or a vendored header. Nothing reported this. The `--version` `libevent=` field shows the runtime library; `openssl=` shows the build headers. The JSON output had no library versions at all.
- `evthread_use_pthreads()` / `evthread_use_windows_threads()` failing only printed a warning. Cross-thread `event_base_loopbreak()` (Ctrl+C, `--connection-stage-timeout`) depends on it, so the run could hang later.
- `bufferevent_openssl_socket_new()` / `bufferevent_socket_new()` returning NULL in `shard_connection::setup_event()` hit `assert(m_bev != NULL)`, and the process aborted with SIGABRT.
- `configure.ac`, DEVELOPMENT.md and README said the Prometheus exporter needs libevent 2.1.1. The exporter calls `evhttp_request_set_on_complete_cb()`, which first appeared in **2.1.4-alpha**: it is missing from `release-2.1.3-alpha:include/event2/http.h` and was added in upstream commit b083ca05. No document said which libevent versions are supported.
- The comment above the READONLY `bufferevent_write()` said that call goes through `bufferevent_trigger_nolock_()`. In libevent 2.1.12 and 2.2.2-alpha, `bufferevent_write()` is `evbuffer_add(bufev->output, ...)`, the same path the protocol writers use (Refs #532).
- `make check` did not compile on libevent 2.1.8 (RHEL 8): `tests/unit/cluster_transaction_test.cpp` used `EVUTIL_INVALID_SOCKET`, which first appeared in 2.1.9. #812 (now on master) fixed that hunk, so it is no longer in this diff; master builds and passes `make check` on Rocky Linux 8 (libevent 2.1.8, OpenSSL 1.1.1k).

## Fix

- **Mismatch warnings (stderr only).** After option parsing, memtier compares `LIBEVENT_VERSION_NUMBER` with `event_get_version_number()`. If major.minor differ, it prints one warning to stderr. It does the same for OpenSSL, comparing `OPENSSL_VERSION_NUMBER` with `OpenSSL_version_num()` (`SSLeay()` on OpenSSL 1.0.2): before 3.0 it compares major.minor (1.0 vs 1.1); from 3.0 on it reports another major version or a library minor version older than the headers (3.5 built, 3.0 run), because OpenSSL 3 only promises that older headers run on a newer library. Patch levels and newer libraries are not reported, so the el9 RPM case (2.1.13 build, 2.1.12 runtime) stays quiet. Because the check runs after option parsing, `--version` and `--help` print nothing extra, and `--version` stdout is byte-identical. The comparison lives in the new `library_versions.h`.
- **Provenance.** The crash report INFO section gains `libevent_build_version:` and `openssl_runtime_version:`. Existing keys are unchanged; note that the existing `openssl_version:` is the build-time text. `OpenSSL_version()` is pre-resolved like `event_get_version()`. The JSON `run information` section gains four new keys: `libevent runtime version`, `libevent build version`, `OpenSSL runtime version` and `OpenSSL build version`. The two OpenSSL keys appear only when TLS is compiled in. No existing key is renamed.
- **evthread failure** is now fatal for a run. `evthread_use_pthreads()` still runs first, before any `event_base` exists; if it failed, memtier prints an `error:` line and calls `exit(1)` right after option parsing, like the other post-parse error exits, so LeakSanitizer reports nothing. `--help` and `--version` behave as before. This is a behaviour change for release notes: a run on such an install used to continue with a warning.
- **bufferevent/SSL creation failure.** `setup_event()` now returns `bool`. On failure it logs an `error:` line and `connect()` returns -1, which is the existing path for a socket setup failure: standalone aborts the run in prepare, and cluster mode retries the connection and ends the run as failed. Ownership was checked in the libevent source:
  - With `BEV_OPT_CLOSE_ON_FREE`, a failed `bufferevent_openssl_socket_new()` already frees the `SSL` in libevent ≥ 2.1.9 (e86ccfe5, first released in 2.1.9-beta) and in 2.2.2-alpha. memtier therefore does **not** free it; doing so would be a double free.
  - The socket is not closed by libevent, because the SSL's socket BIO is `BIO_NOCLOSE`, and plain `bufferevent_socket_new()` does not close it either. memtier closes it.
  - On libevent ≤ 2.1.8 it depends on where libevent failed. An allocation failure leaves the socket open and leaks the SSL. A failure to arm the handshake events frees the partial bufferevent with the SSL attached, and its destructor closes both. memtier can't tell these apart, so it leaves the socket open, rather than risk closing a descriptor number that another thread has just been given, and logs `error: socket N left open on purpose: libevent <version> may already have closed it.` That is one socket (and possibly one SSL) per failed attempt, and only under libevent allocation failure.
  - The rule lives in `libevent_ssl_failure_socket_is_ours()` in `library_versions.h`, which is unit-tested.
  - `SSL_new()` returning NULL is handled the same way; it was an assert before.
  - `setup_event()` and `disconnect()` now clear the protocol's buffer pointers once the bufferevent is freed. Before, they kept pointing at the freed evbuffers until the next successful connect.
- **Docs and configure.** The `libevent_extra` pkg-config check, the configure error message, DEVELOPMENT.md and README now say 2.1.4. The real gate, the link test, was already effectively 2.1.4, so no build that works today stops working. The core libevent minimum in configure is **unchanged**. DEVELOPMENT.md gains a "Supported libevent versions" table:
  - 2.1.8: oldest release known to work (RHEL 8), checked manually, not built in CI
  - 2.1.12: recommended minimum, runs the main CI suite
  - 2.1.13: current stable with security fixes
  - 2.2.2-alpha: experimental

  It also documents the mismatch warning, the new JSON keys, and the 2.1 vs 2.2 read size difference that makes results from the two series not directly comparable (#535). `tests/run_local_gate.sh` now checks for the 2.1.4 floor in DEVELOPMENT.md.
- **#532 comment**: the comment is corrected. This is a comment-only change; the code path is untouched.

## Tests

- New unit test `tests/unit/library_versions_test.cpp` (in `make check`) covers the series comparison. Cases: libevent patch levels and series; OpenSSL 3.x patch differences, a newer and an older minor, 3 vs 4, 1.0 vs 1.1 vs 3; LibreSSL.
- New RLTest file `tests/test_library_provenance.py`. The LD_PRELOAD tests use the new `tests/library_failure_injector.c` and skip when not on Linux or when the binary is linked statically. Sanitizer runtimes are kept first in `LD_PRELOAD`, as in the crash-handler tests.
  - `test_json_run_information_library_versions`: the new JSON keys are present, `libevent runtime version` equals `--version`'s `libevent=` field, `OpenSSL build version` contains `openssl=`, the existing keys are still there, and a matched install prints no warning.
  - `test_libevent_series_mismatch_warns_on_stderr`: with a fake runtime libevent (2.99) and, in TLS builds, a fake OpenSSL, memtier prints exactly one warning per library on stderr and none on stdout. The JSON reports the runtime version. `--version` stderr stays empty.
  - `test_libevent_patch_difference_does_not_warn`: a 2.1.x patch difference prints no warning.
  - `test_evthread_failure_is_fatal`: exit 1, the `error:` line, no JSON written, and no LeakSanitizer report. `--help` and `--version` keep their exit code and stdout under the same failure.
  - `test_bufferevent_creation_failure_fails_connection`: a positive error exit (not a signal), the `error:` line naming the constructor, and no sanitizer report. TLS runs exercise `bufferevent_openssl_socket_new`, plaintext runs `bufferevent_socket_new`. The shim records the socket it was given and checks at exit that memtier closed it, using the descriptor's device/inode so that a reused number isn't mistaken for it.
  - `test_tls_bufferevent_failure_leaves_socket_on_libevent_2_1_8`: with a faked 2.1.8 runtime, the socket is left open and the log line appears.
  - `test_crash_report_separates_build_and_runtime_versions`: with faked runtime versions, the crash report's runtime fields show the fake and its build fields don't. The mismatch test checks the same for the JSON keys.
- `test_crash_handler_with_active_connections` now also checks the new INFO lines, and that `libevent_version:`/`openssl_version:` equal `--version`'s `libevent=`/`openssl=`.
- **Before/after**: on master d8d4e9f, 4 of the 5 new tests fail:
  - bufferevent: SIGABRT on `Assertion 'm_bev != NULL' failed`.
  - evthread: exit 0 with a warning.
  - JSON: the keys are missing.
  - mismatch: no warning.

  The patch-difference negative control passes on both.

  Two more tests were added later; reading the code says both also fail on master, but they haven't been run there. `test_tls_bufferevent_failure_leaves_socket_on_libevent_2_1_8` would hit the same `m_bev != NULL` assertion, and `test_crash_report_separates_build_and_runtime_versions` would find the new INFO fields missing. That makes 6 of the 7 tests in `test_library_provenance.py`, with the control passing.
- Local results (Docker, aarch64; CI covers x86_64):

| Variant | Build | make check | New tests + crash-handler tests |
|---|---|---|---|
| Ubuntu 24.04, system libevent 2.1.12, OpenSSL 3.0.13 | ✓ | 19/19 | standalone plaintext + TLS pass. Full TLS standalone suite: 727 pass / 109 skip / 1 fail (`test_prometheus:test_F16_ipv6`, no IPv6 in the container; unrelated) |
| libevent 2.2.2-alpha (source) | ✓ | 19/19 | standalone plaintext + TLS, cluster TLS pass |
| `--disable-tls` | ✓ | 19/19 | pass |
| libevent 2.1.8 (source, OpenSSL 3.0.13) | ✓ | 19/19 | standalone plaintext + TLS, cluster TLS pass |
| rockylinux:8, distro libevent 2.1.8-11.el8_10, OpenSSL 1.1.1k, GCC 8.5 | ✓ (TLS + Prometheus) | 19/19 (fails to compile without the test fix) | n/a |
| ASan+UBSan (`detect_leaks=1`), system libevent | ✓ | | standalone plaintext + TLS, cluster TLS pass |

- The libevent 2.1.8 tarball is the GitHub release asset, sha256 `965cc5a8bb46ce4199a47e9b2c9e1cae3b137e8356ffdad6d94d3b9069b71dc2`, which matches Debian's `libevent_2.1.8-stable-4.dsc`. Built from source on glibc ≥ 2.36, 2.1.8 does not link (`arc4random_addrandom` is undefined). That is a libevent 2.1.8 vs new glibc problem, not a memtier one, and RHEL 8 (glibc 2.28) is not affected; the local harness works around it with a no-op define.
- clang-format 18 `--dry-run --Werror` is clean on all changed C++ files.

### When the mismatch check can fire

Distribution packages tie the library file name to the series (`libevent-2.1.so.7`, `libevent-2.2.so.1`, `libssl.so.3`), so a binary built against 2.2 headers and run with `LD_LIBRARY_PATH` pointing at 2.1 fails to load before `main()`. The check therefore fires when the headers and the library come from different installations at build time: mixed `-I`/`-L` prefixes, a Homebrew plus source-built libevent, vendored headers, or a loader that resolves another series under the same name. The runtime path is covered by the preload shim. A real mix was also built locally: 2.2.2-alpha headers via `CPPFLAGS=-I<2.2.2 prefix>/include`, linked against the system 2.1.12 libraries. It builds and links, `--version` is unchanged (`libevent=2.1.12-stable`), and a run prints `warning: memtier_benchmark was built with libevent 2.2.2-alpha-dev headers but is running with libevent 2.1.12-stable; rebuild it against the libevent it runs with.`

## Affected versions

- The assert on bufferevent creation failure and the evthread warning-only handling are in every current release. Hitting them in practice needs allocation failure or a broken libevent install.
- The incorrect 2.1.1 minimum dates from the Prometheus exporter's introduction. Users with 2.1.1–2.1.3 already got a configure error from the link test; only the message and docs were wrong.
- No change for a matched install: stdout, `--version` and existing JSON and crash-report keys are byte-identical. The only additions are the four JSON keys and the two crash INFO lines.

## Interactions

- **#812** (merged) edited the DEVELOPMENT.md prerequisites line, raising the core minimum to 2.0.11. The merge keeps this PR's line, and the "Supported libevent versions" section now says why `configure.ac` requires 2.0.11. The `configure.ac` hunks do not overlap: #812 touches the core/pthreads checks, this PR the Prometheus block.
- **#545** also adds a libevent table to DEVELOPMENT.md ("Libevent versions", with CI coverage) and its own #535 read-size note. Whichever of #545/#823 lands second merges the two tables into one, keeping this PR's support status next to #545's CI coverage, and keeps a single #535 paragraph.
- **#822** (libevent 2.2 TLS error access): no overlap. The `BEV_EVENT_ERROR` handler is untouched here, and this patch applies cleanly on top of #822's head.

Refs #545, #532, #535


<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Touches TLS connection setup, fatal evthread initialization, and version-mismatch detection on every run; behavior changes for broken libevent installs and mismatched header/library pairs, but matched installs stay warning-free.
> 
> **Overview**
> Adds **build vs runtime provenance** for libevent and OpenSSL: startup stderr warnings when major series (or OpenSSL 3.x minor) mismatch, four new JSON `run information` keys, and crash-report INFO lines separating loaded libraries from compile-time headers.
> 
> **Hardens libevent integration:** `evthread_use_pthreads()` failure is **fatal** after option parsing (`--help`/`--version` unchanged). `shard_connection::setup_event()` returns `bool` and replaces asserts on `SSL_new` / bufferevent creation with logged errors and connect failure; TLS socket cleanup follows **runtime** libevent version (leave socket open on ≤2.1.8 when unsafe to close). Protocol buffers are cleared when the bufferevent is freed.
> 
> **Docs/configure:** Prometheus exporter minimum is documented and enforced as **libevent 2.1.4** (`evhttp_request_set_on_complete_cb`). DEVELOPMENT.md adds a supported-libevent table and related CI notes.
> 
> **Tests:** `library_versions.h` unit tests, LD_PRELOAD `library_failure_injector.c`, and `test_library_provenance.py` cover warnings, JSON, evthread fatality, and bufferevent failure paths; crash-handler integration checks new INFO fields.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 9276de2. 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]>
fcostaoliveira added a commit that referenced this pull request Oct 26, 2026
Picks up 14 master commits, including the connect-failure changes in
#855 (libevent 2.1.8's error callback from a failing connect), #823
(hardened libevent failures), #822 (TLS error reporting) and the
libevent compatibility CI from #545. No conflicts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant