From c4d1b92234aefd82e67d92b97c4a52d53eef70bc Mon Sep 17 00:00:00 2001 From: rigazilla Date: Thu, 12 Nov 2026 17:06:16 +0100 Subject: [PATCH] feat(tls): mutual TLS (PEM client cert/key) + PEM-honest URI keys (#18) Add client-certificate (mutual TLS) support and remove the trust-store URI key ambiguity, staying PEM-only (no JKS/PKCS12). Mutual TLS: - TlsConfig gains cert_file / key_file / key_password (all PEM). - Connection::startTls loads the client cert chain + private key (SSL_CTX_use_certificate_chain_file / use_PrivateKey_file / check_private_key) and supplies the key passphrase via a passwd callback so an encrypted key never blocks on a terminal prompt. Cert and key must be set together. PEM-honest URI keys: - trust_store_file_name -> ca_file; new client_cert_file / client_key_file / client_key_password. - The Java keystore keys (trust_store_*, key_store_*, key_alias) are now rejected with a redirect to the PEM equivalent instead of a generic "not supported yet", so a ported Java URI fails fast with the exact fix rather than silently misreading a .jks as PEM. Deliberate backward-compat break on the shipped #18 key. Tests/fixtures: - +4 mutual-TLS unit cases (success, missing-cert rejection, cert-without-key, cert/key mismatch) and URI parse/redirect cases; 266 unit tests pass. - New PEM client fixtures (client.pem/client.key/clientca.pem); gen-test-certs.sh extended to reproduce them. TlsIntegrationTest URI updated to ca_file. - TLS 1.3 note: a missing-client-cert rejection surfaces on first I/O, not at connect(); the test asserts across connect()+first I/O. Docs: STATUS.md, DECISIONS.md (superseding entry), security.adoc, README.md. Co-Authored-By: Claude Opus 4.8 --- README.md | 39 ++++++----- docs/DECISIONS.md | 47 +++++++++++++ docs/STATUS.md | 85 +++++++++++++++--------- documentation/topics/security.adoc | 60 ++++++++++++++++- include/hotrod/HotRodURI.h | 61 ++++++++++++----- include/hotrod/RemoteCache.h | 8 ++- include/hotrod/TlsConfig.h | 26 ++++++-- scripts/gen-test-certs.sh | 8 +++ src/operations/RemoteCache.cpp | 6 +- src/transport/Connection.cpp | 46 +++++++++++++ tests/fixtures/tls/client.key | 28 ++++++++ tests/fixtures/tls/client.pem | 19 ++++++ tests/fixtures/tls/clientca.pem | 19 ++++++ tests/integration/TlsIntegrationTest.cpp | 4 +- tests/unit/HotRodURITest.cpp | 41 ++++++++++-- tests/unit/TlsConnectionTest.cpp | 83 ++++++++++++++++++++++- 16 files changed, 493 insertions(+), 87 deletions(-) create mode 100644 tests/fixtures/tls/client.key create mode 100644 tests/fixtures/tls/client.pem create mode 100644 tests/fixtures/tls/clientca.pem diff --git a/README.md b/README.md index ae0b75d..bf6505e 100644 --- a/README.md +++ b/README.md @@ -200,11 +200,14 @@ coverage breakdown and counts. 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) +- ✅ **TLS, incl. mutual TLS** (`setTls(...)` / `hotrods://`, issue #18) — wraps + every connection in a TLS session (OpenSSL); PEM material only. Server-auth: PEM + trust (`ca_file`, empty = system store), SNI, host-name validation (default on), + min TLS 1.2. Mutual TLS: PEM client cert + key. URI keys: `ca_file`, + `sni_host_name`, `ssl_hostname_validation`, `client_cert_file`, `client_key_file`, + `client_key_password`. Java keystore keys (`*_store_file_name`/`*_store_type`/…) + are rejected with a pointer to the PEM key; JKS/PKCS12 and cipher tuning 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) @@ -259,15 +262,21 @@ cache->connect(); // #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. 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). +// "4.0"/"4.1" form) are honoured. hotrods:// enables TLS (PEM material only); the +// ca_file (PEM CA) / sni_host_name / ssl_hostname_validation params and the mutual- +// TLS client_cert_file / client_key_file / client_key_password params map to +// setTls(...). The Java keystore keys (trust_store_file_name, key_store_*, …) are +// rejected with a pointer to the PEM key. 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 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"); +// // Server-auth TLS from a URI (private CA): +// auto c = RemoteCache::fromUri("hotrods://cache:11222?ca_file=/etc/pki/ca.pem"); +// // Mutual TLS (client cert + key): +// auto m = RemoteCache::fromUri("hotrods://cache:11222?ca_file=/etc/pki/ca.pem" +// "&client_cert_file=/etc/pki/client.pem" +// "&client_key_file=/etc/pki/client-key.pem"); // // or programmatically: // RemoteCache cache("cache", 11222); // cache.setTls("/etc/pki/ca.pem"); // ca_file; empty = system trust store @@ -285,9 +294,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(...)` +- ✅ **TLS, incl. mutual TLS** (shipped, issue #18): `hotrods://` + `setTls(...)`, PEM only - **Step 12 — Bulk operations** (next): `GET_ALL`, `PUT_ALL`, `BULK_GET` -- Also: multiplexing benchmarks, mutual TLS (client cert/key, issue #10) +- Also: multiplexing benchmarks, non-SCRAM SASL + PKCS12/JKS keystores (issue #10) ## Project Structure diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index fbab15c..38468e4 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -1271,3 +1271,50 @@ when the fixtures must actually change, and the regenerated files must then be 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). + +## 2026-11-12 — PEM-honest TLS URI keys + mutual TLS (client cert/key) + +**What:** Two linked changes to the TLS story. + +1. **Mutual TLS (client certificate).** `TlsConfig` gains `cert_file` / `key_file` / + `key_password` (all PEM). `Connection::startTls` now loads a client cert chain + + private key (`SSL_CTX_use_certificate_chain_file` + + `SSL_CTX_use_PrivateKey_file` + `SSL_CTX_check_private_key`) and supplies the key + passphrase via `SSL_CTX_set_default_passwd_cb` so an encrypted key never blocks on + a terminal prompt. cert and key must be set together (fail-fast otherwise). + +2. **PEM-honest URI keys + fail-fast on Java keystore keys.** The server-trust URI + key was renamed `trust_store_file_name` → **`ca_file`** (the name no longer + implies a JKS/PKCS12 container). New client-identity keys **`client_cert_file`**, + **`client_key_file`**, **`client_key_password`**. The Java keystore keys + (`trust_store_file_name`, `trust_store_type`, `trust_store_password`, + `key_store_file_name`, `key_store_type`, `key_store_password`, `key_alias`) are + now **rejected with a redirect message** pointing at the PEM equivalent, instead + of the old generic "not supported yet". + +**Why it matters:** This client uses PEM, not Java keystores (decided for the #18 +trust store). The shipped #18 key `trust_store_file_name` *accepted* a path but read +it as PEM — so a ported Java URI (`trust_store_file_name=truststore.jks`) would have +been silently misread. That was the one TLS URI footgun that failed silently rather +than loudly. Renaming to `ca_file` and making every keystore key throw with the fix +("use `ca_file=` / `client_cert_file=`+`client_key_file=` (PEM)") removes the +ambiguity: a ported Java URI now fails fast with the exact correction. + +**Superseded:** the 2026-11-06 #18 decision that the URI carried +`trust_store_file_name` as a PEM CA path — that key is now rejected; use `ca_file`. +This is a deliberate backward-compat break, taken while #18 is still fresh. + +**Gotcha discovered (TLS 1.3 mutual-TLS failure surfaces late):** when the server +requires a client cert and the client presents none, `SSL_connect()` *succeeds* +under TLS 1.3 — the server's "certificate required" alert only arrives on the first +I/O. (Under TLS 1.2 it fails at the handshake.) Production is unaffected because a +PING/SASL exchange immediately follows connect(); the unit test asserts the failure +across connect()+first-I/O rather than at connect() alone. + +**Deferred still:** PKCS12/JKS keystore formats (PEM only, by decision), non-SCRAM +SASL, timeouts (issue #10). EXTERNAL SASL (which authenticates via the client cert) +is now unblocked by this change but not yet implemented. + +**Keys still rejected (not keystore-related):** `use_ssl`, `ssl_protocol`, +`ssl_ciphers`, `ssl_named_groups`, `ssl_provider`, `ssl_context` — protocol/cipher +tuning deferred (issue #10). diff --git a/docs/STATUS.md b/docs/STATUS.md index fc96817..55c3fbf 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-09 +> **Last updated:** 2026-11-12 --- @@ -41,9 +41,11 @@ _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)): -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._ +mutual TLS (PEM client cert/key) + PEM-honest TLS URI keys (`ca_file`, +`client_cert_file`/`client_key_file`; Java keystore keys now rejected with a +redirect) (#18, 2026-11-12), 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._ --- @@ -59,19 +61,26 @@ pull from here next. Step numbers follow `BULK_GET` (0x1F, iterator-style). **Other known work (not roadmap steps):** +- [ ] **Mutual-TLS integration coverage** — client cert/key is unit-tested + (in-process OpenSSL server requiring a client cert) but not yet covered by the + Docker `TlsIntegrationTest`, which needs the Infinispan server configured to + require/verify client certs (extend `scripts/start_infinispan_tls.sh` + + `gen-test-certs.sh` already emits the unit client cert). - [ ] **Benchmark the multiplexing path** — the async rewrite targets 5–10× 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):** `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". + `socket_timeout`, non-SCRAM SASL (PLAIN/OAUTHBEARER `token`, EXTERNAL — now + unblocked by mutual TLS), `protocol_version=AUTO`/3.x. Each drops its + "unsupported" throw from `HotRodURI::parse` once the capability lands. + (Multi-server seed list — #12 — and TLS incl. mutual TLS — #18 — are already + shipped; see "Working and shipped".) +- [ ] **TLS keystore formats + tuning (deferred part of #18/#10):** Java keystore + formats (JKS/PKCS12, `*_store_file_name`/`*_store_type`/password/`key_alias`) — + this client is PEM-only, so these URI keys are rejected with a redirect to the + PEM keys (`ca_file`, `client_cert_file`/`client_key_file`). Also deferred: + `ssl_protocol`/`ssl_ciphers`/`ssl_named_groups`/`ssl_provider`/`use_ssl`. **Longer horizon (Step 14+ advanced features):** transactions (XA), client listeners/events, counters, Ickle queries, streaming ops (4.1+), multimap, @@ -93,23 +102,32 @@ Rod URI `fromUri` (#9), multi-server seed list + failover (#12)._ `hotrod[s]://[user:pass@]host[:port][,host...][?k=v]` connection string (issue #9); pure header-only parser `HotRodURI::parse` (`include/hotrod/HotRodURI.h`). `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(...)` + `sasl_mechanism`/`client_intelligence`/`protocol_version` + the PEM TLS params + (`ca_file`/`sni_host_name`/`ssl_hostname_validation` and mutual-TLS + `client_cert_file`/`client_key_file`/`client_key_password`); userinfo and query + values are percent-decoded (java.net.URI parity); unsupported schemes/params and + the Java keystore keys throw. timeouts/non-SCRAM deferred (issue #10) +- **TLS incl. mutual 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 + topology-discovered) in a TLS session over OpenSSL. All certificate material is + **PEM** (not Java JKS/PKCS12). Server-auth: PEM trust material (`ca_file`, empty = + system store), SNI (`sni_host`, skipped for literal IPs), host-name validation + (`hostname_validation`, default on; chain verification always on), min TLS 1.2. + **Mutual TLS:** PEM client cert chain (`cert_file`) + private key (`key_file`) + + optional passphrase (`key_password`), loaded with a passwd callback so an + encrypted key never blocks on a prompt; cert/key must be set together. + `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). **URI keys:** `ca_file`, `sni_host_name`, + `ssl_hostname_validation`, `client_cert_file`, `client_key_file`, + `client_key_password`; the Java keystore keys (`trust_store_file_name`, + `key_store_*`, `*_store_type`/password, `key_alias`) are rejected with a redirect + to the PEM key. Unit-tested against an in-process OpenSSL server (server-auth + + mutual TLS) 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) + death. JKS/PKCS12 keystore formats + cipher/protocol tuning 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 @@ -171,19 +189,22 @@ Rod URI `fromUri` (#9), multi-server seed list + failover (#12)._ that stalls a subprocess fails fast instead of hanging the whole CI job. See [`DECISIONS.md`](DECISIONS.md). -**Test status (verified 2026-10-19):** **250 unit** + **96 integration** (20 -suites), all passing. This is the one authoritative count — other docs describe -*what* is covered rather than repeating totals. Counts read from the built test -binaries via `--gtest_list_tests`, so they match what actually runs. +**Test status:** **266 unit** (verified 2026-11-12) + **96 integration** (20 +suites, verified 2026-10-19), all passing. This is the one authoritative count — +other docs describe *what* is covered rather than repeating totals. Counts read +from the built test binaries via `--gtest_list_tests`, so they match what actually +runs. (The +16 unit tests since 2026-11-09 are the mutual-TLS handshake cases and +the PEM-honest URI-key parsing/redirect cases.) - Unit (`./build/unit_tests`, <1s) — wire primitives/headers, consistent hashing, - server-selection/retry helpers, the SASL/SCRAM handshake, and the Hot Rod URI - parser. + server-selection/retry helpers, the SASL/SCRAM handshake, the TLS handshake + (server-auth + mutual TLS, in-process OpenSSL server), and the Hot Rod URI parser. - Integration (`ctest`, spins up Docker Infinispan single-server + multi-node clusters; also green on Linux CI) — CRUD + metadata/CAS, topology & hash-aware routing, keyed/keyless retry (`RetryView`/ping), SASL/SCRAM against a secured server, Hot Rod URI `fromUri`, and multi-server seed failover. - Full run: `ctest --test-dir build --output-on-failure` → **100% pass, 21/21** - (1 unit + 20 integration suites) — verified end-to-end this session. + (1 unit + 20 integration suites) — last full end-to-end run 2026-10-19; unit + suite re-verified 2026-11-12 (266 pass) after the mutual-TLS/URI changes. - **Concurrency validated (2026-09-25):** the concurrent suites pass 8/8 (incl. `ConcurrentWithFailover`), and a ThreadSanitizer run (`build-tsan/`) reports **no races in production code** — slice-4's `stateMutex_`/`shared_ptr` diff --git a/documentation/topics/security.adoc b/documentation/topics/security.adoc index 2ce7d98..8ee7a6e 100644 --- a/documentation/topics/security.adoc +++ b/documentation/topics/security.adoc @@ -146,5 +146,61 @@ tested config): === TLS / mutual TLS -Transport encryption (TLS/SSL) is **not yet implemented**. See `docs/STATUS.md` -for the current roadmap. +Transport encryption (TLS/SSL) is supported over OpenSSL. All certificate +material is **PEM** — Java keystore formats (JKS/PKCS12) are not supported. + +Enable it with the `hotrods://` URI scheme or `RemoteCache::setTls(...)`; every +connection the client opens (the seed connection and every topology-discovered +cluster member) is then wrapped in a TLS session (minimum TLS 1.2). + +**Server-authenticated TLS** verifies the server's certificate chain (always on) +and, by default, that the certificate matches the host name: + +[source,cpp] +---- +// URI form (private CA): +auto c = RemoteCache::fromUri("hotrods://cache:11222?ca_file=/etc/pki/ca.pem"); + +// Programmatic form (empty ca_file = system/default trust store): +RemoteCache cache("cache", 11222); +cache.setTls("/etc/pki/ca.pem"); +---- + +**Mutual TLS** additionally presents a client certificate. Supply a PEM client +cert chain and its private key (and a passphrase if the key is encrypted): + +[source,cpp] +---- +auto c = RemoteCache::fromUri( + "hotrods://cache:11222" + "?ca_file=/etc/pki/ca.pem" + "&client_cert_file=/etc/pki/client.pem" + "&client_key_file=/etc/pki/client-key.pem"); + +// Or programmatically: +TlsConfig tls; +tls.enabled = true; +tls.ca_file = "/etc/pki/ca.pem"; +tls.cert_file = "/etc/pki/client.pem"; +tls.key_file = "/etc/pki/client-key.pem"; +// tls.key_password = "..."; // only if the key is encrypted +cache.setTls(tls); +---- + +.TLS URI query keys +[cols="1,2",options="header"] +|=== +| Key | Meaning +| `ca_file` | PEM CA bundle to verify the server; empty = system trust store +| `sni_host_name` | SNI server name (skipped for literal IP addresses) +| `ssl_hostname_validation` | `true` (default) / `false` — host-name match toggle +| `client_cert_file` | PEM client certificate chain (mutual TLS) +| `client_key_file` | PEM client private key matching `client_cert_file` +| `client_key_password` | passphrase for an encrypted `client_key_file` +|=== + +NOTE: The Java keystore keys (`trust_store_file_name`, `key_store_file_name`, +`*_store_type`/`*_store_password`, `key_alias`) are rejected — this client uses +PEM. Use `ca_file` for trust and `client_cert_file` + `client_key_file` for the +client identity. Protocol/cipher tuning (`ssl_protocol`, `ssl_ciphers`, …) is not +yet supported (issue #10). See `docs/STATUS.md` for the current roadmap. diff --git a/include/hotrod/HotRodURI.h b/include/hotrod/HotRodURI.h index 720ed96..a40ef73 100644 --- a/include/hotrod/HotRodURI.h +++ b/include/hotrod/HotRodURI.h @@ -30,16 +30,19 @@ namespace hotrod { * * Scope (the rest is deferred to issue #10): * - 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. + * enables TLS; the PEM TLS keys are parsed into `tls`: `ca_file` (server trust), + * `sni_host_name`, `ssl_hostname_validation`, and the mutual-TLS client identity + * `client_cert_file` / `client_key_file` / `client_key_password`. The Java + * keystore keys (trust_store_file_name, key_store_file_name, *_store_type/ + * password, key_alias) are rejected with a message pointing at the PEM keys, + * because this client uses PEM, not JKS/PKCS12 (see docs/DECISIONS.md). * - 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, non-SCRAM SASL, mutual-TLS / - * keystore TLS keys) are therefore rejected rather than silently ignored. + * known key throws. Deferred params (timeouts, non-SCRAM SASL) and the Java + * keystore TLS keys are therefore rejected rather than silently ignored. */ struct HotRodURI { std::vector servers; // all parsed, in order (>=1) @@ -265,9 +268,9 @@ 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. + } else if (key == "ca_file") { + // PEM file holding the trusted CA cert(s) used to verify the + // server. This client uses PEM, not a Java JKS/PKCS12 keystore. tls.ca_file = value; sawTlsParam = true; } else if (key == "sni_host_name") { @@ -276,18 +279,42 @@ inline HotRodURI HotRodURI::parse(const std::string& uri) { } 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" || + } else if (key == "client_cert_file") { + // PEM client certificate chain for mutual TLS (presented to the + // server). Must be paired with client_key_file. + tls.cert_file = value; + sawTlsParam = true; + } else if (key == "client_key_file") { + // PEM client private key matching client_cert_file. + tls.key_file = value; + sawTlsParam = true; + } else if (key == "client_key_password") { + // Passphrase for an encrypted client_key_file. + tls.key_password = value; + sawTlsParam = true; + } else if (key == "trust_store_file_name" || key == "trust_store_type" || + key == "trust_store_password") { + // Java keystore trust keys. This client uses PEM: point the user + // at the PEM equivalent instead of silently misreading the file. + fail("Hot Rod URI parameter '" + key + + "' is not supported; this client uses PEM — use 'ca_file=' " + "(a PEM CA bundle) instead. JKS/PKCS12 keystores are not supported."); + } else if (key == "key_store_file_name" || key == "key_store_type" || + key == "key_store_password" || key == "key_alias") { + // Java keystore identity keys -> PEM client cert/key equivalents. + fail("Hot Rod URI parameter '" + key + + "' is not supported; this client uses PEM — use " + "'client_cert_file=' + 'client_key_file=' (PEM) instead. " + "JKS/PKCS12 keystores are not supported."); + } else if (key == "use_ssl" || 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. + // Recognized Java TLS keys this client does not implement: + // scheme-independent SSL toggle and protocol/cipher/provider + // tuning are deferred (issue #10). Reject explicitly. fail("Hot Rod URI parameter '" + key + - "' is not supported yet (mutual TLS / keystore TLS / " - "cipher tuning are deferred; issue #10)"); + "' is not supported yet (use the hotrods:// scheme to enable " + "TLS; protocol/cipher tuning is deferred, issue #10)"); } else { fail("unsupported Hot Rod URI parameter: " + key); } diff --git a/include/hotrod/RemoteCache.h b/include/hotrod/RemoteCache.h index a0e4cca..a80100e 100644 --- a/include/hotrod/RemoteCache.h +++ b/include/hotrod/RemoteCache.h @@ -389,9 +389,11 @@ class RemoteCache { * 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. + * every topology-discovered cluster member). Certificate material is PEM + * (not Java JKS/PKCS12 keystores). This convenience overload configures + * server-authenticated TLS; for mutual TLS set cert_file/key_file on a + * TlsConfig and use the setTls(const TlsConfig&) overload. See TlsConfig for + * field semantics. * * @param ca_file PEM CA file to verify the server; empty uses the * system/default trust store. diff --git a/include/hotrod/TlsConfig.h b/include/hotrod/TlsConfig.h index 7978ab7..c68c30b 100644 --- a/include/hotrod/TlsConfig.h +++ b/include/hotrod/TlsConfig.h @@ -12,11 +12,11 @@ namespace hotrod { * 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). + * The client always verifies the server's certificate chain. It additionally + * presents a client certificate (mutual TLS) when `cert_file`/`key_file` are set. + * All 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 @@ -30,16 +30,30 @@ namespace hotrod { * 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. + * - cert_file: path to a PEM file holding the client certificate chain presented + * to the server for mutual TLS. Empty means "no client certificate" (the + * default; server-authenticated TLS only). Set together with key_file. + * - key_file: path to a PEM file holding the client private key matching + * cert_file. Empty means none. cert_file and key_file must be set together; a + * cert without a key (or vice versa) is a configuration error caught at handshake. + * - key_password: passphrase for an encrypted key_file. Empty means the key is + * unencrypted. Supplied to OpenSSL so an encrypted key never blocks on a + * terminal passphrase prompt. * * Reference: * - Java: org.infinispan.client.hotrod.configuration.SslConfiguration - * (hostnameValidation default true; sniHostName; trustStore*). + * (hostnameValidation default true; sniHostName; trustStore and keyStore). Java's + * trust/key stores are keystore containers; the PEM equivalents here are + * ca_file (trust) and cert_file/key_file (client identity). */ 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 + std::string cert_file; // PEM client cert chain (mTLS); empty = none + std::string key_file; // PEM client private key; empty = none + std::string key_password; // passphrase for an encrypted key_file }; } // namespace hotrod diff --git a/scripts/gen-test-certs.sh b/scripts/gen-test-certs.sh index 806e7b9..6968355 100755 --- a/scripts/gen-test-certs.sh +++ b/scripts/gen-test-certs.sh @@ -65,6 +65,14 @@ make_leaf "$UNIT_DIR/ca.pem" "$TMP/ca.key" \ 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" +# Client identity for the mutual-TLS tests: a client CA (committed, so the test +# server can trust it) and a client leaf signed by it (client.pem + client.key). +# The client CA *private* key is discarded, like the other CAs. +make_ca "$UNIT_DIR/clientca.pem" "$TMP/clientca.key" "Test Client CA" +make_leaf "$UNIT_DIR/clientca.pem" "$TMP/clientca.key" \ + "$UNIT_DIR/client.key" "$UNIT_DIR/client.pem" \ + "test-client" "DNS:test-client" +chmod 600 "$UNIT_DIR/client.key" echo ">> integration certs -> $INT_DIR" make_ca "$INT_DIR/ca.pem" "$TMP/int-ca.key" "Integration Test CA" diff --git a/src/operations/RemoteCache.cpp b/src/operations/RemoteCache.cpp index 756a64d..7eb7ed8 100644 --- a/src/operations/RemoteCache.cpp +++ b/src/operations/RemoteCache.cpp @@ -95,9 +95,9 @@ 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). + // TLS: the hotrods:// scheme enables it; the PEM TLS keys (ca_file / + // sni_host_name / ssl_hostname_validation and the mutual-TLS client_cert_file + // / client_key_file / client_key_password) are carried in parsed.tls (#18). if (parsed.tls) { cache->setTls(*parsed.tls); diff --git a/src/transport/Connection.cpp b/src/transport/Connection.cpp index 7690ee5..a1ad000 100644 --- a/src/transport/Connection.cpp +++ b/src/transport/Connection.cpp @@ -53,6 +53,18 @@ std::string opensslErrors() { return out.empty() ? "unknown OpenSSL error" : out; } +// OpenSSL private-key passphrase callback. `userdata` is a NUL-terminated +// passphrase (the TlsConfig::key_password); copy it into `buf` (truncated to +// `size`) so an encrypted client key never blocks on an interactive prompt. +int tlsKeyPasswordCb(char* buf, int size, int /*rwflag*/, void* userdata) { + if (userdata == nullptr || size <= 0) return 0; + const char* pw = static_cast(userdata); + int len = static_cast(std::strlen(pw)); + if (len > size) len = size; + std::memcpy(buf, pw, static_cast(len)); + return len; +} + // 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). @@ -310,6 +322,40 @@ void Connection::startTls() { // separately controlled by tls_.hostname_validation. SSL_CTX_set_verify(ctx_, SSL_VERIFY_PEER, nullptr); + // Client identity (mutual TLS): present a PEM certificate chain + private key + // when configured. cert_file and key_file must be set together — a cert + // without its key (or vice versa) cannot complete the handshake, so fail fast + // with a clear message rather than a late, opaque OpenSSL error. + if (!tls_.cert_file.empty() || !tls_.key_file.empty()) { + if (tls_.cert_file.empty() || tls_.key_file.empty()) { + throw std::runtime_error( + "TLS: mutual TLS requires both a client certificate (cert_file) and " + "its private key (key_file); only one was provided"); + } + // Supply the key passphrase (if any) so an encrypted key never blocks on a + // terminal prompt. The userdata pointer is read synchronously inside + // SSL_CTX_use_PrivateKey_file below, while tls_ is alive. + if (!tls_.key_password.empty()) { + SSL_CTX_set_default_passwd_cb(ctx_, tlsKeyPasswordCb); + SSL_CTX_set_default_passwd_cb_userdata( + ctx_, const_cast(tls_.key_password.c_str())); + } + if (SSL_CTX_use_certificate_chain_file(ctx_, tls_.cert_file.c_str()) != 1) { + throw std::runtime_error("TLS: failed to load client certificate '" + + tls_.cert_file + "': " + opensslErrors()); + } + if (SSL_CTX_use_PrivateKey_file(ctx_, tls_.key_file.c_str(), + SSL_FILETYPE_PEM) != 1) { + throw std::runtime_error("TLS: failed to load client private key '" + + tls_.key_file + "': " + opensslErrors()); + } + if (SSL_CTX_check_private_key(ctx_) != 1) { + throw std::runtime_error( + "TLS: client certificate and private key do not match: " + + opensslErrors()); + } + } + ssl_ = SSL_new(ctx_); if (!ssl_) { throw std::runtime_error("TLS: SSL_new failed: " + opensslErrors()); diff --git a/tests/fixtures/tls/client.key b/tests/fixtures/tls/client.key new file mode 100644 index 0000000..978d8f8 --- /dev/null +++ b/tests/fixtures/tls/client.key @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDfk7dDCi98JZhm +6iendTUyF1fBO9RbimWmRlwl6zobTP0iWP0kP8mFczTBe0Jcc3T0LgpGzo4+9IIO +9ajVToGt9k5WZOPN1H8RFbgsEYQ4ot3CgBWak8ltcjFgsFZij1wNjfT9tUqtWXxb +cOtFwbRcy78G+N60eMYUQo06lreO9JTRJcOdqKuwxISo2MaK8nWqoDAifLjpir9/ +ysnkZk+frN01iQZcXyuLkarMQ1ZWLxa0KRtuqOHKtIdHyKbAJ8NJV4KlSBevIuee +np4Do+I3wW9GtNETTS98vM99Du2zDsDxOmJVLXbucrQ3X1WurJyiy2GAs2OZa3on +R+4vezYbAgMBAAECggEARr5V0ZeqeMzokT/sNjeHEoeCU/lbc2+yRE+lHrZ0l2jf ++/tOdibc3CYc/k/DKr+5tP3QcKExL0hs0tD2kDAcJnB2Ty3zSxC++Cf4M7GDNeyK +4N1oeJXkuYXVi/OgEeWsyfkuGQ1BSOK0z7ZGK7dkG6y4kDs1NMO2YXjBeVVxVYEF +B+/y9F7CGTLicC4XES8ddxFv7tSmvCHxINuM+0HQdTob7K24tLzoB+46uaKe6Tfr +QBQbNiV58JhZccCdrrHKQWS4v0dpnenLs4Y8ZT+kxzEucEj0jMqiqjH452zy8VXG +2IUOKzaiX09bzcvcAU1g0eH2Rx9SDTvBOW4JLzEsAQKBgQD4WavSY1RHZFpNNy54 +onsh5i/3ruPwBpN3EpC7tFjn18eQGh3FZ22/VDHjHr/crvvmTTLo1mNCETzUkGJS +SfelMa73KHKo8PlIczlBOFRjm50oPHC0P3VlYGEiEmSrdPbrUYI1xDgeczAam1dC +1SpeMxkaTv9U8Eb9Amrv0B/uAQKBgQDmdrLnYodfBxXLBC66G/4EM3V6wPGjPJuL +Gt1FkfOO7TU4rbmUG40JDN3m0FKLfmbMTuviywbGJ2J2zfDsPZrHmbn5cf4l4Mw8 +Z6cv/OZ2VzthNLdILJoO9h4WKOeVp59RzKghG0/qDi6sdWIb2OMD9365GegwO4VE +xikxOBUcGwKBgGCMS9YAs5UFmG2IVFKlqATnviImJYr8o3uZBhdS53VKV9TXslc5 +/FpzWumW3LPoexlvTaljHzdiCCoC75ZaFyJrjD+dw+WVuPPHh6ypP3Vx28j2pkIM +oZEFxP0/9U8Kq6uUBnDslXyQ/1R4q5XZ1RzF9K5bo7vbpV1bAUO1v5QBAoGAGk+O +2S+8eLLcYBMYKpMrits9HEiOza4Lq/PjMyAYiEa4fsIGn8wNa+0WIFXENry1i7mu +4HOBUHoKmbmlObNGymbYfovvEe/6ISNMSQQ8Y2JOGyjji8/bvr2Gbc05szIx1Crj +PvRZSUVZOsMj8j3unPNSeltk0Kza6CEfbskST+UCgYAXueUwydplhJHCgJNw5JZm +5K2ZM1exeAoGtMgXrXet/pj+ln9wKf41PIUKvihNLbemz7+vIzoEMFAASndSC5Nr +FhQBv6cZhbvY8//XvXqB5hsSOhPguxVdHfRv7U83OPBw/IZv6pmwuZAJn3dgG+WR +dUz1cduD1uX/3XVfOg5eSQ== +-----END PRIVATE KEY----- diff --git a/tests/fixtures/tls/client.pem b/tests/fixtures/tls/client.pem new file mode 100644 index 0000000..9126ec5 --- /dev/null +++ b/tests/fixtures/tls/client.pem @@ -0,0 +1,19 @@ +-----BEGIN CERTIFICATE----- +MIIDGTCCAgGgAwIBAgIUHU22nlhh/c3K2HTpkzR0TTR8QD0wDQYJKoZIhvcNAQEL +BQAwGTEXMBUGA1UEAwwOVGVzdCBDbGllbnQgQ0EwIBcNMjYxMTEyMTU0OTE4WhgP +MjEyNjEwMTkxNTQ5MThaMBYxFDASBgNVBAMMC3Rlc3QtY2xpZW50MIIBIjANBgkq +hkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA35O3QwovfCWYZuonp3U1MhdXwTvUW4pl +pkZcJes6G0z9Ilj9JD/JhXM0wXtCXHN09C4KRs6OPvSCDvWo1U6BrfZOVmTjzdR/ +ERW4LBGEOKLdwoAVmpPJbXIxYLBWYo9cDY30/bVKrVl8W3DrRcG0XMu/BvjetHjG +FEKNOpa3jvSU0SXDnairsMSEqNjGivJ1qqAwIny46Yq/f8rJ5GZPn6zdNYkGXF8r +i5GqzENWVi8WtCkbbqjhyrSHR8imwCfDSVeCpUgXryLnnp6eA6PiN8FvRrTRE00v +fLzPfQ7tsw7A8TpiVS127nK0N19VrqycosthgLNjmWt6J0fuL3s2GwIDAQABo1ow +WDAWBgNVHREEDzANggt0ZXN0LWNsaWVudDAdBgNVHQ4EFgQUz5n2Vqqz1bf8/cFY +nfKC1KfPeOQwHwYDVR0jBBgwFoAUkw7qZjU1wQQtF0o/RjGN7PkvTe0wDQYJKoZI +hvcNAQELBQADggEBAIYSEFAvmauCxIPF4y73kmJDxvaoqxaTEUeTXyRnhtO39nQg +f5lCa12Qv1bHbJ7o9JWdrQPTfxEklnJFIMhgLo0b/5qW1yDdJ68Z0OE8JbMdTrDe +5kjOQ0IZg/35kWcoucFjF/4PFCPrsZngIf3vgd+ZhdX4/xAMu2gQqqPoD+kFB66s +sGhO2VGx+6CLGA9jDAC0NWti21phRaTjlvJnT2f2F52VADK4LHfgu9KjzRbJ7S1m +Zjda1T02j7h2lF/sFAJYsKUpa36ngH6qkcPfRiCHqEHj1vBWeXWHbyEXg9JvTnw9 +WfgT+w/qKmDF0duOHiz+X6vylkdbwhkgW+ikQas= +-----END CERTIFICATE----- diff --git a/tests/fixtures/tls/clientca.pem b/tests/fixtures/tls/clientca.pem new file mode 100644 index 0000000..ce90149 --- /dev/null +++ b/tests/fixtures/tls/clientca.pem @@ -0,0 +1,19 @@ +-----BEGIN CERTIFICATE----- +MIIDFTCCAf2gAwIBAgIUBj5RoHwB9IFqt6WCKWlFcb6IkLAwDQYJKoZIhvcNAQEL +BQAwGTEXMBUGA1UEAwwOVGVzdCBDbGllbnQgQ0EwIBcNMjYxMTEyMTU0OTE4WhgP +MjEyNjEwMTkxNTQ5MThaMBkxFzAVBgNVBAMMDlRlc3QgQ2xpZW50IENBMIIBIjAN +BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAo1s9R5gcpwKew10e/ydYPopYMM3A +F6c3GxtXvOkyI1zntc+fjGE6kEgoZaqXovOgVRwbgiW9ogOOeHhxjRHqsiSvaz/S +KW8w8oF/7GrjV/nq/H+FhxYfLLG7+n1J81TrvAVhoSiiesSACpPVEBw/QKXDLvCz +0ZzKRp9h6SZGsbKv6gir6DQzWMCd8wHcZvEIbpDZswsdfTxrb6oKoD70dI5GjeXM +zpH0VlTgrpzkObvNxgRYJc/xZUAN/nlCH1todDdtx4RgRH/3K7rDloLGlbt72KpZ ++SYrzS00wbw7yZs1AWO2qTWFZhFqRWRZyFRZx6o1zynWYM42tepP3ZkAQQIDAQAB +o1MwUTAdBgNVHQ4EFgQUkw7qZjU1wQQtF0o/RjGN7PkvTe0wHwYDVR0jBBgwFoAU +kw7qZjU1wQQtF0o/RjGN7PkvTe0wDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0B +AQsFAAOCAQEAalHsdaO00IwZs8SZo1tXaPUxvYPRIXX+tnomxTEqb11FCbzfK2sT +X4Ym+0TmQkSljPaqr6gatfReRnz+PGn7nIMyWua0WNgAbs0nDf64ohAFjJn46gL+ +3UhgzNA8lPygGQnkp1Hyi4BHXcI8yaNaozYSZag5bhH25KpeS0eKcU4AjkqS/hFg +cIe6mOa6WsXzkr0MVNd8v44S6fG2cNpRpQbF46RyTUb7AIISxLlgGtkCie5agVjU +U64HW2HvVDmnU/MYpJpEa+ODXK6DpZ7CYo8xJcYH9SD+CdJ3RO0GAPIaZmEuipdf +7CYusRWh0beRolIGavjOWhcXDBJ+oQ4DWQ== +-----END CERTIFICATE----- diff --git a/tests/integration/TlsIntegrationTest.cpp b/tests/integration/TlsIntegrationTest.cpp index b7edd17..c852390 100644 --- a/tests/integration/TlsIntegrationTest.cpp +++ b/tests/integration/TlsIntegrationTest.cpp @@ -6,7 +6,7 @@ * 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. + * 2. hotrods:// URI with ca_file -> 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. @@ -107,7 +107,7 @@ TEST(TlsIntegrationTest, FromUriHotrodsRoundTrips) { const std::string uri = "hotrods://" + TlsServerEnvironment::host + ":" + std::to_string(TlsServerEnvironment::port) + - "?trust_store_file_name=" + TlsServerEnvironment::caFile; + "?ca_file=" + TlsServerEnvironment::caFile; auto cache = RemoteCache::fromUri(uri, kTlsCache); cache->connect(); diff --git a/tests/unit/HotRodURITest.cpp b/tests/unit/HotRodURITest.cpp index ef18e54..5df87eb 100644 --- a/tests/unit/HotRodURITest.cpp +++ b/tests/unit/HotRodURITest.cpp @@ -209,7 +209,7 @@ TEST(HotRodURITest, PlainSchemeHasNoTls) { TEST(HotRodURITest, TlsParamsParsedIntoConfig) { HotRodURI u = HotRodURI::parse( "hotrods://localhost" - "?trust_store_file_name=/etc/pki/ca.pem" + "?ca_file=/etc/pki/ca.pem" "&sni_host_name=cache.example.com" "&ssl_hostname_validation=false"); ASSERT_TRUE(u.tls.has_value()); @@ -217,6 +217,24 @@ TEST(HotRodURITest, TlsParamsParsedIntoConfig) { 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); + // No client identity unless explicitly supplied. + EXPECT_TRUE(u.tls->cert_file.empty()); + EXPECT_TRUE(u.tls->key_file.empty()); + EXPECT_TRUE(u.tls->key_password.empty()); +} + +TEST(HotRodURITest, MutualTlsClientIdentityParsedIntoConfig) { + HotRodURI u = HotRodURI::parse( + "hotrods://localhost" + "?ca_file=/ca.pem" + "&client_cert_file=/client.pem" + "&client_key_file=/client-key.pem" + "&client_key_password=s3cret"); + ASSERT_TRUE(u.tls.has_value()); + EXPECT_EQ(u.tls->ca_file, "/ca.pem"); + EXPECT_EQ(u.tls->cert_file, "/client.pem"); + EXPECT_EQ(u.tls->key_file, "/client-key.pem"); + EXPECT_EQ(u.tls->key_password, "s3cret"); } TEST(HotRodURITest, TlsHostnameValidationBooleanCaseInsensitive) { @@ -234,21 +252,32 @@ TEST(HotRodURITest, TlsHostnameValidationBadBooleanThrows) { 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"), + EXPECT_THROW(HotRodURI::parse("hotrod://h?ca_file=/ca.pem"), HotRodClientException); + EXPECT_THROW(HotRodURI::parse("hotrod://h?client_cert_file=/c.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. +TEST(HotRodURITest, JavaKeystoreKeysRejectedWithRedirect) { + // The Java keystore (JKS/PKCS12) TLS keys are rejected — this client uses PEM. + // They throw regardless of scheme so a ported Java URI fails fast with a fix. for (const char* uri : { - "hotrods://h?use_ssl=true", + "hotrods://h?trust_store_file_name=/truststore.jks", "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", + }) { + EXPECT_THROW(HotRodURI::parse(uri), HotRodClientException) << uri; + } +} + +TEST(HotRodURITest, DeferredTlsKeysThrow) { + // Recognized Java TLS keys we do not implement: the scheme-independent SSL + // toggle and protocol/cipher/provider tuning are deferred (issue #10). + for (const char* uri : { + "hotrods://h?use_ssl=true", "hotrods://h?ssl_protocol=TLSv1.3", "hotrods://h?ssl_ciphers=TLS_AES_256_GCM_SHA384", "hotrods://h?ssl_named_groups=x25519", diff --git a/tests/unit/TlsConnectionTest.cpp b/tests/unit/TlsConnectionTest.cpp index 2c1a097..ed2b801 100644 --- a/tests/unit/TlsConnectionTest.cpp +++ b/tests/unit/TlsConnectionTest.cpp @@ -61,7 +61,10 @@ std::string fixture(const char* name) { // cert + key. Robust to clients that abort mid-handshake (failure-path tests). class TlsEchoServer { public: - TlsEchoServer(const std::string& certFile, const std::string& keyFile) { + // clientCaFile != "" turns on mutual TLS: the server requires a client + // certificate and verifies it against that PEM CA. + TlsEchoServer(const std::string& certFile, const std::string& keyFile, + const std::string& clientCaFile = "") { 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) @@ -69,6 +72,14 @@ class TlsEchoServer { if (SSL_CTX_use_PrivateKey_file(ctx_, keyFile.c_str(), SSL_FILETYPE_PEM) != 1) throw std::runtime_error("server key load failed: " + keyFile); + if (!clientCaFile.empty()) { + if (SSL_CTX_load_verify_locations(ctx_, clientCaFile.c_str(), nullptr) != 1) + throw std::runtime_error("server client-CA load failed: " + clientCaFile); + SSL_CTX_set_verify(ctx_, + SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, + nullptr); + } + listenFd_ = ::socket(AF_INET, SOCK_STREAM, 0); if (listenFd_ < 0) throw std::runtime_error("server socket() failed"); int one = 1; @@ -207,4 +218,74 @@ TEST(TlsConnectionTest, HostnameMismatch_ValidationOff_Succeeds) { server.stop(); } +// --- mutual TLS (client certificate) ----------------------------------------- + +TEST(MutualTlsConnectionTest, ClientCertPresentedAndTrusted_HandshakeSucceeds) { + // Server requires a client cert signed by clientca.pem. + TlsEchoServer server(fixture("server.pem"), fixture("server.key"), + fixture("clientca.pem")); + + Connection conn("127.0.0.1", server.port()); + TlsConfig tls = clientTls(fixture("ca.pem"), "test.local", true); + tls.cert_file = fixture("client.pem"); + tls.key_file = fixture("client.key"); + conn.setTls(tls); + ASSERT_NO_THROW(conn.connect()); + + const ByteArray msg{0x11, 0x22, 0x33}; + conn.send(msg); + EXPECT_EQ(conn.receive(msg.size()), msg); + + conn.close(); + server.stop(); +} + +TEST(MutualTlsConnectionTest, NoClientCertWhenServerRequires_Fails) { + TlsEchoServer server(fixture("server.pem"), fixture("server.key"), + fixture("clientca.pem")); + + Connection conn("127.0.0.1", server.port()); + // Server-auth only: no client cert presented, but the server demands one. + conn.setTls(clientTls(fixture("ca.pem"), "test.local", true)); + // Under TLS 1.2 the server's "certificate required" rejection fails the + // handshake at connect(); under TLS 1.3 SSL_connect completes and the alert + // only surfaces on the first I/O (which is what production does next: a PING / + // SASL exchange). Either way the exchange must fail, not silently succeed. + EXPECT_THROW({ + conn.connect(); + conn.send(ByteArray{0x01}); + conn.receive(1); + }, std::runtime_error); + + server.stop(); +} + +TEST(MutualTlsConnectionTest, CertWithoutKey_IsConfigError) { + TlsEchoServer server(fixture("server.pem"), fixture("server.key"), + fixture("clientca.pem")); + + Connection conn("127.0.0.1", server.port()); + TlsConfig tls = clientTls(fixture("ca.pem"), "test.local", true); + tls.cert_file = fixture("client.pem"); // key_file deliberately left empty + conn.setTls(tls); + EXPECT_THROW(conn.connect(), std::runtime_error); + + server.stop(); +} + +TEST(MutualTlsConnectionTest, MismatchedCertAndKey_IsConfigError) { + TlsEchoServer server(fixture("server.pem"), fixture("server.key"), + fixture("clientca.pem")); + + Connection conn("127.0.0.1", server.port()); + TlsConfig tls = clientTls(fixture("ca.pem"), "test.local", true); + // Client cert paired with the *server* key -> SSL_CTX_check_private_key fails. + tls.cert_file = fixture("client.pem"); + tls.key_file = fixture("server.key"); + conn.setTls(tls); + EXPECT_THROW(conn.connect(), std::runtime_error); + + server.stop(); +} + #endif // !_WIN32