Repository navigation
feat(tls): log negotiated TLS protocol/cipher once and record in JSON - #403
Conversation
When --tls is enabled, capture the negotiated TLS version and
ciphersuite from the first completed handshake and surface them in
two places:
- a single stderr line for the run (not per connection/thread/shard):
"TLS connection established: protocol TLSv1.3, cipher TLS_AES_256_GCM_SHA384"
- a "TLS" object in --json-out-file (mb.json):
"TLS": { "negotiated_version": "...", "negotiated_cipher": "..." }
A std::call_once on shard_connection::handle_event(BEV_EVENT_CONNECTED)
makes the capture thread-safe across the per-thread event loops; the
values (static OpenSSL strings) are stashed on the shared
benchmark_config and read on the main thread after worker join.
config_print_to_json runs before the benchmark, so the JSON object is
emitted post-run (next to "run information"). The object is only
written when --tls is on AND a value was captured; absent otherwise.
Tests (tests/test_tls_logging.py) assert the stderr line and JSON
object in TLS mode (standalone + cluster) and assert both are ABSENT
in plaintext. Verified locally in three modes:
- plaintext standalone: PASS
- TLS standalone: PASS
- TLS oss-cluster (3 shards): PASS — one log line across all shards.
Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes and found 1 potential issue.
Reviewed by Cursor Bugbot for commit 714ccce. Configure here.
| fprintf(stderr, "TLS connection established: protocol %s, cipher %s\n", | ||
| m_config->tls_negotiated_version, m_config->tls_negotiated_cipher); | ||
| } | ||
| }); |
There was a problem hiding this comment.
call_once consumed even when SSL object is null
Low Severity
The static std::once_flag is consumed if bufferevent_openssl_get_ssl(m_bev) returns NULL inside the lambda. Since std::call_once permanently marks the flag on any normal return (even if the ssl != NULL branch was not taken), no subsequent connection will ever log or capture TLS info for the rest of the process. Moving the ssl retrieval and null check before std::call_once — or restructuring so the flag is only consumed on success — would avoid silently losing the TLS metadata in that edge case.
Reviewed by Cursor Bugbot for commit 714ccce. Configure here.
UBSan caught a pre-existing race in shard_connection::get_last_request_type(), which the crash handler signal context calls to print "last_cmd=..." for each connection: shard_connection.cpp:607: runtime error: member access within address ... which does not point to an object of type 'request' The function dereferenced m_pipeline->front()->m_type while worker threads were concurrently popping/destroying requests, so the queue's front pointer could point to recycled memory. Master happened to be lucky; the timing change from the previous commit (one-shot fprintf during the TLS handshake) shifted the worker schedule enough to expose this reliably under UBSan on the OSS TCP TLS v1.2/v1.3 cells. Fix: snapshot req->m_type into a volatile int member at push_req() time and have get_last_request_type() read that cached int instead of dereferencing the queue. Aligned int reads can't tear on the platforms we support, the value is purely diagnostic (one stale read is fine), and we never touch the request* whose lifetime we don't own. Locally re-ran test_crash_handler_integration under TLSv1.2 — both "with_active_connections" and "worker_thread" tests pass, producing "last_cmd=GET"/"last_cmd=SET" output as expected. Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
|
CI on the first push surfaced a UBSan failure on `UBSan OSS TCP TLS v1.2` and `v1.3` (both standalone). Root cause: a pre-existing race in the SEGV signal handler. `shard_connection::get_last_request_type()`, called from the crash handler's CLIENT LIST output, dereferenced `m_pipeline->front()->m_type` while worker threads were concurrently popping and destroying `request` objects. UBSan caught this on `shard_connection.cpp:607`: ``` Master is green on this workflow today by luck — the one-shot `fprintf` added in 714ccce shifts worker schedule timing just enough to expose it reliably under sanitizers. Pushed 967d10d to fix the race by snapshotting `req->m_type` into a `volatile int` cache at `push_req()` time and having `get_last_request_type()` read that cached int instead of dereferencing the queue. The cached read is signal-safe (aligned int can't tear on the platforms we support), one stale read is acceptable for diagnostic-only output, and we never touch the request* whose lifetime we don't own. Locally verified under TLSv1.2 — `last_cmd=GET`/`SET` lines come through and both `test_crash_handler_integration` cases pass. Re-watching CI now. |
|
Review: performance (haiku 4.5) verdict: negligible overhead per connection ✓ • std::call_once overhead: Single-flag atomic check on BEV_EVENT_CONNECTED per-connection (per-thread event loop). On x86-64 this is a lock-free load + compare; amortized to once-across-all-connections via the static once_flag. Zero hot-path repetition. ✓ • SSL_get_version/cipher calls: Idiomatic OpenSSL introspection; these return stable static string pointers, not heap allocations. Called once globally via call_once, not per-frame. ✓ • Volatile int snapshot in push_req(): One aligned • JSON emission post-run: Fires once after benchmark completes (no per-request impact). One fprintf to stderr on first handshake (once per run). ✓ Summary: No heap churn, no hot-loop regressions. The call_once pattern is the right choice here—cheaper than mutexes and ensures single evaluation. Crash-handler fix (volatile snapshot) actually improves safety on contended queue access. |
|
Review: docs & commit message (haiku 4.5)
Verdict: Nothing new. Clean commits, clear feature scope, and one-shot diagnostic with no env vars or protocol changes. |
|
Review: design & API (sonnet 4.6) Verdict: Approach is sound but the shared-config mutation and thin JSON object deserve tightening before merge.
|
fcostaoliveira
left a comment
There was a problem hiding this comment.
Review: security (opus 4.7)
SSL_get_version()/SSL_get_cipher()return pointers into OpenSSL's static read-only string tables in 1.0.2 / 1.1.x / 3.x — stable for the process lifetime and outlive bothSSL_free()andSSL_CTX_free(). Stashing onm_configand reading on the main thread after worker join is safe; the JSON write at memtier_benchmark.cpp:3402 also runs before theSSL_CTX_freeat line 3537, so even non-static returns would be fine.- No TLS-context teardown race: the
call_onceruns on a worker, the main thread reads the pointer only afterpthread_join(full happens-before edge), andtls_negotiated_version/tls_negotiated_cipherare value-initialized to NULL viabenchmark_config()at line 2693 —cfg.tls && version != NULLguards the write. - JSON-injection surface:
json_handler::write_obj("...", "\"%s\"", cipher)usesvfprintfagainst attacker-influenceable text (the negotiated cipher name comes off the wire). OpenSSL's cipher table values are static, well-formed ASCII (e.g.TLS_AES_256_GCM_SHA384), so there's no realistic injection vector — but for defense in depth consider JSON-escaping the value (a cipher containing"or\from a future OpenSSL build, or a custom OPENSSL_CIPHERS string, would break the JSON). No shell-meta risk; nothing here is fed to a shell. volatile int m_last_pushed_req_typefor the crash-handler diagnostic is fine for tear-free reads on the supported platforms (aligned int on x86_64 / arm64 is atomic w.r.t. natural-aligned stores), butvolatiledoesn't give you cross-thread ordering —std::atomic<int>withmemory_order_relaxedwould be the correct C++11 idiom and matches the rest of the codebase's direction. Functionally equivalent here.get_last_request_type()is documented as signal-safe;fprintf/switch/return-literal is fine, but note this is called from a SIGSEGV handler andm_last_pushed_req_type = (int) req->m_typeinpush_req()is a non-atomic store. If the crash occurs mid-store, a torn read is possible (low impact — diagnostic only).- One-shot logging via
std::call_oncecorrectly dedups across threads; the first-completed-handshake assumption holds becauseSSL_CTXis shared. No credential leakage in the stderr/JSON line (only protocol + cipher suite, not session keys / SNI / cert subject).
Verdict: LGTM from a security lens. Optional hardening: JSON-escape negotiated_cipher / negotiated_version and switch the diagnostic counter to std::atomic<int> to remove the (theoretical) torn-read on the signal path.
fcostaoliveira
left a comment
There was a problem hiding this comment.
Review: correctness & latent bugs (opus 4.7)
shard_connection.cpp:1037-1052— the lambda capturesthisbut writes tom_config(the sharedbenchmark_config). The first thread to wincall_oncemay not be the thread the main thread later reads from, andpthread_joinprovides the happens-before only for the main read. Worker threads that race with thecall_oncewinner observetls_negotiated_versionstrictly through atomic-ish init viastd::call_once's internal sync — that's fine for the JSON, but if a future change reads these fields from another worker pre-join (e.g. for periodic stderr output), there is no synchronization. Worth a one-line comment guarding the field as "main-thread, post-join only".shard_connection.cpp:594-621get_last_request_type()— the comment claims "signal-safe diagnostic output", but the call site (memtier_benchmark.cpp:2008) is reached fromcrash_handlerviaprint_client_list, which already usesfprintfand walksg_threads(neither async-signal-safe). The PR doesn't make things worse, but the comment is misleading; consider rephrasing to "best-effort, no UAF" rather than "signal-safe".shard_connection.cpp:594-620semantic drift — original returned"none"when the pipeline was empty; new code returns the last ever pushed type even after the pipeline has fully drained. For a long-idle connection at crash time this now misreports a stale command. Minor, but the field name suggests "currently pending".shard_connection.cpp:600volatile intis sufficient for tearing avoidance on aligned ints, butvolatiledoes not imply atomicity or release semantics. Astd::atomic<int>withmemory_order_relaxedwould be the idiomatic spelling and avoid relying on platform-specific aligned-int guarantees called out in the comment.shard_connection.cpp:1046SSL_get_cipher(ssl)returns the name ofSSL_get_current_cipher(ssl); if the handshake reportsBEV_EVENT_CONNECTEDbut the cipher pointer is somehow NULL (extremely unlikely, but observed on some early-data / 0-RTT paths), this yields the static string"(NONE)"rather than NULL. The JSON-side NULL fallback atmemtier_benchmark.cpp:3406therefore can't kick in for cipher; the JSON will record"(NONE)". Probably fine, just worth a comment.- Cursor-flagged
call_onceconsumed when SSL NULL — acknowledged, not repeated.
Verdict: Comment
fcostaoliveira
left a comment
There was a problem hiding this comment.
Review: edge cases & failure modes (opus 4.7)
Verdict: LGTM with two soft notes; nothing blocking.
std::call_onceconsumes the once_flag even when the lambda emits nothing (the NULL-bufferevent_openssl_get_ssl(m_bev)path Cursor flagged). That means a single transient half-torndown bufferevent at the moment of the very firstBEV_EVENT_CONNECTEDpermanently disables stderr+JSON capture for the rest of the run, even when every subsequent handshake succeeds. Consider either gating the once_flag onSSL != NULL(so a NULL hit doesn't burn the latch) orcompare_exchangeon the cfg pointers — leaves the dedup but allows recovery.m_last_pushed_req_type = (int) req->m_typeis set AFTERm_pipeline->push(req). If the crash-handler signal lands between push and the store on the same thread,get_last_request_type()reports the previous request's type while the queue contains the new one. For diagnostics this is acceptable, but worth a brief comment so a future reader doesn't tighten the ordering and re-introduce a deref race.volatile intis notsig_atomic_t— strictly speaking, signal-safety of the load is platform-dependent. On x86_64/aarch64 aligned int loads are atomic so it works, but the comment claiming "signal-safe" overstates the guarantee.sig_atomic_t(orstd::atomic<int>withmemory_order_relaxed) would match the comment.tls_negotiated_version/tls_negotiated_cipherare static OpenSSL strings, so storing the bare pointer oncfgis fine until OpenSSL is unloaded —SSL_CTX_freedoesn't invalidate them, but a re-init across--run-count > 1would. Not exercised today; worth a one-line note next to the cfg field.- The new
enum request_typeincludesrt_unknown(value 0) butget_last_request_type()has no case for it — falls through to default → "none". Fine, but the constructor seedsm_last_pushed_req_type = -1, also "none". Two sentinels for the same state; consider initializing tort_unknownto match the enum. - Test asserts
len(lines) == 1but the line is emitted from a worker thread viafprintf(stderr, ...)without locking. Under--threads N --clients M, if a second handshake completes in the (very small) window beforecall_oncefinishes the store, you could theoretically see two lines on stderr (call_once protects the callable, not the fprintf reordering vs other unrelated stderr writes). Low probability; flagging because the test asserts== 1strictly.
fcostaoliveira
left a comment
There was a problem hiding this comment.
Review: style & readability (sonnet 4.6)
Verdict: mostly clean; three targeted notes.
-
call_oncecomment omits reconnect-suppression intent (shard_connection.cpp, TLS block): the comment explains why one line is representative (sharedSSL_CTX/config), but doesn't say that TLS renegotiation on reconnect is intentionally silent after the first handshake. A reader maintaining reconnect logic may add a secondfprintfthinking the first one was a bug. One sentence like "reconnects reuse the same negotiated parameters, so suppressing them is intentional" would close that gap. -
m_last_pushed_req_typecomment describes the mechanism, not the hazard (shard_connection.h): "volatile + aligned int avoids the racy deref" is what it does. The why worth preserving: the crash handler is an async signal that can fire mid-pop()on any thread, so dereffingm_pipeline->front()from signal context is UB even with a lock (locks are not async-signal-safe). That's the actual constraint driving the design. -
get_last_request_type(): default"none"now returned for initialised-but-unpushed state (shard_connection.cpp): the previous code returned"unknown"for a null queue front; the new code returns"none"form_last_pushed_req_type == -1. This is fine, but thedefault:label now silently covers both the true "no type" case (-1) and any future enum extension. A short comment "// -1 = initialised but no request pushed yet" on them_last_pushed_req_typedeclaration (or in thedefault:branch) would document the sentinel meaning. -
Python test: list-comprehension variable shadows builtin (
test_tls_logging.pyline 68):[l for l in stderr.splitlines() ...])—lshadows the builtinl(not a real builtin, harmless) but more importantly reads poorly at a glance.lineis idiomatic. -
Commit messages: two commits, both Conventional Commits-clean (
feat(tls):/fix(crash-handler):); the second commit's body is unusually thorough and accurate — good model for the series.


Summary
When pointing memtier_benchmark at a TLS endpoint (standalone or cluster), there's no easy way today to confirm which TLS protocol/cipher actually got negotiated. This adds a one-shot surface for that:
TLSobject in--json-out-file(mb.json):Both are absent in plaintext runs.
Implementation
shard_connection::handle_event(BEV_EVENT_CONNECTED): on the first completed handshake across all worker threads, astd::call_oncecallsSSL_get_version()/SSL_get_cipher()on the bufferevent's SSL, stashes the (static) strings on the sharedbenchmark_config, and prints the single stderr line. All connections share oneSSL_CTXand target the same server config, so one line is representative.benchmark_configgainstls_negotiated_version/tls_negotiated_cipher(set once on a worker thread, read on the main thread after join).config_print_to_jsonruns before the benchmark, so the JSON object is emitted post-run (next torun information). Only written when--tlsis on AND a value was captured.No new dependencies; no per-connection overhead beyond a
std::call_oncecheck.Test plan
tests/test_tls_logging.pyasserts the stderr line and the JSON object in TLS mode, and asserts both are absent in plaintext.Verified locally across the three modes that matter:
TLSobject absent, zero stderr lines)make format-checkclean🤖 Generated with Claude Code
Note
Low Risk
Diagnostic TLS/JSON output and a crash-handler concurrency fix; no changes to auth, verification, or connection security policy.
Overview
Adds one-shot visibility into negotiated TLS when
--tlsis on: the first completed handshake across all worker threads records protocol and cipher on sharedbenchmark_config(viastd::call_once), prints a single stderr line, and after the run writes aTLSobject in--json-out-filewithnegotiated_versionandnegotiated_cipher(omitted for plaintext or if nothing was captured).Separately hardens crash-report “last command” diagnostics:
get_last_request_type()reads avolatile intsnapshot updated inpush_req()instead of dereferencing the pipeline queue, avoiding races with concurrent pops from worker threads.New
tests/test_tls_logging.pyasserts exactly one stderr line and matching JSON under TLS, and absence without TLS.Reviewed by Cursor Bugbot for commit 967d10d. Bugbot is set up for automated code reviews on this repo. Configure here.