Skip to content

feat(tls): log negotiated TLS protocol/cipher once and record in JSON - #403

Merged
fcostaoliveira merged 2 commits into
redis:masterfrom
filipecosta90:feat/log-negotiated-tls
Jun 1, 2026
Merged

fcostaoliveira merged 2 commits into
redis:masterfrom
filipecosta90:feat/log-negotiated-tls

Conversation

@fcostaoliveira

@fcostaoliveira fcostaoliveira commented May 29, 2026 •

Copy link
Copy Markdown
Collaborator

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:

  • One stderr line per run (not per connection / thread / shard):
    TLS connection established: protocol TLSv1.3, cipher TLS_AES_256_GCM_SHA384
    
  • One TLS object in --json-out-file (mb.json):
    "TLS": {
      "negotiated_version": "TLSv1.3",
      "negotiated_cipher": "TLS_AES_256_GCM_SHA384"
    }

Both are absent in plaintext runs.

Implementation

  • shard_connection::handle_event (BEV_EVENT_CONNECTED): on the first completed handshake across all worker threads, a std::call_once calls SSL_get_version() / SSL_get_cipher() on the bufferevent's SSL, stashes the (static) strings on the shared benchmark_config, and prints the single stderr line. All connections share one SSL_CTX and target the same server config, so one line is representative.
  • benchmark_config gains tls_negotiated_version / tls_negotiated_cipher (set once on a worker thread, read on the main thread after join).
  • config_print_to_json runs before the benchmark, so the JSON object is emitted post-run (next to run information). Only written when --tls is on AND a value was captured.

No new dependencies; no per-connection overhead beyond a std::call_once check.

Test plan

tests/test_tls_logging.py asserts 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:

  • Plaintext standalone: PASS (TLS object absent, zero stderr lines)
  • TLS standalone: PASS (1 stderr line + JSON object)
  • TLS oss-cluster (3 shards, 2 threads × 4 clients): PASS — exactly one stderr line across all shard connections + JSON object. This is the "point at a cluster" case from the original ask.
  • make format-check clean
  • CI matrix (standalone + cluster, plaintext + TLS) — to be confirmed by CI on this PR

🤖 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 --tls is on: the first completed handshake across all worker threads records protocol and cipher on shared benchmark_config (via std::call_once), prints a single stderr line, and after the run writes a TLS object in --json-out-file with negotiated_version and negotiated_cipher (omitted for plaintext or if nothing was captured).

Separately hardens crash-report “last command” diagnostics: get_last_request_type() reads a volatile int snapshot updated in push_req() instead of dereferencing the pipeline queue, avoiding races with concurrent pops from worker threads.

New tests/test_tls_logging.py asserts 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.

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]>

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes and found 1 potential issue.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit 714ccce. Configure here.

