From f28a911d878e8444a80442c3d9486cb569a42b6c Mon Sep 17 00:00:00 2001 From: rigazilla Date: Fri, 6 Nov 2026 18:15:29 +0100 Subject: [PATCH 1/6] feat: server-authenticated TLS for hotrods:// (issue #18) Wrap client connections in a TLS session over OpenSSL (server-auth only, PEM trust material). The hotrods:// URI scheme no longer throws; TLS applies to every connection the client opens (seed + topology-discovered). - TlsConfig value type + RemoteCache::setTls(...) (mirrors setAuthentication), pushed down through MultiplexedConnection to Connection at the same build sites as auth/protocol/intelligence. - Connection::startTls(): TLS_client_method, min TLS 1.2, PEM ca_file (empty = system trust store), SSL_VERIFY_PEER always, SNI (skipped for literal IPs), host-name match via SSL_set1_host (toggle: hostname_validation, default on; chain verification unconditional). send/receive route through SSL_write/read. Quiet shutdown on teardown to avoid SIGPIPE writing close_notify to a dead peer. - HotRodURI: hotrods:// enables TLS; recognizes the three Java-named keys that map onto TlsConfig (trust_store_file_name -> ca_file [PEM], sni_host_name, ssl_hostname_validation). Other Java TLS keys (mutual TLS / keystore / cipher tuning) are rejected "not supported yet"; TLS params on hotrod:// error. - OpenSSL::SSL link is now live (was dead weight next to libcrypto). - Tests: TlsConnectionTest drives the real handshake against an in-process OpenSSL echo server with PEM fixtures (SAN=test.local); trusted/untrusted CA and host-name match on/off. HotRodURITest covers the URI surface. 260 unit tests green. Mutual TLS, keystore formats, and cipher/protocol tuning remain deferred (#10). Docs: STATUS (shipped + remaining), DECISIONS (dated rationale, supersedes the OpenSSL::SSL "dead weight" aside), README (feature + URI/setTls usage). Co-Authored-By: Claude Opus 4.8 --- CMakeLists.txt | 7 + README.md | 38 +++-- docs/DECISIONS.md | 64 ++++++++ docs/STATUS.md | 42 +++-- include/hotrod/Connection.h | 22 +++ include/hotrod/HotRodURI.h | 66 +++++++- include/hotrod/MultiplexedConnection.h | 11 ++ include/hotrod/RemoteCache.h | 40 +++++ include/hotrod/TlsConfig.h | 45 +++++ src/operations/RemoteCache.cpp | 10 ++ src/transport/Connection.cpp | 165 +++++++++++++++++++ src/transport/MultiplexedConnection.cpp | 11 +- tests/fixtures/tls/ca.pem | 19 +++ tests/fixtures/tls/otherca.pem | 19 +++ tests/fixtures/tls/server.key | 28 ++++ tests/fixtures/tls/server.pem | 19 +++ tests/unit/HotRodURITest.cpp | 79 ++++++++- tests/unit/TlsConnectionTest.cpp | 209 ++++++++++++++++++++++++ 18 files changed, 853 insertions(+), 41 deletions(-) create mode 100644 include/hotrod/TlsConfig.h create mode 100644 tests/fixtures/tls/ca.pem create mode 100644 tests/fixtures/tls/otherca.pem create mode 100644 tests/fixtures/tls/server.key create mode 100644 tests/fixtures/tls/server.pem create mode 100644 tests/unit/TlsConnectionTest.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index cb7a64a..88aa397 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -95,6 +95,7 @@ if(GTest_FOUND) tests/unit/AuthCodecTest.cpp tests/unit/HotRodURITest.cpp tests/unit/SaslAuthenticatorTest.cpp + tests/unit/TlsConnectionTest.cpp ) target_link_libraries(unit_tests @@ -104,6 +105,12 @@ if(GTest_FOUND) GTest::gtest_main ) + # TlsConnectionTest reads PEM fixtures by absolute path (no working-dir + # assumption); the server side links OpenSSL directly. + target_compile_definitions(unit_tests PRIVATE + TLS_FIXTURE_DIR="${CMAKE_CURRENT_SOURCE_DIR}/tests/fixtures/tls") + target_link_libraries(unit_tests PRIVATE OpenSSL::SSL OpenSSL::Crypto) + add_test(NAME UnitTests COMMAND unit_tests) # Copy test scripts and configs to build directory diff --git a/README.md b/README.md index 7c9f027..ae0b75d 100644 --- a/README.md +++ b/README.md @@ -196,9 +196,15 @@ coverage breakdown and counts. - ✅ **SASL/SCRAM authentication** (`setAuthentication(...)`) — end-to-end for the SCRAM family (`SCRAM-SHA-1`/`SCRAM-SHA-256`/`SCRAM-SHA-512`), applied to every connection; see [`documentation/topics/security.adoc`](documentation/topics/security.adoc) -- ✅ **Hot Rod URI** (`RemoteCache::fromUri("hotrod://...")`) — build a client from a - connection string (hosts, credentials, `sasl_mechanism`/`client_intelligence`/ - `protocol_version` params); `hotrod://` only for now (TLS and more in issue #10) +- ✅ **Hot Rod URI** (`RemoteCache::fromUri("hotrod[s]://...")`) — build a client from + a connection string (hosts, credentials, `sasl_mechanism`/`client_intelligence`/ + `protocol_version` params, and the server-auth TLS params below); timeouts and more + in issue #10 +- ✅ **Server-authenticated TLS** (`setTls(...)` / `hotrods://`, issue #18) — wraps + every connection in a TLS session (OpenSSL). PEM trust (`ca_file`, empty = system + store), SNI, and host-name validation (default on); min TLS 1.2. URI keys: + `trust_store_file_name` (PEM CA), `sni_host_name`, `ssl_hostname_validation`. + Mutual TLS / keystore formats are deferred (issue #10) - ✅ **Multi-server seed list** (issue #12) — all hosts in the URI become seed servers with startup *and* runtime failover (ops fall back to the seed list when the connected server dies or no topology is known, e.g. in BASIC mode) @@ -249,14 +255,23 @@ auto cache = RemoteCache::fromUri( "my-cache"); cache->connect(); -// Supports hotrod:// only. All hosts become seed servers (issue #12): connect() -// tries each in order, and ops fall back to the seed list when the connected -// server dies or no topology is known (e.g. BASIC mode). Credentials +// Supports hotrod:// and hotrods:// (TLS). All hosts become seed servers (issue +// #12): connect() tries each in order, and ops fall back to the seed list when the +// connected server dies or no topology is known (e.g. BASIC mode). Credentials // enable SCRAM, and sasl_mechanism/client_intelligence/protocol_version (Java -// "4.0"/"4.1" form) are honoured. Userinfo and query values are percent-decoded -// (RFC 3986), so a reserved character in a password is written encoded — e.g. a -// password of p@ss is "...://admin:p%40ss@host". hotrods:// (TLS), timeouts, and -// other parameters throw for now (see issue #10). +// "4.0"/"4.1" form) are honoured. hotrods:// enables server-auth TLS; the +// trust_store_file_name (PEM CA) / sni_host_name / ssl_hostname_validation params +// map to setTls(...). Userinfo and query values are percent-decoded (RFC 3986), so +// a reserved character in a password is written encoded — e.g. a password of p@ss +// is "...://admin:p%40ss@host". Timeouts, mutual TLS, and other parameters throw +// for now (see issue #10). +// +// // TLS from a URI (private CA): +// auto c = RemoteCache::fromUri("hotrods://cache:11222?trust_store_file_name=/etc/pki/ca.pem"); +// // or programmatically: +// RemoteCache cache("cache", 11222); +// cache.setTls("/etc/pki/ca.pem"); // ca_file; empty = system trust store +// cache.connect(); ``` ### Future @@ -270,8 +285,9 @@ cache->connect(); `replaceWithVersion`, `removeWithVersion`, `putIfAbsent`, `replace`, `containsKey` - ✅ **Step 11 — Error handling** (shipped): ERROR response parsing, typed exception, user-decided retry (keyed + keyless) +- ✅ **Server-authenticated TLS** (shipped, issue #18): `hotrods://` + `setTls(...)` - **Step 12 — Bulk operations** (next): `GET_ALL`, `PUT_ALL`, `BULK_GET` -- Also: multiplexing benchmarks, TLS/SSL support +- Also: multiplexing benchmarks, mutual TLS (client cert/key, issue #10) ## Project Structure diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index 6bdae75..122890a 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -1075,3 +1075,67 @@ overclaim until now. entry) — the `TIMEOUT 300` guard per ctest suite plus `cli.sh -f -` batch mode keep a server-side change failing fast rather than hanging CI. Verified the full multi-node suite set green against `:latest` = 16.3.0 on 2026-10-19 after the switch. + +## 2026-11-06 — Server-authenticated TLS for `hotrods://` (issue #18, sub-issue of #10) + +**What:** first TLS slice. `hotrods://` no longer throws; the client wraps every +connection it opens (seed + topology-discovered) in a TLS session over OpenSSL. +New pure value `TlsConfig` (`include/hotrod/TlsConfig.h`); `RemoteCache::setTls(...)` +mirrors `setAuthentication` and is pushed to each `MultiplexedConnection` → +`Connection` at the same two build sites as auth/protocol/intelligence. The +handshake lives in `Connection::startTls()` (`src/transport/Connection.cpp`): +`TLS_client_method`, min TLS 1.2, trust anchors from a PEM `ca_file` (empty = +`SSL_CTX_set_default_verify_paths`, the system store), `SSL_VERIFY_PEER` always, +SNI via `SSL_set_tlsext_host_name`, host-name match via `SSL_set1_host`. `send`/ +`receive` route through `SSL_write`/`SSL_read` when a session is live. + +**Scope decisions (settled with the maintainer before coding):** +- **Server-auth only this slice.** Mutual TLS (client cert/key) is deferred. +- **PEM, not Java keystores.** This is an OpenSSL-native client; JKS/PKCS12 + + type/alias/store-password make no sense here. We deliberately diverge from the + Java `SslConfiguration` surface. Note the semantic reuse: the URI key + `trust_store_file_name` (a keystore in Java) is interpreted here as a **PEM CA + file**; `trust_store_type` is not accepted (PEM is implied). Java itself supports + `trust_store_type=pem`, so this isn't alien to Infinispan. +- **URI = option C.** `hotrods://` enables TLS with defaults; the URI additionally + recognizes exactly the three Java-named keys that map onto `TlsConfig` + (`trust_store_file_name`→`ca_file`, `sni_host_name`→`sni_host`, + `ssl_hostname_validation`→`hostname_validation`). Every settable `TlsConfig` + field is reachable both programmatically and from the URI; nothing more. The + other recognized Java TLS keys (`use_ssl`, `key_store_*`, `*_store_type`, + `*_password`, `key_alias`, `ssl_protocol`/`ciphers`/`named_groups`/`provider`/ + `context`) are rejected with "not supported yet (… deferred; issue #10)" rather + than silently ignored — preserving the parser's fail-fast contract. TLS params on + a plain `hotrod://` URI are a hard error ("require the hotrods:// scheme"). + +**Behavioral calls:** +- **Min TLS 1.2** (`SSL_CTX_set_min_proto_version`). +- **SNI skipped for literal IPs** (RFC 6066) — and such a name is not host-validated + as a DNS name either (`isLiteralIp` guards both). To dial a loopback IP but still + verify a name, set `sni_host` to the DNS name (what the unit test does). +- **`hostname_validation=false` disables only the host-name match, not chain + verification** — chain verification is unconditional. Matches Java's + `hostnameValidation` semantics. +- **Quiet shutdown on teardown.** `Connection::close()` sets + `SSL_set_quiet_shutdown` before `SSL_shutdown`, so teardown never writes a + close_notify. Writing it to an already-dead peer raises SIGPIPE/EPIPE, which with + the default disposition kills the process for no benefit. (The in-process test + server also installs `SIG_IGN` for SIGPIPE, since its echo thread writes on close.) + +**OpenSSL::SSL link is now live.** Supersedes the 2026-10-09 "Aside": `CMakeLists.txt` +already linked `OpenSSL::SSL` as dead weight next to libcrypto; the handshake code +now uses it (`SSL_*`), so the link is no longer dead. The entry's "folded into the +TLS work" prediction holds. + +**Tests:** `tests/unit/TlsConnectionTest.cpp` drives the real handshake against an +in-process OpenSSL echo server (loopback, ephemeral port) presenting a PEM leaf +(SAN=`test.local`) signed by a test CA — fixtures in `tests/fixtures/tls/` +(36500-day validity; path injected via the `TLS_FIXTURE_DIR` compile definition). +Cases: trusted-CA + matching name → handshake + encrypted round-trip; untrusted CA +→ throw; name mismatch with validation on → throw, with validation off → succeed. +POSIX-only (like the integration suites); the cross-platform URI-level parsing is in +`HotRodURITest.cpp`. Full unit suite green (260 tests), stable across repeated runs. + +**Deferred (unchanged, issue #10):** mutual TLS / client cert+key, Java keystore +formats, cipher/protocol/provider tuning, `connect_timeout`/`socket_timeout`, +non-SCRAM SASL, `protocol_version=AUTO`/3.x. diff --git a/docs/STATUS.md b/docs/STATUS.md index e2a4171..140e594 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -4,7 +4,7 @@ > If any other doc disagrees with this file, this file wins. Point-in-time > snapshots live in [`archive/`](archive/) and are historical only. > -> **Last updated:** 2026-10-19 +> **Last updated:** 2026-11-06 --- @@ -41,8 +41,9 @@ _The 1–3 concrete things to do next. Keep this short and current._ (two `TODO`s in `src/operations/RemoteCache.cpp`). _Recently shipped (detail in "Working and shipped" + [`DECISIONS.md`](DECISIONS.md)): -multi-server seed list + failover (#12, 2026-10-19), Hot Rod URI `fromUri` (#9), -SASL/SCRAM auth, Step 11 error handling + user-decided retry, Step 10 metadata/CAS._ +server-authenticated TLS for `hotrods://` (#18, 2026-11-06), multi-server seed +list + failover (#12), Hot Rod URI `fromUri` (#9), SASL/SCRAM auth, Step 11 error +handling + user-decided retry, Step 10 metadata/CAS._ --- @@ -62,12 +63,15 @@ pull from here next. Step numbers follow concurrent throughput; unmeasured so far. - [ ] **Code cleanup:** read header "other params" when `paramCount > 0` (`src/operations/RemoteCache.cpp:140,182`). -- [ ] **Hot Rod URI — deferred features (issue #10):** `hotrods://`/TLS + - cert/SNI/hostname-validation params, `connect_timeout`/`socket_timeout`, - non-SCRAM SASL (PLAIN/OAUTHBEARER `token`), `protocol_version=AUTO`/3.x. Each - drops its "unsupported" throw from `HotRodURI::parse` once the capability lands. - (Multi-server seed list is already shipped — issue #12; see "Working and shipped".) -- [ ] **TLS/SSL support** (transport encryption). Also unblocks `hotrods://` above. +- [ ] **Hot Rod URI — deferred features (issue #10):** `connect_timeout`/ + `socket_timeout`, non-SCRAM SASL (PLAIN/OAUTHBEARER `token`), + `protocol_version=AUTO`/3.x. Each drops its "unsupported" throw from + `HotRodURI::parse` once the capability lands. (Multi-server seed list — #12 — + and server-auth TLS — #18 — are already shipped; see "Working and shipped".) +- [ ] **Mutual TLS + TLS tuning (deferred part of #18/#10):** client cert/key + (`key_store_*`), Java keystore formats (JKS/PKCS12, `*_store_type`/password/ + alias), and `ssl_protocol`/`ssl_ciphers`/`ssl_named_groups`/`ssl_provider`. + These URI keys are currently recognized and rejected with "not supported yet". **Longer horizon (Step 14+ advanced features):** transactions (XA), client listeners/events, counters, Ickle queries, streaming ops (4.1+), multimap, @@ -82,16 +86,24 @@ Rod URI `fromUri` (#9), multi-server seed list + failover (#12)._ --- -## Current state (verified 2026-10-19) +## Current state (verified 2026-11-06) **Working and shipped:** - **Hot Rod URI (`RemoteCache::fromUri`)** — build a configured client from a - `hotrod://[user:pass@]host[:port][,host...][?k=v]` connection string (issue #9); + `hotrod[s]://[user:pass@]host[:port][,host...][?k=v]` connection string (issue #9); pure header-only parser `HotRodURI::parse` (`include/hotrod/HotRodURI.h`). - `hotrod://` scheme only, SCRAM via credentials, - `sasl_mechanism`/`client_intelligence`/`protocol_version` params; userinfo and - query values are percent-decoded (java.net.URI parity); unsupported - schemes/params throw. TLS/timeouts/non-SCRAM deferred (issue #10) + `hotrod://` and `hotrods://` (TLS) schemes, SCRAM via credentials, + `sasl_mechanism`/`client_intelligence`/`protocol_version` + the server-auth TLS + params (`trust_store_file_name`/`sni_host_name`/`ssl_hostname_validation`); + userinfo and query values are percent-decoded (java.net.URI parity); unsupported + schemes/params throw. timeouts/non-SCRAM/mutual-TLS deferred (issue #10) +- **Server-authenticated TLS (`hotrods://`, issue #18)** — `RemoteCache::setTls(...)` + (and the `hotrods://` scheme) wrap every connection the client opens (seed + + topology-discovered) in a TLS session over OpenSSL. PEM trust material + (`ca_file`, empty = system store), SNI (`sni_host`, skipped for literal IPs), + and host-name validation (`hostname_validation`, default on; chain verification + always on). Min TLS 1.2. `include/hotrod/TlsConfig.h`; handshake in + `src/transport/Connection.cpp`. Mutual TLS / keystore formats deferred (#10) - **Multi-server seed list + failover (`fromUri`, issue #12)** — all comma-separated hosts become seed servers. **Startup failover:** `connect()` tries each seed in order; all unreachable → one `HotRodClientException` listing diff --git a/include/hotrod/Connection.h b/include/hotrod/Connection.h index b1f6ed0..7d28760 100644 --- a/include/hotrod/Connection.h +++ b/include/hotrod/Connection.h @@ -1,9 +1,15 @@ #pragma once #include "Types.h" +#include "TlsConfig.h" #include #include +// Forward-declare the OpenSSL types so this header does not drag +// into every translation unit that merely talks to a Connection. +struct ssl_st; +struct ssl_ctx_st; + namespace hotrod { // Portable socket handle type. On Windows a SOCKET is an unsigned @@ -28,6 +34,11 @@ class Connection { Connection(const std::string& host, uint16_t port); ~Connection(); + // Configure TLS. Must be called before connect(). When tls.enabled is true, + // connect() performs a TLS handshake over the TCP socket and all subsequent + // send()/receive() traffic is encrypted. + void setTls(const TlsConfig& tls) { tls_ = tls; } + // Connect to server void connect(); @@ -53,10 +64,21 @@ class Connection { EntryMetadata receiveMetadata(); // entry_metadata (Protocol 4.0+) private: + // Perform the TLS handshake on the already-connected socket_ (server-auth, + // OpenSSL). Throws std::runtime_error with a descriptive message on failure. + void startTls(); + std::string host_; uint16_t port_; bool connected_; socket_t socket_; // Socket descriptor (platform-specific) + + // TLS state. tls_.enabled gates the handshake in connect(); when a session is + // live, ssl_ is non-null and send()/receive() route through it. ctx_ owns the + // per-connection OpenSSL context. Both are freed in close()/dtor. + TlsConfig tls_; + ssl_st* ssl_{nullptr}; + ssl_ctx_st* ctx_{nullptr}; }; } // namespace hotrod diff --git a/include/hotrod/HotRodURI.h b/include/hotrod/HotRodURI.h index 27a7e44..720ed96 100644 --- a/include/hotrod/HotRodURI.h +++ b/include/hotrod/HotRodURI.h @@ -2,6 +2,7 @@ #include "HeaderCodec.h" // ClientIntelligence, Protocol::VERSION_* #include "HotRodClientException.h" // HotRodClientException, ServerAddress, FailurePhase +#include "TlsConfig.h" // TlsConfig #include #include #include @@ -28,15 +29,17 @@ namespace hotrod { * and applies the flat setters. * * Scope (the rest is deferred to issue #10): - * - scheme: only "hotrod://". "hotrods://" (TLS) throws, since the transport has - * no TLS yet. + * - scheme: "hotrod://" (plain) or "hotrods://" (TLS, issue #18). "hotrods://" + * enables server-authenticated TLS; the PEM trust subset of the Java query + * keys is parsed into `tls` (trust_store_file_name, sni_host_name, + * ssl_hostname_validation). Mutual-TLS / keystore keys remain rejected. * - multiple comma-separated servers are parsed into `servers`; all of them become * seed servers with startup + runtime failover (issue #12) — RemoteCache tries * them in order at connect() and falls back to the list when the learned * topology is empty or exhausted. `seed()` is retained as the first host. * - query parameters are a typed whitelist; an unknown key or a bad value for a - * known key throws. Deferred params (timeouts, TLS, use_ssl, non-SCRAM SASL) - * are therefore rejected rather than silently ignored. + * known key throws. Deferred params (timeouts, non-SCRAM SASL, mutual-TLS / + * keystore TLS keys) are therefore rejected rather than silently ignored. */ struct HotRodURI { std::vector servers; // all parsed, in order (>=1) @@ -45,6 +48,7 @@ struct HotRodURI { std::optional saslMechanism; // e.g. "SCRAM-SHA-256" std::optional clientIntelligence; std::optional protocolVersion; // Protocol::VERSION_40 / _41 + std::optional tls; // set when scheme is hotrods:// /** The first server in the list — the bootstrap seed RemoteCache connects to * first; the full `servers` list is used for startup/runtime failover (#12). */ @@ -108,6 +112,16 @@ struct HotRodURI { if (c >= 'a' && c <= 'f') return c - 'a' + 10; return c - 'A' + 10; // caller validated with std::isxdigit } + + /** Parse a strict boolean query value. "true"/"false" (case-insensitive) only; + * anything else throws (fail-fast, rather than Java's lenient parseBoolean). */ + static bool parseBool(const std::string& value, const char* what) { + const std::string v = toLower(value); + if (v == "true") return true; + if (v == "false") return false; + fail(std::string("invalid ") + what + " value '" + value + + "' (expected true or false)"); + } }; inline HotRodURI HotRodURI::parse(const std::string& uri) { @@ -117,10 +131,8 @@ inline HotRodURI HotRodURI::parse(const std::string& uri) { fail("not a Hot Rod URI (missing scheme): " + uri); } const std::string scheme = toLower(uri.substr(0, schemeEnd)); - if (scheme == "hotrods") { - fail("hotrods:// (TLS) is not supported"); - } - if (scheme != "hotrod") { + const bool ssl = (scheme == "hotrods"); + if (!ssl && scheme != "hotrod") { fail("not a Hot Rod URI (unsupported scheme '" + scheme + "')"); } @@ -206,6 +218,10 @@ inline HotRodURI HotRodURI::parse(const std::string& uri) { } // --- query parameters (typed whitelist; throw on unknown key / bad value) --- + // TLS fields accumulate here; finalized into result.tls after the loop so a + // "requires hotrods://" check can see both the scheme and any TLS params. + TlsConfig tls; + bool sawTlsParam = false; if (!query.empty()) { size_t qpos = 0; while (qpos <= query.size()) { @@ -249,6 +265,29 @@ inline HotRodURI HotRodURI::parse(const std::string& uri) { fail("unsupported protocol_version '" + value + "' (supported: 4.0, 4.1)"); } + } else if (key == "trust_store_file_name") { + // PEM CA file for server verification (issue #18). We diverge + // from Java (which reads a JKS/PKCS12 keystore) by requiring PEM. + tls.ca_file = value; + sawTlsParam = true; + } else if (key == "sni_host_name") { + tls.sni_host = value; + sawTlsParam = true; + } else if (key == "ssl_hostname_validation") { + tls.hostname_validation = parseBool(value, "ssl_hostname_validation"); + sawTlsParam = true; + } else if (key == "use_ssl" || key == "trust_store_type" || + key == "trust_store_password" || key == "key_store_file_name" || + key == "key_store_type" || key == "key_store_password" || + key == "key_alias" || key == "ssl_protocol" || + key == "ssl_ciphers" || key == "ssl_named_groups" || + key == "ssl_provider" || key == "ssl_context") { + // Recognized Java TLS keys that this slice does not implement: + // mutual TLS, keystore formats, and protocol/cipher tuning are + // deferred (issue #10). Reject explicitly rather than silently. + fail("Hot Rod URI parameter '" + key + + "' is not supported yet (mutual TLS / keystore TLS / " + "cipher tuning are deferred; issue #10)"); } else { fail("unsupported Hot Rod URI parameter: " + key); } @@ -258,6 +297,17 @@ inline HotRodURI HotRodURI::parse(const std::string& uri) { } } + // --- finalize TLS --- + // TLS params only make sense with the hotrods:// scheme; a plain hotrod:// URI + // carrying them is a configuration error, not silently ignored. + if (sawTlsParam && !ssl) { + fail("TLS parameters require the hotrods:// scheme"); + } + if (ssl) { + tls.enabled = true; + result.tls = tls; + } + return result; } diff --git a/include/hotrod/MultiplexedConnection.h b/include/hotrod/MultiplexedConnection.h index 3632e00..422b98b 100644 --- a/include/hotrod/MultiplexedConnection.h +++ b/include/hotrod/MultiplexedConnection.h @@ -4,6 +4,7 @@ #include "TopologyInfo.h" #include "HeaderCodec.h" #include "Authentication.h" +#include "TlsConfig.h" #include #include #include @@ -149,6 +150,13 @@ class MultiplexedConnection { */ void setAuthentication(const Authentication& auth); + /** + * Set TLS transport configuration. + * Must be called before connect(). When tls.enabled is true, connect() wraps + * the socket in a TLS session before the SASL handshake and read loop. + */ + void setTls(const TlsConfig& tls); + /** * Get current topology ID. */ @@ -189,6 +197,9 @@ class MultiplexedConnection { // SASL authentication (disabled by default). Applied during connect(). Authentication auth_; + // TLS transport (disabled by default). Applied to the socket during connect(). + TlsConfig tls_; + /** * Read loop (runs in dedicated thread). * Continuously reads responses and dispatches to waiters. diff --git a/include/hotrod/RemoteCache.h b/include/hotrod/RemoteCache.h index 7544e49..a0e4cca 100644 --- a/include/hotrod/RemoteCache.h +++ b/include/hotrod/RemoteCache.h @@ -7,6 +7,7 @@ #include "ConsistentHash.h" #include "RetryContext.h" #include "Authentication.h" +#include "TlsConfig.h" #include #include #include @@ -384,6 +385,44 @@ class RemoteCache { return auth_; } + /** + * Configure TLS transport encryption. Must be called before connect(). + * + * Enables TLS on every connection the client opens (the seed connection and + * every topology-discovered cluster member). This first slice is + * server-authenticated TLS with PEM trust material; mutual TLS is not yet + * supported (issue #10). See TlsConfig for field semantics. + * + * @param ca_file PEM CA file to verify the server; empty uses the + * system/default trust store. + * @param sni_host SNI server name; empty derives it from the host + * (and is skipped for literal IP addresses). + * @param hostname_validation verify the certificate matches the host name + * (default true; chain verification is always on). + */ + void setTls(const std::string& ca_file = "", + const std::string& sni_host = "", + bool hostname_validation = true) { + tls_.enabled = true; + tls_.ca_file = ca_file; + tls_.sni_host = sni_host; + tls_.hostname_validation = hostname_validation; + } + + /** + * Configure TLS from a prebuilt TlsConfig. Must be called before connect(). + */ + void setTls(const TlsConfig& tls) { + tls_ = tls; + } + + /** + * Current TLS configuration (tls_.enabled is false by default). + */ + const TlsConfig& getTls() const { + return tls_; + } + /** * Control non-owner proxy fallback for hash-aware routing (Step 11b, D5). * @@ -516,6 +555,7 @@ class RemoteCache { // a connection via a seed. Guarded by stateMutex_ (issue #12). bool active_ = false; Authentication auth_; // SASL auth config (disabled by default); applied at connect() + TlsConfig tls_; // TLS transport config (disabled by default); applied at connect() // stateMutex_ guards the routing/pool state below (topology_, consistentHash_, // connectionPool_) against concurrent access by the read-loop thread (topology diff --git a/include/hotrod/TlsConfig.h b/include/hotrod/TlsConfig.h new file mode 100644 index 0000000..7978ab7 --- /dev/null +++ b/include/hotrod/TlsConfig.h @@ -0,0 +1,45 @@ +#pragma once + +#include + +namespace hotrod { + +/** + * TLS transport configuration for a client connection (issue #18, sub-issue of #10). + * + * Pure data, applied before connect(). When `enabled` is true the client wraps + * every socket it opens — the seed connection and every topology-discovered + * cluster member — in a TLS session (OpenSSL) before the connection is used for + * operations. + * + * This first slice is *server-authenticated* TLS only: the client verifies the + * server's certificate chain, but does not present a client certificate (mutual + * TLS is deferred — see issue #10). Certificate material is PEM, loaded directly + * by OpenSSL; Java keystore formats (JKS/PKCS12) are intentionally not supported + * for this native/OpenSSL client (see docs/DECISIONS.md). + * + * Fields: + * - ca_file: path to a PEM file holding the trusted CA certificate(s) used to + * verify the server. Empty means "use OpenSSL's default/system trust store" + * (SSL_CTX_set_default_verify_paths), which is correct for servers whose + * certificates chain to a publicly trusted CA. + * - sni_host: the SNI server name sent in the handshake. Empty means "derive + * from the connection host" (and skip SNI entirely when the host is a literal + * IP address, per RFC 6066 — SNI carries host names, not addresses). + * - hostname_validation: when true (the default, matching the Java client) the + * server certificate must match the connection host name. When false only the + * certificate *chain* is verified, not the host name — chain verification is + * always on; this toggle governs the host-name match alone. + * + * Reference: + * - Java: org.infinispan.client.hotrod.configuration.SslConfiguration + * (hostnameValidation default true; sniHostName; trustStore*). + */ +struct TlsConfig { + bool enabled = false; + std::string ca_file; // PEM; empty = system trust store + std::string sni_host; // empty = derive from host (skip for IPs) + bool hostname_validation = true; // Java's default +}; + +} // namespace hotrod diff --git a/src/operations/RemoteCache.cpp b/src/operations/RemoteCache.cpp index 0c2b427..756a64d 100644 --- a/src/operations/RemoteCache.cpp +++ b/src/operations/RemoteCache.cpp @@ -95,6 +95,14 @@ namespace hotrod } } + // TLS: the hotrods:// scheme enables it; the server-auth PEM subset of the + // Java query keys (trust_store_file_name / sni_host_name / + // ssl_hostname_validation) is carried in parsed.tls (issue #18). + if (parsed.tls) + { + cache->setTls(*parsed.tls); + } + return cache; } @@ -121,6 +129,7 @@ namespace hotrod candidate->setProtocolVersion(protocolVersion_); candidate->setClientIntelligence(clientIntelligence_); candidate->setAuthentication(auth_); + candidate->setTls(tls_); try { candidate->connect(); @@ -1270,6 +1279,7 @@ namespace hotrod newConnection->setProtocolVersion(protocolVersion_); newConnection->setClientIntelligence(clientIntelligence_); newConnection->setAuthentication(auth_); + newConnection->setTls(tls_); // connect() can throw if server is unreachable - let it propagate to caller newConnection->connect(); diff --git a/src/transport/Connection.cpp b/src/transport/Connection.cpp index 7175d6a..513e671 100644 --- a/src/transport/Connection.cpp +++ b/src/transport/Connection.cpp @@ -1,6 +1,11 @@ #include "hotrod/Connection.h" #include #include +#include + +#include +#include +#include // Platform-specific includes #ifdef _WIN32 @@ -20,6 +25,32 @@ namespace hotrod { +namespace { + +// Drain the OpenSSL error queue into a human-readable string for exceptions. +std::string opensslErrors() { + std::string out; + unsigned long e; + char buf[256]; + while ((e = ERR_get_error()) != 0) { + ERR_error_string_n(e, buf, sizeof(buf)); + if (!out.empty()) out += "; "; + out += buf; + } + return out.empty() ? "unknown OpenSSL error" : out; +} + +// True when host is a literal IPv4 or IPv6 address. SNI (RFC 6066) carries host +// names only, so for a literal IP we neither send SNI nor use it for the +// certificate host-name match (which would be a DNS-name check). +bool isLiteralIp(const std::string& host) { + unsigned char buf[16]; + return inet_pton(AF_INET, host.c_str(), buf) == 1 || + inet_pton(AF_INET6, host.c_str(), buf) == 1; +} + +} // namespace + // Platform-specific initialization #ifdef _WIN32 struct WinsockInitializer { @@ -154,6 +185,95 @@ void Connection::connect() { if (!connected_) { throw std::runtime_error("Failed to connect to " + host_ + ":" + std::to_string(port_)); } + + // TLS handshake over the connected socket. On failure the socket is closed so + // the Connection is left in a clean, unconnected state. + if (tls_.enabled) { + try { + startTls(); + } catch (...) { + close(); + throw; + } + } +} + +void Connection::startTls() { + // Client context. TLS_client_method() negotiates the highest mutually + // supported protocol; we additionally pin a sane floor of TLS 1.2. + ctx_ = SSL_CTX_new(TLS_client_method()); + if (!ctx_) { + throw std::runtime_error("TLS: SSL_CTX_new failed: " + opensslErrors()); + } + SSL_CTX_set_min_proto_version(ctx_, TLS1_2_VERSION); + + // Trust anchors: an explicit PEM CA file, otherwise the system default store. + if (!tls_.ca_file.empty()) { + if (SSL_CTX_load_verify_locations(ctx_, tls_.ca_file.c_str(), nullptr) != 1) { + throw std::runtime_error("TLS: failed to load CA file '" + tls_.ca_file + + "': " + opensslErrors()); + } + } else { + if (SSL_CTX_set_default_verify_paths(ctx_) != 1) { + throw std::runtime_error("TLS: failed to load system trust store: " + + opensslErrors()); + } + } + + // Always verify the server's certificate chain. The hostname match below is + // separately controlled by tls_.hostname_validation. + SSL_CTX_set_verify(ctx_, SSL_VERIFY_PEER, nullptr); + + ssl_ = SSL_new(ctx_); + if (!ssl_) { + throw std::runtime_error("TLS: SSL_new failed: " + opensslErrors()); + } + + // The SNI name / host-name to validate: an explicit override, else the + // connection host (never a literal IP). + const std::string serverName = + !tls_.sni_host.empty() ? tls_.sni_host : host_; + const bool nameIsIp = isLiteralIp(serverName); + + // SNI (skipped for literal IPs per RFC 6066). + if (!nameIsIp) { + // SSL_set_tlsext_host_name takes a non-const char*; the string is copied. + if (SSL_set_tlsext_host_name(ssl_, serverName.c_str()) != 1) { + throw std::runtime_error("TLS: failed to set SNI host name: " + + opensslErrors()); + } + } + + // Host-name validation. SSL_set1_host makes OpenSSL enforce the match as part + // of chain verification; omitting it leaves only chain verification on. We do + // not validate a literal IP as a DNS name. + if (tls_.hostname_validation && !nameIsIp) { + SSL_set_hostflags(ssl_, X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS); + if (SSL_set1_host(ssl_, serverName.c_str()) != 1) { + throw std::runtime_error("TLS: failed to set validation host name: " + + opensslErrors()); + } + } + + if (SSL_set_fd(ssl_, static_cast(socket_)) != 1) { + throw std::runtime_error("TLS: SSL_set_fd failed: " + opensslErrors()); + } + + const int rc = SSL_connect(ssl_); + if (rc != 1) { + // A verification failure surfaces a specific, actionable reason. + const long vr = SSL_get_verify_result(ssl_); + std::string msg = "TLS handshake with " + host_ + ":" + + std::to_string(port_) + " failed"; + if (vr != X509_V_OK) { + msg += ": certificate verification failed ("; + msg += X509_verify_cert_error_string(vr); + msg += ")"; + } else { + msg += ": " + opensslErrors(); + } + throw std::runtime_error(msg); + } } void Connection::send(const ByteArray& data) { @@ -166,6 +286,15 @@ void Connection::send(const ByteArray& data) { const char* ptr = reinterpret_cast(data.data()) + totalSent; size_t remaining = data.size() - totalSent; + if (ssl_) { + int sent = SSL_write(ssl_, ptr, static_cast(remaining)); + if (sent <= 0) { + throw std::runtime_error("TLS send failed: " + opensslErrors()); + } + totalSent += static_cast(sent); + continue; + } + #ifdef _WIN32 int sent = ::send(socket_, ptr, static_cast(remaining), 0); if (sent == SOCKET_ERROR) { @@ -194,6 +323,19 @@ ByteArray Connection::receive(size_t length) { char* ptr = reinterpret_cast(buffer.data()) + totalReceived; size_t remaining = length - totalReceived; + if (ssl_) { + int received = SSL_read(ssl_, ptr, static_cast(remaining)); + if (received <= 0) { + const int err = SSL_get_error(ssl_, received); + if (err == SSL_ERROR_ZERO_RETURN) { + throw std::runtime_error("Connection closed by peer"); + } + throw std::runtime_error("TLS recv failed: " + opensslErrors()); + } + totalReceived += static_cast(received); + continue; + } + #ifdef _WIN32 int received = ::recv(socket_, ptr, static_cast(remaining), 0); if (received == SOCKET_ERROR) { @@ -231,7 +373,30 @@ void Connection::shutdown() { } void Connection::close() { + // Tear down TLS first, independent of connected_ so a failed handshake in + // connect() still frees the context it allocated. Quiet shutdown skips the + // close_notify write: if the peer has already gone, writing it would raise + // SIGPIPE/EPIPE and kill the process for no benefit during teardown. + if (ssl_) { + SSL_set_quiet_shutdown(ssl_, 1); + SSL_shutdown(ssl_); + SSL_free(ssl_); + ssl_ = nullptr; + } + if (ctx_) { + SSL_CTX_free(ctx_); + ctx_ = nullptr; + } + if (!connected_) { + if (socket_ != INVALID_SOCK) { +#ifdef _WIN32 + closesocket(socket_); +#else + ::close(socket_); +#endif + socket_ = INVALID_SOCK; + } return; } diff --git a/src/transport/MultiplexedConnection.cpp b/src/transport/MultiplexedConnection.cpp index 03caf4b..1fe1495 100644 --- a/src/transport/MultiplexedConnection.cpp +++ b/src/transport/MultiplexedConnection.cpp @@ -28,8 +28,10 @@ void MultiplexedConnection::connect() { throw std::runtime_error("Already connected"); } - // Create underlying TCP connection + // Create underlying TCP connection. TLS (when enabled) is negotiated inside + // Connection::connect(), so the SASL handshake below already runs encrypted. connection_ = std::make_unique(host_, port_); + connection_->setTls(tls_); connection_->connect(); // SASL handshake (synchronous, before the read thread consumes any bytes). @@ -107,6 +109,13 @@ void MultiplexedConnection::setAuthentication(const Authentication& auth) { auth_ = auth; } +void MultiplexedConnection::setTls(const TlsConfig& tls) { + if (connected_) { + throw std::runtime_error("Cannot change TLS configuration after connect()"); + } + tls_ = tls; +} + int32_t MultiplexedConnection::getTopologyId() const { return topologyId_.load(); } diff --git a/tests/fixtures/tls/ca.pem b/tests/fixtures/tls/ca.pem new file mode 100644 index 0000000..45f4334 --- /dev/null +++ b/tests/fixtures/tls/ca.pem @@ -0,0 +1,19 @@ +-----BEGIN CERTIFICATE----- +MIIDETCCAfmgAwIBAgIUSqD1fkqCqt0Jq309wy5UbsHrQMgwDQYJKoZIhvcNAQEL +BQAwFzEVMBMGA1UEAwwMVGVzdCBSb290IENBMCAXDTI2MTEwNjE3MDgyNloYDzIx +MjYxMDEzMTcwODI2WjAXMRUwEwYDVQQDDAxUZXN0IFJvb3QgQ0EwggEiMA0GCSqG +SIb3DQEBAQUAA4IBDwAwggEKAoIBAQC/l719m2EEJ8LaAqZcG2dd/CBQXL+apJid +nvTAsJZeS2mO1q44O03HULW6vPv4yYkP2AGd+CLkolCO2jXqr82Gi9jM9n87Gsbp +R2i2CQP90RNhIIurzN7IBNl2ehj5Y2RFmqDNyEdDCZmGv5Ep10HnB2wUAfPo5vXz +l2GY8ZBiPEzgXM34fO45rSfnmLbpEn1xU0spRwtD2vhCzrqg/u4aMC7xyPkhQCg7 +7Tr1j3iWcZ1Wjxns+rWR/2+pylpyleLgc0j+QJJklpYfHbCaoz5gfsv9wGdhrg2l +A7xrtK0WcwmyD676Rhz9WwPE3ucxCJcOX0PYTYtzkg0WEhRZGsSvAgMBAAGjUzBR +MB0GA1UdDgQWBBSj7I5zU9GLKNmQ/nPBukMaqttjITAfBgNVHSMEGDAWgBSj7I5z +U9GLKNmQ/nPBukMaqttjITAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBCwUA +A4IBAQBoeQrvRD7hbpCIsczJyRaKa1WxCDZLw+D+vlT1XLW9IlkRZv4b3G0DpS8T +uCHH9AzbsPQmUT0s8adeFuze96E6zCWlM/bGPkFMAtudJ45A5oQPaT4Kxh5T9Ls3 +DTwpVLTrhfd7QLuU3brjbN9aONam+p5xtq5a/UcQDDgo8Eiy3+yTyBCT9ha6IVXd +/dy35a/NT+44FXMoxK1x8E5dAUgO1IzZo05LZfrhLoc4ye97viVlJJD6yRlrpfBT +yUoFnGOSeFPyRrVLPcwfCXywduFVC8UA2h/poZn13R0105ax74M53+TN1Evd8H0x +WF2IKUgs2rT0V0ymLDLXHPJnFViY +-----END CERTIFICATE----- diff --git a/tests/fixtures/tls/otherca.pem b/tests/fixtures/tls/otherca.pem new file mode 100644 index 0000000..7f707e4 --- /dev/null +++ b/tests/fixtures/tls/otherca.pem @@ -0,0 +1,19 @@ +-----BEGIN CERTIFICATE----- +MIIDEzCCAfugAwIBAgIUaJwJ10wPitjs0QwChJ63XAzsfDcwDQYJKoZIhvcNAQEL +BQAwGDEWMBQGA1UEAwwNT3RoZXIgUm9vdCBDQTAgFw0yNjExMDYxNzA4MjZaGA8y +MTI2MTAxMzE3MDgyNlowGDEWMBQGA1UEAwwNT3RoZXIgUm9vdCBDQTCCASIwDQYJ +KoZIhvcNAQEBBQADggEPADCCAQoCggEBAKwmv+Aps451KEi/4GwrMXXFjK2V8kcy +I+XyS2guZzl+l++2WQLfKTKdfD/gM97JpZHmiU3qznVswsjdaG+I2zFcibYqRg48 +z7fmfvOxDrvCdxZVVGn662on2KwgeJjGcFLYjlho1/kX+ZRvJ3o7HQePtzeamNm+ +UWt5ftPjasuRuVh4myUZYE9tDO0YEKdfVUZLGMVZd1IbDLCVusk4o6rn9Hj1vQfb +Y5rCG6iLE+hn4RKloSbRB1rwauQoGwPAI3MbUVP93QYF9bfs82fRQGocYGys5qxK +sLT7uf4AET0W0JrLXLiI1lP1+fk3eJ9ShicAznCvhsY9f5SNh8eaoYkCAwEAAaNT +MFEwHQYDVR0OBBYEFCoViVwLfQKUyvdpJSSm020VTiEUMB8GA1UdIwQYMBaAFCoV +iVwLfQKUyvdpJSSm020VTiEUMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQEL +BQADggEBADQiKnc5vc2Kp2YEyMICBXeYuiGc3RooazOcZ/T+4CdknvK5byvyPZpZ +2+s8woic9+rPHekm+myhe0xqvceAhNNlPz//7S1daqt4IDP+B5S2lHrqbhgFsBSn +esqCi6ma/qauUxJ+SE92wfOWTTHf9VKm0OJfRyIzITqNCuzA3NzxySuIrzuEhS5L +obwelInmSSfGzHuR0A/P9FQQzUbvYZOaz8L6TAl65/2obDj3XPPmkuKHyiYBdFyB +1egBFkbg9/kQA/xicREA/6AUAVj4mla7zP5uhS6i05XFMUsLu7o4R+gBkg+h1eJ/ +oQfXh9RuyML3pN8H89pKYb7exFgtTSE= +-----END CERTIFICATE----- diff --git a/tests/fixtures/tls/server.key b/tests/fixtures/tls/server.key new file mode 100644 index 0000000..8d44e32 --- /dev/null +++ b/tests/fixtures/tls/server.key @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCsy8U/EoWrtKse +frvndLb3zPfQtLkXKkG9IfMXPL0vHWxmma1O2/eiDVkWlpgtqr2QgOk5vIQVfm1l +GzOYL0a0zUZk3K1KhI3YL+i4DhxMlmD66tNYJpiybPJempUs2a4lEFJ6Fq2xHq26 +zqEKhzrUh8fx4VD39GZJRfHG9cxJ/hrYoiwkFNgyZDbo3Q9P/yL5MLJzyucwh8ep +xPsYdMBOmRwGrp5kreuFQzLYco24q1No5OtSTmNahxmo6Wux0OkyEgdXXxg6Ip0V +GJa3Zuc5i3DsvVnd/jt0Ab4JrbQ48bcw4KFuzzsX+u9FmQ8B+W0qLEWctcEX8/sV +b1qXV0PfAgMBAAECggEAGPjnVrLXPUts94lFSrFOyAfdQKeoSuAWhBOQotO/sObF +sHDr37EL3BBQcbft4kZXWGI+Un5wxafHKOIs1gTvE64e9ZtW3VAZgnGEu89+PitK +yg3UjAbNRpasKF6aydKOcljQ3UgYbg01pQEREQkeHXJKGSYroh9gsPI6JjuGUfhO +cO9b5b/Ag70vYJObYLVIp2ZoVLRoU2PdY416XhrtJWM50bqtmhfXBXM6/GaJju/F +AqWmv4ma27DASxjuGDkIQLwm6/Mns3iu8pfKrBjTja6OdG+pVjGdFHp0diQV81dl +UquCyIz72DKGZkAUZtLl2ER1FKGzO2o7Vffai2XGMQKBgQD0RJ5kmuU1unldxc8V +e/13e3nwrWU71Lfp8DBKZfVUUssJnuc34Nwx7RN6g23zAZsHyOgksZXB6cJG6hqc +8k7mT/RazGhXHDZsNrghcIkiu/tvqMvdIz5eyFVJISHjJOXxXu/uUNYU0RgEJgic +fqJorLvLBkC9y+LzRJDAFiKLTQKBgQC1GF8v0dAyh0KJMRnerr4mncuqpOpV5g0A +pN8KOnROXpOe6Xfho0vGiJMsuoiUJvtJTqYC5/73nBkHHQ068NUMnrZ8oHV1GDfX +sVg5otBxVfQCHxvWtCWQgCbRebHaWw9EvwP1hDiRFNGfL+UQ998d/eihjVF26i6m +5xv2nxv92wKBgAMyqsgyZvHPISujHVTwrJ7V1QDbpEmmPUooxNkUgKO7+cCEfg5z +OS7GJc0iz1uxF7CAZtmkIYvKXarEAdkwKuxE+7P8nRkW23eLN9noOUNlJqONmC2q ++nQPN16fumvY3dHNJmL+V+8p1aCoRtCVr9ai/EpqKIrTkoMQ0LxTDdy5AoGAWnJd +uCh2b4YWuSaI4SstVWQiQIw1bcmEXPn7W8RuKmYaHJhGg69nPTUhLInNhREjGC3r +xC/SrCCOb3sXDIUUI0VxpzUM9PqviU7N3Ztvt+tR/21CHi3DRTR8Lss1BPXN3mv4 +sjrjdbKML5FgOuVRzkzuTyGhul6kBkAPO1GkTVkCgYEA4VaEc2D61hO/t00ydSLk +eXotSe2IcPGw3b4DX94OCIDRlP4SoqdTf0pDCzPcNVdJviAton2nJZjG6hGCeoYF +nYraPPuDwxNh6aOuT5IVT+g5eTXbmeBOmvyaYEh6+AHlV91pjEp16Uk6vQln0raa +qL5e/80gVUpGO93VAeAw9so= +-----END PRIVATE KEY----- diff --git a/tests/fixtures/tls/server.pem b/tests/fixtures/tls/server.pem new file mode 100644 index 0000000..520b2fb --- /dev/null +++ b/tests/fixtures/tls/server.pem @@ -0,0 +1,19 @@ +-----BEGIN CERTIFICATE----- +MIIDFTCCAf2gAwIBAgIUPpkwaAde1sINI0fQKbksa4RlKtEwDQYJKoZIhvcNAQEL +BQAwFzEVMBMGA1UEAwwMVGVzdCBSb290IENBMCAXDTI2MTEwNjE3MDgyNloYDzIx +MjYxMDEzMTcwODI2WjAVMRMwEQYDVQQDDAp0ZXN0LmxvY2FsMIIBIjANBgkqhkiG +9w0BAQEFAAOCAQ8AMIIBCgKCAQEArMvFPxKFq7SrHn6753S298z30LS5FypBvSHz +Fzy9Lx1sZpmtTtv3og1ZFpaYLaq9kIDpObyEFX5tZRszmC9GtM1GZNytSoSN2C/o +uA4cTJZg+urTWCaYsmzyXpqVLNmuJRBSehatsR6tus6hCoc61IfH8eFQ9/RmSUXx +xvXMSf4a2KIsJBTYMmQ26N0PT/8i+TCyc8rnMIfHqcT7GHTATpkcBq6eZK3rhUMy +2HKNuKtTaOTrUk5jWocZqOlrsdDpMhIHV18YOiKdFRiWt2bnOYtw7L1Z3f47dAG+ +Ca20OPG3MOChbs87F/rvRZkPAfltKixFnLXBF/P7FW9al1dD3wIDAQABo1kwVzAV +BgNVHREEDjAMggp0ZXN0LmxvY2FsMB0GA1UdDgQWBBQtAZ6wJNzLy6/+idjHvPja +6ENvAjAfBgNVHSMEGDAWgBSj7I5zU9GLKNmQ/nPBukMaqttjITANBgkqhkiG9w0B +AQsFAAOCAQEAhV0qp6X4T0gC+0SpL54VGljJZUVOfIyFPpUTPgxgTTk32niaX7rP +PTWyMsUiYfJHjf2YBgMQuJG//JaK1aOfKhg2andO4SyMv47fIul0lSF0NnUcnxDq +/qzgaF5Hb8hQ3M6JC76G0kHZZKHCPiaF9M68IfRzBEXfC8z5glOeQBOWBoCvJOL3 +GBFAhdRsoT3qQiBD059T7NbTHcJjRCD+OjCzl3fwj82unOrO8vVZMTh7gH1M1Ri8 +ct9VK44XsS98yWE2Vg/syD2R4sUyFfmHVS7RKLBWLAyZQ5cHpWDZeoj5bT+i3C4u +bZ2jOsMZSLLs7zBW1gXKA+sKpOXSOVSMvQ== +-----END CERTIFICATE----- diff --git a/tests/unit/HotRodURITest.cpp b/tests/unit/HotRodURITest.cpp index 45411fb..ef18e54 100644 --- a/tests/unit/HotRodURITest.cpp +++ b/tests/unit/HotRodURITest.cpp @@ -181,17 +181,84 @@ TEST(HotRodURITest, QueryParamMissingEqualsThrows) { // --- rejections: unsupported / deferred features (issue #10) ----------------- -TEST(HotRodURITest, HotRodsSchemeThrows) { - EXPECT_THROW(HotRodURI::parse("hotrods://localhost:11222"), HotRodClientException); -} - TEST(HotRodURITest, UnknownParamThrows) { EXPECT_THROW(HotRodURI::parse("hotrod://h?connect_timeout=5000"), HotRodClientException); EXPECT_THROW(HotRodURI::parse("hotrod://h?socket_timeout=5000"), HotRodClientException); - EXPECT_THROW(HotRodURI::parse("hotrod://h?use_ssl=true"), HotRodClientException); EXPECT_THROW(HotRodURI::parse("hotrod://h?token=abc"), HotRodClientException); } +// --- TLS: hotrods:// scheme + server-auth PEM subset (issue #18) ------------- + +TEST(HotRodURITest, HotRodsSchemeEnablesTlsWithDefaults) { + HotRodURI u = HotRodURI::parse("hotrods://localhost:11222"); + ASSERT_TRUE(u.tls.has_value()); + EXPECT_TRUE(u.tls->enabled); + EXPECT_TRUE(u.tls->ca_file.empty()); // system/default trust store + EXPECT_TRUE(u.tls->sni_host.empty()); // derived from host at connect + EXPECT_TRUE(u.tls->hostname_validation); // Java default + // Host/port still parse as usual. + EXPECT_EQ(u.seed().host, "localhost"); + EXPECT_EQ(u.seed().port, 11222); +} + +TEST(HotRodURITest, PlainSchemeHasNoTls) { + HotRodURI u = HotRodURI::parse("hotrod://localhost"); + EXPECT_FALSE(u.tls.has_value()); +} + +TEST(HotRodURITest, TlsParamsParsedIntoConfig) { + HotRodURI u = HotRodURI::parse( + "hotrods://localhost" + "?trust_store_file_name=/etc/pki/ca.pem" + "&sni_host_name=cache.example.com" + "&ssl_hostname_validation=false"); + ASSERT_TRUE(u.tls.has_value()); + EXPECT_TRUE(u.tls->enabled); + EXPECT_EQ(u.tls->ca_file, "/etc/pki/ca.pem"); + EXPECT_EQ(u.tls->sni_host, "cache.example.com"); + EXPECT_FALSE(u.tls->hostname_validation); +} + +TEST(HotRodURITest, TlsHostnameValidationBooleanCaseInsensitive) { + EXPECT_TRUE(HotRodURI::parse( + "hotrods://h?ssl_hostname_validation=TRUE").tls->hostname_validation); + EXPECT_FALSE(HotRodURI::parse( + "hotrods://h?ssl_hostname_validation=False").tls->hostname_validation); +} + +TEST(HotRodURITest, TlsHostnameValidationBadBooleanThrows) { + EXPECT_THROW(HotRodURI::parse("hotrods://h?ssl_hostname_validation=yes"), + HotRodClientException); +} + +TEST(HotRodURITest, TlsParamsOnPlainSchemeThrow) { + // TLS params require hotrods://; silently ignoring them would hide a mistake. + EXPECT_THROW(HotRodURI::parse("hotrod://h?sni_host_name=x"), HotRodClientException); + EXPECT_THROW(HotRodURI::parse("hotrod://h?trust_store_file_name=/ca.pem"), + HotRodClientException); +} + +TEST(HotRodURITest, DeferredTlsKeysThrow) { + // Recognized Java TLS keys we do not implement in this slice (mutual TLS, + // keystore formats, cipher/protocol tuning) are rejected, not ignored. + for (const char* uri : { + "hotrods://h?use_ssl=true", + "hotrods://h?trust_store_type=pkcs12", + "hotrods://h?trust_store_password=secret", + "hotrods://h?key_store_file_name=/client.p12", + "hotrods://h?key_store_type=pkcs12", + "hotrods://h?key_store_password=secret", + "hotrods://h?key_alias=client", + "hotrods://h?ssl_protocol=TLSv1.3", + "hotrods://h?ssl_ciphers=TLS_AES_256_GCM_SHA384", + "hotrods://h?ssl_named_groups=x25519", + "hotrods://h?ssl_provider=openssl", + "hotrods://h?ssl_context=ctx", + }) { + EXPECT_THROW(HotRodURI::parse(uri), HotRodClientException) << uri; + } +} + TEST(HotRodURITest, UnsupportedProtocolVersionThrows) { EXPECT_THROW(HotRodURI::parse("hotrod://h?protocol_version=AUTO"), HotRodClientException); EXPECT_THROW(HotRodURI::parse("hotrod://h?protocol_version=3.1"), HotRodClientException); @@ -204,7 +271,7 @@ TEST(HotRodURITest, BadClientIntelligenceValueThrows) { // The parse error is surfaced as a BeforeSend failure (nothing was sent). TEST(HotRodURITest, ParseErrorIsBeforeSend) { try { - HotRodURI::parse("hotrods://localhost"); + HotRodURI::parse("hotrod://h?connect_timeout=5000"); FAIL() << "expected throw"; } catch (const HotRodClientException& e) { EXPECT_EQ(e.phase, FailurePhase::BeforeSend); diff --git a/tests/unit/TlsConnectionTest.cpp b/tests/unit/TlsConnectionTest.cpp new file mode 100644 index 0000000..990c88c --- /dev/null +++ b/tests/unit/TlsConnectionTest.cpp @@ -0,0 +1,209 @@ +/** + * Unit tests for server-authenticated TLS on the transport (Connection), issue #18. + * + * These exercise the real OpenSSL handshake end-to-end against an in-process TLS + * server that presents a PEM leaf certificate (SAN=test.local) signed by a test + * CA. The client (hotrod::Connection) connects over loopback and verifies the + * server against a PEM trust anchor, mirroring how MultiplexedConnection drives + * it in production. + * + * Coverage: + * - Trusted CA + matching host name -> handshake succeeds; encrypted data + * round-trips through SSL_read/SSL_write. + * - Untrusted CA (wrong trust anchor) -> handshake throws (chain verification). + * - Host-name mismatch with validation on -> throws. + * - Host-name mismatch with validation off -> succeeds (chain still verified). + * + * The socket server half uses POSIX sockets, so (like this repo's integration + * tests) the meaningful body is compiled on non-Windows only. The cross-platform + * URI-level TLS parsing is covered separately in HotRodURITest.cpp. + */ +#include + +#ifndef _WIN32 + +#include "hotrod/Connection.h" +#include "hotrod/TlsConfig.h" + +#include +#include + +#include +#include +#include +#include + +#include +#include +#include +#include + +using namespace hotrod; + +namespace { + +// The in-process server thread writes a TLS close_notify on teardown; if the +// client fd is already closed this raises SIGPIPE, whose default action would +// kill the whole test process. Ignore it for the lifetime of these tests. +[[maybe_unused]] const bool kSigpipeIgnored = [] { + std::signal(SIGPIPE, SIG_IGN); + return true; +}(); + +std::string fixture(const char* name) { + return std::string(TLS_FIXTURE_DIR) + "/" + name; +} + +// Minimal in-process TLS server: binds an ephemeral loopback port, accepts one +// connection in a background thread, completes the TLS handshake, and echoes +// back whatever it reads until the client closes. Presents the given PEM leaf +// cert + key. Robust to clients that abort mid-handshake (failure-path tests). +class TlsEchoServer { +public: + TlsEchoServer(const std::string& certFile, const std::string& keyFile) { + ctx_ = SSL_CTX_new(TLS_server_method()); + if (!ctx_) throw std::runtime_error("server SSL_CTX_new failed"); + if (SSL_CTX_use_certificate_chain_file(ctx_, certFile.c_str()) != 1) + throw std::runtime_error("server cert load failed: " + certFile); + if (SSL_CTX_use_PrivateKey_file(ctx_, keyFile.c_str(), SSL_FILETYPE_PEM) != 1) + throw std::runtime_error("server key load failed: " + keyFile); + + listenFd_ = ::socket(AF_INET, SOCK_STREAM, 0); + if (listenFd_ < 0) throw std::runtime_error("server socket() failed"); + int one = 1; + ::setsockopt(listenFd_, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)); + + sockaddr_in addr{}; + addr.sin_family = AF_INET; + addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); + addr.sin_port = 0; // ephemeral + if (::bind(listenFd_, reinterpret_cast(&addr), sizeof(addr)) != 0) + throw std::runtime_error("server bind() failed"); + if (::listen(listenFd_, 1) != 0) + throw std::runtime_error("server listen() failed"); + + socklen_t len = sizeof(addr); + if (::getsockname(listenFd_, reinterpret_cast(&addr), &len) != 0) + throw std::runtime_error("server getsockname() failed"); + port_ = ntohs(addr.sin_port); + + thread_ = std::thread([this] { run(); }); + } + + ~TlsEchoServer() { stop(); } + + TlsEchoServer(const TlsEchoServer&) = delete; + TlsEchoServer& operator=(const TlsEchoServer&) = delete; + + uint16_t port() const { return port_; } + + void stop() { + if (stopped_.exchange(true)) return; + if (listenFd_ >= 0) { + ::shutdown(listenFd_, SHUT_RDWR); + ::close(listenFd_); + listenFd_ = -1; + } + if (thread_.joinable()) thread_.join(); + if (ctx_) { + SSL_CTX_free(ctx_); + ctx_ = nullptr; + } + } + +private: + void run() { + int fd = ::accept(listenFd_, nullptr, nullptr); + if (fd < 0) return; + + SSL* ssl = SSL_new(ctx_); + if (ssl) { + SSL_set_fd(ssl, fd); + if (SSL_accept(ssl) == 1) { + char buf[4096]; + for (;;) { + int n = SSL_read(ssl, buf, sizeof(buf)); + if (n <= 0) break; + if (SSL_write(ssl, buf, n) <= 0) break; + } + } + SSL_shutdown(ssl); + SSL_free(ssl); + } + ::close(fd); + } + + SSL_CTX* ctx_{nullptr}; + int listenFd_{-1}; + uint16_t port_{0}; + std::thread thread_; + std::atomic stopped_{false}; +}; + +// A Connection to the loopback server with the given trust/validation settings. +// Uses sni_host to drive the validated DNS name independently of the loopback +// IP we actually dial (a literal IP would skip SNI/host validation by design). +TlsConfig clientTls(const std::string& caFile, + const std::string& sniHost, + bool hostnameValidation) { + TlsConfig tls; + tls.enabled = true; + tls.ca_file = caFile; + tls.sni_host = sniHost; + tls.hostname_validation = hostnameValidation; + return tls; +} + +} // namespace + +TEST(TlsConnectionTest, TrustedCaMatchingHost_HandshakeSucceeds_DataRoundTrips) { + TlsEchoServer server(fixture("server.pem"), fixture("server.key")); + + Connection conn("127.0.0.1", server.port()); + conn.setTls(clientTls(fixture("ca.pem"), "test.local", true)); + ASSERT_NO_THROW(conn.connect()); + + const ByteArray msg{0xDE, 0xAD, 0xBE, 0xEF, 0x01}; + conn.send(msg); + const ByteArray echoed = conn.receive(msg.size()); + EXPECT_EQ(echoed, msg); + + conn.close(); + server.stop(); +} + +TEST(TlsConnectionTest, UntrustedCa_HandshakeThrows) { + TlsEchoServer server(fixture("server.pem"), fixture("server.key")); + + Connection conn("127.0.0.1", server.port()); + // Trust a different, unrelated CA -> chain verification must fail. + conn.setTls(clientTls(fixture("otherca.pem"), "test.local", true)); + EXPECT_THROW(conn.connect(), std::runtime_error); + + server.stop(); +} + +TEST(TlsConnectionTest, HostnameMismatch_ValidationOn_Throws) { + TlsEchoServer server(fixture("server.pem"), fixture("server.key")); + + Connection conn("127.0.0.1", server.port()); + // Cert SAN is test.local; validate against a different name -> reject. + conn.setTls(clientTls(fixture("ca.pem"), "wrong.local", true)); + EXPECT_THROW(conn.connect(), std::runtime_error); + + server.stop(); +} + +TEST(TlsConnectionTest, HostnameMismatch_ValidationOff_Succeeds) { + TlsEchoServer server(fixture("server.pem"), fixture("server.key")); + + Connection conn("127.0.0.1", server.port()); + // Name does not match, but validation is off; the chain is still verified. + conn.setTls(clientTls(fixture("ca.pem"), "wrong.local", false)); + ASSERT_NO_THROW(conn.connect()); + + conn.close(); + server.stop(); +} + +#endif // !_WIN32 From 7d39cfaac0b0f08ac449bb573177b57dde2839db Mon Sep 17 00:00:00 2001 From: rigazilla Date: Fri, 6 Nov 2026 18:30:27 +0100 Subject: [PATCH 2/6] test(tls): Docker integration suite for hotrods:// (issue #18) End-to-end coverage against a real TLS-enabled Infinispan, mirroring the auth suite. New test-configs/infinispan-tls.xml (Hot Rod endpoint with a PKCS12 server identity, no SASL), scripts/start_infinispan_tls.sh, and PEM/PKCS12 fixtures under test-configs/tls/ (CA + server cert, SAN localhost/127.0.0.1). TlsIntegrationTest cases (all green against :latest): - programmatic setTls(ca) -> connect + PUT/GET round-trip over TLS; - hotrods://?trust_store_file_name= -> same round-trip; - untrusted anchor (empty CA -> system store) -> connect() throws; - host-name mismatch: validation on -> throws; off -> round-trip (chain still verified). Notes captured in DECISIONS: the mounted keystore must be world-readable (the in-container user can't read a 0600 :ro mount), and keystore-password is deprecated in favor of password. Also surfaced a library-robustness follow-up: a dropped TLS connection can raise SIGPIPE on a client write; both test mains install SIG_IGN, and whether the library should be SIGPIPE-safe by default is left as an open item. Co-Authored-By: Claude Opus 4.8 --- CMakeLists.txt | 19 ++- docs/DECISIONS.md | 24 +++ docs/STATUS.md | 5 +- scripts/start_infinispan_tls.sh | 62 ++++++++ test-configs/infinispan-tls.xml | 65 ++++++++ test-configs/tls/ca.pem | 19 +++ test-configs/tls/server.p12 | Bin 0 -> 2624 bytes tests/integration/TlsIntegrationTest.cpp | 180 +++++++++++++++++++++++ 8 files changed, 372 insertions(+), 2 deletions(-) create mode 100755 scripts/start_infinispan_tls.sh create mode 100644 test-configs/infinispan-tls.xml create mode 100644 test-configs/tls/ca.pem create mode 100644 test-configs/tls/server.p12 create mode 100644 tests/integration/TlsIntegrationTest.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 88aa397..3633fc9 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -338,6 +338,18 @@ if(GTest_FOUND) # Note: NOT gtest_main - we provide our own main() ) + # Server-authenticated TLS integration tests (TLS-enabled single server, #18) + add_executable(tls_integration_tests + tests/integration/TlsIntegrationTest.cpp + ) + + target_link_libraries(tls_integration_tests + PRIVATE + hotrod-client + GTest::gtest + # Note: NOT gtest_main - we provide our own main() + ) + # SASL/SCRAM authentication integration tests (auth-enabled single server) add_executable(auth_integration_tests tests/integration/AuthIntegrationTest.cpp @@ -377,6 +389,7 @@ if(GTest_FOUND) add_test(NAME PingRetryIntegrationTests COMMAND pingretry_integration_tests) add_test(NAME MultiSeedIntegrationTests COMMAND multiseed_integration_tests) add_test(NAME AuthIntegrationTests COMMAND auth_integration_tests) + add_test(NAME TlsIntegrationTests COMMAND tls_integration_tests) # Set working directory so scripts can be found set_tests_properties(PingIntegrationTests PROPERTIES @@ -459,6 +472,10 @@ if(GTest_FOUND) WORKING_DIRECTORY ${CMAKE_BINARY_DIR} LABELS "integration;docker;auth" ) + set_tests_properties(TlsIntegrationTests PROPERTIES + WORKING_DIRECTORY ${CMAKE_BINARY_DIR} + LABELS "integration;docker;tls" + ) # Fail fast if a suite hangs (e.g. a server/CLI-version regression stalls a # subprocess) instead of letting one stuck test burn the whole CI job budget. @@ -470,7 +487,7 @@ if(GTest_FOUND) TopologyIntegrationTests ConcurrentClientsTests HashAwareRoutingIntegrationTests ConcurrentMultiServerTests RetryViewIntegrationTests PingRetryIntegrationTests MultiSeedIntegrationTests - AuthIntegrationTests + AuthIntegrationTests TlsIntegrationTests PROPERTIES TIMEOUT 300 ) endif() # NOT WIN32 (integration tests) diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index 122890a..54c47f9 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -1136,6 +1136,30 @@ Cases: trusted-CA + matching name → handshake + encrypted round-trip; untruste POSIX-only (like the integration suites); the cross-platform URI-level parsing is in `HotRodURITest.cpp`. Full unit suite green (260 tests), stable across repeated runs. +**Integration test (Docker):** `tests/integration/TlsIntegrationTest.cpp` + +`scripts/start_infinispan_tls.sh` + `test-configs/infinispan-tls.xml` run the full +parse→connect→PUT/GET chain over `hotrods://` against a real TLS-enabled Infinispan +(Hot Rod endpoint with a PKCS12 server identity, no SASL). Server cert +`test-configs/tls/server.p12` (alias `server`, SAN DNS:localhost / IP:127.0.0.1, +password `password`); client trusts `test-configs/tls/ca.pem`. Cases: programmatic +`setTls` round-trip, `hotrods://?trust_store_file_name=` round-trip, untrusted +anchor (empty CA → system store) rejected, host-name mismatch rejected / accepted +with validation off. Label `integration;docker;tls`, `TIMEOUT 300`. Two gotchas hit +while wiring it: the mounted keystore must be world-readable (the in-container user +can't read a 0600 `:ro` mount → `FileNotFoundException: … (Permission denied)`), and +`keystore-password` is deprecated in favor of `password` on the `` element. + +**SIGPIPE on a dropped TLS connection (library robustness).** The first integration +run was killed by SIGPIPE (exit 141): a client-side write onto a closed TLS peer +raises SIGPIPE, whose default disposition terminates the process. `close()`'s quiet +shutdown prevents the *teardown* write, but the data path can still trip it. Both +test mains (unit + integration) install `std::signal(SIGPIPE, SIG_IGN)` — the +conventional stance that the application owns signal disposition. **Open follow-up:** +decide whether the client library itself should be SIGPIPE-safe by default +(e.g. `MSG_NOSIGNAL` on the plain send path; a custom BIO or documented app-level +`SIG_IGN` for the OpenSSL path) rather than relying on the app. Not fixed in this +slice. + **Deferred (unchanged, issue #10):** mutual TLS / client cert+key, Java keystore formats, cipher/protocol/provider tuning, `connect_timeout`/`socket_timeout`, non-SCRAM SASL, `protocol_version=AUTO`/3.x. diff --git a/docs/STATUS.md b/docs/STATUS.md index 140e594..57e5668 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -103,7 +103,10 @@ Rod URI `fromUri` (#9), multi-server seed list + failover (#12)._ (`ca_file`, empty = system store), SNI (`sni_host`, skipped for literal IPs), and host-name validation (`hostname_validation`, default on; chain verification always on). Min TLS 1.2. `include/hotrod/TlsConfig.h`; handshake in - `src/transport/Connection.cpp`. Mutual TLS / keystore formats deferred (#10) + `src/transport/Connection.cpp`. Unit-tested against an in-process OpenSSL + server and end-to-end against a TLS-enabled Infinispan + (`tests/integration/TlsIntegrationTest.cpp`, Docker). Mutual TLS / keystore + formats deferred (#10) - **Multi-server seed list + failover (`fromUri`, issue #12)** — all comma-separated hosts become seed servers. **Startup failover:** `connect()` tries each seed in order; all unreachable → one `HotRodClientException` listing diff --git a/scripts/start_infinispan_tls.sh b/scripts/start_infinispan_tls.sh new file mode 100755 index 0000000..4886cce --- /dev/null +++ b/scripts/start_infinispan_tls.sh @@ -0,0 +1,62 @@ +#!/bin/bash +# Start Infinispan server with TLS enabled on the Hot Rod endpoint (issue #18). +# +# Mirrors start_infinispan_auth.sh but mounts a TLS server-identity config plus +# the PKCS12 keystore the server presents. No SASL — this exercises +# server-authenticated TLS in isolation. The client trusts test-configs/tls/ca.pem. + +set -e + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +CONFIG_DIR="$SCRIPT_DIR/../test-configs" +CONFIG_FILE="$CONFIG_DIR/infinispan-tls.xml" +KEYSTORE_FILE="$CONFIG_DIR/tls/server.p12" +CA_FILE="$CONFIG_DIR/tls/ca.pem" + +for f in "$CONFIG_FILE" "$KEYSTORE_FILE" "$CA_FILE"; do + if [ ! -f "$f" ]; then + echo "ERROR: Config file not found: $f" >&2 + exit 1 + fi +done + +CONF=/opt/infinispan/server/conf + +# Start container with the TLS config + keystore mounted into the conf dir. +CONTAINER_ID=$(docker run -d \ + -p 0:11222 \ + -v "$CONFIG_FILE:$CONF/infinispan.xml:ro" \ + -v "$KEYSTORE_FILE:$CONF/server.p12:ro" \ + quay.io/infinispan/server:latest) + +# Wait for server ready (ISPN080001 = "Infinispan Server started") +echo "Waiting for Infinispan server to start (TLS mode)..." >&2 +timeout 120 bash -c " +while ! docker logs $CONTAINER_ID 2>&1 | grep -q 'ISPN080001'; do + sleep 1 +done +" || { + echo "ERROR: Server failed to start within 120 seconds" >&2 + docker logs $CONTAINER_ID >&2 + docker rm -f $CONTAINER_ID >&2 + exit 1 +} + +# Get mapped port +HOST=localhost +PORT=$(docker port $CONTAINER_ID 11222 | cut -d: -f2) + +if [ -z "$PORT" ]; then + echo "ERROR: Failed to get mapped port" >&2 + docker rm -f $CONTAINER_ID >&2 + exit 1 +fi + +# Export for C++ tests (stdout only - for parsing) +echo "export ISPN_CONTAINER_ID=$CONTAINER_ID" +echo "export ISPN_HOST=$HOST" +echo "export ISPN_PORT=$PORT" +echo "export ISPN_TLS=true" +echo "export ISPN_CA_FILE=$CA_FILE" + +echo "Server started: $HOST:$PORT (container: $CONTAINER_ID, TLS mode)" >&2 diff --git a/test-configs/infinispan-tls.xml b/test-configs/infinispan-tls.xml new file mode 100644 index 0000000..5191b5c --- /dev/null +++ b/test-configs/infinispan-tls.xml @@ -0,0 +1,65 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/test-configs/tls/ca.pem b/test-configs/tls/ca.pem new file mode 100644 index 0000000..6ebf2ea --- /dev/null +++ b/test-configs/tls/ca.pem @@ -0,0 +1,19 @@ +-----BEGIN CERTIFICATE----- +MIIDHzCCAgegAwIBAgIUJei/JyHCLe0XJ99HkYHrEGMXDYAwDQYJKoZIhvcNAQEL +BQAwHjEcMBoGA1UEAwwTSW50ZWdyYXRpb24gVGVzdCBDQTAgFw0yNjExMDYxNzIx +MzNaGA8yMTI2MTAxMzE3MjEzM1owHjEcMBoGA1UEAwwTSW50ZWdyYXRpb24gVGVz +dCBDQTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANe2lvUfrizKSeEs +rAZoBWnQSAqAC513g/Pp1opH6GDmA9PSGPYsS6DRO21+/h0j8+wvUaX6BaCo5AWI +EHfYqNMiEqWEMzJ/6RIf66xNBToRSBbLLSGUcSTF9eWZDjq0pajbU6a3RvjV37gB +nlXeLP4kUpEQ6/44WqXBA92B00yA2Z0kfI7eY94CnjIDxvzDNbmZFEM+M+olPXi0 +DoNsXAIfs6Vkqef01zTDnIauNK6oRENu5Y+vCrhpy0mZRtB7SuSR0e1NB3F9f9HR +ziksn8NanywnVEUMRH6TeR8gu9kAlxka63qWoZqw5cjJUftO2FWPxH2a58MU9yUl +C+8v5WMCAwEAAaNTMFEwHQYDVR0OBBYEFMpN1gxRQn5F7N2HBIgciaOhhrp/MB8G +A1UdIwQYMBaAFMpN1gxRQn5F7N2HBIgciaOhhrp/MA8GA1UdEwEB/wQFMAMBAf8w +DQYJKoZIhvcNAQELBQADggEBACiwacHGVNE5Sdzx0KKUGNIHP9oghsRQspGg0+0Z +peGKPrfYvKnpv7InH+930f00IBffDbLy7s/YGN3BOn2bNEUzreMBrIMDRhog6Xts +S6So5tNBNgVvZJUozQFjWH77Yr0X8WE1W9nqk/MnSdzmwJzb5vACvHUhwUPLyAqr +YSTqF74cmUGwO8SwNE/aMKHeXk5TK50tQ8cDT2ME1ZY3Ph+kO15u/P4dLCGfLJJ1 +XxLeqRqc5bsV3u9hVSw9SerLxkbv/NvL6g3u1gekutjPw65e+W9Dl7Www0OmQUWb +IseL+Y6jTAR27mpNkFaPG8LgPDcLvs5/Xax0xxle10xSsIk= +-----END CERTIFICATE----- diff --git a/test-configs/tls/server.p12 b/test-configs/tls/server.p12 new file mode 100644 index 0000000000000000000000000000000000000000..f666093e560366cb57d6f9c4a2cc5524431aef93 GIT binary patch literal 2624 zcmai$X*d*$7sid*?1qt)Y#~OL8QHfk%9>>?ktk-6ea#vfBND>QwWTYgl6{%%#xDE5 z@4GBF3MD(&eg6NaKHd-KoacSt59ibQJqL-WQ=$d{k$Bo22(3tjR>U47016=CX_r8F z+PQOk3W*1a{Ei?bJc#q$x=0P6Iv=p#2>|)Y~Wm%cOVVnrGAbJ`7=Eo{LL~?;mqCT}7J&OPV}Mh>VnP zZAY!qHQox@t|pDMyqIMXGce#z?8(u3qKpH#2aa!~cA2|MLYbwtEzTxBzhLoTu5MV5 zx9N#4Z`bZFxkzREqdvsOAx52xIW)rq;+8evc`NJ_G!LFtFxp73E!?(N7oS0XJdyj^ zSiV8Jm1d$+p^PGTEewS@5MZn;PQWC-st!pkJ)(reCB zy|c|4>?Pv(Fy7g&=N)p@F=a=rW|iJ$V)cTJ{9?+F9`~T^w~C|D+dD8@b^aUOn&2@G zq4q$XC?b+KF7KOUyd%b-o3p=0GZ!U~AO%+BIT;0NNY&Rm%r(RpY-VJNVwczQg^vu9 zd4tc_;H`c*!E7KV$;^No?R4CC#;oSLzNVaWW7vbw#U!Dj6bmX{-ms2`r z{c??rM^Q|Re5=pkOyBZkow6+f`-XJdL%AjJmL@b6v@}e2RSi6obFw^0soPV4Uo(E5 zI6WF?Wz}$3eS35A=mFDCJtCFMHC9%$FK1w|x7P{zLcXaJ%ZxYEXESCoHQ4$Y))v5h zrT&kFSAL5uN*a6DX~a7PoOd4@J4kirL$Z9^+&ec0AMB?3t?&eF-mxE*NtW05Xh7XL zn_fd&+@BiShJA&g%bt=#c`B3(>;n2{#HzHnjl;eRue>nNNTtP@zx9R+CF0 z`dofzB;_IXmy~_Yg3Ed{e^hrHC9qAbkM64fR{b30htMvPc- zH=}5x(Jq92aY!?D%zgbortSb%RLWJ72aPH_-XxV>dGj>=bcFWVykQ^`56<~@_y2+f zoC?B&lg@48dBsBL|IZi(Iso-~D1UBB{}(to8uL5ETf>gpI;nT-!dWDzq6#8I?$YZ&vz~*O& z4Hosq7{-XFUN-zfQi?Uf!$h)(8ZXlPVWmSudl!4&HTz+xBgY$U*gmfs4#TYjvA&d6 z7m|626Us3roJvlj2$@!YAHq+LGV7WY#TP4$-OP3TIH3(~+VPv=YH|4xDhy|mOg!?A z7PlK;DP^C3KOH|`O-_acfYCy`oTbLWIiC7#`dMYXdRg>5F^>pa3!8Dm*82sCHIiYm z(9fxw>`e<=y>ev_&m;!ZV15Zb6_QwgM2>;DiooFv{oDaw_rqd~Okv?`5~q^Fy-Q-s zxwkImknaw2N#Lx$R4eOKLqzz*%C{^lsiNM*qo)ai+VxX(iu&n8R}#2T9LHlb`h`Il zfHh>n(6@0~2ecDJ z1CJRhv~)xxSeVUuk8Hp0U=7`=N1@D<$U)+uS21sSyj4P`eLr8*EQD>r$3Nq#h{)ll zRZ&4bE#I&^Ys}At(1@bHhmwqq!u6axQxz1`WT88=C{VzvV`1Y(%|Fkx+P&r~tyUcY%Q``BM))0C1kx1HNxd+&t%rxRjnBqe&x zg;mY-{oUiBHr5*zLde^vm#Yo+Joa&?6?P2{QbxmtJ2wBc-&V|o>WB;e9p|3jP-B1%PbkEk66gOtSICfxLvt3#HYW-&< z>(}ZY^5{+3!xTqCth=MKHp7F{whw*0b2ki4Wa=sK4%e4kGK1*vlJjN(zSj|s_Ngq#g~ckefZdI-e~Q( zfoq+aRs0h=YGKo~9GEupD#YnhCf8SuNh`-;le*?XJFF{u?ViMXnSJ(PK968_tD%r- z*RY<~bwaL&0S4ot3PKnH!7}*BK_1$y6FW?i@y#CyhWnvN%P{UGt-=Kl*JXIgCN~Os zJF>cXeOZ(V4cyC+I59<^VD)7r)5eKcZx{3uI9<{WB4Z|Z*&U367H!H~mlCr&G6-{W zG$%<3>--*{qOXw8BuJkI@=v#4PQPU!LhIW&LShrv2Ef z0R)J%H79Jk96YQ>ozZ883MQvGpgy3nk1IaLk!w4LHcEb+)#+I(nuUs&u6n!mqSTO_ zzd%dNhGODopz@}&qw=Ei{kJ3ee}@-P>>##Y;INd^IuPQggG connect + put/get round-trip over TLS. + * 2. hotrods:// URI with trust_store_file_name -> same round-trip. + * 3. Untrusted anchor (system store, no CA) -> connect() throws. + * 4. Host-name mismatch with validation on -> throws; with validation off, + * the (still chain-verified) connection succeeds. + * + * Excluded from the default CI unit run via the "integration;docker;tls" label. + */ +#include +#include "hotrod/RemoteCache.h" +#include "hotrod/HotRodClientException.h" + +#include +#include +#include +#include +#include +#include + +using namespace hotrod; + +namespace { + +// Starts/stops the TLS-enabled Infinispan container once for the whole suite and +// carries the trust anchor (ca_file) the start script exports. +class TlsServerEnvironment : public ::testing::Environment { +public: + static std::string containerID; + static std::string host; + static int port; + static std::string caFile; + + void SetUp() override { + int result = system("./scripts/start_infinispan_tls.sh > /tmp/ispn-tls-env.sh 2>&1"); + if (result != 0) { + throw std::runtime_error("Failed to start TLS Infinispan server. Check Docker is running."); + } + + std::ifstream env("/tmp/ispn-tls-env.sh"); + if (!env.is_open()) { + throw std::runtime_error("Failed to open /tmp/ispn-tls-env.sh"); + } + + std::string line; + while (std::getline(env, line)) { + if (line.rfind("export ISPN_CONTAINER_ID=", 0) == 0) { + containerID = line.substr(25); + } else if (line.rfind("export ISPN_HOST=", 0) == 0) { + host = line.substr(17); + } else if (line.rfind("export ISPN_PORT=", 0) == 0) { + port = std::stoi(line.substr(17)); + } else if (line.rfind("export ISPN_CA_FILE=", 0) == 0) { + caFile = line.substr(20); + } + } + + if (containerID.empty() || port == 0 || caFile.empty()) { + throw std::runtime_error("Failed to parse TLS server info from startup script"); + } + } + + void TearDown() override { + if (!containerID.empty()) { + std::string cmd = "./scripts/stop_infinispan.sh " + containerID + " >/dev/null"; + std::ignore = system(cmd.c_str()); + } + } +}; + +std::string TlsServerEnvironment::containerID; +std::string TlsServerEnvironment::host = "localhost"; +int TlsServerEnvironment::port = 0; +std::string TlsServerEnvironment::caFile; + +} // namespace + +// Cache pre-defined in infinispan-tls.xml. +constexpr const char* kTlsCache = "tlscache"; + +// 1. Programmatic TLS: trust the test CA, connect, round-trip a value. The client +// dials "localhost" (a DNS name), so host-name validation (default on) checks +// the server cert's SAN DNS:localhost. +TEST(TlsIntegrationTest, SetTlsTrustedCaRoundTrips) { + RemoteCache cache(TlsServerEnvironment::host, TlsServerEnvironment::port, kTlsCache); + cache.setTls(TlsServerEnvironment::caFile); // sni/host derived; validation on + cache.connect(); + + const ByteArray key{'t', 'l', 's', '1'}; + const ByteArray value{'v', '1'}; + cache.put(key, value).get(); + auto got = cache.get(key).get(); + + ASSERT_TRUE(got.has_value()); + EXPECT_EQ(*got, value); + + cache.disconnect(); +} + +// 2. Same round-trip driven from a hotrods:// URI carrying the PEM trust anchor. +TEST(TlsIntegrationTest, FromUriHotrodsRoundTrips) { + const std::string uri = + "hotrods://" + TlsServerEnvironment::host + ":" + + std::to_string(TlsServerEnvironment::port) + + "?trust_store_file_name=" + TlsServerEnvironment::caFile; + + auto cache = RemoteCache::fromUri(uri, kTlsCache); + cache->connect(); + + const ByteArray key{'u', 'r', 'i', 't', 'l', 's'}; + const ByteArray value{'v', '1'}; + cache->put(key, value).get(); + auto got = cache->get(key).get(); + + ASSERT_TRUE(got.has_value()); + EXPECT_EQ(*got, value); + + cache->disconnect(); +} + +// 3. Untrusted anchor: with no CA file the client uses the system trust store, +// which does not contain the test CA -> chain verification fails at connect(). +TEST(TlsIntegrationTest, UntrustedAnchorThrowsAtConnect) { + RemoteCache cache(TlsServerEnvironment::host, TlsServerEnvironment::port, kTlsCache); + cache.setTls(""); // empty ca_file -> system/default trust store + EXPECT_THROW(cache.connect(), std::exception); +} + +// 4a. Host-name mismatch with validation on -> connect() throws even though the +// chain is trusted (SNI/validated name forced to a value not in the SAN). +TEST(TlsIntegrationTest, HostnameMismatchValidationOnThrows) { + RemoteCache cache(TlsServerEnvironment::host, TlsServerEnvironment::port, kTlsCache); + TlsConfig tls; + tls.enabled = true; + tls.ca_file = TlsServerEnvironment::caFile; + tls.sni_host = "wrong.example.com"; // not in the server cert SAN + tls.hostname_validation = true; + cache.setTls(tls); + EXPECT_THROW(cache.connect(), std::exception); +} + +// 4b. Same mismatch, but validation off: the chain is still verified, so the +// connection succeeds and a value round-trips. +TEST(TlsIntegrationTest, HostnameMismatchValidationOffRoundTrips) { + RemoteCache cache(TlsServerEnvironment::host, TlsServerEnvironment::port, kTlsCache); + TlsConfig tls; + tls.enabled = true; + tls.ca_file = TlsServerEnvironment::caFile; + tls.sni_host = "wrong.example.com"; + tls.hostname_validation = false; + cache.setTls(tls); + cache.connect(); + + const ByteArray key{'n', 'o', 'v', 'a', 'l'}; + const ByteArray value{'v', '1'}; + cache.put(key, value).get(); + auto got = cache.get(key).get(); + + ASSERT_TRUE(got.has_value()); + EXPECT_EQ(*got, value); + + cache.disconnect(); +} + +int main(int argc, char** argv) { + // A dropped TLS connection can make a client-side write hit a closed peer, + // raising SIGPIPE whose default action kills the process. Network clients + // conventionally ignore it (the app, here the test, owns signal disposition). + std::signal(SIGPIPE, SIG_IGN); + + ::testing::InitGoogleTest(&argc, argv); + ::testing::AddGlobalTestEnvironment(new TlsServerEnvironment()); + return RUN_ALL_TESTS(); +} From ef3b7bdeb76075302d0aa7bf574b0a4d78ad30d4 Mon Sep 17 00:00:00 2001 From: rigazilla Date: Fri, 6 Nov 2026 18:48:34 +0100 Subject: [PATCH 3/6] fix(tls): make the client SIGPIPE-safe per-connection (no global SIG_IGN) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A write onto a dropped TLS peer raised SIGPIPE, whose default disposition kills the process (the integration suite died with exit 141). The Java client avoids this only because the JVM sets SIGPIPE to SIG_IGN process-wide at startup — a runtime/process-owner decision. This client is a guest in someone else's process and must not flip global signal state (it would, e.g., break a CLI tool relying on shell-pipeline SIGPIPE semantics). So suppress SIGPIPE per connection instead: - plain send() uses MSG_NOSIGNAL on Linux (HOTROD_SEND_FLAGS); - macOS/BSD set SO_NOSIGPIPE on the socket (covers OpenSSL writes too); - the Linux TLS path routes all OpenSSL socket I/O through a custom MSG_NOSIGNAL BIO, covering SSL_write plus the writes SSL_connect/SSL_read trigger internally; - Windows is unaffected (no SIGPIPE) and keeps SSL_set_fd. Observably identical to Java (dropped connection -> thrown exception, process survives) but with a narrower blast radius. The integration test main() no longer installs SIG_IGN, so it proves the library is self-sufficient (exit 0, not 141); the unit test keeps SIG_IGN only to guard its in-process echo server thread. 260 unit tests + 5 TLS integration tests green. Co-Authored-By: Claude Opus 4.8 --- docs/DECISIONS.md | 40 ++++++--- docs/STATUS.md | 6 +- src/transport/Connection.cpp | 101 ++++++++++++++++++++++- tests/integration/TlsIntegrationTest.cpp | 10 +-- tests/unit/TlsConnectionTest.cpp | 7 +- 5 files changed, 142 insertions(+), 22 deletions(-) diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index 54c47f9..3c9e1e9 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -1149,16 +1149,36 @@ while wiring it: the mounted keystore must be world-readable (the in-container u can't read a 0600 `:ro` mount → `FileNotFoundException: … (Permission denied)`), and `keystore-password` is deprecated in favor of `password` on the `` element. -**SIGPIPE on a dropped TLS connection (library robustness).** The first integration -run was killed by SIGPIPE (exit 141): a client-side write onto a closed TLS peer -raises SIGPIPE, whose default disposition terminates the process. `close()`'s quiet -shutdown prevents the *teardown* write, but the data path can still trip it. Both -test mains (unit + integration) install `std::signal(SIGPIPE, SIG_IGN)` — the -conventional stance that the application owns signal disposition. **Open follow-up:** -decide whether the client library itself should be SIGPIPE-safe by default -(e.g. `MSG_NOSIGNAL` on the plain send path; a custom BIO or documented app-level -`SIG_IGN` for the OpenSSL path) rather than relying on the app. Not fixed in this -slice. +**SIGPIPE on a dropped TLS connection — fixed at the library, per-connection.** +The first integration run was killed by SIGPIPE (exit 141): a client-side write onto +a closed TLS peer raises SIGPIPE, whose default disposition terminates the process. +We checked the authoritative Java client — it has *no* SIGPIPE handling because the +**JVM** sets `SIGPIPE` to `SIG_IGN` process-wide at startup; a broken connection then +surfaces as an `IOException`. That is a *runtime* (process-owner) decision. Our C++ +client is a **guest** linked into someone else's process and has no business flipping +process-global signal disposition — a global `SIG_IGN` would, e.g., break a +well-behaved CLI tool that relies on SIGPIPE for shell-pipeline semantics. So instead +of mirroring the JVM's global flip, we suppress SIGPIPE **per connection**, confining +the effect to our own sockets (option 2): +- Plain `send()` uses `MSG_NOSIGNAL` on Linux (`HOTROD_SEND_FLAGS`). +- macOS/BSD set the socket option `SO_NOSIGPIPE` after `socket()` — socket-level, so + it also covers OpenSSL's writes on that fd. +- Linux's TLS path routes all OpenSSL socket I/O through a **custom `BIO`** + (`sigpipeSafeBioMethod` in `Connection.cpp`) whose write uses `MSG_NOSIGNAL`. One + mechanism covers every OpenSSL write — `SSL_write`, plus the writes + `SSL_connect`/`SSL_read` trigger internally (handshake, renegotiation, TLS 1.3 + post-handshake). The BIO never closes the fd (Connection owns it); `SSL_set_bio` + takes ownership and frees it in `SSL_free`. Windows has no SIGPIPE, so it keeps the + default `SSL_set_fd` BIO. + +Net: observably identical to Java (dropped connection → our thrown exception, process +survives), but with a *narrower blast radius* than the JVM — we never touch the app's +global signal disposition. The integration test's `main()` deliberately does **not** +install `SIG_IGN`, so it genuinely proves the library is self-sufficient (exit 0, not +141). The unit test still installs `SIG_IGN`, but only to guard its in-process echo +*server* thread (harness code doing raw `SSL_write`/`SSL_shutdown`), not the client. +`close()` additionally uses quiet shutdown so teardown performs no close_notify write +at all. **Deferred (unchanged, issue #10):** mutual TLS / client cert+key, Java keystore formats, cipher/protocol/provider tuning, `connect_timeout`/`socket_timeout`, diff --git a/docs/STATUS.md b/docs/STATUS.md index 57e5668..6d1331e 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -105,8 +105,10 @@ Rod URI `fromUri` (#9), multi-server seed list + failover (#12)._ always on). Min TLS 1.2. `include/hotrod/TlsConfig.h`; handshake in `src/transport/Connection.cpp`. Unit-tested against an in-process OpenSSL server and end-to-end against a TLS-enabled Infinispan - (`tests/integration/TlsIntegrationTest.cpp`, Docker). Mutual TLS / keystore - formats deferred (#10) + (`tests/integration/TlsIntegrationTest.cpp`, Docker). A dropped connection is + SIGPIPE-safe per-connection (MSG_NOSIGNAL / SO_NOSIGPIPE / custom TLS BIO) — no + process-global signal change — so it surfaces as a thrown exception, not process + death. Mutual TLS / keystore formats deferred (#10) - **Multi-server seed list + failover (`fromUri`, issue #12)** — all comma-separated hosts become seed servers. **Startup failover:** `connect()` tries each seed in order; all unreachable → one `HotRodClientException` listing diff --git a/src/transport/Connection.cpp b/src/transport/Connection.cpp index 513e671..1a5278e 100644 --- a/src/transport/Connection.cpp +++ b/src/transport/Connection.cpp @@ -23,6 +23,18 @@ #include #endif +// Per-send SIGPIPE suppression (option 2: no process-global signal change). +// Linux has the MSG_NOSIGNAL send flag; the BSDs/macOS instead use the +// SO_NOSIGPIPE socket option (set in connect()), so no flag is needed there; +// Windows has no SIGPIPE at all. +#if defined(_WIN32) + #define HOTROD_SEND_FLAGS 0 +#elif defined(MSG_NOSIGNAL) + #define HOTROD_SEND_FLAGS MSG_NOSIGNAL +#else + #define HOTROD_SEND_FLAGS 0 +#endif + namespace hotrod { namespace { @@ -49,6 +61,68 @@ bool isLiteralIp(const std::string& host) { inet_pton(AF_INET6, host.c_str(), buf) == 1; } +#ifndef _WIN32 +// A custom OpenSSL BIO over a plain fd whose write uses HOTROD_SEND_FLAGS +// (MSG_NOSIGNAL on Linux). OpenSSL's default socket BIO writes with plain +// write()/send(), so a TLS write onto a dropped peer would raise SIGPIPE and +// kill the process. Routing every OpenSSL socket write through this BIO confines +// the suppression to our connections (no process-global SIG_IGN) and covers all +// writes — app data via SSL_write, plus the writes SSL_connect/SSL_read trigger +// internally (handshake, renegotiation, TLS 1.3 post-handshake). The BIO never +// closes the fd; Connection owns the socket lifecycle. Windows has no SIGPIPE, +// so there the default SSL_set_fd BIO is used unchanged. +int bioWrite(BIO* b, const char* buf, int len) { + const int fd = static_cast(reinterpret_cast(BIO_get_data(b))); + BIO_clear_retry_flags(b); + const ssize_t n = ::send(fd, buf, static_cast(len), HOTROD_SEND_FLAGS); + if (n <= 0 && (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK)) { + BIO_set_retry_write(b); + } + return static_cast(n); +} + +int bioRead(BIO* b, char* buf, int len) { + const int fd = static_cast(reinterpret_cast(BIO_get_data(b))); + BIO_clear_retry_flags(b); + const ssize_t n = ::recv(fd, buf, static_cast(len), 0); + if (n < 0 && (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK)) { + BIO_set_retry_read(b); + } + return static_cast(n); +} + +long bioCtrl(BIO*, int cmd, long, void*) { + // Nothing is buffered, so FLUSH is a no-op success; everything else (pending + // counts, eof, push/pop, close flags) defaults to 0, which is correct here. + return cmd == BIO_CTRL_FLUSH ? 1 : 0; +} + +int bioCreate(BIO* b) { + BIO_set_init(b, 0); + BIO_set_data(b, nullptr); + return 1; +} + +int bioDestroy(BIO* b) { + return b != nullptr; // do not close the fd — Connection owns it +} + +// The BIO_METHOD, created once and intentionally leaked for process lifetime. +BIO_METHOD* sigpipeSafeBioMethod() { + static BIO_METHOD* method = [] { + BIO_METHOD* m = BIO_meth_new(BIO_get_new_index() | BIO_TYPE_SOURCE_SINK, + "hotrod sigpipe-safe socket"); + BIO_meth_set_write(m, bioWrite); + BIO_meth_set_read(m, bioRead); + BIO_meth_set_ctrl(m, bioCtrl); + BIO_meth_set_create(m, bioCreate); + BIO_meth_set_destroy(m, bioDestroy); + return m; + }(); + return method; +} +#endif // !_WIN32 + } // namespace // Platform-specific initialization @@ -113,6 +187,17 @@ void Connection::connect() { } #endif + // SIGPIPE suppression on platforms with the socket-level option (macOS/ + // BSD). This covers both plain send() and OpenSSL's writes on this fd. + // Linux lacks it and uses MSG_NOSIGNAL per write instead (HOTROD_SEND_FLAGS + // + the custom TLS BIO). +#ifdef SO_NOSIGPIPE + { + int on = 1; + setsockopt(socket_, SOL_SOCKET, SO_NOSIGPIPE, &on, sizeof(on)); + } +#endif + // Set socket to non-blocking mode for connect with timeout #ifdef _WIN32 u_long mode = 1; @@ -255,9 +340,23 @@ void Connection::startTls() { } } +#ifdef _WIN32 + // Windows has no SIGPIPE; the default socket BIO is fine. if (SSL_set_fd(ssl_, static_cast(socket_)) != 1) { throw std::runtime_error("TLS: SSL_set_fd failed: " + opensslErrors()); } +#else + // Route all OpenSSL socket I/O through our MSG_NOSIGNAL BIO so a write onto a + // dropped peer never raises SIGPIPE. SSL takes ownership of the BIO (same BIO + // for read and write) and frees it in SSL_free; it does not close the fd. + BIO* bio = BIO_new(sigpipeSafeBioMethod()); + if (!bio) { + throw std::runtime_error("TLS: BIO_new failed: " + opensslErrors()); + } + BIO_set_data(bio, reinterpret_cast(static_cast(socket_))); + BIO_set_init(bio, 1); + SSL_set_bio(ssl_, bio, bio); +#endif const int rc = SSL_connect(ssl_); if (rc != 1) { @@ -301,7 +400,7 @@ void Connection::send(const ByteArray& data) { throw std::runtime_error("send failed: " + std::to_string(WSAGetLastError())); } #else - ssize_t sent = ::send(socket_, ptr, remaining, 0); + ssize_t sent = ::send(socket_, ptr, remaining, HOTROD_SEND_FLAGS); if (sent == -1) { throw std::runtime_error("send failed: " + std::string(strerror(errno))); } diff --git a/tests/integration/TlsIntegrationTest.cpp b/tests/integration/TlsIntegrationTest.cpp index 86fa300..b7edd17 100644 --- a/tests/integration/TlsIntegrationTest.cpp +++ b/tests/integration/TlsIntegrationTest.cpp @@ -17,7 +17,6 @@ #include "hotrod/RemoteCache.h" #include "hotrod/HotRodClientException.h" -#include #include #include #include @@ -169,11 +168,10 @@ TEST(TlsIntegrationTest, HostnameMismatchValidationOffRoundTrips) { } int main(int argc, char** argv) { - // A dropped TLS connection can make a client-side write hit a closed peer, - // raising SIGPIPE whose default action kills the process. Network clients - // conventionally ignore it (the app, here the test, owns signal disposition). - std::signal(SIGPIPE, SIG_IGN); - + // Deliberately NO signal(SIGPIPE, SIG_IGN) here: the client library suppresses + // SIGPIPE per-connection (MSG_NOSIGNAL / SO_NOSIGPIPE / custom TLS BIO), so a + // dropped TLS connection must surface as a thrown exception, not kill this + // process. If this binary ever dies with signal 13, that protection regressed. ::testing::InitGoogleTest(&argc, argv); ::testing::AddGlobalTestEnvironment(new TlsServerEnvironment()); return RUN_ALL_TESTS(); diff --git a/tests/unit/TlsConnectionTest.cpp b/tests/unit/TlsConnectionTest.cpp index 990c88c..2c1a097 100644 --- a/tests/unit/TlsConnectionTest.cpp +++ b/tests/unit/TlsConnectionTest.cpp @@ -42,9 +42,10 @@ using namespace hotrod; namespace { -// The in-process server thread writes a TLS close_notify on teardown; if the -// client fd is already closed this raises SIGPIPE, whose default action would -// kill the whole test process. Ignore it for the lifetime of these tests. +// This guards the in-process echo *server* half (harness code), which does raw +// SSL_write/SSL_shutdown onto client sockets that may already be closed -> SIGPIPE. +// The client (the library under test) suppresses SIGPIPE itself per-connection, so +// it does not rely on this; it is here only for the test's own server thread. [[maybe_unused]] const bool kSigpipeIgnored = [] { std::signal(SIGPIPE, SIG_IGN); return true; From 9d9afc6e76870fce3ecefb03614ec014b13fda44 Mon Sep 17 00:00:00 2001 From: rigazilla Date: Mon, 9 Nov 2026 17:20:39 +0100 Subject: [PATCH 4/6] test: force --pull always so integration tests never run a stale :latest server MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The cluster and single-server integration suites bring up quay.io/infinispan/server:latest, but Docker reuses a locally cached tag instead of pulling. An 8-month-old cached :latest (pre-rest/v3) kept being reused, so the REST probes 404'd — clusters appeared to never form and owner/size lookups came back empty. Pin the pull behaviour (not the API): pull_policy: always on all four nodes in docker-compose-cluster.yml, and docker run --pull always in the start_infinispan_{noauth,auth,tls}.sh scripts. The test code is unchanged and still correctly uses the rest/v3 API. See docs/DECISIONS.md (2026-11-09). Co-Authored-By: Claude Opus 4.8 --- docs/DECISIONS.md | 36 +++++++++++++++++++++++++ scripts/start_infinispan_auth.sh | 3 ++- scripts/start_infinispan_noauth.sh | 5 ++-- scripts/start_infinispan_tls.sh | 3 ++- test-configs/docker-compose-cluster.yml | 4 +++ 5 files changed, 47 insertions(+), 4 deletions(-) diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index 3c9e1e9..6dd977a 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -1183,3 +1183,39 @@ at all. **Deferred (unchanged, issue #10):** mutual TLS / client cert+key, Java keystore formats, cipher/protocol/provider tuning, `connect_timeout`/`socket_timeout`, non-SCRAM SASL, `protocol_version=AUTO`/3.x. + +## 2026-11-09 — Integration tests force `--pull always` (stale `:latest` cache, not an API change) + +**What:** The integration suites bring up `quay.io/infinispan/server:latest`. Every +cluster-dependent suite (Topology, HashAwareRouting, ConcurrentMultiServer, +RetryView, PingRetry, MultiSeed) suddenly failed — first `"Failed to start +cluster"`, and once the cluster did start, `"Resource not found"` from the REST +helpers (`getServerClusterSize`, `getPrimaryOwnerForKey`, `RestAPIHelper`). The +fix: pin the *pull behavior*, not the API — `pull_policy: always` on all four +nodes in `test-configs/docker-compose-cluster.yml`, and `docker run -d --pull +always` in `scripts/start_infinispan_{noauth,auth,tls}.sh`. + +**Why it matters / how it was found:** The tests query the server over the REST +`v3` API (`/rest/v3/cluster/_distribution`, `/rest/v3/caches/{c}/...`). That API +is correct for current server builds. The failures were **environmental**: Docker +only pulls `:latest` when the tag is absent locally, so an 8-month-old cached +`:latest` (Feb 2026, id `43285deb7485`) — which predates `rest/v3` and 404s on it +— kept being reused, even though newer tags (`16.3`, id `fa22dddecda4`, +2026-10-20) were present under other names. The REST probes counted 0 members / +returned 404, so clusters "never formed" and owner lookups came back empty. +Confirmed by probing both images directly: cached `:latest` → `rest/v3` 404; +`16.3` → `rest/v3` 200. A manual `docker pull …:latest` (now resolves to the 16.3 +build) turned the suite green; the pull-policy change makes that automatic so a +stale local cache can never again silently run an old server. CI (no cache) was +unaffected, which is why this only bit local runs. + +**Dead end (not shipped):** first mis-diagnosed as an API removal and rewrote the +test helpers + cluster scripts from `rest/v3` to `rest/v2 ?action=`. Reverted in +full once the 16.3 probe showed `rest/v3` still present — the API was never the +problem. Test code stays on `rest/v3`. + +**Gotcha for next time:** `scripts/` and `test-configs/` are copied into the build +dir by `file(COPY …)` at **configure** time (`CMakeLists.txt`), and integration +tests run from `${CMAKE_BINARY_DIR}` using those copies. After editing a script +or compose file, re-run `cmake -S . -B build` (a *reconfigure*, not `cmake +--build`) or the test keeps executing the stale build copy. diff --git a/scripts/start_infinispan_auth.sh b/scripts/start_infinispan_auth.sh index 49e1663..a08047b 100755 --- a/scripts/start_infinispan_auth.sh +++ b/scripts/start_infinispan_auth.sh @@ -27,7 +27,8 @@ done CONF=/opt/infinispan/server/conf # Start container with the auth config + property files mounted into the conf dir. -CONTAINER_ID=$(docker run -d \ +# --pull always: :latest is unpinned; refresh so a stale local cache can't run an old server. +CONTAINER_ID=$(docker run -d --pull always \ -p 0:11222 \ -v "$CONFIG_FILE:$CONF/infinispan.xml:ro" \ -v "$USERS_FILE:$CONF/test-users.properties:ro" \ diff --git a/scripts/start_infinispan_noauth.sh b/scripts/start_infinispan_noauth.sh index 6840d9b..5680549 100755 --- a/scripts/start_infinispan_noauth.sh +++ b/scripts/start_infinispan_noauth.sh @@ -11,8 +11,9 @@ if [ ! -f "$CONFIG_FILE" ]; then exit 1 fi -# Start container with custom XML mounted (anonymous mode) -CONTAINER_ID=$(docker run -d \ +# Start container with custom XML mounted (anonymous mode). +# --pull always: :latest is unpinned; refresh so a stale local cache can't run an old server. +CONTAINER_ID=$(docker run -d --pull always \ -p 0:11222 \ -v "$CONFIG_FILE:/opt/infinispan/server/conf/infinispan.xml:ro" \ quay.io/infinispan/server:latest) diff --git a/scripts/start_infinispan_tls.sh b/scripts/start_infinispan_tls.sh index 4886cce..30249cc 100755 --- a/scripts/start_infinispan_tls.sh +++ b/scripts/start_infinispan_tls.sh @@ -23,7 +23,8 @@ done CONF=/opt/infinispan/server/conf # Start container with the TLS config + keystore mounted into the conf dir. -CONTAINER_ID=$(docker run -d \ +# --pull always: :latest is unpinned; refresh so a stale local cache can't run an old server. +CONTAINER_ID=$(docker run -d --pull always \ -p 0:11222 \ -v "$CONFIG_FILE:$CONF/infinispan.xml:ro" \ -v "$KEYSTORE_FILE:$CONF/server.p12:ro" \ diff --git a/test-configs/docker-compose-cluster.yml b/test-configs/docker-compose-cluster.yml index b801d27..1c7ae5b 100644 --- a/test-configs/docker-compose-cluster.yml +++ b/test-configs/docker-compose-cluster.yml @@ -15,6 +15,7 @@ services: # Node 1: Primary node, always started first ispn-node1: image: quay.io/infinispan/server:latest + pull_policy: always # :latest is unpinned; always refresh so a stale local cache can't run an old server container_name: ispn-node1 hostname: ispn-node1 networks: @@ -36,6 +37,7 @@ services: # Node 2: Second node ispn-node2: image: quay.io/infinispan/server:latest + pull_policy: always container_name: ispn-node2 hostname: ispn-node2 networks: @@ -61,6 +63,7 @@ services: # Node 3: Third node (optional, for 3-node tests) ispn-node3: image: quay.io/infinispan/server:latest + pull_policy: always container_name: ispn-node3 hostname: ispn-node3 networks: @@ -86,6 +89,7 @@ services: # Node 4: Fourth node (optional, for 4-node tests) ispn-node4: image: quay.io/infinispan/server:latest + pull_policy: always container_name: ispn-node4 hostname: ispn-node4 networks: From 7b5677cb808dad7af3ba7fd5bb38509754cc7194 Mon Sep 17 00:00:00 2001 From: rigazilla Date: Mon, 9 Nov 2026 18:13:52 +0100 Subject: [PATCH 5/6] fix(tls): avoid deprecated SSL_set1_host (OpenSSL 4.0 / Fedora CI) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fedora CI builds with OpenSSL 4.0 and -Werror=deprecated-declarations, where SSL_set_hostflags / SSL_set1_host are deprecated, breaking the build (Ubuntu and Windows, on older OpenSSL, were unaffected). Configure host-name validation on the SSL's X509_VERIFY_PARAM directly via SSL_get0_param + X509_VERIFY_PARAM_set_hostflags / X509_VERIFY_PARAM_set1_host. These are the functions the deprecated wrappers alias, so behaviour is identical, and they exist since OpenSSL 1.1.0 — builds clean on 1.1.0 through 4.0. See docs/DECISIONS.md (2026-11-09). Co-Authored-By: Claude Opus 4.8 --- docs/DECISIONS.md | 25 +++++++++++++++++++++++++ docs/STATUS.md | 5 +++-- src/transport/Connection.cpp | 11 +++++++++-- 3 files changed, 37 insertions(+), 4 deletions(-) diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index 6dd977a..a490220 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -1219,3 +1219,28 @@ dir by `file(COPY …)` at **configure** time (`CMakeLists.txt`), and integratio tests run from `${CMAKE_BINARY_DIR}` using those copies. After editing a script or compose file, re-run `cmake -S . -B build` (a *reconfigure*, not `cmake --build`) or the test keeps executing the stale build copy. + +## 2026-11-09 — TLS host validation uses X509_VERIFY_PARAM (SSL_set1_host deprecated in OpenSSL 4.0) + +**What:** The Fedora CI job failed to build `src/transport/Connection.cpp`: +`SSL_set1_host` is deprecated as of OpenSSL 4.0 and the build uses +`-Werror=deprecated-declarations`. Ubuntu and Windows (older OpenSSL) built fine, +so this was CI-only on Fedora's bleeding-edge OpenSSL. Fix: drop the deprecated +`SSL_set_hostflags` / `SSL_set1_host` convenience wrappers in `startTls()` and +configure the SSL's verification params directly: +`X509_VERIFY_PARAM_set_hostflags(SSL_get0_param(ssl), …)` and +`X509_VERIFY_PARAM_set1_host(SSL_get0_param(ssl), host, 0)`. + +**Why it matters:** The `SSL_set1_host` family are thin aliases over the +`X509_VERIFY_PARAM_*` functions, so behaviour is byte-for-byte identical on every +OpenSSL version, and the param API exists since OpenSSL 1.1.0 — the change builds +clean on 1.1.0 through 4.0 with `-Werror=deprecated-declarations`. Verified +locally against OpenSSL 3.5.9 (compiles) and confirmed the replacement against the +OpenSSL 4.0 docs. (Cannot reproduce the 4.0 deprecation locally — local Fedora +ships 3.5.9 where the symbol is not yet deprecated — but the fix references no +deprecated symbol, which is what the 4.0 build needs.) + +**Watch out (not yet an issue):** OpenSSL 4.1 additionally drops the common-name +fallback entirely (RFC 9525 — SAN-only matching). Our test certs/validation +already rely on SANs, so no action needed now, but keep it in mind if a future +runner moves to 4.1. diff --git a/docs/STATUS.md b/docs/STATUS.md index 6d1331e..fc96817 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -4,7 +4,7 @@ > If any other doc disagrees with this file, this file wins. Point-in-time > snapshots live in [`archive/`](archive/) and are historical only. > -> **Last updated:** 2026-11-06 +> **Last updated:** 2026-11-09 --- @@ -103,7 +103,8 @@ Rod URI `fromUri` (#9), multi-server seed list + failover (#12)._ (`ca_file`, empty = system store), SNI (`sni_host`, skipped for literal IPs), and host-name validation (`hostname_validation`, default on; chain verification always on). Min TLS 1.2. `include/hotrod/TlsConfig.h`; handshake in - `src/transport/Connection.cpp`. Unit-tested against an in-process OpenSSL + `src/transport/Connection.cpp` (host-name validation via the `X509_VERIFY_PARAM` + API, so it builds clean on OpenSSL 1.1.0 through 4.0). Unit-tested against an in-process OpenSSL server and end-to-end against a TLS-enabled Infinispan (`tests/integration/TlsIntegrationTest.cpp`, Docker). A dropped connection is SIGPIPE-safe per-connection (MSG_NOSIGNAL / SO_NOSIGPIPE / custom TLS BIO) — no diff --git a/src/transport/Connection.cpp b/src/transport/Connection.cpp index 1a5278e..7690ee5 100644 --- a/src/transport/Connection.cpp +++ b/src/transport/Connection.cpp @@ -6,6 +6,7 @@ #include #include #include +#include // Platform-specific includes #ifdef _WIN32 @@ -333,8 +334,14 @@ void Connection::startTls() { // of chain verification; omitting it leaves only chain verification on. We do // not validate a literal IP as a DNS name. if (tls_.hostname_validation && !nameIsIp) { - SSL_set_hostflags(ssl_, X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS); - if (SSL_set1_host(ssl_, serverName.c_str()) != 1) { + // Configure host-name validation on the SSL's X509_VERIFY_PARAM directly. + // SSL_set_hostflags / SSL_set1_host are thin convenience wrappers for these + // and are deprecated as of OpenSSL 4.0 (Fedora CI builds with + // -Werror=deprecated-declarations). The param API is behaviourally + // identical and available since OpenSSL 1.1.0. + X509_VERIFY_PARAM* vparam = SSL_get0_param(ssl_); + X509_VERIFY_PARAM_set_hostflags(vparam, X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS); + if (X509_VERIFY_PARAM_set1_host(vparam, serverName.c_str(), 0) != 1) { throw std::runtime_error("TLS: failed to set validation host name: " + opensslErrors()); } From 118d13fcd8931e836d3e99959e4efd3ff21ca410 Mon Sep 17 00:00:00 2001 From: rigazilla Date: Mon, 9 Nov 2026 18:33:23 +0100 Subject: [PATCH 6/6] test(tls): add scripts/gen-test-certs.sh to reproduce the TLS cert fixtures The TLS test certificates were hand-made with openssl and committed as opaque blobs (unit set in tests/fixtures/tls/, integration set in test-configs/tls/) with no way to regenerate them. Add a documented, self-contained generator that reproduces both sets with the same properties (subjects, SANs, RSA-2048/SHA-256, ~100-year validity). The committed fixtures are left unchanged (they do not expire); the script is for when they must actually change (new SAN, mutual-TLS client certs for #10, rotation). Output dirs are overridable via UNIT_DIR/INT_DIR for self-testing. See docs/DECISIONS.md (2026-11-09). Co-Authored-By: Claude Opus 4.8 --- docs/DECISIONS.md | 27 +++++++++++++ scripts/gen-test-certs.sh | 81 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 108 insertions(+) create mode 100755 scripts/gen-test-certs.sh diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index a490220..fbab15c 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -1244,3 +1244,30 @@ deprecated symbol, which is what the 4.0 build needs.) fallback entirely (RFC 9525 — SAN-only matching). Our test certs/validation already rely on SANs, so no action needed now, but keep it in mind if a future runner moves to 4.1. + +## 2026-11-09 — TLS test certs: committed fixtures + a generator to reproduce them + +**What:** The TLS suites use certificate fixtures that were hand-made with +`openssl` and committed as opaque blobs in the #18 commits (`f28a911` added the +unit set `tests/fixtures/tls/{ca,otherca,server}.pem` + `server.key`; `7d39cfa` +added the integration set `test-configs/tls/{ca.pem,server.p12}`). There was **no +script** to regenerate them — the "how" lived only in prose. Added +`scripts/gen-test-certs.sh` which reproduces both sets. + +**Why it matters:** The fixtures carry ~100-year validity so they never expire and +normally need no touching, but any change (a new SAN, different key type, mutual-TLS +client certs for #10, rotation) previously meant reverse-engineering the chain. The +generator documents it as runnable code: self-signed roots via stock `req -x509` +(critical `CA:TRUE` + SKI/AKI), leaves carrying only the SAN, RSA-2048/SHA-256. +Unit set: `CN=Test Root CA` + leaf `CN=test.local` SAN `DNS:test.local`, plus an +unrelated `CN=Other Root CA` for the untrusted-anchor test. Integration set: +`CN=Integration Test CA` + `CN=localhost` leaf (SAN `DNS:localhost,IP:127.0.0.1`) +exported to `server.p12` (alias `server`, password `password`). + +**Note:** Output is NOT byte-identical to the committed files (fresh random +keys/serials/timestamps) — the committed set is left as-is; the script is only run +when the fixtures must actually change, and the regenerated files must then be +`git add`ed deliberately. CA private keys are not written to the tree (not part of +the committed fixtures); each run regenerates the whole chain together. Output dirs +overridable via `UNIT_DIR`/`INT_DIR` env vars (used to self-test without clobbering +the committed set). diff --git a/scripts/gen-test-certs.sh b/scripts/gen-test-certs.sh new file mode 100755 index 0000000..806e7b9 --- /dev/null +++ b/scripts/gen-test-certs.sh @@ -0,0 +1,81 @@ +#!/bin/bash +# Regenerate the test TLS certificate fixtures used by the #18 TLS suites. +# +# The fixtures are committed to git and normally need no regeneration (they carry +# ~100-year validity, so they do not expire). This script exists to *document* how +# they were built and to reproduce them when something must change — e.g. a new SAN, +# a different key type, or mutual-TLS client certs (issue #10). +# +# It produces certificates with the SAME PROPERTIES as the committed fixtures +# (subjects, SANs, RSA-2048, SHA-256, long validity), NOT byte-identical files: +# keys, serials and timestamps are freshly random each run. After running you must +# `git add` the regenerated files if you intend to replace the committed set. +# +# Two independent sets are produced: +# tests/fixtures/tls/ — unit test in-process TlsEchoServer (TlsConnectionTest) +# test-configs/tls/ — Docker integration server identity (TlsIntegrationTest) +# +# CA private keys are intentionally NOT written to the tree (they are not part of +# the committed fixtures); each run regenerates the whole chain together. +# +# Usage: +# scripts/gen-test-certs.sh +# Override output locations (used by the project's own self-test): +# UNIT_DIR=/tmp/u INT_DIR=/tmp/i scripts/gen-test-certs.sh + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO="$(cd "$SCRIPT_DIR/.." && pwd)" + +UNIT_DIR="${UNIT_DIR:-$REPO/tests/fixtures/tls}" +INT_DIR="${INT_DIR:-$REPO/test-configs/tls}" +DAYS="${DAYS:-36500}" # ~100 years, matches the committed fixtures +P12_PASS="${P12_PASS:-password}" # server.p12 password expected by the integration test + +mkdir -p "$UNIT_DIR" "$INT_DIR" +TMP="$(mktemp -d)" +trap 'rm -rf "$TMP"' EXIT + +# make_ca +# Self-signed root. Stock `req -x509` adds critical basicConstraints CA:TRUE plus +# Subject/Authority Key Identifier (the default v3_ca extensions) — matching the +# committed CAs. +make_ca() { + openssl req -x509 -newkey rsa:2048 -nodes -sha256 -days "$DAYS" \ + -keyout "$2" -out "$1" -subj "/CN=$3" 2>/dev/null +} + +# make_leaf +# Leaf signed by the given CA, carrying only a subjectAltName (as the fixtures do). +make_leaf() { + openssl req -newkey rsa:2048 -nodes -sha256 \ + -keyout "$3" -out "$TMP/leaf.csr" -subj "/CN=$5" 2>/dev/null + openssl x509 -req -in "$TMP/leaf.csr" -CA "$1" -CAkey "$2" \ + -CAserial "$TMP/$(basename "$1").srl" -CAcreateserial \ + -sha256 -days "$DAYS" -out "$4" \ + -extfile <(printf 'subjectAltName=%s\n' "$6") 2>/dev/null +} + +echo ">> unit fixtures -> $UNIT_DIR" +make_ca "$UNIT_DIR/ca.pem" "$TMP/ca.key" "Test Root CA" +make_leaf "$UNIT_DIR/ca.pem" "$TMP/ca.key" \ + "$UNIT_DIR/server.key" "$UNIT_DIR/server.pem" \ + "test.local" "DNS:test.local" +chmod 600 "$UNIT_DIR/server.key" +# Second, unrelated root for the untrusted-anchor rejection test (key discarded). +make_ca "$UNIT_DIR/otherca.pem" "$TMP/otherca.key" "Other Root CA" + +echo ">> integration certs -> $INT_DIR" +make_ca "$INT_DIR/ca.pem" "$TMP/int-ca.key" "Integration Test CA" +make_leaf "$INT_DIR/ca.pem" "$TMP/int-ca.key" \ + "$TMP/int-server.key" "$TMP/int-server.pem" \ + "localhost" "DNS:localhost,IP:127.0.0.1" +# PKCS12 identity the Infinispan server presents: alias 'server', password 'password'. +openssl pkcs12 -export -out "$INT_DIR/server.p12" \ + -inkey "$TMP/int-server.key" -in "$TMP/int-server.pem" \ + -name server -passout "pass:$P12_PASS" 2>/dev/null + +echo ">> done." +echo " Regenerated fixtures are NOT byte-identical to the committed ones (fresh" +echo " random keys/serials). 'git add' them only if you mean to replace the set."