Skip to main content

confluent_kafka/common/config/
sasl_configs.rs

1// Copyright 2025 Confluent Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! SASL configuration for Kafka connections.
16//!
17//! Translated from `org.apache.kafka.common.config.SaslConfigs`.
18//!
19//! In Java this class has 40+ constants, most for Kerberos and OAuth (out of
20//! scope for the current milestone). For SASL PLAIN we only need a minimal
21//! subset.
22//!
23//! `sasl.mechanism` keeps Java's definition and its `GSSAPI` default, but PLAIN
24//! is the only mechanism this client implements: under a SASL
25//! `security.protocol` the client configurations reject any other value when
26//! they are built (`CommonClientConfigs::post_validate_supported_sasl_mechanism`),
27//! so `sasl.mechanism=PLAIN` must be set explicitly.
28//!
29//! **Excluded Java constants (out of scope):**
30//! - All `SASL_KERBEROS_*` — Kerberos not supported
31//! - All `SASL_OAUTHBEARER_*` — OAuth not supported
32//! - All `SASL_LOGIN_REFRESH_*` — Token refresh not supported
33//! - `SASL_CLIENT_CALLBACK_HANDLER_CLASS` — No pluggable callback handlers
34//! - `SASL_LOGIN_CLASS` — No pluggable login implementations
35
36use std::borrow::Cow;
37
38use crate::common::Error;
39use crate::common::config::abstract_config::ValuesReader;
40use crate::common::config::config_def::{
41    CaseInsensitiveValidString, ConfigDef, DefaultValue, Importance, Range, Type, ValidList,
42};
43use crate::common::config::types::Password;
44
45// ---------------------------------------------------------------------------
46// Config key constants (matching Java SaslConfigs constant values)
47// ---------------------------------------------------------------------------
48
49// ---------------------------------------------------------------------------
50// SaslConfigs value fields
51// ---------------------------------------------------------------------------
52
53impl SaslConfigs {
54    /// Config key: `sasl.mechanism`.
55    ///
56    /// SASL mechanism used for client connections. This may be any mechanism for
57    /// which a security provider is available. GSSAPI is the default mechanism.
58    pub const SASL_MECHANISM: &str = "sasl.mechanism";
59
60    /// Config key: `sasl.jaas.config`.
61    ///
62    /// JAAS login context parameters for SASL connections in the format used by
63    /// JAAS configuration files.
64    pub const SASL_JAAS_CONFIG: &str = "sasl.jaas.config";
65
66    /// The GSSAPI (Kerberos) mechanism name.
67    pub const GSSAPI_MECHANISM: &str = "GSSAPI";
68
69    /// The PLAIN mechanism name, the only one the client authenticator implements.
70    pub(crate) const PLAIN_MECHANISM: &str = "PLAIN";
71
72    /// Default SASL mechanism (matches Java `DEFAULT_SASL_MECHANISM`).
73    pub const DEFAULT_SASL_MECHANISM: &str = Self::GSSAPI_MECHANISM;
74}
75
76/// SASL configuration for Kafka connections.
77///
78/// The Java class
79/// hosts only the `sasl.*` config keys and defaults; the values themselves
80/// travel in the `Map<String, ?>` handed to `SaslChannelBuilder.configure`.
81/// The Rust struct keeps Java's name and constants, and additionally holds the
82/// client-relevant subset of those values, parsed once from the client config
83/// properties. The fields are crate-private: callers set them through the
84/// `sasl.*` properties of a client config, as a Java caller does.
85///
86/// Currently supports PLAIN mechanism only.
87#[derive(Debug)]
88#[non_exhaustive]
89#[doc(alias = "org.apache.kafka.common.config.SaslConfigs")]
90pub struct SaslConfigs {
91    /// SASL mechanism. Default: `"GSSAPI"` (matches Java `DEFAULT_SASL_MECHANISM`).
92    /// Corresponds to `sasl.mechanism`.
93    pub(crate) mechanism: String,
94
95    /// JAAS configuration string for embedded credentials.
96    /// Corresponds to `sasl.jaas.config`.
97    ///
98    /// Example:
99    /// ```text
100    /// org.apache.kafka.common.security.plain.PlainLoginModule required
101    ///     username="alice" password="secret";
102    /// ```
103    ///
104    /// If set, `username` and `password` can be extracted from this string
105    /// via [`SaslConfigs::resolve_username`] and [`SaslConfigs::resolve_password`].
106    ///
107    /// A [`Password`] because Java defines `sasl.jaas.config` as
108    /// `ConfigDef.Type.PASSWORD` (`org.apache.kafka.common.config.SaslConfigs#addClientSaslSupport`): the string embeds
109    /// the credentials, so every rendering of it is `[hidden]`.
110    pub(crate) jaas_config: Option<Password>,
111
112    /// Username for PLAIN authentication.
113    /// Convenience field — used when `jaas_config` is not set.
114    pub(crate) username: Option<String>,
115
116    /// Password for PLAIN authentication.
117    /// Convenience field — used when `jaas_config` is not set.
118    ///
119    /// Rust-only. No config key is parsed into it; tests set it directly. A
120    /// [`Password`] like every other secret, so every rendering of it is
121    /// `[hidden]`. [`SaslConfigs::resolve_password`] yields the plaintext.
122    pub(crate) password: Option<Password>,
123}
124
125impl Default for SaslConfigs {
126    fn default() -> Self {
127        SaslConfigs {
128            mechanism: SaslConfigs::DEFAULT_SASL_MECHANISM.to_owned(),
129            jaas_config: None,
130            username: None,
131            password: None,
132        }
133    }
134}
135
136impl SaslConfigs {
137    /// The `sasl.*` settings of a configuration parsed with
138    /// [`Self::add_client_sasl_support`]'s definitions: `sasl.mechanism` and
139    /// `sasl.jaas.config`, the two the client's PLAIN authenticator reads. An
140    /// empty `sasl.jaas.config` counts as unset.
141    ///
142    /// # Errors
143    ///
144    /// [`Error::LocalIllegalState`] if a key's definition is missing or of
145    /// another type, a defect of the definition rather than of the input.
146    pub(crate) fn from_values(values: &mut ValuesReader<'_>) -> Result<SaslConfigs, Error> {
147        Ok(SaslConfigs {
148            mechanism: values.string(SaslConfigs::SASL_MECHANISM)?.to_string(),
149            jaas_config: values
150                .password_or_null(SaslConfigs::SASL_JAAS_CONFIG)?
151                .filter(|jaas| !jaas.value().is_empty())
152                .cloned(),
153            username: None,
154            password: None,
155        })
156    }
157
158    /// Parses an option value from a JAAS configuration string.
159    ///
160    /// JAAS config format:
161    /// ```text
162    /// <loginModuleClass> <controlFlag> (<key>=<value>)*;
163    /// ```
164    ///
165    /// Values may be quoted with double or single quotes, or left bare. Whitespace
166    /// is tolerated on either side of the `=` — a JAAS string legally carries
167    /// `name="v"`, `name = "v"`, `name='v'`, or `name=v`.
168    ///
169    /// A key is recognized only at an **option start** — the beginning of the
170    /// string or immediately after whitespace — and quoted regions are skipped
171    /// wholesale (honoring `\`-escaped quotes), so a `key=` sequence appearing
172    /// inside another option's quoted value is never mistaken for a real option
173    /// (e.g. `password="username=x" username="right"` resolves `username` to
174    /// `right`, not `x`). This mirrors Java's JAAS lexer, which tokenizes options
175    /// rather than substring-matching. The same option-start rule rejects
176    /// `serviceName=` / `foo.username=` when searching for `name=` / `username=`
177    /// (the char before the substring is a letter / `.`, not whitespace).
178    ///
179    /// A quoted value has its `\`-escapes decoded as Java's `StreamTokenizer`
180    /// decodes them inside a string constant (see [`Self::decode_quoted_escapes`]),
181    /// so `password="b\\a\"ck"` yields `b\a"ck` as in Java; an escaped quote
182    /// neither ends the value nor misaligns later options. A raw line
183    /// terminator inside the quotes ends the string there, as in Java, which
184    /// then rejects the config, so the value is malformed (`None`); an escaped
185    /// one is part of the value. A bare value is returned as written: Java's
186    /// tokenizer decodes escapes only in quoted strings.
187    ///
188    /// Returns the value borrowed from `jaas` when there is nothing to decode,
189    /// an owned copy otherwise, and `None` if the option is absent.
190    fn parse_jaas_option<'a>(jaas: &'a str, key: &str) -> Option<Cow<'a, str>> {
191        let bytes = jaas.as_bytes();
192        let n = bytes.len();
193
194        // Advance past a quoted region that opens at `bytes[i]` (a quote byte),
195        // honoring backslash escapes. Returns the index just past the closing
196        // quote, or `n` if the quote is unterminated. Quote and backslash are
197        // ASCII, and UTF-8 continuation bytes are always >= 0x80, so this never
198        // lands a false match inside a multi-byte character.
199        fn skip_quoted(bytes: &[u8], mut i: usize) -> usize {
200            let quote = bytes[i];
201            i += 1;
202            while i < bytes.len() {
203                if bytes[i] == b'\\' {
204                    i += 2; // skip the escape and the escaped byte
205                    continue;
206                }
207                if bytes[i] == quote {
208                    return i + 1;
209                }
210                // `StreamTokenizer` also ends a quoted string at a raw line
211                // terminator.
212                if bytes[i] == b'\n' || bytes[i] == b'\r' {
213                    return i;
214                }
215                i += 1;
216            }
217            i
218        }
219
220        // Walk the string once, skipping quoted regions, and only consider a match
221        // where an option can legally begin (start of string or after whitespace).
222        let mut i = 0;
223        while i < n {
224            let c = bytes[i];
225
226            // Skip a quoted region wholesale so `key=` inside a value cannot match.
227            if c == b'"' || c == b'\'' {
228                i = skip_quoted(bytes, i);
229                continue;
230            }
231
232            // A key can only begin at an option start.
233            let at_option_start = i == 0 || bytes[i - 1].is_ascii_whitespace();
234            if at_option_start && jaas[i..].starts_with(key) {
235                // Skip whitespace between the key and '='.
236                let mut j = i + key.len();
237                while j < n && bytes[j].is_ascii_whitespace() {
238                    j += 1;
239                }
240                // The key must be followed by '=' (after the optional whitespace);
241                // otherwise this was e.g. `namespace` starting with `name` — keep
242                // scanning.
243                if j < n && bytes[j] == b'=' {
244                    j += 1; // past '='
245
246                    // Skip whitespace between '=' and the value.
247                    while j < n && bytes[j].is_ascii_whitespace() {
248                        j += 1;
249                    }
250                    if j >= n {
251                        return None;
252                    }
253
254                    // Quoted value: double or single quote, escape-aware.
255                    let quote = bytes[j];
256                    if quote == b'"' || quote == b'\'' {
257                        let value_start = j + 1;
258                        let mut k = value_start;
259                        while k < n {
260                            if bytes[k] == b'\\' {
261                                k += 2; // an escaped quote does not close the value
262                                continue;
263                            }
264                            if bytes[k] == quote {
265                                return Some(SaslConfigs::decode_quoted_escapes(&jaas[value_start..k]));
266                            }
267                            // Java's `StreamTokenizer` ends a quoted string at a
268                            // raw line terminator (an escaped one is part of the
269                            // value), which leaves the rest of the option
270                            // misparsed and `JaasConfig` rejecting the whole
271                            // config. The value is malformed, as with no
272                            // closing quote.
273                            if bytes[k] == b'\n' || bytes[k] == b'\r' {
274                                return None;
275                            }
276                            k += 1;
277                        }
278                        // No closing quote found — malformed.
279                        return None;
280                    }
281
282                    // Unquoted value: read until whitespace or semicolon.
283                    let value_end = jaas[j..]
284                        .find(|ch: char| ch.is_ascii_whitespace() || ch == ';')
285                        .map(|e| j + e)
286                        .unwrap_or(n);
287                    return Some(Cow::Borrowed(&jaas[j..value_end]));
288                }
289            }
290
291            i += 1;
292        }
293
294        None
295    }
296
297    /// Decodes the backslash escapes of a quoted JAAS option value.
298    ///
299    /// Java parses `sasl.jaas.config` with a `java.io.StreamTokenizer`
300    /// (in `JaasConfig`'s constructor), which, as its documentation says, recognizes
301    /// "the usual escape sequences" in a string constant and converts each to
302    /// the character it stands for:
303    ///
304    /// - `\a`, `\b`, `\f`, `\n`, `\r`, `\t` and `\v` are the control
305    ///   characters U+0007, U+0008, U+000C, U+000A, U+000D, U+0009 and U+000B;
306    /// - `\` followed by one to three octal digits is the character with that
307    ///   code, three digits being read only when the first is `0` to `3`, so
308    ///   the code stays below 256;
309    /// - `\` followed by any other character is that character, so `\\`,
310    ///   `\"` and `\'` are a backslash and the two quotes.
311    ///
312    /// A value without a backslash is returned borrowed.
313    fn decode_quoted_escapes(raw: &str) -> Cow<'_, str> {
314        if !raw.contains('\\') {
315            return Cow::Borrowed(raw);
316        }
317        let mut decoded = String::with_capacity(raw.len());
318        let mut chars = raw.chars().peekable();
319        while let Some(c) = chars.next() {
320            if c != '\\' {
321                decoded.push(c);
322                continue;
323            }
324            // The scanner ends a quoted value only on an unescaped quote, so a
325            // backslash is always followed by the character it escapes.
326            let Some(escaped) = chars.next() else {
327                break;
328            };
329            match escaped {
330                'a' => decoded.push('\u{7}'),
331                'b' => decoded.push('\u{8}'),
332                'f' => decoded.push('\u{c}'),
333                'n' => decoded.push('\n'),
334                'r' => decoded.push('\r'),
335                't' => decoded.push('\t'),
336                'v' => decoded.push('\u{b}'),
337                '0'..='7' => {
338                    let mut code = escaped as u32 - '0' as u32;
339                    if let Some(second) = chars.peek().and_then(|c| c.to_digit(8)) {
340                        chars.next();
341                        code = code * 8 + second;
342                        if escaped <= '3'
343                            && let Some(third) = chars.peek().and_then(|c| c.to_digit(8))
344                        {
345                            chars.next();
346                            code = code * 8 + third;
347                        }
348                    }
349                    // At most 0o377, a Latin-1 code point.
350                    decoded.extend(char::from_u32(code));
351                },
352                other => decoded.push(other),
353            }
354        }
355        Cow::Owned(decoded)
356    }
357
358    /// Resolve the effective username, checking the `username` field first,
359    /// then parsing from `jaas_config` if present.
360    pub(crate) fn resolve_username(&self) -> Option<Cow<'_, str>> {
361        if let Some(ref u) = self.username {
362            return Some(Cow::Borrowed(u.as_str()));
363        }
364        if let Some(ref jaas) = self.jaas_config {
365            return SaslConfigs::parse_jaas_option(jaas.value(), "username");
366        }
367        None
368    }
369
370    /// Resolve the effective password, checking the `password` field first,
371    /// then parsing from `jaas_config` if present.
372    ///
373    /// Returns the **plaintext**: the authenticator must send it, just as
374    /// Java's `PlainLoginModule` yields a plain `String`. Never log the result.
375    pub(crate) fn resolve_password(&self) -> Option<Cow<'_, str>> {
376        if let Some(ref p) = self.password {
377            return Some(Cow::Borrowed(p.value()));
378        }
379        if let Some(ref jaas) = self.jaas_config {
380            return SaslConfigs::parse_jaas_option(jaas.value(), "password");
381        }
382        None
383    }
384}
385
386impl SaslConfigs {
387    /// Defines the client `sasl.*` keys on `config`: Java's
388    /// `SaslConfigs.addClientSaslSupport(ConfigDef)`, in Java's order, except
389    /// the class-valued keys (CLAUDE.md §2): `sasl.client.callback.handler.class`,
390    /// `sasl.login.callback.handler.class`, `sasl.login.class`,
391    /// `sasl.oauthbearer.jwt.retriever.class` and
392    /// `sasl.oauthbearer.jwt.validator.class`.
393    ///
394    /// Java names each key by a public `SaslConfigs` constant; only the ones
395    /// this crate already exports are referenced by name, the others are
396    /// written as literals to add no public constant.
397    pub(crate) fn add_client_sasl_support(config: ConfigDef) -> ConfigDef {
398        config
399            .define(
400                "sasl.kerberos.service.name",
401                Type::String,
402                DefaultValue::Null,
403                Importance::Medium,
404            )
405            .define("sasl.kerberos.kinit.cmd", Type::String, "/usr/bin/kinit", Importance::Low)
406            .define("sasl.kerberos.ticket.renew.window.factor", Type::Double, 0.80, Importance::Low)
407            .define("sasl.kerberos.ticket.renew.jitter", Type::Double, 0.05, Importance::Low)
408            .define("sasl.kerberos.min.time.before.relogin", Type::Long, 60_000i64, Importance::Low)
409            .define_with_validator(
410                "sasl.login.refresh.window.factor",
411                Type::Double,
412                0.80,
413                Range::between(0.5, 1.0),
414                Importance::Low,
415            )
416            .define_with_validator(
417                "sasl.login.refresh.window.jitter",
418                Type::Double,
419                0.05,
420                Range::between(0.0, 0.25),
421                Importance::Low,
422            )
423            .define_with_validator(
424                "sasl.login.refresh.min.period.seconds",
425                Type::Short,
426                60i16,
427                Range::between(0, 900),
428                Importance::Low,
429            )
430            .define_with_validator(
431                "sasl.login.refresh.buffer.seconds",
432                Type::Short,
433                300i16,
434                Range::between(0, 3600),
435                Importance::Low,
436            )
437            .define(
438                SaslConfigs::SASL_MECHANISM,
439                Type::String,
440                SaslConfigs::DEFAULT_SASL_MECHANISM,
441                Importance::Medium,
442            )
443            .define(
444                SaslConfigs::SASL_JAAS_CONFIG,
445                Type::Password,
446                DefaultValue::Null,
447                Importance::Medium,
448            )
449            .define("sasl.login.connect.timeout.ms", Type::Int, DefaultValue::Null, Importance::Low)
450            .define("sasl.login.read.timeout.ms", Type::Int, DefaultValue::Null, Importance::Low)
451            .define("sasl.login.retry.backoff.max.ms", Type::Long, 10_000i64, Importance::Low)
452            .define("sasl.login.retry.backoff.ms", Type::Long, 100i64, Importance::Low)
453            .define("sasl.oauthbearer.scope", Type::String, DefaultValue::Null, Importance::Medium)
454            .define(
455                "sasl.oauthbearer.client.credentials.client.id",
456                Type::String,
457                DefaultValue::Null,
458                Importance::Medium,
459            )
460            .define(
461                "sasl.oauthbearer.client.credentials.client.secret",
462                Type::Password,
463                DefaultValue::Null,
464                Importance::Medium,
465            )
466            .define_with_validator(
467                "sasl.oauthbearer.assertion.algorithm",
468                Type::String,
469                "RS256",
470                CaseInsensitiveValidString::r#in(&["ES256", "RS256"]),
471                Importance::Medium,
472            )
473            .define(
474                "sasl.oauthbearer.assertion.claim.aud",
475                Type::String,
476                DefaultValue::Null,
477                Importance::Medium,
478            )
479            .define_with_validator(
480                "sasl.oauthbearer.assertion.claim.exp.seconds",
481                Type::Int,
482                300,
483                Range::between(0, 86400),
484                Importance::Low,
485            )
486            .define(
487                "sasl.oauthbearer.assertion.claim.iss",
488                Type::String,
489                DefaultValue::Null,
490                Importance::Medium,
491            )
492            .define(
493                "sasl.oauthbearer.assertion.claim.jti.include",
494                Type::Boolean,
495                false,
496                Importance::Medium,
497            )
498            .define_with_validator(
499                "sasl.oauthbearer.assertion.claim.nbf.seconds",
500                Type::Int,
501                60,
502                Range::between(0, 3600),
503                Importance::Low,
504            )
505            .define(
506                "sasl.oauthbearer.assertion.claim.sub",
507                Type::String,
508                DefaultValue::Null,
509                Importance::Medium,
510            )
511            .define(
512                "sasl.oauthbearer.assertion.file",
513                Type::String,
514                DefaultValue::Null,
515                Importance::Medium,
516            )
517            .define(
518                "sasl.oauthbearer.assertion.private.key.file",
519                Type::String,
520                DefaultValue::Null,
521                Importance::Medium,
522            )
523            .define(
524                "sasl.oauthbearer.assertion.private.key.passphrase",
525                Type::Password,
526                DefaultValue::Null,
527                Importance::Medium,
528            )
529            .define(
530                "sasl.oauthbearer.assertion.template.file",
531                Type::String,
532                DefaultValue::Null,
533                Importance::Medium,
534            )
535            .define("sasl.oauthbearer.scope.claim.name", Type::String, "scope", Importance::Low)
536            .define("sasl.oauthbearer.sub.claim.name", Type::String, "sub", Importance::Low)
537            .define(
538                "sasl.oauthbearer.token.endpoint.url",
539                Type::String,
540                DefaultValue::Null,
541                Importance::Medium,
542            )
543            .define(
544                "sasl.oauthbearer.jwks.endpoint.url",
545                Type::String,
546                DefaultValue::Null,
547                Importance::Medium,
548            )
549            .define(
550                "sasl.oauthbearer.jwks.endpoint.refresh.ms",
551                Type::Long,
552                3_600_000i64,
553                Importance::Low,
554            )
555            .define(
556                "sasl.oauthbearer.jwks.endpoint.retry.backoff.max.ms",
557                Type::Long,
558                10_000i64,
559                Importance::Low,
560            )
561            .define(
562                "sasl.oauthbearer.jwks.endpoint.retry.backoff.ms",
563                Type::Long,
564                100i64,
565                Importance::Low,
566            )
567            .define("sasl.oauthbearer.clock.skew.seconds", Type::Int, 30, Importance::Low)
568            .define(
569                "sasl.oauthbearer.allow.unverified.audience",
570                Type::Boolean,
571                false,
572                Importance::Medium,
573            )
574            .define_with_validator(
575                "sasl.oauthbearer.expected.audience",
576                Type::List,
577                Vec::<String>::new(),
578                ValidList::any_non_duplicate_values(true, false),
579                Importance::High,
580            )
581            .define(
582                "sasl.oauthbearer.allow.unverified.issuer",
583                Type::Boolean,
584                false,
585                Importance::Medium,
586            )
587            .define(
588                "sasl.oauthbearer.expected.issuer",
589                Type::String,
590                DefaultValue::Null,
591                Importance::High,
592            )
593            .define("sasl.oauthbearer.header.urlencode", Type::Boolean, false, Importance::Low)
594    }
595}
596
597#[cfg(test)]
598mod tests {
599    use super::*;
600
601    #[test]
602    fn test_default() {
603        let config = SaslConfigs::default();
604        assert_eq!(config.mechanism, "GSSAPI");
605        assert!(config.jaas_config.is_none());
606        assert!(config.username.is_none());
607        assert!(config.password.is_none());
608    }
609
610    #[test]
611    fn test_resolve_username_from_direct_field() {
612        let config = SaslConfigs { username: Some("alice".to_owned()), ..SaslConfigs::default() };
613        assert_eq!(config.resolve_username().as_deref(), Some("alice"));
614    }
615
616    #[test]
617    fn test_resolve_password_from_direct_field() {
618        let config = SaslConfigs { password: Some(Password::new("secret")), ..SaslConfigs::default() };
619        assert_eq!(config.resolve_password().as_deref(), Some("secret"));
620    }
621
622    #[test]
623    fn test_resolve_username_from_jaas_config() {
624        let config = SaslConfigs {
625            jaas_config: Some(Password::new(
626                "org.apache.kafka.common.security.plain.PlainLoginModule required \
627                 username=\"alice\" password=\"secret\";",
628            )),
629            ..SaslConfigs::default()
630        };
631        assert_eq!(config.resolve_username().as_deref(), Some("alice"));
632    }
633
634    #[test]
635    fn test_resolve_password_from_jaas_config() {
636        let config = SaslConfigs {
637            jaas_config: Some(Password::new(
638                "org.apache.kafka.common.security.plain.PlainLoginModule required \
639                 username=\"alice\" password=\"secret\";",
640            )),
641            ..SaslConfigs::default()
642        };
643        assert_eq!(config.resolve_password().as_deref(), Some("secret"));
644    }
645
646    #[test]
647    fn test_direct_fields_take_precedence_over_jaas() {
648        let config = SaslConfigs {
649            jaas_config: Some(Password::new(
650                "org.apache.kafka.common.security.plain.PlainLoginModule required \
651                 username=\"jaas_user\" password=\"jaas_pass\";",
652            )),
653            username: Some("direct_user".to_owned()),
654            password: Some(Password::new("direct_pass")),
655            ..SaslConfigs::default()
656        };
657        assert_eq!(config.resolve_username().as_deref(), Some("direct_user"));
658        assert_eq!(config.resolve_password().as_deref(), Some("direct_pass"));
659    }
660
661    #[test]
662    fn test_resolve_from_empty_config() {
663        let config = SaslConfigs::default();
664        assert_eq!(config.resolve_username().as_deref(), None);
665        assert_eq!(config.resolve_password().as_deref(), None);
666    }
667
668    #[test]
669    fn test_jaas_config_unquoted_values() {
670        let config = SaslConfigs {
671            jaas_config: Some(Password::new("PlainLoginModule required username=alice password=secret;")),
672            ..SaslConfigs::default()
673        };
674        assert_eq!(config.resolve_username().as_deref(), Some("alice"));
675        assert_eq!(config.resolve_password().as_deref(), Some("secret"));
676    }
677
678    #[test]
679    fn test_jaas_config_missing_field() {
680        let config = SaslConfigs {
681            jaas_config: Some(Password::new("PlainLoginModule required username=\"alice\";")),
682            ..SaslConfigs::default()
683        };
684        assert_eq!(config.resolve_username().as_deref(), Some("alice"));
685        assert_eq!(config.resolve_password().as_deref(), None);
686    }
687
688    #[test]
689    fn test_jaas_config_malformed_no_closing_quote() {
690        let config = SaslConfigs {
691            jaas_config: Some(Password::new("PlainLoginModule required username=\"alice password=\"secret\";")),
692            ..SaslConfigs::default()
693        };
694        // The first quote for username opens, and the next quote is in " password=" —
695        // so we get "alice password=" as the value up to the next quote.
696        // This is technically malformed input; we just get whatever is between quotes.
697        assert_eq!(config.resolve_username().as_deref(), Some("alice password="));
698    }
699
700    #[test]
701    fn test_jaas_config_empty_string() {
702        let config = SaslConfigs { jaas_config: Some(Password::new("")), ..SaslConfigs::default() };
703        assert_eq!(config.resolve_username().as_deref(), None);
704        assert_eq!(config.resolve_password().as_deref(), None);
705    }
706
707    #[test]
708    fn test_jaas_config_no_options() {
709        let config = SaslConfigs {
710            jaas_config: Some(Password::new("PlainLoginModule required;")),
711            ..SaslConfigs::default()
712        };
713        assert_eq!(config.resolve_username().as_deref(), None);
714        assert_eq!(config.resolve_password().as_deref(), None);
715    }
716
717    #[test]
718    fn test_jaas_config_with_extra_whitespace() {
719        let config = SaslConfigs {
720            jaas_config: Some(Password::new(
721                "PlainLoginModule   required   username=\"bob\"   password=\"pass123\"  ;",
722            )),
723            ..SaslConfigs::default()
724        };
725        assert_eq!(config.resolve_username().as_deref(), Some("bob"));
726        assert_eq!(config.resolve_password().as_deref(), Some("pass123"));
727    }
728
729    #[test]
730    fn test_jaas_config_key_as_substring_not_matched() {
731        // Ensure that "myusername" is not matched when searching for "username"
732        let config = SaslConfigs {
733            jaas_config: Some(Password::new(
734                "PlainLoginModule required myusername=\"wrong\" username=\"right\";",
735            )),
736            ..SaslConfigs::default()
737        };
738        assert_eq!(config.resolve_username().as_deref(), Some("right"));
739    }
740
741    #[test]
742    fn test_jaas_config_spaces_around_equals() {
743        // A JAAS string legally carries spaces around '='.
744        let config = SaslConfigs {
745            jaas_config: Some(Password::new(
746                "PlainLoginModule required username = \"alice\" password = \"secret\";",
747            )),
748            ..SaslConfigs::default()
749        };
750        assert_eq!(config.resolve_username().as_deref(), Some("alice"));
751        assert_eq!(config.resolve_password().as_deref(), Some("secret"));
752    }
753
754    #[test]
755    fn test_jaas_config_single_quoted_values() {
756        let config = SaslConfigs {
757            jaas_config: Some(Password::new("PlainLoginModule required username='alice' password='secret';")),
758            ..SaslConfigs::default()
759        };
760        assert_eq!(config.resolve_username().as_deref(), Some("alice"));
761        assert_eq!(config.resolve_password().as_deref(), Some("secret"));
762    }
763
764    #[test]
765    fn test_jaas_config_single_quoted_with_spaces() {
766        let config = SaslConfigs {
767            jaas_config: Some(Password::new(
768                "PlainLoginModule required username = 'alice' password = 'secret';",
769            )),
770            ..SaslConfigs::default()
771        };
772        assert_eq!(config.resolve_username().as_deref(), Some("alice"));
773        assert_eq!(config.resolve_password().as_deref(), Some("secret"));
774    }
775
776    #[test]
777    fn test_jaas_config_bare_value_with_spaces_around_equals() {
778        let config = SaslConfigs {
779            jaas_config: Some(Password::new("PlainLoginModule required username = alice password = secret;")),
780            ..SaslConfigs::default()
781        };
782        assert_eq!(config.resolve_username().as_deref(), Some("alice"));
783        assert_eq!(config.resolve_password().as_deref(), Some("secret"));
784    }
785
786    #[test]
787    fn test_jaas_config_service_name_does_not_false_match() {
788        // `serviceName=` must not be picked up when searching for `name`, and a
789        // dotted-prefix `something.username=` must not match `username=`.
790        let config = SaslConfigs {
791            jaas_config: Some(Password::new(
792                "com.sun.security.auth.module.Krb5LoginModule required \
793                 serviceName=\"kafka\" foo.username=\"wrong\" username=\"right\" \
794                 password=\"pass\";",
795            )),
796            ..SaslConfigs::default()
797        };
798        assert_eq!(config.resolve_username().as_deref(), Some("right"));
799        assert_eq!(config.resolve_password().as_deref(), Some("pass"));
800    }
801
802    #[test]
803    fn test_jaas_config_namespace_does_not_false_match_name() {
804        // A longer key sharing a prefix (`usernamespace=`) must not match
805        // `username`, because '=' does not immediately follow (after optional
806        // whitespace) the matched key text.
807        assert_eq!(
808            SaslConfigs::parse_jaas_option("m required usernamespace=\"x\";", "username"),
809            None
810        );
811    }
812
813    #[test]
814    fn test_jaas_config_key_inside_a_quoted_value_does_not_match() {
815        // A `key=` sequence appearing inside another option's quoted value must
816        // not be mistaken for a real option — quoted regions are skipped
817        // wholesale. Here the real `username` option must resolve to `right`,
818        // not the `username=x` embedded in the password value.
819        let config = SaslConfigs {
820            jaas_config: Some(Password::new(
821                "PlainLoginModule required password=\"username=x\" username=\"right\";",
822            )),
823            ..SaslConfigs::default()
824        };
825        assert_eq!(config.resolve_username().as_deref(), Some("right"));
826        assert_eq!(config.resolve_password().as_deref(), Some("username=x"));
827    }
828
829    #[test]
830    fn test_jaas_config_escaped_quote_in_value_does_not_split_or_misalign() {
831        // An escaped quote inside a quoted value must not terminate the value
832        // (which would truncate it) nor misalign the scan of later options. The
833        // password value here contains a `\"`; `username` after it must still
834        // resolve to `right`, and the password is the decoded `a"b`.
835        let config = SaslConfigs {
836            jaas_config: Some(Password::new(
837                "PlainLoginModule required password=\"a\\\"b\" username=\"right\";",
838            )),
839            ..SaslConfigs::default()
840        };
841        assert_eq!(config.resolve_username().as_deref(), Some("right"));
842        assert_eq!(config.resolve_password().as_deref(), Some("a\"b"));
843    }
844
845    fn jaas_password(value: &str) -> Option<String> {
846        let config = SaslConfigs {
847            jaas_config: Some(Password::new(format!(
848                "org.apache.kafka.common.security.plain.PlainLoginModule required username=\"u\" password={value};"
849            ))),
850            ..SaslConfigs::default()
851        };
852        config.resolve_password().map(Cow::into_owned)
853    }
854
855    /// Quoted values decode their escapes as Java's `JaasConfig` does. Each
856    /// expected value is what `new JaasConfig("KafkaClient", jaas)` returns for
857    /// the `password` option on Kafka 4.4.0, printed code point by code point.
858    #[test]
859    fn test_jaas_config_quoted_value_escapes_are_decoded_like_java() {
860        let cases: &[(&str, &str)] = &[
861            // A backslash and a double quote, escaped as Java requires.
862            (r#""b\\a\"ck""#, "b\\a\"ck"),
863            // An escaped single quote inside single quotes.
864            (r"'it\'s'", "it's"),
865            // The control-character escapes.
866            (r#""\a\b\f\n\r\t\v""#, "\u{7}\u{8}\u{c}\n\r\t\u{b}"),
867            // Octal escapes take three digits only when the first is 0 to 3
868            // (`\477` is `\47` then `7`), stop at a non-octal digit (`\08` is
869            // NUL then `8`), and any other escaped character is itself (`\8`,
870            // `\q`).
871            (r#""\101\0\477\8\q\08\377\400""#, "A\u{0}'78q\u{0}8\u{ff} 0"),
872            (r#""tab\there""#, "tab\there"),
873            // A non-ASCII character, plain and escaped.
874            (r#""é\é""#, "éé"),
875            // A Windows path written with doubled backslashes.
876            (r#""C:\\temp\\x""#, "C:\\temp\\x"),
877        ];
878        for (value, expected) in cases {
879            assert_eq!(jaas_password(value).as_deref(), Some(*expected), "password={value}");
880        }
881    }
882
883    /// Java's `StreamTokenizer` ends a quoted string at a raw line terminator,
884    /// and `JaasConfig` then rejects the whole config ("Value not specified for
885    /// key 'cd' in JAAS config" on Kafka 4.4.0 for `password="ab<LF>cd"`). The
886    /// value is malformed here too, so the client fails at construction for
887    /// want of a password. An escaped line terminator is part of the value, and
888    /// one between options is only whitespace.
889    #[test]
890    fn test_jaas_config_raw_line_terminator_ends_a_quoted_value() {
891        for raw in ["\n", "\r"] {
892            assert_eq!(jaas_password(&format!("\"ab{raw}cd\"")), None, "{raw:?}");
893        }
894        assert_eq!(jaas_password("\"ab\\\ncd\"").as_deref(), Some("ab\ncd"));
895
896        let config = SaslConfigs {
897            jaas_config: Some(Password::new("PlainLoginModule required username=\"u\"\n password=\"abcd\";")),
898            ..SaslConfigs::default()
899        };
900        assert_eq!(config.resolve_username().as_deref(), Some("u"));
901        assert_eq!(config.resolve_password().as_deref(), Some("abcd"));
902    }
903
904    /// A bare (unquoted) value is returned as written, backslash included:
905    /// escapes are decoded only inside quotes. Java is stricter here: its
906    /// tokenizer does not take a backslash in a bare value, and `JaasConfig`
907    /// rejects such a config ("Value not specified for key 'null' in JAAS
908    /// config"). This parser does not validate the whole config, so it keeps
909    /// accepting it, as it did before quoted values were decoded.
910    #[test]
911    fn test_jaas_config_bare_value_with_a_backslash_is_returned_as_written() {
912        assert_eq!(
913            SaslConfigs::parse_jaas_option("PlainLoginModule required password=a\\b;", "password").as_deref(),
914            Some("a\\b")
915        );
916    }
917
918    /// A value without a backslash is not copied.
919    #[test]
920    fn test_jaas_config_value_without_escapes_is_borrowed() {
921        let jaas = "PlainLoginModule required username=\"alice\" password='secret';";
922        for key in ["username", "password"] {
923            assert!(
924                matches!(SaslConfigs::parse_jaas_option(jaas, key), Some(Cow::Borrowed(_))),
925                "{key}"
926            );
927        }
928    }
929
930    #[test]
931    fn test_config_key_constants() {
932        assert_eq!(SaslConfigs::SASL_MECHANISM, "sasl.mechanism");
933        assert_eq!(SaslConfigs::SASL_JAAS_CONFIG, "sasl.jaas.config");
934        assert_eq!(SaslConfigs::DEFAULT_SASL_MECHANISM, "GSSAPI");
935        assert_eq!(SaslConfigs::GSSAPI_MECHANISM, "GSSAPI");
936    }
937
938    /// The finding's requested test: `{:?}` of a config holding credentials
939    /// renders neither the password nor the JAAS string, while the non-secret
940    /// fields stay visible and `resolve_*` still yield the plaintext.
941    #[test]
942    fn test_debug_redacts_jaas_config_and_password() {
943        let config = SaslConfigs {
944            mechanism: "PLAIN".to_owned(),
945            jaas_config: Some(Password::new(
946                "org.apache.kafka.common.security.plain.PlainLoginModule required \
947                 username=\"jaas-user\" password=\"jaas-S3cr3t-Pa55\";",
948            )),
949            username: Some("direct-user".to_owned()),
950            password: Some(Password::new("direct-S3cr3t-Pa55")),
951        };
952
953        let rendered = format!("{config:?}");
954        assert_eq!(
955            rendered,
956            "SaslConfigs { mechanism: \"PLAIN\", jaas_config: Some([hidden]), \
957             username: Some(\"direct-user\"), password: Some([hidden]) }"
958        );
959        for secret in [
960            "direct-S3cr3t-Pa55",
961            "jaas-S3cr3t-Pa55",
962            "PlainLoginModule",
963            "jaas-user",
964        ] {
965            assert!(!rendered.contains(secret), "{secret:?} leaked: {rendered}");
966        }
967        let pretty = format!("{config:#?}");
968        assert!(pretty.contains("mechanism: \"PLAIN\""), "{pretty}");
969        assert!(pretty.contains("username: Some("), "{pretty}");
970        assert!(!pretty.contains("S3cr3t"), "{pretty}");
971        assert!(!pretty.contains("PlainLoginModule"), "{pretty}");
972
973        // The authenticator still receives the plaintext.
974        assert_eq!(config.resolve_username().as_deref(), Some("direct-user"));
975        assert_eq!(config.resolve_password().as_deref(), Some("direct-S3cr3t-Pa55"));
976
977        // Credentials carried only by the JAAS string are hidden as well, and
978        // still resolve to plaintext.
979        let jaas_only = SaslConfigs { username: None, password: None, ..config };
980        let rendered = format!("{jaas_only:?}");
981        assert!(!rendered.contains("jaas-S3cr3t-Pa55"), "{rendered}");
982        assert!(!rendered.contains("jaas-user"), "{rendered}");
983        assert!(rendered.contains("jaas_config: Some([hidden])"), "{rendered}");
984        assert_eq!(jaas_only.resolve_username().as_deref(), Some("jaas-user"));
985        assert_eq!(jaas_only.resolve_password().as_deref(), Some("jaas-S3cr3t-Pa55"));
986    }
987}