Comment thread shard_connection.cpp
fprintf(stderr, "TLS connection established: protocol %s, cipher %s\n",
m_config->tls_negotiated_version, m_config->tls_negotiated_cipher);
}
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Fix in Cursor Fix in Web

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]>
@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

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`:

```
runtime error: member access within address ... which does not point to an object of type 'request'
```

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.

@fcostaoliveira fcostaoliveira added this to the 2.4 milestone Jun 1, 2026
@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

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 volatile int write per request (m_last_pushed_req_type). This is already in the hot path (every request writes to m_pending_resp); one more atomic store is sub-nanosecond overhead and eliminates unsafe queue derefs from signal context. ✓

• 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.

@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Review: docs & commit message (haiku 4.5)

  • Conventional Commits: ✓ feat(tls): ... compliant
  • Test plan: ✓ Honest and complete (4 local modes verified, CI awaiting)
  • Issue refs: N/A — diagnostic feature, no bug reference needed
  • Schema documentation: ✓ JSON TLS object structure documented inline in PR body; no gaps

Verdict: Nothing new. Clean commits, clear feature scope, and one-shot diagnostic with no env vars or protocol changes.

@fcostaoliveira

Copy link
Copy Markdown
Collaborator Author

Review: design & API (sonnet 4.6)

Verdict: Approach is sound but the shared-config mutation and thin JSON object deserve tightening before merge.

  • Shared-config mutation from a worker thread (load-bearing): Writing m_config->tls_negotiated_version/cipher from inside call_once is sequenced only with other call_once invocations, not with the main thread's post-join read. std::call_once provides no happens-before with threads that never called call_once. The implementation relies on the join providing the necessary barrier, which is correct in practice on all mainstream architectures, but the comment ("read on the main thread post-join") is the only documentation of this. A std::atomic<const char*> pair with memory_order_release / memory_order_acquire would make the contract explicit and self-documenting without adding overhead.

  • Per-connection struct vs. shared config: Storing the negotiated values on benchmark_config conflates two concerns: a per-run diagnostic (what did we negotiate?) and the mutable, shared benchmark configuration. A small tls_session_info POD (negotiated_version, negotiated_cipher) captured once and kept alongside other post-run results (e.g. near where RUN RESULTS is assembled) would avoid polluting the config struct with fields that are only valid post-handshake and only set from a worker.

  • JSON object completeness: The TLS object records negotiated_version and negotiated_cipher, but the configured sni, cert path, and tls_skip_verify are already written in configuration (via config_print_to_json). Consumers correlating the negotiated cipher with the cert used need to cross-reference two JSON sections. Adding at least "sni": "<value>" (or a cross-reference key) to the TLS object would make it self-contained for audit tooling.

  • tls_negotiated_cipher nullable path in JSON: tls_negotiated_version is guarded (!= NULL) but tls_negotiated_cipher falls back to "" — so a partial capture (version set, cipher not) emits a misleading empty string rather than being absent. If SSL_get_version and SSL_get_cipher are both called on the same non-null ssl pointer inside the call_once body, both should always be non-null together; the asymmetric null-check suggests the guard was added defensively but leaves a confusing JSON artifact.

  • static once_flag inside handle_event (scope concern): The flag is function-local static, so it survives across benchmark runs within the same process invocation (multiple --run-count runs). If a TLS benchmark is run with --run-count > 1, only the first run logs the handshake; subsequent runs silently emit no TLS line and leave tls_negotiated_* from the first run. The PR description acknowledges the one-shot design, but it should be called out explicitly and the JSON output should be gated on whether the current run's connections captured the value, not on whether any prior run did.

@fcostaoliveira fcostaoliveira left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 both SSL_free() and SSL_CTX_free(). Stashing on m_config and reading on the main thread after worker join is safe; the JSON write at memtier_benchmark.cpp:3402 also runs before the SSL_CTX_free at line 3537, so even non-static returns would be fine.
  • No TLS-context teardown race: the call_once runs on a worker, the main thread reads the pointer only after pthread_join (full happens-before edge), and tls_negotiated_version / tls_negotiated_cipher are value-initialized to NULL via benchmark_config() at line 2693 — cfg.tls && version != NULL guards the write.
  • JSON-injection surface: json_handler::write_obj("...", "\"%s\"", cipher) uses vfprintf against 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_type for 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), but volatile doesn't give you cross-thread ordering — std::atomic<int> with memory_order_relaxed would 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 and m_last_pushed_req_type = (int) req->m_type in push_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_once correctly dedups across threads; the first-completed-handshake assumption holds because SSL_CTX is 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 fcostaoliveira left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review: correctness & latent bugs (opus 4.7)

  • shard_connection.cpp:1037-1052 — the lambda captures this but writes to m_config (the shared benchmark_config). The first thread to win call_once may not be the thread the main thread later reads from, and pthread_join provides the happens-before only for the main read. Worker threads that race with the call_once winner observe tls_negotiated_version strictly through atomic-ish init via std::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-621 get_last_request_type() — the comment claims "signal-safe diagnostic output", but the call site (memtier_benchmark.cpp:2008) is reached from crash_handler via print_client_list, which already uses fprintf and walks g_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-620 semantic 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:600 volatile int is sufficient for tearing avoidance on aligned ints, but volatile does not imply atomicity or release semantics. A std::atomic<int> with memory_order_relaxed would be the idiomatic spelling and avoid relying on platform-specific aligned-int guarantees called out in the comment.
  • shard_connection.cpp:1046 SSL_get_cipher(ssl) returns the name of SSL_get_current_cipher(ssl); if the handshake reports BEV_EVENT_CONNECTED but 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 at memtier_benchmark.cpp:3406 therefore can't kick in for cipher; the JSON will record "(NONE)". Probably fine, just worth a comment.
  • Cursor-flagged call_once consumed when SSL NULL — acknowledged, not repeated.

Verdict: Comment

@fcostaoliveira fcostaoliveira left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review: edge cases & failure modes (opus 4.7)

Verdict: LGTM with two soft notes; nothing blocking.

  • std::call_once consumes 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 first BEV_EVENT_CONNECTED permanently disables stderr+JSON capture for the rest of the run, even when every subsequent handshake succeeds. Consider either gating the once_flag on SSL != NULL (so a NULL hit doesn't burn the latch) or compare_exchange on the cfg pointers — leaves the dedup but allows recovery.
  • m_last_pushed_req_type = (int) req->m_type is set AFTER m_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 int is not sig_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 (or std::atomic<int> with memory_order_relaxed) would match the comment.
  • tls_negotiated_version/tls_negotiated_cipher are static OpenSSL strings, so storing the bare pointer on cfg is fine until OpenSSL is unloaded — SSL_CTX_free doesn't invalidate them, but a re-init across --run-count > 1 would. Not exercised today; worth a one-line note next to the cfg field.
  • The new enum request_type includes rt_unknown (value 0) but get_last_request_type() has no case for it — falls through to default → "none". Fine, but the constructor seeds m_last_pushed_req_type = -1, also "none". Two sentinels for the same state; consider initializing to rt_unknown to match the enum.
  • Test asserts len(lines) == 1 but the line is emitted from a worker thread via fprintf(stderr, ...) without locking. Under --threads N --clients M, if a second handshake completes in the (very small) window before call_once finishes 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 == 1 strictly.

@fcostaoliveira fcostaoliveira left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review: style & readability (sonnet 4.6)

Verdict: mostly clean; three targeted notes.

  • call_once comment omits reconnect-suppression intent (shard_connection.cpp, TLS block): the comment explains why one line is representative (shared SSL_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 second fprintf thinking 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_type comment 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 dereffing m_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" for m_last_pushed_req_type == -1. This is fine, but the default: 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 the m_last_pushed_req_type declaration (or in the default: branch) would document the sentinel meaning.

  • Python test: list-comprehension variable shadows builtin (test_tls_logging.py line 68): [l for l in stderr.splitlines() ...]) — l shadows the builtin l (not a real builtin, harmless) but more importantly reads poorly at a glance. line is 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.

@fcostaoliveira
fcostaoliveira merged commit 1cd8ed2 into redis:master Jun 1, 2026
65 checks passed
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