diff --git a/CMakeLists.txt b/CMakeLists.txt index cb7a64a..3633fc9 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 @@ -331,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 @@ -370,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 @@ -452,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. @@ -463,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/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..fbab15c 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -1075,3 +1075,199 @@ 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. + +**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 — 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`, +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. + +## 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. + +## 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/docs/STATUS.md b/docs/STATUS.md index e2a4171..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-10-19 +> **Last updated:** 2026-11-09 --- @@ -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,30 @@ 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` (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 + 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/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/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." 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 new file mode 100755 index 0000000..30249cc --- /dev/null +++ b/scripts/start_infinispan_tls.sh @@ -0,0 +1,63 @@ +#!/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. +# --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" \ + 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/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..7690ee5 100644 --- a/src/transport/Connection.cpp +++ b/src/transport/Connection.cpp @@ -1,6 +1,12 @@ #include "hotrod/Connection.h" #include #include +#include + +#include +#include +#include +#include // Platform-specific includes #ifdef _WIN32 @@ -18,8 +24,108 @@ #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 { + +// 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; +} + +#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 #ifdef _WIN32 struct WinsockInitializer { @@ -82,6 +188,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; @@ -154,6 +271,115 @@ 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) { + // 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()); + } + } + +#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) { + // 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,13 +392,22 @@ 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) { 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))); } @@ -194,6 +429,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 +479,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/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: 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 0000000..f666093 Binary files /dev/null and b/test-configs/tls/server.p12 differ 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/integration/TlsIntegrationTest.cpp b/tests/integration/TlsIntegrationTest.cpp new file mode 100644 index 0000000..b7edd17 --- /dev/null +++ b/tests/integration/TlsIntegrationTest.cpp @@ -0,0 +1,178 @@ +/** + * Server-authenticated TLS Integration Tests (Docker-backed), issue #18. + * + * Runs against a TLS-enabled Infinispan server started by + * scripts/start_infinispan_tls.sh (Hot Rod endpoint with a PKCS12 server + * identity, SAN DNS:localhost / IP:127.0.0.1, no SASL). The client trusts the + * test CA (test-configs/tls/ca.pem). Verifies the real wire end-to-end: + * 1. Programmatic setTls(ca) -> 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 + +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) { + // 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/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..2c1a097 --- /dev/null +++ b/tests/unit/TlsConnectionTest.cpp @@ -0,0 +1,210 @@ +/** + * 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 { + +// 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; +}(); + +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