From b0d32f5d8b9d3182ce66611b738bb1b4cb91d265 Mon Sep 17 00:00:00 2001 From: rigazilla Date: Thu, 12 Nov 2026 18:15:33 +0100 Subject: [PATCH] =?UTF-8?q?feat(auth):=20non-SCRAM=20SASL=20=E2=80=94=20PL?= =?UTF-8?q?AIN,=20EXTERNAL,=20OAUTHBEARER=20(#10)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Generalize the SASL driver beyond SCRAM to three single-message mechanisms. The wire layer (AuthCodec/SaslTransport) was already mechanism-agnostic; only SaslAuthenticator was SCRAM-specific. Mechanisms: - PLAIN (RFC 4616): username/password; requires a username. Use over TLS. - EXTERNAL (RFC 4422): identity from the mutual-TLS client cert; no creds. - OAUTHBEARER (RFC 7628): bearer token, incl. the failure-continuation turn. GSSAPI/GS2-KRB5 and DIGEST-MD5 remain unsupported (throw at connect()). API/config: - Authentication gains a `token` field; new RemoteCache::setAuthentication(const Authentication&) overload for token/cert mechanisms. - HotRodURI parses `token`; fromUri enables auth on any signal (mechanism, creds, or token) since EXTERNAL/OAUTHBEARER need no username. - Pure, unit-testable initial-response builders in SaslMechanisms.h. Tests (+18): pure builders + driver flows against fake servers (success, bad creds, missing username/token, mechanism-not-offered, OAUTHBEARER failure continuation) + URI cases. 284 unit tests pass. Integration coverage is unit-only (needs server realms/token issuer) β€” tracked in STATUS backlog. Docs: STATUS.md, DECISIONS.md, security.adoc, README.md. Co-Authored-By: Claude Opus 4.8 --- CMakeLists.txt | 1 + README.md | 17 +-- docs/DECISIONS.md | 45 ++++++++ docs/STATUS.md | 43 +++++--- documentation/topics/security.adoc | 60 ++++++++-- include/hotrod/Authentication.h | 17 ++- include/hotrod/HotRodURI.h | 14 ++- include/hotrod/RemoteCache.h | 30 +++-- include/hotrod/SaslMechanisms.h | 76 +++++++++++++ src/auth/SaslAuthenticator.cpp | 74 +++++++++++-- src/operations/RemoteCache.cpp | 27 +++-- tests/unit/HotRodURITest.cpp | 28 ++++- tests/unit/SaslAuthenticatorTest.cpp | 159 ++++++++++++++++++++++++++- tests/unit/SaslMechanismsTest.cpp | 57 ++++++++++ 14 files changed, 575 insertions(+), 73 deletions(-) create mode 100644 include/hotrod/SaslMechanisms.h create mode 100644 tests/unit/SaslMechanismsTest.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 3633fc9..0a3b063 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/SaslMechanismsTest.cpp tests/unit/TlsConnectionTest.cpp ) diff --git a/README.md b/README.md index bf6505e..669ac47 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ A cross-platform C++17 implementation of the Infinispan Hot Rod protocol client. πŸŽ‰ **Smart client** - hash-aware routing, automatic failover, full CRUD + metadata ops, typed error handling and user-decided retry (keyed & keyless), -and SASL/SCRAM authentication (SCRAM-SHA-1/256/512). +and SASL authentication (SCRAM-SHA-1/256/512, PLAIN, EXTERNAL, OAUTHBEARER). ## Quick Start @@ -193,9 +193,11 @@ coverage breakdown and counts. tried nodes) + `isTransient` / `outcomeUncertain` classification (Step 11a) - βœ… **User-decided retry** (`cache.excluding(e)` bound view) for keyed ops and keyless `ping`, with automatic before-send failover (Step 11b/11c) -- βœ… **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) +- βœ… **SASL authentication** (`setAuthentication(...)`) β€” end-to-end, applied to + every connection: SCRAM family (`SCRAM-SHA-1`/`-256`/`-512`), **PLAIN**, + **EXTERNAL** (identity from the mutual-TLS client cert), and **OAUTHBEARER** + (bearer `token`). GSSAPI/DIGEST-MD5 throw at connect(). See + [`documentation/topics/security.adoc`](documentation/topics/security.adoc) - βœ… **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 @@ -261,8 +263,9 @@ cache->connect(); // 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. hotrods:// enables TLS (PEM material only); the +// enable SCRAM by default; sasl_mechanism (SCRAM*/PLAIN/EXTERNAL/OAUTHBEARER, with +// token for OAUTHBEARER) / client_intelligence / protocol_version (Java "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 @@ -296,7 +299,7 @@ cache->connect(); user-decided retry (keyed + keyless) - βœ… **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, non-SCRAM SASL + PKCS12/JKS keystores (issue #10) +- Also: multiplexing benchmarks, GSSAPI SASL (Kerberos) + PKCS12/JKS keystores (issue #10) ## Project Structure diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index 38468e4..759a8dd 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -1318,3 +1318,48 @@ 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). + +## 2026-11-12 β€” Non-SCRAM SASL: PLAIN, EXTERNAL, OAUTHBEARER + +**What:** The SASL driver (`SaslAuthenticator`) now supports three single-message +mechanisms beyond the SCRAM family: **PLAIN** (RFC 4616), **EXTERNAL** (RFC 4422), +and **OAUTHBEARER** (RFC 7628). GSSAPI/GS2-KRB5 (Kerberos) and DIGEST-MD5 remain +unsupported and throw at connect(). + +- `Authentication` gains a `token` field (OAUTHBEARER bearer token). A new + `RemoteCache::setAuthentication(const Authentication&)` overload configures + mechanisms the username/password convenience setter can't (OAUTHBEARER token, + EXTERNAL cert identity). +- `HotRodURI` now parses `token` (previously an unknown-key error) and keeps + `sasl_mechanism`; `fromUri` enables auth on *any* auth signal (mechanism, creds, + or token) rather than requiring a username β€” EXTERNAL/OAUTHBEARER have none. +- Pure, unit-testable initial-response builders live in + `include/hotrod/SaslMechanisms.h` (header-only, like `AuthCodec.h`). + +**Why it matters:** The wire layer (`AuthCodec`, `SaslTransport`) was already +mechanism-agnostic β€” it carries a mechanism name + opaque token bytes β€” so only the +driver was SCRAM-specific. Generalizing it (classify mechanism β†’ SCRAM multi-turn +vs single-message path) kept the well-tested SCRAM flow untouched while adding the +common non-Kerberos mechanisms cheaply. EXTERNAL was unblocked by mutual TLS +(same-day #18 work): the client identity is the TLS client certificate. + +**Design notes / gotchas:** +- **PLAIN** builds `authzid NUL authcid NUL passwd` as raw bytes (NULs), never a C + string; authzid empty = authorize as the authcid. Must be used over TLS (password + is effectively cleartext). Requires a username (throws otherwise, BeforeSend). +- **EXTERNAL** sends the authorization id (usually empty β€” identity from the cert). + Needs no credentials; pointless without a mutual-TLS client cert. +- **OAUTHBEARER** sends `n,[a=authzid],^Aauth=Bearer ^A^A` (^A = 0x01). + Requires a token (throws otherwise). On failure the server returns a non-completed + error challenge and expects a lone `0x01` continuation before failing the exchange + with an ERROR frame (RFC 7628) β€” the driver handles that extra turn. +- Mechanism names are matched case-sensitively against the server's offered list + (as on the wire): use the canonical upper-case names. + +**Coverage:** unit only β€” pure builders + driver flows against fake servers +(success, bad credentials, missing username/token, mechanism-not-offered, +OAUTHBEARER failure continuation). End-to-end integration against a real server is +deferred (needs server realms/token issuer; see STATUS backlog), as with mutual TLS. + +**Deferred:** GSSAPI/GS2-KRB5 (needs MIT krb5/Heimdal + multi-round GSS exchange), +DIGEST-MD5 (obsolete). SASL QOP/`sasl_properties.*` not wired. diff --git a/docs/STATUS.md b/docs/STATUS.md index 55c3fbf..3cd47d8 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -41,7 +41,8 @@ _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)): -mutual TLS (PEM client cert/key) + PEM-honest TLS URI keys (`ca_file`, +non-SCRAM SASL (PLAIN/EXTERNAL/OAUTHBEARER) (#10, 2026-11-12), 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), @@ -66,16 +67,20 @@ pull from here next. Step numbers follow 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). +- [ ] **Non-SCRAM SASL integration coverage** β€” PLAIN/EXTERNAL/OAUTHBEARER are + unit-tested against fake servers but not end-to-end: PLAIN needs a server SASL + realm offering it; EXTERNAL needs mutual TLS + a certβ†’identity mapping; + OAUTHBEARER needs a token issuer/realm. `AuthIntegrationTest` covers SCRAM only. - [ ] **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`, 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".) + `socket_timeout`, `protocol_version=AUTO`/3.x, and GSSAPI/GS2-KRB5 SASL (needs a + Kerberos lib). Each drops its "unsupported" throw from `HotRodURI::parse` once + the capability lands. (Multi-server seed list β€” #12 β€” TLS incl. mutual TLS β€” #18 β€” + and non-SCRAM SASL PLAIN/EXTERNAL/OAUTHBEARER 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 @@ -138,11 +143,15 @@ Rod URI `fromUri` (#9), multi-server seed list + failover (#12)._ Excluding every known server still throws (no seed rescue of an excluded node) - Wire primitives (vInt, vLong, strings, byte arrays) - Protocol 4.0 headers (all conditional fields) -- **SASL/SCRAM authentication (end-to-end)** β€” `setAuthentication(...)` runs the - AUTH_MECH_LIST + two-turn SCRAM handshake on every connection (seed + - topology-discovered), for the whole family (`SCRAM-SHA-1/256/512`, RFC 5802, - OpenSSL); non-SCRAM mechanisms throw at connect(). See - `documentation/topics/security.adoc` +- **SASL authentication (end-to-end)** β€” `setAuthentication(...)` runs the + AUTH_MECH_LIST + AUTH handshake on every connection (seed + topology-discovered). + Mechanisms: SCRAM family (`SCRAM-SHA-1/256/512`, RFC 5802, two-turn), **PLAIN** + (RFC 4616), **EXTERNAL** (RFC 4422 β€” identity from the mutual-TLS client cert), + **OAUTHBEARER** (RFC 7628 β€” bearer `token`); single-message mechanisms share a + generalized path, pure initial-response builders in `include/hotrod/SaslMechanisms.h`. + URI selects via `sasl_mechanism` (+ `token`); the `Authentication` overload of + `setAuthentication` covers token/cert mechanisms. GSSAPI/DIGEST-MD5 throw at + connect(). All OpenSSL, no JDK SASL provider. See `documentation/topics/security.adoc` - Cluster topology awareness (failover, load balancing) - Consistent hashing (MurmurHash3 x64_32, seed 9001) - Hash-aware routing β†’ primary owner, with automatic failover @@ -189,15 +198,17 @@ 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:** **266 unit** (verified 2026-11-12) + **96 integration** (20 +**Test status:** **284 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.) +runs. (The +34 unit tests since 2026-11-09 are the mutual-TLS handshake cases, the +PEM-honest URI-key parsing/redirect cases, and the non-SCRAM SASL mechanism cases +β€” pure initial-response builders + PLAIN/EXTERNAL/OAUTHBEARER driver flows.) - Unit (`./build/unit_tests`, <1s) β€” wire primitives/headers, consistent hashing, - 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. + server-selection/retry helpers, the SASL handshake (SCRAM family + + PLAIN/EXTERNAL/OAUTHBEARER, against fake servers), 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 diff --git a/documentation/topics/security.adoc b/documentation/topics/security.adoc index 8ee7a6e..1ddd1a7 100644 --- a/documentation/topics/security.adoc +++ b/documentation/topics/security.adoc @@ -2,17 +2,20 @@ === Authentication -The client authenticates over SASL. The **SCRAM family** is implemented: +The client authenticates over SASL. These mechanisms are implemented: * **SCRAM-SHA-256** -- the default when you call `setAuthentication(...)`. -* **SCRAM-SHA-1** -* **SCRAM-SHA-512** - -Any other mechanism (`PLAIN`, `DIGEST-MD5`, `EXTERNAL`, `GSSAPI`, -`OAUTHBEARER`, …) throws a `HotRodClientException` at `connect()` time with a -clear "unsupported SASL mechanism" message. C++ has no JDK-style SASL provider -framework, so each mechanism is hand-rolled over OpenSSL; only the SCRAM variants -share the generalized implementation today. +* **SCRAM-SHA-1**, **SCRAM-SHA-512** +* **PLAIN** -- username + password (always use over TLS; the password is sent + effectively in the clear). +* **EXTERNAL** -- the identity comes from the mutual-TLS client certificate (no + username/password needed); requires a `hotrods://` connection presenting a + client cert (see _TLS / mutual TLS_ below). +* **OAUTHBEARER** -- a bearer `token` (e.g. an OAuth2/OIDC access token). + +Any other mechanism (`DIGEST-MD5`, `GSSAPI`, …) throws a `HotRodClientException` +at `connect()` time with a clear "unsupported SASL mechanism" message. C++ has no +JDK-style SASL provider framework, so each mechanism is hand-rolled over OpenSSL. ==== Configuring authentication @@ -56,12 +59,49 @@ void setAuthentication(const std::string& username, const std::string& mechanism = "SCRAM-SHA-256"); ---- -To use a different SCRAM variant, pass the mechanism explicitly: +To use a different username/password mechanism (another SCRAM variant, or PLAIN), +pass the mechanism explicitly: [source,cpp] ---- cache.setAuthentication("username", "password", "default", "infinispan", "SCRAM-SHA-512"); + +cache.setAuthentication("username", "password", + "default", "infinispan", "PLAIN"); // use over TLS +---- + +For **EXTERNAL** (identity from the client cert) and **OAUTHBEARER** (bearer +token), build an `Authentication` and use the overload that takes it: + +[source,cpp] +---- +#include "hotrod/Authentication.h" + +// OAUTHBEARER: authenticate with a bearer token (no username/password). +Authentication oauth; +oauth.mechanism = "OAUTHBEARER"; +oauth.token = ""; +cache.setAuthentication(oauth); + +// EXTERNAL: identity is the mutual-TLS client certificate (configure TLS too). +Authentication external; +external.mechanism = "EXTERNAL"; +cache.setAuthentication(external); +---- + +From a URI, select the mechanism with `sasl_mechanism` (and `token` for +OAUTHBEARER): + +[source,cpp] +---- +// PLAIN over TLS: +RemoteCache::fromUri("hotrods://user:pass@host?sasl_mechanism=PLAIN&ca_file=/ca.pem"); +// OAUTHBEARER: +RemoteCache::fromUri("hotrods://host?sasl_mechanism=OAUTHBEARER&token=&ca_file=/ca.pem"); +// EXTERNAL (client cert): +RemoteCache::fromUri("hotrods://host?sasl_mechanism=EXTERNAL" + "&ca_file=/ca.pem&client_cert_file=/client.pem&client_key_file=/client-key.pem"); ---- ==== Defaults diff --git a/include/hotrod/Authentication.h b/include/hotrod/Authentication.h index 23d8caa..3d19f47 100644 --- a/include/hotrod/Authentication.h +++ b/include/hotrod/Authentication.h @@ -12,11 +12,17 @@ namespace hotrod { * seed connection and every topology-discovered cluster member β€” before the * connection is used for operations. * - * Only the SCRAM family is implemented (SCRAM-SHA-1 / SCRAM-SHA-256 / - * SCRAM-SHA-512); any other configured mechanism throws a HotRodClientException - * at connect time. For the SCRAM mechanisms only `username` and `password` - * actually enter the exchange; `realm` and `serverName` are carried for parity - * with the Java client (and future mechanisms) but are unused by SCRAM. + * Supported mechanisms: + * - SCRAM family: SCRAM-SHA-1 / SCRAM-SHA-256 / SCRAM-SHA-512 β€” uses + * `username` + `password`. + * - PLAIN β€” uses `username` + `password` (send over TLS). + * - EXTERNAL β€” identity comes from the mutual-TLS client certificate; no + * credentials needed (`username`, if set, is sent as the authorization id). + * - OAUTHBEARER β€” uses `token` (a bearer token); `username`, if set, is sent as + * the authorization id. + * Any other configured mechanism throws a HotRodClientException at connect time. + * `realm` and `serverName` are carried for parity with the Java client but are + * not used on the wire by these mechanisms. * * Reference: * - Java: org.infinispan.client.hotrod.configuration.AuthenticationConfiguration @@ -26,6 +32,7 @@ struct Authentication { bool enabled = false; std::string username; std::string password; + std::string token; // bearer token for OAUTHBEARER std::string realm = "default"; std::string serverName = "infinispan"; std::string mechanism = "SCRAM-SHA-256"; diff --git a/include/hotrod/HotRodURI.h b/include/hotrod/HotRodURI.h index a40ef73..332fe69 100644 --- a/include/hotrod/HotRodURI.h +++ b/include/hotrod/HotRodURI.h @@ -41,14 +41,17 @@ namespace hotrod { * 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) and the Java - * keystore TLS keys are therefore rejected rather than silently ignored. + * known key throws. Deferred params (timeouts) and the Java keystore TLS keys + * are therefore rejected rather than silently ignored. SASL mechanism selection + * (`sasl_mechanism`) and the OAUTHBEARER `token` are parsed here and validated + * at connect() (SCRAM family, PLAIN, EXTERNAL, OAUTHBEARER are supported). */ struct HotRodURI { std::vector servers; // all parsed, in order (>=1) std::optional username; std::optional password; std::optional saslMechanism; // e.g. "SCRAM-SHA-256" + std::optional token; // bearer token for OAUTHBEARER std::optional clientIntelligence; std::optional protocolVersion; // Protocol::VERSION_40 / _41 std::optional tls; // set when scheme is hotrods:// @@ -244,8 +247,13 @@ inline HotRodURI HotRodURI::parse(const std::string& uri) { "query parameter value"); if (key == "sasl_mechanism") { - // SCRAM-only is enforced later at connect(); pass through here. + // The mechanism is validated at connect() (SaslAuthenticator); + // pass it through here. result.saslMechanism = value; + } else if (key == "token") { + // Bearer token for OAUTHBEARER (used only when the mechanism is + // OAUTHBEARER; validated at connect()). + result.token = value; } else if (key == "client_intelligence") { const std::string v = toLower(value); if (v == "basic") { diff --git a/include/hotrod/RemoteCache.h b/include/hotrod/RemoteCache.h index a80100e..04b3dc0 100644 --- a/include/hotrod/RemoteCache.h +++ b/include/hotrod/RemoteCache.h @@ -349,20 +349,23 @@ class RemoteCache { } /** - * Configure SASL authentication. Must be called before connect(). + * Configure username/password SASL authentication. Must be called before + * connect(). * * Enables the SASL handshake on every connection the client opens (the seed - * connection and every topology-discovered cluster member). Only the SCRAM - * family is supported β€” SCRAM-SHA-1 / SCRAM-SHA-256 / SCRAM-SHA-512 β€” any - * other mechanism throws a HotRodClientException at connect() time. + * connection and every topology-discovered cluster member). Supported + * mechanisms: the SCRAM family (SCRAM-SHA-1 / -256 / -512) and PLAIN β€” all of + * which use username + password. For EXTERNAL (mutual-TLS client cert) or + * OAUTHBEARER (bearer token), build an Authentication and use the overload + * below. Any other mechanism throws a HotRodClientException at connect() time. * - * For SCRAM only username/password enter the exchange; realm and serverName - * are accepted for parity with the Java client but are unused by SCRAM. + * realm and serverName are accepted for parity with the Java client but are + * not used on the wire by the supported mechanisms. * * @param username SASL authentication username * @param password SASL authentication password - * @param realm Security realm (default "default"; unused by SCRAM) - * @param serverName SASL server name (default "infinispan"; unused by SCRAM) + * @param realm Security realm (default "default"; unused on the wire) + * @param serverName SASL server name (default "infinispan"; unused on the wire) * @param mechanism SASL mechanism (default "SCRAM-SHA-256") */ void setAuthentication(const std::string& username, @@ -378,6 +381,17 @@ class RemoteCache { auth_.mechanism = mechanism; } + /** + * Configure SASL authentication from a prebuilt Authentication. Must be called + * before connect(). Use this for mechanisms the convenience overload above does + * not cover β€” notably OAUTHBEARER (set `token`) and EXTERNAL (identity from the + * mutual-TLS client certificate). Sets `enabled = true`. + */ + void setAuthentication(const Authentication& auth) { + auth_ = auth; + auth_.enabled = true; + } + /** * Current authentication configuration (auth_.enabled is false by default). */ diff --git a/include/hotrod/SaslMechanisms.h b/include/hotrod/SaslMechanisms.h new file mode 100644 index 0000000..129b308 --- /dev/null +++ b/include/hotrod/SaslMechanisms.h @@ -0,0 +1,76 @@ +#pragma once + +#include "Types.h" +#include + +namespace hotrod { + +/** + * Pure, I/O-free builders for the SASL *initial responses* of the single-message + * (non-SCRAM) mechanisms this client supports. Kept header-only and side-effect + * free so the exact wire bytes are unit-testable in isolation (same precedent as + * AuthCodec.h / ServerSelection.h). SaslAuthenticator wraps these in the + * AUTH_MECH_LIST + AUTH exchange. + * + * These mechanisms complete in a single client message (the server answers with + * AUTH_RESPONSE completed=true on success, or an ERROR frame on failure), unlike + * the multi-turn SCRAM family. OAUTHBEARER has one extra client turn only on the + * failure path (RFC 7628), which SaslAuthenticator handles. + * + * References: + * - PLAIN: RFC 4616 β€” message = authzid NUL authcid NUL passwd + * - EXTERNAL: RFC 4422 Β§A β€” message = authorization identity (often empty) + * - OAUTHBEARER: RFC 7628 β€” gs2-header + ^Aauth=Bearer ^A^A (^A = 0x01) + */ + +/** + * PLAIN (RFC 4616): authzid NUL authcid NUL passwd. The response carries NUL + * bytes, so it is built as raw bytes (never a C string). An empty authzid means + * "authorize as the authentication id", which is the usual case. + */ +inline ByteArray saslPlainInitialResponse(const std::string& authzid, + const std::string& authcid, + const std::string& password) { + ByteArray out; + out.reserve(authzid.size() + authcid.size() + password.size() + 2); + out.insert(out.end(), authzid.begin(), authzid.end()); + out.push_back(0x00); + out.insert(out.end(), authcid.begin(), authcid.end()); + out.push_back(0x00); + out.insert(out.end(), password.begin(), password.end()); + return out; +} + +/** + * EXTERNAL (RFC 4422): the initial response is the authorization identity, which + * is typically empty β€” the identity is taken from the mutual-TLS client + * certificate. A non-empty authzid requests authorization as that identity. + */ +inline ByteArray saslExternalInitialResponse(const std::string& authzid) { + return ByteArray(authzid.begin(), authzid.end()); +} + +/** + * OAUTHBEARER (RFC 7628) client-first: + * gs2-header kvsep "auth=Bearer " token kvsep kvsep + * where gs2-header = "n," [ "a=" authzid ] "," and kvsep = 0x01. With an empty + * authzid the header is "n,,". + */ +inline ByteArray saslOAuthBearerInitialResponse(const std::string& authzid, + const std::string& token) { + constexpr char kvsep = 0x01; + std::string msg = "n,"; + if (!authzid.empty()) { + msg += "a="; + msg += authzid; + } + msg += ","; + msg += kvsep; + msg += "auth=Bearer "; + msg += token; + msg += kvsep; + msg += kvsep; + return ByteArray(msg.begin(), msg.end()); +} + +} // namespace hotrod diff --git a/src/auth/SaslAuthenticator.cpp b/src/auth/SaslAuthenticator.cpp index 2bbca74..747ba7c 100644 --- a/src/auth/SaslAuthenticator.cpp +++ b/src/auth/SaslAuthenticator.cpp @@ -4,6 +4,7 @@ #include "hotrod/HotRodClientException.h" #include "hotrod/AuthCodec.h" #include "hotrod/SCRAM.h" +#include "hotrod/SaslMechanisms.h" #include "hotrod/TopologyInfo.h" #include @@ -127,15 +128,25 @@ SaslAuthenticator::SaslAuthenticator(Authentication auth, std::string host, uint void SaslAuthenticator::authenticate(SaslTransport& transport) { const std::vector node{{host_, port_}}; + const std::string& mech = auth_.mechanism; - // 1. Only SCRAM-SHA-1/256/512 are supported this session. - SCRAM::Digest digest; + // 1. Classify the mechanism up-front (before any I/O). SCRAM is a multi-turn + // exchange; PLAIN/EXTERNAL/OAUTHBEARER complete in a single client message. + SCRAM::Digest digest{}; + bool isScram = false; try { - digest = SCRAM::digestForMechanism(auth_.mechanism); + digest = SCRAM::digestForMechanism(mech); + isScram = true; } catch (const std::exception&) { + isScram = false; + } + const bool isSimple = + (mech == "PLAIN" || mech == "EXTERNAL" || mech == "OAUTHBEARER"); + if (!isScram && !isSimple) { throw HotRodClientException( - "Unsupported SASL mechanism: " + auth_.mechanism + - " (supported: SCRAM-SHA-1, SCRAM-SHA-256, SCRAM-SHA-512)", + "Unsupported SASL mechanism: " + mech + + " (supported: SCRAM-SHA-1, SCRAM-SHA-256, SCRAM-SHA-512, PLAIN, " + "EXTERNAL, OAUTHBEARER)", FailurePhase::BeforeSend, std::nullopt, node); } @@ -148,18 +159,65 @@ void SaslAuthenticator::authenticate(SaslTransport& transport) { VInt mechCount = transport.readVInt(); bool offered = false; for (VInt i = 0; i < mechCount; ++i) { - if (transport.readString() == auth_.mechanism) { + if (transport.readString() == mech) { offered = true; // keep reading to drain the rest of the list off the wire } } if (!offered) { throw HotRodClientException( - "SASL mechanism " + auth_.mechanism + " is not offered by the server", + "SASL mechanism " + mech + " is not offered by the server", FailurePhase::AfterSend, std::nullopt, node); } - // 3. SCRAM client-first (initial response carried in the first AUTH request). + // 3a. Single-message mechanisms (PLAIN / EXTERNAL / OAUTHBEARER): one AUTH + // request carrying the initial response; the server answers completed=true + // on success, or an ERROR frame on failure (surfaced by readResponseHeader). + if (isSimple) { + ByteArray initial; + if (mech == "PLAIN") { + if (auth_.username.empty()) { + throw HotRodClientException("PLAIN authentication requires a username", + FailurePhase::BeforeSend, std::nullopt, node); + } + // Empty authzid: authorize as the authentication id (the usual case). + initial = saslPlainInitialResponse("", auth_.username, auth_.password); + } else if (mech == "EXTERNAL") { + // Identity comes from the mutual-TLS client cert; the authorization id + // (auth_.username, usually empty) is the only payload. + initial = saslExternalInitialResponse(auth_.username); + } else { // OAUTHBEARER + if (auth_.token.empty()) { + throw HotRodClientException("OAUTHBEARER authentication requires a token", + FailurePhase::BeforeSend, std::nullopt, node); + } + initial = saslOAuthBearerInitialResponse(auth_.username, auth_.token); + } + + transport.sendRequest(Opcode::AUTH_REQUEST, encodeAuthRequestBody(mech, initial)); + if (transport.readResponseHeader() != Opcode::AUTH_RESPONSE) { + throw HotRodClientException("Auth: expected AUTH_RESPONSE", + FailurePhase::AfterSend, std::nullopt, node); + } + const bool completed = transport.readByte() != 0; + (void)transport.readByteArray(); // drain the (empty on success) challenge + if (completed) { + return; // authenticated + } + + // Not completed. Only OAUTHBEARER defines a continuation (RFC 7628): on an + // error the server returns a result challenge and expects a lone kvsep + // (0x01) before it fails the exchange with an ERROR frame. + if (mech == "OAUTHBEARER") { + transport.sendRequest(Opcode::AUTH_REQUEST, + encodeAuthRequestBody(mech, ByteArray{0x01})); + (void)transport.readResponseHeader(); // expected to throw on the ERROR frame + } + throw HotRodClientException(mech + " authentication did not complete", + FailurePhase::ServerError, std::nullopt, node); + } + + // 3b. SCRAM client-first (initial response carried in the first AUTH request). std::string nonce = SCRAM::generateNonce(); std::string clientFirst = SCRAM::createClientFirstMessage(auth_.username, nonce); // client-first-message-bare = client-first without the "n,," GS2 header. diff --git a/src/operations/RemoteCache.cpp b/src/operations/RemoteCache.cpp index 7eb7ed8..d677ab2 100644 --- a/src/operations/RemoteCache.cpp +++ b/src/operations/RemoteCache.cpp @@ -78,21 +78,20 @@ namespace hotrod { cache->setProtocolVersion(*parsed.protocolVersion); } - if (parsed.username) + // Authentication is enabled when the URI carries any auth signal: a + // mechanism, credentials, or an OAUTHBEARER token. EXTERNAL (identity from + // the client cert) and OAUTHBEARER (token) need no username, so the gate is + // not "username present". The mechanism defaults to SCRAM-SHA-256 and is + // validated at connect() (SaslAuthenticator). + if (parsed.saslMechanism || parsed.username || parsed.token) { - // Credentials present -> enable SCRAM. Mechanism from the query if given, - // else the setAuthentication default (SCRAM-SHA-256). Non-SCRAM mechanisms - // are rejected later at connect(). - const std::string password = parsed.password.value_or(""); - if (parsed.saslMechanism) - { - cache->setAuthentication(*parsed.username, password, "default", - "infinispan", *parsed.saslMechanism); - } - else - { - cache->setAuthentication(*parsed.username, password); - } + Authentication auth; + auth.enabled = true; + if (parsed.username) auth.username = *parsed.username; + if (parsed.password) auth.password = *parsed.password; + if (parsed.token) auth.token = *parsed.token; + if (parsed.saslMechanism) auth.mechanism = *parsed.saslMechanism; + cache->setAuthentication(auth); } // TLS: the hotrods:// scheme enables it; the PEM TLS keys (ca_file / diff --git a/tests/unit/HotRodURITest.cpp b/tests/unit/HotRodURITest.cpp index 5df87eb..3c7cf36 100644 --- a/tests/unit/HotRodURITest.cpp +++ b/tests/unit/HotRodURITest.cpp @@ -184,7 +184,33 @@ TEST(HotRodURITest, QueryParamMissingEqualsThrows) { 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?token=abc"), HotRodClientException); + EXPECT_THROW(HotRodURI::parse("hotrod://h?nonsense=1"), HotRodClientException); +} + +// --- SASL mechanism selection + OAUTHBEARER token ---------------------------- + +TEST(HotRodURITest, SaslMechanismParsed) { + HotRodURI u = HotRodURI::parse("hotrod://admin:pass@h?sasl_mechanism=PLAIN"); + ASSERT_TRUE(u.saslMechanism.has_value()); + EXPECT_EQ(*u.saslMechanism, "PLAIN"); + EXPECT_EQ(*u.username, "admin"); + EXPECT_FALSE(u.token.has_value()); +} + +TEST(HotRodURITest, OAuthBearerTokenParsed) { + // OAUTHBEARER needs no userinfo; the token carries the identity. + HotRodURI u = HotRodURI::parse("hotrod://h?sasl_mechanism=OAUTHBEARER&token=abc.def"); + ASSERT_TRUE(u.saslMechanism.has_value()); + EXPECT_EQ(*u.saslMechanism, "OAUTHBEARER"); + ASSERT_TRUE(u.token.has_value()); + EXPECT_EQ(*u.token, "abc.def"); + EXPECT_FALSE(u.username.has_value()); +} + +TEST(HotRodURITest, TokenPercentDecoded) { + HotRodURI u = HotRodURI::parse("hotrod://h?token=a%2Bb%2Fc"); + ASSERT_TRUE(u.token.has_value()); + EXPECT_EQ(*u.token, "a+b/c"); } // --- TLS: hotrods:// scheme + server-auth PEM subset (issue #18) ------------- diff --git a/tests/unit/SaslAuthenticatorTest.cpp b/tests/unit/SaslAuthenticatorTest.cpp index f641f63..f6fc9ff 100644 --- a/tests/unit/SaslAuthenticatorTest.cpp +++ b/tests/unit/SaslAuthenticatorTest.cpp @@ -299,9 +299,166 @@ TEST(SaslAuthenticatorTest, MechanismNotOfferedThrows) { TEST(SaslAuthenticatorTest, UnsupportedMechanismThrowsBeforeIO) { FakeScramServer server; - SaslAuthenticator auth(makeAuth("PLAIN", "user", "pencil"), "host", 11222); + // GSSAPI is not implemented by this client -> rejected before any I/O. + SaslAuthenticator auth(makeAuth("GSSAPI", "user", "pencil"), "host", 11222); EXPECT_THROW(auth.authenticate(server), HotRodClientException); // Nothing should have been sent to the transport. EXPECT_TRUE(server.outbox.empty()); EXPECT_EQ(server.phase, FakeScramServer::Phase::MechList); } + +// --- Single-message mechanisms: PLAIN / EXTERNAL / OAUTHBEARER ---------------- + +namespace { + +// A fake server for the single-message mechanisms. It serves the mech list, then +// captures the one AUTH request and answers with a configurable AUTH_RESPONSE +// (completed flag) or an ERROR frame. Also models the OAUTHBEARER failure +// continuation (a non-completed challenge turn followed by an ERROR). +struct FakeSimpleServer : public SaslTransport { + std::vector mechs{"PLAIN", "EXTERNAL", "OAUTHBEARER", "SCRAM-SHA-256"}; + bool completedFlag = true; // AUTH_RESPONSE completed flag for the first turn + bool errorOnFirstAuth = false; + + // Captured from the first AUTH request. + std::string lastMech; + ByteArray lastInitial; + int authRequests = 0; + + struct Frame { uint8_t opcode = 0; ByteArray body; bool isError = false; std::string errorMsg; }; + std::deque outbox; + ByteArray cursorBody; + size_t cursorOffset = 0; + + void sendRequest(uint8_t opcode, const ByteArray& body) override { + if (opcode == Opcode::AUTH_MECH_LIST_REQUEST) { + Frame f; + f.opcode = Opcode::AUTH_MECH_LIST_RESPONSE; + Codec::writeVInt(f.body, static_cast(mechs.size())); + for (const auto& m : mechs) Codec::writeString(f.body, m); + outbox.push_back(std::move(f)); + return; + } + ASSERT_EQ(opcode, Opcode::AUTH_REQUEST); + ++authRequests; + + if (authRequests == 1) { + size_t off = 0; + lastMech = Codec::readString(body, off); + lastInitial = Codec::readByteArray(body, off); + if (errorOnFirstAuth) { + outbox.push_back(Frame{Opcode::ERROR_RESPONSE, {}, true, "bad credentials"}); + return; + } + Frame f; + f.opcode = Opcode::AUTH_RESPONSE; + f.body.push_back(completedFlag ? 1 : 0); + Codec::writeByteArray(f.body, ByteArray{}); // empty challenge + outbox.push_back(std::move(f)); + return; + } + // Second AUTH turn (OAUTHBEARER failure continuation): fail with an ERROR. + outbox.push_back(Frame{Opcode::ERROR_RESPONSE, {}, true, "oauth rejected"}); + } + + uint8_t readResponseHeader() override { + if (outbox.empty()) throw std::runtime_error("FakeSimpleServer: no response queued"); + Frame f = std::move(outbox.front()); + outbox.pop_front(); + if (f.isError) { + throw HotRodClientException("Authentication failed: " + f.errorMsg, + FailurePhase::ServerError, Status::SERVER_ERROR, + {{"fake", 0}}); + } + cursorBody = std::move(f.body); + cursorOffset = 0; + return f.opcode; + } + uint8_t readByte() override { return cursorBody.at(cursorOffset++); } + VInt readVInt() override { return Codec::readVInt(cursorBody, cursorOffset); } + std::string readString() override { return Codec::readString(cursorBody, cursorOffset); } + ByteArray readByteArray() override { return Codec::readByteArray(cursorBody, cursorOffset); } +}; + +} // namespace + +TEST(SaslSimpleMechanismTest, PlainSuccessSendsCorrectInitialResponse) { + FakeSimpleServer server; + SaslAuthenticator auth(makeAuth("PLAIN", "user", "pencil"), "host", 11222); + EXPECT_NO_THROW(auth.authenticate(server)); + + EXPECT_EQ(server.lastMech, "PLAIN"); + // authzid NUL authcid NUL passwd, authzid empty. + const ByteArray expected{0x00, 'u','s','e','r', 0x00, 'p','e','n','c','i','l'}; + EXPECT_EQ(server.lastInitial, expected); + EXPECT_EQ(server.authRequests, 1); +} + +TEST(SaslSimpleMechanismTest, PlainRequiresUsername) { + FakeSimpleServer server; + SaslAuthenticator auth(makeAuth("PLAIN", "", "pencil"), "host", 11222); + EXPECT_THROW(auth.authenticate(server), HotRodClientException); +} + +TEST(SaslSimpleMechanismTest, PlainBadCredentialsThrows) { + FakeSimpleServer server; + server.errorOnFirstAuth = true; + SaslAuthenticator auth(makeAuth("PLAIN", "user", "wrong"), "host", 11222); + EXPECT_THROW(auth.authenticate(server), HotRodClientException); +} + +TEST(SaslSimpleMechanismTest, ExternalSendsEmptyAuthzidByDefault) { + FakeSimpleServer server; + Authentication a; + a.enabled = true; + a.mechanism = "EXTERNAL"; // no username/password: identity from the client cert + SaslAuthenticator auth(a, "host", 11222); + EXPECT_NO_THROW(auth.authenticate(server)); + + EXPECT_EQ(server.lastMech, "EXTERNAL"); + EXPECT_TRUE(server.lastInitial.empty()); +} + +TEST(SaslSimpleMechanismTest, OAuthBearerSendsBearerToken) { + FakeSimpleServer server; + Authentication a; + a.enabled = true; + a.mechanism = "OAUTHBEARER"; + a.token = "tok123"; + SaslAuthenticator auth(a, "host", 11222); + EXPECT_NO_THROW(auth.authenticate(server)); + + EXPECT_EQ(server.lastMech, "OAUTHBEARER"); + const std::string got(server.lastInitial.begin(), server.lastInitial.end()); + const std::string expected = std::string("n,,") + '\x01' + "auth=Bearer tok123" + '\x01' + '\x01'; + EXPECT_EQ(got, expected); +} + +TEST(SaslSimpleMechanismTest, OAuthBearerRequiresToken) { + FakeSimpleServer server; + Authentication a; + a.enabled = true; + a.mechanism = "OAUTHBEARER"; // no token + SaslAuthenticator auth(a, "host", 11222); + EXPECT_THROW(auth.authenticate(server), HotRodClientException); +} + +TEST(SaslSimpleMechanismTest, OAuthBearerFailureContinuationThrows) { + FakeSimpleServer server; + server.completedFlag = false; // server returns a non-completed error challenge + Authentication a; + a.enabled = true; + a.mechanism = "OAUTHBEARER"; + a.token = "bad"; + SaslAuthenticator auth(a, "host", 11222); + EXPECT_THROW(auth.authenticate(server), HotRodClientException); + // The client sent the initial token plus the RFC 7628 kvsep continuation. + EXPECT_EQ(server.authRequests, 2); +} + +TEST(SaslSimpleMechanismTest, MechanismNotOfferedThrows) { + FakeSimpleServer server; + server.mechs = {"SCRAM-SHA-256"}; // PLAIN not offered + SaslAuthenticator auth(makeAuth("PLAIN", "user", "pencil"), "host", 11222); + EXPECT_THROW(auth.authenticate(server), HotRodClientException); +} diff --git a/tests/unit/SaslMechanismsTest.cpp b/tests/unit/SaslMechanismsTest.cpp new file mode 100644 index 0000000..f1d4f10 --- /dev/null +++ b/tests/unit/SaslMechanismsTest.cpp @@ -0,0 +1,57 @@ +/** + * Unit tests for the pure SASL initial-response builders (SaslMechanisms.h): + * PLAIN (RFC 4616), EXTERNAL (RFC 4422), OAUTHBEARER (RFC 7628). These assert the + * exact bytes placed on the wire, independent of the transport. + */ +#include +#include "hotrod/SaslMechanisms.h" + +using namespace hotrod; + +TEST(SaslMechanismsTest, PlainEmptyAuthzid) { + // authzid NUL authcid NUL passwd, authzid empty. + const ByteArray got = saslPlainInitialResponse("", "user", "pencil"); + const ByteArray expected{0x00, 'u','s','e','r', 0x00, 'p','e','n','c','i','l'}; + EXPECT_EQ(got, expected); +} + +TEST(SaslMechanismsTest, PlainWithAuthzid) { + const ByteArray got = saslPlainInitialResponse("admin", "user", "pw"); + const ByteArray expected{'a','d','m','i','n', 0x00, 'u','s','e','r', 0x00, 'p','w'}; + EXPECT_EQ(got, expected); +} + +TEST(SaslMechanismsTest, PlainPasswordWithNulAndColonPreserved) { + // The builder uses raw bytes, so a NUL/':' in the password is carried verbatim. + const ByteArray got = saslPlainInitialResponse("", "u", std::string("a\0b", 3)); + const ByteArray expected{'u', 0x00, 'a', 0x00, 'b'}; + // leading authzid-NUL: + ByteArray full{0x00}; + full.insert(full.end(), expected.begin(), expected.end()); + EXPECT_EQ(got, full); +} + +TEST(SaslMechanismsTest, ExternalEmpty) { + EXPECT_TRUE(saslExternalInitialResponse("").empty()); +} + +TEST(SaslMechanismsTest, ExternalWithAuthzid) { + const ByteArray got = saslExternalInitialResponse("alice"); + const ByteArray expected{'a','l','i','c','e'}; + EXPECT_EQ(got, expected); +} + +TEST(SaslMechanismsTest, OAuthBearerEmptyAuthzid) { + const ByteArray got = saslOAuthBearerInitialResponse("", "tok"); + const std::string s(got.begin(), got.end()); + const std::string expected = std::string("n,,") + '\x01' + "auth=Bearer tok" + '\x01' + '\x01'; + EXPECT_EQ(s, expected); +} + +TEST(SaslMechanismsTest, OAuthBearerWithAuthzid) { + const ByteArray got = saslOAuthBearerInitialResponse("alice", "tok"); + const std::string s(got.begin(), got.end()); + const std::string expected = + std::string("n,a=alice,") + '\x01' + "auth=Bearer tok" + '\x01' + '\x01'; + EXPECT_EQ(s, expected); +}