Skip to main content

confluent_kafka/admin/
admin_client_config.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//! Configuration for the `KafkaAdminClient`.
16//!
17//! Corresponds to `org.apache.kafka.clients.admin.AdminClientConfig`: the keys
18//! are defined on a `ConfigDef` in Java's order
19//! and parsed and validated by it, and the configuration answers Java's
20//! `AbstractConfig` getters.
21//!
22//! Not defined, and so reported by [`AdminClientConfig::unused`] and the
23//! client's [`AdminClientConfig::log_unused`] line when set:
24//!
25//! - `metric.reporters`, a list of classes: a configuration never takes a
26//!   class (CLAUDE.md §2).
27//! - `security.providers`: Java's JCA security providers have no counterpart.
28//! - `config.providers`: config providers are not translated, so the key is
29//!   left undefined and a value set for it is reported as unused, rather than
30//!   accepted and ignored.
31//! - `enable.metrics.push`: KIP-714 client telemetry is not implemented, so
32//!   the key is left undefined and a value set for it is reported as unused,
33//!   rather than accepted and ignored.
34//!
35//! `AbstractConfig`'s `getPassword`, `typeOf`, `originals*()` and `values*()`
36//! are not translated yet: each needs a public type the crate does not have
37//! (`Password`, `ConfigDef.Type`, Java's `RecordingMap`). See `CHANGELOG.md`.
38
39use std::collections::{BTreeSet, HashMap, HashSet};
40use std::fmt;
41use std::hash::{Hash, Hasher};
42use std::sync::LazyLock;
43
44use crate::common::Error;
45use crate::common::config::abstract_config::{AbstractConfig, ConfigMap, ValuesReader, string_originals};
46use crate::common::config::config_def::{
47    CaseInsensitiveValidString, ConfigDef, Importance, Range, Type, ValidList, ValidString,
48};
49use crate::common::config::{SaslConfigs, SslConfigs};
50use crate::common::security::auth::SecurityProtocol;
51use crate::{ClientDnsLookup, CommonClientConfigs, MetadataRecoveryStrategy};
52
53/// Java's `AdminClientConfig.CONFIG`, built in its static initializer.
54static CONFIG: LazyLock<ConfigDef> = LazyLock::new(|| {
55    ConfigDef::new()
56        .define_with_validator(
57            AdminClientConfig::BOOTSTRAP_SERVERS_CONFIG,
58            Type::List,
59            Vec::<String>::new(),
60            ValidList::any_non_duplicate_values(true, false),
61            Importance::High,
62        )
63        .define_with_validator(
64            AdminClientConfig::BOOTSTRAP_CONTROLLERS_CONFIG,
65            Type::List,
66            Vec::<String>::new(),
67            ValidList::any_non_duplicate_values(true, false),
68            Importance::High,
69        )
70        .define(AdminClientConfig::CLIENT_ID_CONFIG, Type::String, "", Importance::Medium)
71        .define_with_validator(
72            AdminClientConfig::METADATA_MAX_AGE_CONFIG,
73            Type::Long,
74            5 * 60 * 1000_i64,
75            Range::at_least(0),
76            Importance::Low,
77        )
78        .define_with_validator(
79            CommonClientConfigs::SEND_BUFFER_CONFIG,
80            Type::Int,
81            128 * 1024,
82            Range::at_least(CommonClientConfigs::SEND_BUFFER_LOWER_BOUND),
83            Importance::Medium,
84        )
85        .define_with_validator(
86            CommonClientConfigs::RECEIVE_BUFFER_CONFIG,
87            Type::Int,
88            64 * 1024,
89            Range::at_least(CommonClientConfigs::RECEIVE_BUFFER_LOWER_BOUND),
90            Importance::Medium,
91        )
92        .define_with_validator(
93            AdminClientConfig::RECONNECT_BACKOFF_MS_CONFIG,
94            Type::Long,
95            50_i64,
96            Range::at_least(0_i64),
97            Importance::Low,
98        )
99        .define_with_validator(
100            AdminClientConfig::RECONNECT_BACKOFF_MAX_MS_CONFIG,
101            Type::Long,
102            1000_i64,
103            Range::at_least(0_i64),
104            Importance::Low,
105        )
106        .define_with_validator(
107            AdminClientConfig::RETRY_BACKOFF_MS_CONFIG,
108            Type::Long,
109            CommonClientConfigs::DEFAULT_RETRY_BACKOFF_MS,
110            Range::at_least(0_i64),
111            Importance::Low,
112        )
113        .define_with_validator(
114            AdminClientConfig::RETRY_BACKOFF_MAX_MS_CONFIG,
115            Type::Long,
116            CommonClientConfigs::DEFAULT_RETRY_BACKOFF_MAX_MS,
117            Range::at_least(0_i64),
118            Importance::Low,
119        )
120        .define_with_validator(
121            AdminClientConfig::BOOTSTRAP_RESOLVE_TIMEOUT_MS_CONFIG,
122            Type::Long,
123            CommonClientConfigs::DEFAULT_BOOTSTRAP_RESOLVE_TIMEOUT_MS,
124            Range::at_least(0_i64),
125            Importance::High,
126        )
127        // Java defines `enable.metrics.push` here; it is left undefined until KIP-714
128        // client telemetry is implemented.
129        .define_with_validator(
130            AdminClientConfig::REQUEST_TIMEOUT_MS_CONFIG,
131            Type::Int,
132            30000,
133            Range::at_least(0),
134            Importance::Medium,
135        )
136        .define(
137            AdminClientConfig::SOCKET_CONNECTION_SETUP_TIMEOUT_MS_CONFIG,
138            Type::Long,
139            CommonClientConfigs::DEFAULT_SOCKET_CONNECTION_SETUP_TIMEOUT_MS,
140            Importance::Medium,
141        )
142        .define(
143            CommonClientConfigs::SOCKET_CONNECTION_SETUP_TIMEOUT_MAX_MS_CONFIG,
144            Type::Long,
145            CommonClientConfigs::DEFAULT_SOCKET_CONNECTION_SETUP_TIMEOUT_MAX_MS,
146            Importance::Medium,
147        )
148        .define(
149            AdminClientConfig::CONNECTIONS_MAX_IDLE_MS_CONFIG,
150            Type::Long,
151            5 * 60 * 1000_i64,
152            Importance::Medium,
153        )
154        .define_with_validator(
155            AdminClientConfig::RETRIES_CONFIG,
156            Type::Int,
157            i32::MAX,
158            Range::between(0, i32::MAX),
159            Importance::Low,
160        )
161        .define_with_validator(
162            AdminClientConfig::DEFAULT_API_TIMEOUT_MS_CONFIG,
163            Type::Int,
164            60000,
165            Range::at_least(0),
166            Importance::Medium,
167        )
168        .define_with_validator(
169            CommonClientConfigs::METRICS_SAMPLE_WINDOW_MS_CONFIG,
170            Type::Long,
171            30000_i64,
172            Range::at_least(0),
173            Importance::Low,
174        )
175        .define_with_validator(
176            CommonClientConfigs::METRICS_NUM_SAMPLES_CONFIG,
177            Type::Int,
178            2,
179            Range::at_least(1),
180            Importance::Low,
181        )
182        // `metric.reporters` is a list of classes (CLAUDE.md §2): not defined.
183        .define_with_validator(
184            CommonClientConfigs::METRICS_RECORDING_LEVEL_CONFIG,
185            Type::String,
186            "INFO",
187            ValidString::r#in(&["INFO", "DEBUG", "TRACE"]),
188            Importance::Low,
189        )
190        .define_with_validator(
191            AdminClientConfig::CLIENT_DNS_LOOKUP_CONFIG,
192            Type::String,
193            ClientDnsLookup::UseAllDnsIps.config_value(),
194            ValidString::r#in(&[
195                ClientDnsLookup::UseAllDnsIps.config_value(),
196                ClientDnsLookup::ResolveCanonicalBootstrapServersOnly.config_value(),
197            ]),
198            Importance::Medium,
199        )
200        // security support; `security.providers` (JCA providers) is not defined.
201        .define_with_validator(
202            AdminClientConfig::SECURITY_PROTOCOL_CONFIG,
203            Type::String,
204            CommonClientConfigs::DEFAULT_SECURITY_PROTOCOL,
205            CaseInsensitiveValidString::r#in(&SecurityProtocol::names()),
206            Importance::Medium,
207        )
208        .with_client_ssl_support()
209        .with_client_sasl_support()
210        .define_with_validator(
211            CommonClientConfigs::METADATA_RECOVERY_STRATEGY_CONFIG,
212            Type::String,
213            CommonClientConfigs::DEFAULT_METADATA_RECOVERY_STRATEGY,
214            CaseInsensitiveValidString::r#in(&["NONE", "REBOOTSTRAP"]),
215            Importance::Low,
216        )
217        .define_with_validator(
218            CommonClientConfigs::METADATA_RECOVERY_REBOOTSTRAP_TRIGGER_MS_CONFIG,
219            Type::Long,
220            CommonClientConfigs::DEFAULT_METADATA_RECOVERY_REBOOTSTRAP_TRIGGER_MS,
221            Range::at_least(0),
222            Importance::Low,
223        )
224        .define(
225            AdminClientConfig::METADATA_CLUSTER_CHECK_ENABLE_CONFIG,
226            Type::Boolean,
227            true,
228            Importance::Low,
229        )
230    // Java ends the chain with `config.providers`; it is left undefined until config
231    // providers are translated.
232});
233
234/// The AdminClient configuration class, which also contains constants for
235/// configuration entry names.
236#[doc(alias = "org.apache.kafka.clients.admin.AdminClientConfig")]
237pub struct AdminClientConfig {
238    /// The originals, the parsed values and the keys used so far.
239    config: AbstractConfig,
240    /// The keys the typed fields below were read from, which the client marks
241    /// used when it is built from this configuration (`ValuesReader`).
242    read_keys: Vec<&'static str>,
243    bootstrap_servers: Vec<String>,
244    bootstrap_controllers: Vec<String>,
245    client_dns_lookup: ClientDnsLookup,
246    client_id: String,
247    request_timeout_ms: i32,
248    default_api_timeout_ms: i32,
249    retries: i32,
250    retry_backoff_ms: i64,
251    retry_backoff_max_ms: i64,
252    bootstrap_resolve_timeout_ms: i64,
253    reconnect_backoff_ms: i64,
254    reconnect_backoff_max_ms: i64,
255    connections_max_idle_ms: i64,
256    send_buffer_bytes: i32,
257    receive_buffer_bytes: i32,
258    metadata_max_age_ms: i64,
259    socket_connection_setup_timeout_ms: i64,
260    socket_connection_setup_timeout_max_ms: i64,
261    metadata_recovery_strategy: MetadataRecoveryStrategy,
262    metadata_recovery_rebootstrap_trigger_ms: i64,
263    metadata_cluster_check_enable: bool,
264
265    // --- Security ---
266    /// `security.protocol` - Protocol used to communicate with brokers.
267    /// Default: `SecurityProtocol::Plaintext`.
268    security_protocol: SecurityProtocol,
269
270    /// SASL configuration (mechanism, JAAS config, credentials).
271    sasl_config: SaslConfigs,
272
273    /// SSL/TLS configuration.
274    ssl_config: SslConfigs,
275}
276
277impl fmt::Debug for AdminClientConfig {
278    // The typed settings, whose secrets are `Password`s rendered as
279    // `[hidden]`, and the keys of the properties, never their values: they
280    // also hold keys this configuration does not define, whose values may be
281    // secrets, and Java never prints a raw original value.
282    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
283        // Destructured exhaustively: a field added to the struct fails to
284        // compile until it is bound here, and a bound but unrendered field is
285        // an unused variable, which the lint rejects.
286        let Self {
287            config,
288            read_keys: _,
289            bootstrap_servers,
290            bootstrap_controllers,
291            client_dns_lookup,
292            client_id,
293            request_timeout_ms,
294            default_api_timeout_ms,
295            retries,
296            retry_backoff_ms,
297            retry_backoff_max_ms,
298            bootstrap_resolve_timeout_ms,
299            reconnect_backoff_ms,
300            reconnect_backoff_max_ms,
301            connections_max_idle_ms,
302            send_buffer_bytes,
303            receive_buffer_bytes,
304            metadata_max_age_ms,
305            socket_connection_setup_timeout_ms,
306            socket_connection_setup_timeout_max_ms,
307            metadata_recovery_strategy,
308            metadata_recovery_rebootstrap_trigger_ms,
309            metadata_cluster_check_enable,
310            security_protocol,
311            sasl_config,
312            ssl_config,
313        } = self;
314        let originals: BTreeSet<&str> = config.originals_map().keys().map(String::as_str).collect();
315        f.debug_struct("AdminClientConfig")
316            .field("bootstrap_servers", bootstrap_servers)
317            .field("bootstrap_controllers", bootstrap_controllers)
318            .field("client_dns_lookup", client_dns_lookup)
319            .field("client_id", client_id)
320            .field("request_timeout_ms", request_timeout_ms)
321            .field("default_api_timeout_ms", default_api_timeout_ms)
322            .field("retries", retries)
323            .field("retry_backoff_ms", retry_backoff_ms)
324            .field("retry_backoff_max_ms", retry_backoff_max_ms)
325            .field("bootstrap_resolve_timeout_ms", bootstrap_resolve_timeout_ms)
326            .field("reconnect_backoff_ms", reconnect_backoff_ms)
327            .field("reconnect_backoff_max_ms", reconnect_backoff_max_ms)
328            .field("connections_max_idle_ms", connections_max_idle_ms)
329            .field("send_buffer_bytes", send_buffer_bytes)
330            .field("receive_buffer_bytes", receive_buffer_bytes)
331            .field("metadata_max_age_ms", metadata_max_age_ms)
332            .field("socket_connection_setup_timeout_ms", socket_connection_setup_timeout_ms)
333            .field("socket_connection_setup_timeout_max_ms", socket_connection_setup_timeout_max_ms)
334            .field("metadata_recovery_strategy", metadata_recovery_strategy)
335            .field(
336                "metadata_recovery_rebootstrap_trigger_ms",
337                metadata_recovery_rebootstrap_trigger_ms,
338            )
339            .field("metadata_cluster_check_enable", metadata_cluster_check_enable)
340            .field("security_protocol", security_protocol)
341            .field("sasl_config", sasl_config)
342            .field("ssl_config", ssl_config)
343            .field("originals", &originals)
344            .finish()
345    }
346}
347
348impl PartialEq for AdminClientConfig {
349    // Java's `AbstractConfig.equals`: the originals are equal.
350    fn eq(&self, other: &Self) -> bool {
351        self.config == other.config
352    }
353}
354
355impl Eq for AdminClientConfig {}
356
357impl Hash for AdminClientConfig {
358    // Java's `AbstractConfig.hashCode`, over the originals.
359    fn hash<H: Hasher>(&self, state: &mut H) {
360        self.config.hash(state);
361    }
362}
363
364impl AdminClientConfig {
365    /// `bootstrap.servers`
366    pub const BOOTSTRAP_SERVERS_CONFIG: &'static str = "bootstrap.servers";
367    /// `bootstrap.controllers` (KIP-919): a list of host/port pairs to use for
368    /// establishing the initial connection to the KRaft controller quorum. This
369    /// list should be in the form `host1:port1,host2:port2,...`.
370    ///
371    /// Set it in place of `bootstrap.servers`: the client then talks to the
372    /// controllers directly, and fails at once every call the controllers
373    /// cannot serve. Setting both, or neither, fails client creation, as
374    /// Java's `KafkaAdminClient.determineBootstrapType` does.
375    pub const BOOTSTRAP_CONTROLLERS_CONFIG: &'static str = "bootstrap.controllers";
376    /// `client.dns.lookup`
377    pub const CLIENT_DNS_LOOKUP_CONFIG: &'static str = CommonClientConfigs::CLIENT_DNS_LOOKUP_CONFIG;
378    /// `client.id`
379    pub const CLIENT_ID_CONFIG: &'static str = "client.id";
380    /// `request.timeout.ms`
381    pub const REQUEST_TIMEOUT_MS_CONFIG: &'static str = "request.timeout.ms";
382    /// `default.api.timeout.ms`
383    pub const DEFAULT_API_TIMEOUT_MS_CONFIG: &'static str = "default.api.timeout.ms";
384    /// `retries`
385    pub const RETRIES_CONFIG: &'static str = "retries";
386    /// `retry.backoff.ms`
387    pub const RETRY_BACKOFF_MS_CONFIG: &'static str = "retry.backoff.ms";
388    /// `retry.backoff.max.ms`
389    pub const RETRY_BACKOFF_MAX_MS_CONFIG: &'static str = "retry.backoff.max.ms";
390    /// `bootstrap.resolve.timeout.ms` (KIP-909): `0` (the default) resolves
391    /// `bootstrap.servers` synchronously when the client is created; a
392    /// positive value resolves asynchronously, retrying for at most this long.
393    pub const BOOTSTRAP_RESOLVE_TIMEOUT_MS_CONFIG: &'static str =
394        CommonClientConfigs::BOOTSTRAP_RESOLVE_TIMEOUT_MS_CONFIG;
395    /// `reconnect.backoff.ms`
396    pub const RECONNECT_BACKOFF_MS_CONFIG: &'static str = "reconnect.backoff.ms";
397    /// `reconnect.backoff.max.ms`
398    pub const RECONNECT_BACKOFF_MAX_MS_CONFIG: &'static str = "reconnect.backoff.max.ms";
399    /// `connections.max.idle.ms`
400    pub const CONNECTIONS_MAX_IDLE_MS_CONFIG: &'static str = "connections.max.idle.ms";
401    /// `metadata.max.age.ms`
402    pub const METADATA_MAX_AGE_CONFIG: &'static str = "metadata.max.age.ms";
403    /// `socket.connection.setup.timeout.ms`
404    pub const SOCKET_CONNECTION_SETUP_TIMEOUT_MS_CONFIG: &'static str = "socket.connection.setup.timeout.ms";
405    /// `metadata.cluster.check.enable` (KIP-1242).
406    ///
407    /// Whether the client should send cluster and node information when
408    /// connecting to a broker to enable it to check for a misrouted
409    /// connection. This configuration is ignored if rebootstrapping is
410    /// disabled by setting the configuration `metadata.recovery.strategy=none`.
411    /// If the client is connecting to a broker older than Apache Kafka 4.4, no
412    /// checking is performed and this configuration has no effect.
413    pub const METADATA_CLUSTER_CHECK_ENABLE_CONFIG: &'static str =
414        CommonClientConfigs::METADATA_CLUSTER_CHECK_ENABLE_CONFIG;
415    /// `security.protocol`
416    pub const SECURITY_PROTOCOL_CONFIG: &'static str = CommonClientConfigs::SECURITY_PROTOCOL_CONFIG;
417
418    /// Creates a config from a property map.
419    ///
420    /// # Arguments
421    ///
422    /// - `props` - The admin client configuration properties
423    ///
424    /// # Errors
425    ///
426    /// - `Error::is_config_error` if a value fails to parse or validate, with
427    ///   `ConfigDef`'s message, or if a SASL `security.protocol` has an empty
428    ///   `sasl.mechanism` or one other than `PLAIN`. Any combination of
429    ///   `bootstrap.servers` and `bootstrap.controllers` is accepted here, as in
430    ///   Java: exactly one of them must be set, but the client checks it when it
431    ///   is created ([`AdminClient::create`](crate::admin::AdminClient::create)).
432    ///
433    /// WARNING: `sasl.mechanism` must be `PLAIN`.
434    #[doc(alias = "org.apache.kafka.clients.admin.AdminClientConfig#AdminClientConfig(Map)")]
435    pub fn new(props: &HashMap<String, String>) -> Result<Self, Error> {
436        Self::build(string_originals(props), true)
437    }
438
439    /// The configuration of one more client given this one: the same
440    /// properties, with its own record of the keys used, as [`Self::new`]
441    /// leaves it. It is not `Clone`: a `*Config` holder never is.
442    ///
443    /// Java's `Admin.create` builds one `AdminClientConfig` and hands it to
444    /// one client, which logs nothing about it. The copy therefore logs none
445    /// of the warnings [`Self::new`] logs: it makes the same parse and the
446    /// same reads, marking the same keys used and failing the same way, but
447    /// logs neither the parse's warning that a list's duplicate values are
448    /// removed, nor the post-processing's warnings (the reconnect and retry
449    /// backoff, the connection setup timeout).
450    ///
451    /// Unlike the consumer's and producer's, an admin configuration derives
452    /// no `client.id`: `KafkaAdminClient.createInternal` does, taking one
453    /// number per client (`KafkaAdminClient.generateClientId`), so the copy
454    /// leaves `client.id` as given.
455    ///
456    /// # Errors
457    ///
458    /// Fails as [`Self::new`] does; this configuration's properties already
459    /// passed it, so it does not in practice.
460    #[cfg_attr(
461        not(any(feature = "ffi", test)),
462        expect(dead_code, reason = "only the C config handle copies a configuration")
463    )]
464    pub(crate) fn copy_for_client(&self) -> Result<Self, Error> {
465        Self::build(self.config.originals_map().clone(), false)
466    }
467
468    /// Java's `AdminClientConfig(Map)`: parses `originals` and post-processes them,
469    /// logging the parse's and the post-processing's warnings only when
470    /// `log_warnings` is true.
471    fn build(originals: ConfigMap, log_warnings: bool) -> Result<Self, Error> {
472        let config = AbstractConfig::with_hooks_and_log_warnings(
473            &CONFIG,
474            originals,
475            false,
476            log_warnings,
477            "AdminClientConfig",
478            |originals| originals,
479            // Java's `postProcessParsedConfig`.
480            |config| {
481                CommonClientConfigs::post_validate_sasl_mechanism_config(config)?;
482                CommonClientConfigs::post_validate_supported_sasl_mechanism(config)?;
483                CommonClientConfigs::warn_disabling_exponential_backoff(config, log_warnings)?;
484                Ok(CommonClientConfigs::post_process_reconnect_backoff_configs(
485                    config,
486                    config.parsed_values(),
487                    log_warnings,
488                ))
489            },
490        )?;
491        let mut values = ValuesReader::new(&config);
492        let bootstrap_servers = values.list(Self::BOOTSTRAP_SERVERS_CONFIG)?.to_vec();
493        // Read, and so marked used by the client, whichever list it bootstraps
494        // from, as Java's `determineBootstrapType` reads both.
495        let bootstrap_controllers = values.list(Self::BOOTSTRAP_CONTROLLERS_CONFIG)?.to_vec();
496        let client_dns_lookup = ClientDnsLookup::parse_config_value(values.string(Self::CLIENT_DNS_LOOKUP_CONFIG)?)?;
497        let client_id = values.string(Self::CLIENT_ID_CONFIG)?.to_string();
498        let request_timeout_ms = values.int(Self::REQUEST_TIMEOUT_MS_CONFIG)?;
499        let default_api_timeout_ms = values.int(Self::DEFAULT_API_TIMEOUT_MS_CONFIG)?;
500        let retries = values.int(Self::RETRIES_CONFIG)?;
501        let retry_backoff_ms = values.long(Self::RETRY_BACKOFF_MS_CONFIG)?;
502        let retry_backoff_max_ms = values.long(Self::RETRY_BACKOFF_MAX_MS_CONFIG)?;
503        let bootstrap_resolve_timeout_ms = values.long(Self::BOOTSTRAP_RESOLVE_TIMEOUT_MS_CONFIG)?;
504        let reconnect_backoff_ms = values.long(Self::RECONNECT_BACKOFF_MS_CONFIG)?;
505        let reconnect_backoff_max_ms = values.long(Self::RECONNECT_BACKOFF_MAX_MS_CONFIG)?;
506        let connections_max_idle_ms = values.long(Self::CONNECTIONS_MAX_IDLE_MS_CONFIG)?;
507        let send_buffer_bytes = values.int(CommonClientConfigs::SEND_BUFFER_CONFIG)?;
508        let receive_buffer_bytes = values.int(CommonClientConfigs::RECEIVE_BUFFER_CONFIG)?;
509        let metadata_max_age_ms = values.long(Self::METADATA_MAX_AGE_CONFIG)?;
510        let socket_connection_setup_timeout_ms = values.long(Self::SOCKET_CONNECTION_SETUP_TIMEOUT_MS_CONFIG)?;
511        let socket_connection_setup_timeout_max_ms =
512            values.long(CommonClientConfigs::SOCKET_CONNECTION_SETUP_TIMEOUT_MAX_MS_CONFIG)?;
513        // The validator accepted the strategy case-insensitively, as `forName`
514        // reads it.
515        let strategy = values.string(CommonClientConfigs::METADATA_RECOVERY_STRATEGY_CONFIG)?;
516        let metadata_recovery_strategy =
517            MetadataRecoveryStrategy::for_name(strategy).map_err(Error::local_illegal_argument)?;
518        let metadata_recovery_rebootstrap_trigger_ms =
519            values.long(CommonClientConfigs::METADATA_RECOVERY_REBOOTSTRAP_TRIGGER_MS_CONFIG)?;
520        let metadata_cluster_check_enable = values.boolean(Self::METADATA_CLUSTER_CHECK_ENABLE_CONFIG)?;
521        let protocol = values.string(Self::SECURITY_PROTOCOL_CONFIG)?;
522        // The validator accepted `protocol` case-insensitively.
523        let security_protocol = SecurityProtocol::for_name(protocol)
524            .ok_or_else(|| Error::local_illegal_state(format!("Unknown security protocol {protocol}")))?;
525
526        // The `ssl.*` and `sasl.*` keys are read by Java's channel builder only
527        // for a protocol that uses them (`ChannelBuilders.clientChannelBuilder`),
528        // so only then are they marked used.
529        let mut ssl_values = ValuesReader::new(&config);
530        let ssl_config = SslConfigs::from_values(&mut ssl_values)?;
531        if matches!(security_protocol, SecurityProtocol::Ssl | SecurityProtocol::SaslSsl) {
532            values.append(ssl_values);
533        }
534        let mut sasl_values = ValuesReader::new(&config);
535        let sasl_config = SaslConfigs::from_values(&mut sasl_values)?;
536        if matches!(security_protocol, SecurityProtocol::SaslPlaintext | SecurityProtocol::SaslSsl) {
537            values.append(sasl_values);
538        }
539        let read_keys = values.into_read_keys();
540
541        Ok(Self {
542            config,
543            read_keys,
544            bootstrap_servers,
545            bootstrap_controllers,
546            client_dns_lookup,
547            client_id,
548            request_timeout_ms,
549            default_api_timeout_ms,
550            retries,
551            retry_backoff_ms,
552            retry_backoff_max_ms,
553            bootstrap_resolve_timeout_ms,
554            reconnect_backoff_ms,
555            reconnect_backoff_max_ms,
556            connections_max_idle_ms,
557            send_buffer_bytes,
558            receive_buffer_bytes,
559            metadata_max_age_ms,
560            socket_connection_setup_timeout_ms,
561            socket_connection_setup_timeout_max_ms,
562            metadata_recovery_strategy,
563            metadata_recovery_rebootstrap_trigger_ms,
564            metadata_cluster_check_enable,
565            security_protocol,
566            sasl_config,
567            ssl_config,
568        })
569    }
570
571    /// The `SHORT` configuration `key`. Reading a key marks it used
572    /// ([`Self::unused`]).
573    ///
574    /// # Arguments
575    ///
576    /// - `key` - the configuration name
577    ///
578    /// # Returns
579    ///
580    /// The value, `None` for Java's `null`.
581    ///
582    /// # Errors
583    ///
584    /// - `Error::is_config_error` with Java's `Unknown configuration '<key>'`
585    ///   if `key` is not a configuration this class defines.
586    /// - `Error::is_local_illegal_argument_error` if `key` is a configuration
587    ///   of another type, where Java's cast fails with a `ClassCastException`.
588    #[doc(alias = "org.apache.kafka.common.config.AbstractConfig#getShort")]
589    pub fn get_short(&self, key: &str) -> Result<Option<i16>, Error> {
590        self.config.get_short(key)
591    }
592
593    /// The `INT` configuration `key`. Reading a key marks it used
594    /// ([`Self::unused`]).
595    ///
596    /// # Arguments
597    ///
598    /// - `key` - the configuration name
599    ///
600    /// # Returns
601    ///
602    /// The value, `None` for Java's `null`.
603    ///
604    /// # Errors
605    ///
606    /// - `Error::is_config_error` with Java's `Unknown configuration '<key>'`
607    ///   if `key` is not a configuration this class defines.
608    /// - `Error::is_local_illegal_argument_error` if `key` is a configuration
609    ///   of another type, where Java's cast fails with a `ClassCastException`.
610    #[doc(alias = "org.apache.kafka.common.config.AbstractConfig#getInt")]
611    pub fn get_int(&self, key: &str) -> Result<Option<i32>, Error> {
612        self.config.get_int(key)
613    }
614
615    /// The `LONG` configuration `key`. Reading a key marks it used
616    /// ([`Self::unused`]).
617    ///
618    /// # Arguments
619    ///
620    /// - `key` - the configuration name
621    ///
622    /// # Returns
623    ///
624    /// The value, `None` for Java's `null`.
625    ///
626    /// # Errors
627    ///
628    /// - `Error::is_config_error` with Java's `Unknown configuration '<key>'`
629    ///   if `key` is not a configuration this class defines.
630    /// - `Error::is_local_illegal_argument_error` if `key` is a configuration
631    ///   of another type, where Java's cast fails with a `ClassCastException`.
632    #[doc(alias = "org.apache.kafka.common.config.AbstractConfig#getLong")]
633    pub fn get_long(&self, key: &str) -> Result<Option<i64>, Error> {
634        self.config.get_long(key)
635    }
636
637    /// The `DOUBLE` configuration `key`. Reading a key marks it used
638    /// ([`Self::unused`]).
639    ///
640    /// # Arguments
641    ///
642    /// - `key` - the configuration name
643    ///
644    /// # Returns
645    ///
646    /// The value, `None` for Java's `null`.
647    ///
648    /// # Errors
649    ///
650    /// - `Error::is_config_error` with Java's `Unknown configuration '<key>'`
651    ///   if `key` is not a configuration this class defines.
652    /// - `Error::is_local_illegal_argument_error` if `key` is a configuration
653    ///   of another type, where Java's cast fails with a `ClassCastException`.
654    #[doc(alias = "org.apache.kafka.common.config.AbstractConfig#getDouble")]
655    pub fn get_double(&self, key: &str) -> Result<Option<f64>, Error> {
656        self.config.get_double(key)
657    }
658
659    /// The `LIST` configuration `key`, borrowed from the parsed values.
660    /// Reading a key marks it used ([`Self::unused`]).
661    ///
662    /// # Arguments
663    ///
664    /// - `key` - the configuration name
665    ///
666    /// # Returns
667    ///
668    /// The value, `None` for Java's `null`.
669    ///
670    /// # Errors
671    ///
672    /// - `Error::is_config_error` with Java's `Unknown configuration '<key>'`
673    ///   if `key` is not a configuration this class defines.
674    /// - `Error::is_local_illegal_argument_error` if `key` is a configuration
675    ///   of another type, where Java's cast fails with a `ClassCastException`.
676    #[doc(alias = "org.apache.kafka.common.config.AbstractConfig#getList")]
677    pub fn get_list(&self, key: &str) -> Result<Option<&[String]>, Error> {
678        self.config.get_list(key)
679    }
680
681    /// The `BOOLEAN` configuration `key`. Reading a key marks it used
682    /// ([`Self::unused`]).
683    ///
684    /// # Arguments
685    ///
686    /// - `key` - the configuration name
687    ///
688    /// # Returns
689    ///
690    /// The value, `None` for Java's `null`.
691    ///
692    /// # Errors
693    ///
694    /// - `Error::is_config_error` with Java's `Unknown configuration '<key>'`
695    ///   if `key` is not a configuration this class defines.
696    /// - `Error::is_local_illegal_argument_error` if `key` is a configuration
697    ///   of another type, where Java's cast fails with a `ClassCastException`.
698    #[doc(alias = "org.apache.kafka.common.config.AbstractConfig#getBoolean")]
699    pub fn get_boolean(&self, key: &str) -> Result<Option<bool>, Error> {
700        self.config.get_boolean(key)
701    }
702
703    /// The `STRING` configuration `key`, trimmed. Reading a key marks it used
704    /// ([`Self::unused`]).
705    ///
706    /// # Arguments
707    ///
708    /// - `key` - the configuration name
709    ///
710    /// # Returns
711    ///
712    /// The value, `None` for Java's `null` (also what an unset `PASSWORD` key
713    /// such as `ssl.keystore.key` answers, as Java's cast of `null` succeeds).
714    ///
715    /// # Errors
716    ///
717    /// - `Error::is_config_error` with Java's `Unknown configuration '<key>'`
718    ///   if `key` is not a configuration this class defines.
719    /// - `Error::is_local_illegal_argument_error` if `key` is a configuration
720    ///   of another type (a set `PASSWORD` key is not a `STRING`), where
721    ///   Java's cast fails with a `ClassCastException`.
722    #[doc(alias = "org.apache.kafka.common.config.AbstractConfig#getString")]
723    pub fn get_string(&self, key: &str) -> Result<Option<&str>, Error> {
724        self.config.get_string(key)
725    }
726
727    /// Returns the keys of the properties this configuration was built from
728    /// that were never read: through a getter, or by the client built from it.
729    #[doc(alias = "org.apache.kafka.common.config.AbstractConfig#unused")]
730    pub fn unused(&self) -> HashSet<String> {
731        self.config.unused()
732    }
733
734    /// Marks the configuration `key` used without reading it.
735    ///
736    /// # Arguments
737    ///
738    /// - `key` - the configuration name
739    #[doc(alias = "org.apache.kafka.common.config.AbstractConfig#ignore")]
740    pub fn ignore(&self, key: &str) {
741        self.config.ignore(key);
742    }
743
744    /// Info level log for any unused configurations
745    // One line, `These configurations '[a, b]' were supplied but are not used
746    // yet.`, and nothing when every key was used.
747    #[doc(alias = "org.apache.kafka.common.config.AbstractConfig#logUnused")]
748    pub fn log_unused(&self) {
749        self.config.log_unused();
750    }
751
752    /// The names of the configurations this class defines.
753    ///
754    /// # Returns
755    ///
756    /// The set of configuration keys
757    #[doc(alias = "org.apache.kafka.clients.admin.AdminClientConfig#configNames")]
758    pub fn config_names() -> HashSet<String> {
759        CONFIG.names()
760    }
761
762    /// Marks used the keys the typed settings were read from, as the client
763    /// does where Java's reads them through the getters.
764    pub(crate) fn mark_read_keys_used(&self) {
765        for key in &self.read_keys {
766            self.config.ignore(key);
767        }
768    }
769
770    /// Java's `logAll()`, which Java runs when `Admin.create` builds the
771    /// configuration with `doLog = true`: every parsed value at INFO.
772    pub(crate) fn log_values(&self) {
773        self.config.log_all("AdminClientConfig");
774    }
775
776    /// The `bootstrap.servers` list.
777    pub(crate) fn bootstrap_servers(&self) -> &[String] {
778        &self.bootstrap_servers
779    }
780
781    /// The `bootstrap.controllers` list (KIP-919), empty when unset.
782    pub(crate) fn bootstrap_controllers(&self) -> &[String] {
783        &self.bootstrap_controllers
784    }
785
786    /// `client.dns.lookup`.
787    pub(crate) fn client_dns_lookup(&self) -> ClientDnsLookup {
788        self.client_dns_lookup
789    }
790
791    /// The `client.id`.
792    pub(crate) fn client_id(&self) -> &str {
793        &self.client_id
794    }
795
796    /// `request.timeout.ms`.
797    pub(crate) fn request_timeout_ms(&self) -> i32 {
798        self.request_timeout_ms
799    }
800
801    /// `default.api.timeout.ms`.
802    pub(crate) fn default_api_timeout_ms(&self) -> i32 {
803        self.default_api_timeout_ms
804    }
805
806    /// Whether the user set `key` explicitly.
807    ///
808    /// Java's `config.originals().containsKey(key)`: a key is "user
809    /// configured" iff it appears in the properties the configuration was
810    /// built from, not merely because it has a (possibly derived) value.
811    pub(crate) fn user_configured(&self, key: &str) -> bool {
812        self.config.originals_map().contains_key(key)
813    }
814
815    /// `retries`.
816    pub(crate) fn retries(&self) -> i32 {
817        self.retries
818    }
819
820    /// `retry.backoff.ms`.
821    pub(crate) fn retry_backoff_ms(&self) -> i64 {
822        self.retry_backoff_ms
823    }
824
825    /// `retry.backoff.max.ms`.
826    pub(crate) fn retry_backoff_max_ms(&self) -> i64 {
827        self.retry_backoff_max_ms
828    }
829
830    /// `bootstrap.resolve.timeout.ms` (KIP-909): selects the client's bootstrap
831    /// DNS resolution mode. `0` (the default) resolves `bootstrap.servers`
832    /// synchronously when the client is created, and a resolution failure fails
833    /// creation with a config error. A positive value resolves asynchronously,
834    /// retrying for at most this long before every subsequent call fails with an
835    /// unrecoverable
836    /// [`BootstrapResolutionError`](crate::common::errors::BootstrapResolutionError);
837    /// the client must then be closed and re-created. Setting a positive value
838    /// enables an evolving feature whose compatibility may be broken in a minor
839    /// release.
840    pub(crate) fn bootstrap_resolve_timeout_ms(&self) -> i64 {
841        self.bootstrap_resolve_timeout_ms
842    }
843
844    /// `reconnect.backoff.ms`.
845    pub(crate) fn reconnect_backoff_ms(&self) -> i64 {
846        self.reconnect_backoff_ms
847    }
848
849    /// `reconnect.backoff.max.ms`.
850    pub(crate) fn reconnect_backoff_max_ms(&self) -> i64 {
851        self.reconnect_backoff_max_ms
852    }
853
854    /// `connections.max.idle.ms`.
855    pub(crate) fn connections_max_idle_ms(&self) -> i64 {
856        self.connections_max_idle_ms
857    }
858
859    /// `send.buffer.bytes`, the socket send buffer (`-1` for the OS default).
860    pub(crate) fn send_buffer_bytes(&self) -> i32 {
861        self.send_buffer_bytes
862    }
863
864    /// `receive.buffer.bytes`, the socket receive buffer (`-1` for the OS
865    /// default).
866    pub(crate) fn receive_buffer_bytes(&self) -> i32 {
867        self.receive_buffer_bytes
868    }
869
870    /// `metadata.max.age.ms`.
871    pub(crate) fn metadata_max_age_ms(&self) -> i64 {
872        self.metadata_max_age_ms
873    }
874
875    /// `socket.connection.setup.timeout.ms`.
876    pub(crate) fn socket_connection_setup_timeout_ms(&self) -> i64 {
877        self.socket_connection_setup_timeout_ms
878    }
879
880    /// `socket.connection.setup.timeout.max.ms`.
881    pub(crate) fn socket_connection_setup_timeout_max_ms(&self) -> i64 {
882        self.socket_connection_setup_timeout_max_ms
883    }
884
885    /// `metadata.recovery.strategy`: whether the client re-resolves
886    /// `bootstrap.servers` when it cannot reach any known broker
887    ///.
888    pub(crate) fn metadata_recovery_strategy(&self) -> MetadataRecoveryStrategy {
889        self.metadata_recovery_strategy
890    }
891
892    /// `metadata.recovery.rebootstrap.trigger.ms`: how long a metadata update
893    /// may go unanswered before the client rebootstraps.
894    pub(crate) fn metadata_recovery_rebootstrap_trigger_ms(&self) -> i64 {
895        self.metadata_recovery_rebootstrap_trigger_ms
896    }
897
898    /// `metadata.cluster.check.enable` (KIP-1242): whether the client sends the
899    /// cluster id and node id it expects in ApiVersions so the broker can detect
900    /// a misrouted connection.
901    ///
902    /// It is passed to the `NetworkClient` as in Java
903    /// (`ClientUtils.createNetworkClient`), but, also as in Java, it has no
904    /// effect on the admin client: the admin's metadata updater does not
905    /// override `MetadataUpdater.clusterId()` (`AdminMetadataManager.java`), so
906    /// the expected cluster id is never known.
907    pub(crate) fn metadata_cluster_check_enable(&self) -> bool {
908        self.metadata_cluster_check_enable
909    }
910
911    /// `security.protocol`.
912    pub(crate) fn security_protocol(&self) -> SecurityProtocol {
913        self.security_protocol
914    }
915
916    /// SASL configuration (mechanism, JAAS config, credentials).
917    pub(crate) fn sasl_config(&self) -> &SaslConfigs {
918        &self.sasl_config
919    }
920
921    /// SSL/TLS configuration.
922    pub(crate) fn ssl_config(&self) -> &SslConfigs {
923        &self.ssl_config
924    }
925}
926
927#[cfg(test)]
928mod tests {
929    /// `postValidateSaslMechanismConfig` runs when the config is built, so an unusable
930    /// `sasl.mechanism` fails here and not later, when a channel builder is created.
931    #[test]
932    fn test_sasl_mechanism_is_validated_when_the_config_is_built() {
933        let build = |protocol: &str, mechanism: &str| {
934            let props = std::collections::HashMap::from([
935                ("bootstrap.servers".to_string(), "localhost:9092".to_string()),
936                ("security.protocol".to_string(), protocol.to_string()),
937                ("sasl.mechanism".to_string(), mechanism.to_string()),
938            ]);
939            AdminClientConfig::new(&props)
940        };
941
942        let err = build("SASL_PLAINTEXT", "SCRAM-SHA-256").expect_err("SCRAM is not implemented");
943        assert!(err.is_config_error(), "must be a ConfigError: {err:?}");
944        assert_eq!(
945            err.message(),
946            "Invalid value SCRAM-SHA-256 for configuration sasl.mechanism: only PLAIN is supported by this client"
947        );
948
949        let err = build("SASL_SSL", "").expect_err("an empty mechanism is invalid with SASL");
950        assert!(err.is_config_error(), "must be a ConfigError: {err:?}");
951        assert!(
952            err.message().contains("mechanism must be non-null and non-empty string"),
953            "got: {}",
954            err.message()
955        );
956
957        build("SASL_PLAINTEXT", "PLAIN").expect("PLAIN is implemented");
958        build("PLAINTEXT", "SCRAM-SHA-256").expect("the mechanism only matters with SASL");
959    }
960
961    use super::*;
962    use crate::common::config::types::Password;
963
964    #[test]
965    fn defaults_and_required_bootstrap() {
966        let mut props = HashMap::new();
967        props.insert("bootstrap.servers".to_string(), "a:9092, b:9092".to_string());
968        let config = AdminClientConfig::new(&props).unwrap();
969        assert_eq!(config.bootstrap_servers(), &["a:9092".to_string(), "b:9092".to_string()]);
970        assert_eq!(config.request_timeout_ms(), 30_000);
971        assert_eq!(config.default_api_timeout_ms(), 60_000);
972        assert_eq!(config.retries(), i32::MAX);
973        assert_eq!(config.security_protocol(), SecurityProtocol::Plaintext);
974    }
975
976    /// `bootstrap.resolve.timeout.ms` (KIP-909): `Type.LONG`, default `0`
977    /// (synchronous resolution), `atLeast(0L)` since KAFKA-20939.
978    #[test]
979    fn bootstrap_resolve_timeout_ms() {
980        assert_eq!(
981            AdminClientConfig::BOOTSTRAP_RESOLVE_TIMEOUT_MS_CONFIG,
982            "bootstrap.resolve.timeout.ms"
983        );
984        let mut props = HashMap::new();
985        props.insert("bootstrap.servers".to_string(), "a:9092".to_string());
986        assert_eq!(AdminClientConfig::new(&props).unwrap().bootstrap_resolve_timeout_ms(), 0);
987
988        props.insert("bootstrap.resolve.timeout.ms".to_string(), "3000".to_string());
989        assert_eq!(AdminClientConfig::new(&props).unwrap().bootstrap_resolve_timeout_ms(), 3000);
990
991        props.insert("bootstrap.resolve.timeout.ms".to_string(), "-1".to_string());
992        assert_eq!(
993            AdminClientConfig::new(&props).unwrap_err().message(),
994            "Invalid value -1 for configuration bootstrap.resolve.timeout.ms: Value must be at least 0"
995        );
996    }
997
998    /// `metadata.cluster.check.enable` (KIP-1242): `Type.BOOLEAN`, default
999    /// `true`.
1000    #[test]
1001    fn metadata_cluster_check_enable() {
1002        assert_eq!(
1003            AdminClientConfig::METADATA_CLUSTER_CHECK_ENABLE_CONFIG,
1004            "metadata.cluster.check.enable"
1005        );
1006        let mut props = HashMap::new();
1007        props.insert("bootstrap.servers".to_string(), "a:9092".to_string());
1008        assert!(AdminClientConfig::new(&props).unwrap().metadata_cluster_check_enable());
1009
1010        props.insert("metadata.cluster.check.enable".to_string(), "false".to_string());
1011        assert!(!AdminClientConfig::new(&props).unwrap().metadata_cluster_check_enable());
1012
1013        // `ConfigDef.parseType(BOOLEAN)` is case-insensitive.
1014        props.insert("metadata.cluster.check.enable".to_string(), " TRUE ".to_string());
1015        assert!(AdminClientConfig::new(&props).unwrap().metadata_cluster_check_enable());
1016
1017        props.insert("metadata.cluster.check.enable".to_string(), "maybe".to_string());
1018        assert_eq!(
1019            AdminClientConfig::new(&props).unwrap_err().message(),
1020            "Invalid value maybe for configuration metadata.cluster.check.enable: Expected value to be either true or false"
1021        );
1022    }
1023
1024    /// Java's `AdminClientConfig` does not require a bootstrap list: an empty
1025    /// map is a valid config, and `KafkaAdminClient.determineBootstrapType`
1026    /// rejects it when the client is created (`kafka_admin_client.rs`'s
1027    /// `test_missing_bootstrap_fails_creation`).
1028    #[test]
1029    fn missing_bootstrap_is_accepted_by_the_config() {
1030        let config = AdminClientConfig::new(&HashMap::new()).unwrap();
1031        assert!(config.bootstrap_servers().is_empty());
1032        assert!(config.bootstrap_controllers().is_empty());
1033    }
1034
1035    /// `bootstrap.controllers` (KIP-919) is defined as Java's
1036    /// `AdminClientConfig.CONFIG` defines it: a `LIST`, empty by default,
1037    /// validated with `ValidList.anyNonDuplicateValues(true, false)`, and
1038    /// accepted in any combination with `bootstrap.servers`, which
1039    /// `KafkaAdminClient.determineBootstrapType` checks when the client is
1040    /// created. The client reads it whichever list it bootstraps from, so it
1041    /// is never reported as unused.
1042    #[test]
1043    fn bootstrap_controllers() {
1044        assert_eq!(AdminClientConfig::BOOTSTRAP_CONTROLLERS_CONFIG, "bootstrap.controllers");
1045        let props = HashMap::from([("bootstrap.controllers".to_string(), "c:9093, d:9093".to_string())]);
1046        let config = AdminClientConfig::new(&props).unwrap();
1047        assert_eq!(config.bootstrap_controllers(), ["c:9093".to_string(), "d:9093".to_string()]);
1048        assert!(config.bootstrap_servers().is_empty());
1049        config.mark_read_keys_used();
1050        assert!(config.unused().is_empty(), "{:?}", config.unused());
1051
1052        let props = HashMap::from([
1053            ("bootstrap.servers".to_string(), "a:9092".to_string()),
1054            ("bootstrap.controllers".to_string(), "c:9093".to_string()),
1055        ]);
1056        let config = AdminClientConfig::new(&props).unwrap();
1057        assert_eq!(config.bootstrap_servers(), ["a:9092".to_string()]);
1058        assert_eq!(config.bootstrap_controllers(), ["c:9093".to_string()]);
1059
1060        for value in ["", " "] {
1061            let props = HashMap::from([("bootstrap.controllers".to_string(), value.to_string())]);
1062            assert!(
1063                AdminClientConfig::new(&props).unwrap().bootstrap_controllers().is_empty(),
1064                "{value:?}"
1065            );
1066        }
1067        // `ConfigDef.parseValue` removes duplicates (with a warning) before validating.
1068        let props = HashMap::from([("bootstrap.controllers".to_string(), "c:1,c:1".to_string())]);
1069        assert_eq!(
1070            AdminClientConfig::new(&props).unwrap().bootstrap_controllers(),
1071            ["c:1".to_string()]
1072        );
1073
1074        let props = HashMap::from([("bootstrap.controllers".to_string(), "c:1,,d:1".to_string())]);
1075        match AdminClientConfig::new(&props) {
1076            Err(Error::Config(e)) => {
1077                assert_eq!(e.message(), "Configuration 'bootstrap.controllers' values must not be empty.")
1078            },
1079            other => panic!("Expected Config, got: {other:?}"),
1080        }
1081    }
1082
1083    /// `enable.metrics.push` is not defined until KIP-714 client telemetry is
1084    /// implemented, so a value set for it is only reported as unused.
1085    #[test]
1086    fn enable_metrics_push_is_unused() {
1087        let mut props = bootstrap_props();
1088        props.insert("enable.metrics.push".to_string(), "true".to_string());
1089        let config = AdminClientConfig::new(&props).unwrap();
1090        config.mark_read_keys_used();
1091        assert_eq!(config.unused(), HashSet::from(["enable.metrics.push".to_string()]));
1092    }
1093
1094    #[test]
1095    fn overrides_and_unknown_keys() {
1096        let mut props = HashMap::new();
1097        props.insert("bootstrap.servers".to_string(), "a:9092".to_string());
1098        props.insert("client.id".to_string(), "admin-1".to_string());
1099        props.insert("request.timeout.ms".to_string(), "5000".to_string());
1100        props.insert("some.unknown.key".to_string(), "ignored".to_string());
1101        let config = AdminClientConfig::new(&props).unwrap();
1102        assert_eq!(config.client_id(), "admin-1");
1103        assert_eq!(config.request_timeout_ms(), 5000);
1104    }
1105
1106    /// `client.dns.lookup` defaults to `use_all_dns_ips` and parses into the
1107    /// typed [`ClientDnsLookup`], as `AdminClientConfig`'s `ConfigDef` defines it.
1108    #[test]
1109    fn test_client_dns_lookup() {
1110        assert_eq!(AdminClientConfig::CLIENT_DNS_LOOKUP_CONFIG, "client.dns.lookup");
1111        let mut props = HashMap::new();
1112        props.insert("bootstrap.servers".to_string(), "a:9092".to_string());
1113        assert_eq!(
1114            AdminClientConfig::new(&props).unwrap().client_dns_lookup(),
1115            ClientDnsLookup::UseAllDnsIps
1116        );
1117
1118        props.insert(
1119            CommonClientConfigs::CLIENT_DNS_LOOKUP_CONFIG.to_string(),
1120            "resolve_canonical_bootstrap_servers_only".to_string(),
1121        );
1122        assert_eq!(
1123            AdminClientConfig::new(&props).unwrap().client_dns_lookup(),
1124            ClientDnsLookup::ResolveCanonicalBootstrapServersOnly
1125        );
1126
1127        props.insert(CommonClientConfigs::CLIENT_DNS_LOOKUP_CONFIG.to_string(), "default".to_string());
1128        assert_eq!(
1129            AdminClientConfig::new(&props).unwrap_err().message(),
1130            "Invalid value default for configuration client.dns.lookup: String must be one of: \
1131             use_all_dns_ips, resolve_canonical_bootstrap_servers_only"
1132        );
1133    }
1134
1135    #[test]
1136    fn invalid_numeric_value_is_error() {
1137        let mut props = HashMap::new();
1138        props.insert("bootstrap.servers".to_string(), "a:9092".to_string());
1139        props.insert("request.timeout.ms".to_string(), "not-a-number".to_string());
1140        let err = AdminClientConfig::new(&props).unwrap_err();
1141        assert!(err.is_config_error());
1142        assert_eq!(
1143            err.message(),
1144            "Invalid value not-a-number for configuration request.timeout.ms: Not a number of type INT"
1145        );
1146    }
1147
1148    fn bootstrap_props() -> HashMap<String, String> {
1149        HashMap::from([("bootstrap.servers".to_string(), "a:9092".to_string())])
1150    }
1151
1152    /// Translated from `AdminClientConfigTest.testDefaultMetadataRecoveryStrategy`.
1153    #[test]
1154    fn test_default_metadata_recovery_strategy() {
1155        let config = AdminClientConfig::new(&HashMap::new()).unwrap();
1156        assert_eq!(
1157            config
1158                .get_string(CommonClientConfigs::METADATA_RECOVERY_STRATEGY_CONFIG)
1159                .unwrap(),
1160            Some("rebootstrap")
1161        );
1162    }
1163
1164    /// Translated from `AdminClientConfigTest.testInvalidMetadataRecoveryStrategy`.
1165    #[test]
1166    fn test_invalid_metadata_recovery_strategy() {
1167        let props = HashMap::from([(
1168            CommonClientConfigs::METADATA_RECOVERY_STRATEGY_CONFIG.to_string(),
1169            "abc".to_string(),
1170        )]);
1171        let err = AdminClientConfig::new(&props).unwrap_err();
1172        assert!(err.is_config_error());
1173        assert!(
1174            err.message().contains(CommonClientConfigs::METADATA_RECOVERY_STRATEGY_CONFIG),
1175            "{}",
1176            err.message()
1177        );
1178    }
1179
1180    /// The client reads the socket buffers and the metadata recovery settings
1181    /// (`ClientUtils.createNetworkClient`), with
1182    /// `AdminClientConfig`'s defaults: 128 KiB / 64 KiB buffers, `rebootstrap` and
1183    /// 300000 ms.
1184    #[test]
1185    fn test_network_client_settings() {
1186        let config = AdminClientConfig::new(&bootstrap_props()).unwrap();
1187        assert_eq!(config.send_buffer_bytes(), 128 * 1024);
1188        assert_eq!(config.receive_buffer_bytes(), 64 * 1024);
1189        assert_eq!(config.metadata_recovery_strategy(), MetadataRecoveryStrategy::Rebootstrap);
1190        assert_eq!(config.metadata_recovery_rebootstrap_trigger_ms(), 300_000);
1191
1192        let mut props = bootstrap_props();
1193        props.insert("send.buffer.bytes".to_string(), "-1".to_string());
1194        props.insert("receive.buffer.bytes".to_string(), "4096".to_string());
1195        props.insert("metadata.recovery.strategy".to_string(), "NONE".to_string());
1196        props.insert("metadata.recovery.rebootstrap.trigger.ms".to_string(), "1000".to_string());
1197        let config = AdminClientConfig::new(&props).unwrap();
1198        assert_eq!(config.send_buffer_bytes(), -1);
1199        assert_eq!(config.receive_buffer_bytes(), 4096);
1200        assert_eq!(config.metadata_recovery_strategy(), MetadataRecoveryStrategy::None);
1201        assert_eq!(config.metadata_recovery_rebootstrap_trigger_ms(), 1000);
1202
1203        // What the client reads is marked used, so `log_unused` leaves it out.
1204        config.mark_read_keys_used();
1205        assert!(config.unused().is_empty(), "{:?}", config.unused());
1206    }
1207
1208    /// The numeric validators of Java's define chain
1209    ///, each value just below its bound.
1210    #[test]
1211    fn test_numeric_validators() {
1212        let cases = [
1213            ("metadata.max.age.ms", "-1", "Value must be at least 0"),
1214            ("send.buffer.bytes", "-2", "Value must be at least -1"),
1215            ("receive.buffer.bytes", "-2", "Value must be at least -1"),
1216            ("reconnect.backoff.ms", "-1", "Value must be at least 0"),
1217            ("reconnect.backoff.max.ms", "-1", "Value must be at least 0"),
1218            ("retry.backoff.ms", "-1", "Value must be at least 0"),
1219            ("retry.backoff.max.ms", "-1", "Value must be at least 0"),
1220            ("bootstrap.resolve.timeout.ms", "-1", "Value must be at least 0"),
1221            ("request.timeout.ms", "-1", "Value must be at least 0"),
1222            ("retries", "-1", "Value must be at least 0"),
1223            ("default.api.timeout.ms", "-1", "Value must be at least 0"),
1224            ("metrics.sample.window.ms", "-1", "Value must be at least 0"),
1225            ("metrics.num.samples", "0", "Value must be at least 1"),
1226            ("metadata.recovery.rebootstrap.trigger.ms", "-1", "Value must be at least 0"),
1227        ];
1228        for (key, value, reason) in cases {
1229            let mut props = bootstrap_props();
1230            props.insert(key.to_string(), value.to_string());
1231            let err = AdminClientConfig::new(&props).unwrap_err();
1232            assert!(err.is_config_error(), "{key}");
1233            assert_eq!(
1234                err.message(),
1235                format!("Invalid value {value} for configuration {key}: {reason}"),
1236            );
1237        }
1238        // The bounds themselves are accepted, and keys without a validator
1239        // take any value, as in Java.
1240        let mut props = bootstrap_props();
1241        props.insert("send.buffer.bytes".to_string(), "-1".to_string());
1242        props.insert("metrics.num.samples".to_string(), "1".to_string());
1243        props.insert("socket.connection.setup.timeout.ms".to_string(), "-5".to_string());
1244        props.insert("connections.max.idle.ms".to_string(), "-5".to_string());
1245        let config = AdminClientConfig::new(&props).unwrap();
1246        assert_eq!(config.socket_connection_setup_timeout_ms(), -5);
1247        assert_eq!(config.connections_max_idle_ms(), -5);
1248    }
1249
1250    #[test]
1251    fn test_metrics_recording_level_and_recovery_strategy_values() {
1252        let mut props = bootstrap_props();
1253        props.insert("metrics.recording.level".to_string(), "info".to_string());
1254        assert_eq!(
1255            AdminClientConfig::new(&props).unwrap_err().message(),
1256            "Invalid value info for configuration metrics.recording.level: String must be one of: INFO, DEBUG, TRACE"
1257        );
1258        let mut props = bootstrap_props();
1259        props.insert("metadata.recovery.strategy".to_string(), "none".to_string());
1260        let config = AdminClientConfig::new(&props).unwrap();
1261        assert_eq!(config.get_string("metadata.recovery.strategy").unwrap(), Some("none"));
1262    }
1263
1264    /// `AbstractConfig`'s typed getters, on the admin client's keys.
1265    #[test]
1266    fn test_typed_getters() {
1267        let mut props = bootstrap_props();
1268        props.insert("client.id".to_string(), " admin-1 ".to_string());
1269        props.insert("ssl.keystore.key".to_string(), "secret".to_string());
1270        let config = AdminClientConfig::new(&props).unwrap();
1271        assert_eq!(config.get_int("request.timeout.ms").unwrap(), Some(30_000));
1272        assert_eq!(config.get_long("metadata.max.age.ms").unwrap(), Some(300_000));
1273        assert_eq!(config.get_boolean("metadata.cluster.check.enable").unwrap(), Some(true));
1274        assert_eq!(
1275            config.get_boolean("enable.metrics.push").unwrap_err().message(),
1276            "Unknown configuration 'enable.metrics.push'"
1277        );
1278        assert_eq!(config.get_string("client.id").unwrap(), Some("admin-1"));
1279        assert_eq!(config.get_list("bootstrap.servers").unwrap(), Some(&["a:9092".to_string()][..]));
1280        assert_eq!(config.get_list("bootstrap.controllers").unwrap(), Some(&[][..]));
1281        assert_eq!(config.get_string("sasl.jaas.config").unwrap(), None);
1282
1283        let err = config.get_int("no.such.key").unwrap_err();
1284        assert!(err.is_config_error());
1285        assert_eq!(err.message(), "Unknown configuration 'no.such.key'");
1286        let err = config.get_long("request.timeout.ms").unwrap_err();
1287        assert!(err.is_local_illegal_argument_error());
1288        assert_eq!(err.message(), "Configuration 'request.timeout.ms' is of type INT, not LONG");
1289        assert!(config.get_short("request.timeout.ms").is_err());
1290        assert!(config.get_double("request.timeout.ms").is_err());
1291        assert!(config.get_string("ssl.keystore.key").is_err());
1292    }
1293
1294    #[test]
1295    fn test_config_names() {
1296        let names = AdminClientConfig::config_names();
1297        for key in [
1298            "bootstrap.servers",
1299            "bootstrap.controllers",
1300            "client.id",
1301            "metadata.recovery.strategy",
1302            "metadata.cluster.check.enable",
1303            "ssl.truststore.type",
1304            "sasl.mechanism",
1305            "ssl.cipher.suites",
1306        ] {
1307            assert!(names.contains(key), "{key}");
1308        }
1309        for key in [
1310            "metric.reporters",
1311            "security.providers",
1312            "config.providers",
1313            "enable.metrics.push",
1314            "ssl.keystore.password",
1315            "ssl.key.password",
1316            "ssl.truststore.password",
1317        ] {
1318            assert!(!names.contains(key), "{key}");
1319        }
1320    }
1321
1322    /// A key the user reads is used; what the client reads it marks used
1323    /// when it is built, and an undefined key is never used.
1324    #[test]
1325    fn test_unused_and_ignore() {
1326        let mut props = bootstrap_props();
1327        props.insert("request.timeout.ms".to_string(), "5000".to_string());
1328        props.insert("metrics.num.samples".to_string(), "3".to_string());
1329        props.insert("some.unknown.key".to_string(), "x".to_string());
1330        props.insert("ssl.keystore.location".to_string(), "/k".to_string());
1331        let config = AdminClientConfig::new(&props).unwrap();
1332        let all: HashSet<String> = props.keys().cloned().collect();
1333        assert_eq!(config.unused(), all);
1334
1335        config.get_int("request.timeout.ms").unwrap();
1336        config.ignore("some.unknown.key");
1337        assert_eq!(
1338            config.unused(),
1339            HashSet::from([
1340                "bootstrap.servers".to_string(),
1341                "metrics.num.samples".to_string(),
1342                "ssl.keystore.location".to_string(),
1343            ])
1344        );
1345
1346        // The client reads `bootstrap.servers`; the `ssl.*` keys only for an
1347        // SSL protocol, and `metrics.num.samples` not at all.
1348        config.mark_read_keys_used();
1349        assert_eq!(
1350            config.unused(),
1351            HashSet::from(["metrics.num.samples".to_string(), "ssl.keystore.location".to_string()])
1352        );
1353        // A copy for one more client has its own used set, as each client
1354        // built from one C handle does.
1355        assert_eq!(config.copy_for_client().unwrap().unused(), all);
1356
1357        props.insert("security.protocol".to_string(), "SSL".to_string());
1358        props.insert("ssl.keystore.password".to_string(), "p".to_string());
1359        props.insert("ssl.keystore.type".to_string(), "JKS".to_string());
1360        let ssl = AdminClientConfig::new(&props).unwrap();
1361        ssl.mark_read_keys_used();
1362        // `ssl.keystore.password` is not defined (`SslConfigs` module docs), so
1363        // it stays unused under TLS too.
1364        assert_eq!(
1365            ssl.unused(),
1366            HashSet::from([
1367                "metrics.num.samples".to_string(),
1368                "some.unknown.key".to_string(),
1369                "ssl.keystore.password".to_string(),
1370            ])
1371        );
1372    }
1373
1374    /// `new` logs each configuration warning once (the parse's duplicate
1375    /// values and the post-processing's); a copy for one more client logs none of them,
1376    /// as Java's client logs nothing about the config it is given, but makes
1377    /// the same reads, so it equals `new`'s and its used set is `new`'s.
1378    #[test]
1379    fn test_copy_for_client_logs_no_configuration_warning() {
1380        use log::Level;
1381
1382        use crate::test_log_capture::capture_logs;
1383
1384        let props: HashMap<String, String> = [
1385            (AdminClientConfig::BOOTSTRAP_SERVERS_CONFIG, "localhost:9092,localhost:9092"),
1386            (AdminClientConfig::RETRY_BACKOFF_MS_CONFIG, "2000"),
1387            (AdminClientConfig::RETRY_BACKOFF_MAX_MS_CONFIG, "1000"),
1388            (AdminClientConfig::RECONNECT_BACKOFF_MS_CONFIG, "100"),
1389            (AdminClientConfig::SOCKET_CONNECTION_SETUP_TIMEOUT_MS_CONFIG, "40000"),
1390            (CommonClientConfigs::SOCKET_CONNECTION_SETUP_TIMEOUT_MAX_MS_CONFIG, "30000"),
1391            ("some.unknown.key", "x"),
1392        ]
1393        .into_iter()
1394        .map(|(key, value)| (key.to_string(), value.to_string()))
1395        .collect();
1396        let (config, new_lines) = capture_logs(|| AdminClientConfig::new(&props).unwrap());
1397        let warnings = |lines: &[(Level, String)]| {
1398            lines
1399                .iter()
1400                .filter(|(level, _)| *level == Level::Warn)
1401                .map(|(_, line)| line.split(' ').take(3).collect::<Vec<_>>().join(" "))
1402                .collect::<Vec<_>>()
1403        };
1404        assert_eq!(
1405            warnings(&new_lines),
1406            [
1407                "Configuration key \"bootstrap.servers\"",
1408                "Configuration 'retry.backoff.ms' with",
1409                "Configuration 'socket.connection.setup.timeout.ms' with",
1410                "Disabling exponential reconnect",
1411            ],
1412            "{new_lines:?}"
1413        );
1414        let (copy, copy_lines) = capture_logs(|| config.copy_for_client().unwrap());
1415        assert!(copy_lines.is_empty(), "{copy_lines:?}");
1416        assert_eq!(copy, config);
1417        assert_eq!(copy.bootstrap_servers(), ["localhost:9092".to_string()]);
1418        let new_unused = config.unused();
1419        assert_eq!(copy.unused(), new_unused);
1420        copy.mark_read_keys_used();
1421        assert_eq!(copy.unused(), HashSet::from(["some.unknown.key".to_string()]));
1422        // The copy's used set is its own.
1423        assert_eq!(config.unused(), new_unused);
1424    }
1425
1426    /// Java's `AbstractConfig.equals` / `hashCode`: equal originals.
1427    #[test]
1428    fn test_equals_and_hash() {
1429        use std::collections::hash_map::DefaultHasher;
1430        let hash = |c: &AdminClientConfig| {
1431            let mut h = DefaultHasher::new();
1432            c.hash(&mut h);
1433            h.finish()
1434        };
1435        let a = AdminClientConfig::new(&bootstrap_props()).unwrap();
1436        let b = AdminClientConfig::new(&bootstrap_props()).unwrap();
1437        b.get_int("retries").unwrap();
1438        assert_eq!(a, b);
1439        assert_eq!(hash(&a), hash(&b));
1440        let mut props = bootstrap_props();
1441        props.insert("retries".to_string(), "3".to_string());
1442        let c = AdminClientConfig::new(&props).unwrap();
1443        assert_ne!(a, c);
1444    }
1445
1446    /// Translated from `ProducerConfigTest.testInvalidSecurityProtocol`, adapted
1447    /// to `AdminClientConfig`.
1448    #[test]
1449    fn test_invalid_security_protocol() {
1450        let mut props = HashMap::new();
1451        props.insert("bootstrap.servers".to_string(), "localhost:9092".to_string());
1452        props.insert("security.protocol".to_string(), "abc".to_string());
1453        let err = AdminClientConfig::new(&props).unwrap_err();
1454        let msg = format!("{}", err);
1455        assert!(
1456            msg.contains("security.protocol"),
1457            "Error message should contain config key, got: {}",
1458            msg
1459        );
1460    }
1461
1462    /// Translated from `ProducerConfigTest.testCaseInsensitiveSecurityProtocol`,
1463    /// adapted to `AdminClientConfig`.
1464    #[test]
1465    fn test_case_insensitive_security_protocol() {
1466        let mut props = HashMap::new();
1467        props.insert("bootstrap.servers".to_string(), "localhost:9092".to_string());
1468        props.insert("security.protocol".to_string(), "sasl_ssl".to_string());
1469        // Only `PLAIN` is accepted under a SASL protocol (`post_validate_supported_sasl_mechanism`).
1470        props.insert("sasl.mechanism".to_string(), "PLAIN".to_string());
1471        let config = AdminClientConfig::new(&props).unwrap();
1472        assert_eq!(config.security_protocol(), SecurityProtocol::SaslSsl);
1473    }
1474
1475    #[test]
1476    fn test_sasl_config_from_properties() {
1477        let mut props = HashMap::new();
1478        props.insert("bootstrap.servers".to_string(), "localhost:9092".to_string());
1479        props.insert("sasl.mechanism".to_string(), "PLAIN".to_string());
1480        props.insert(
1481            "sasl.jaas.config".to_string(),
1482            "org.apache.kafka.common.security.plain.PlainLoginModule required username=\"alice\" password=\"secret\";"
1483                .to_string(),
1484        );
1485        let config = AdminClientConfig::new(&props).unwrap();
1486        assert_eq!(config.sasl_config().mechanism, "PLAIN");
1487        assert_eq!(config.sasl_config().resolve_username().as_deref(), Some("alice"));
1488        assert_eq!(config.sasl_config().resolve_password().as_deref(), Some("secret"));
1489    }
1490
1491    /// Rust-only (`CommonClientConfigs::post_validate_supported_sasl_mechanism`):
1492    /// a SASL `security.protocol` needs `sasl.mechanism=PLAIN`; any other
1493    /// mechanism, the `GSSAPI` default included, fails the build with
1494    /// `LocalUnsupportedOperationError`, while an empty one keeps Java's
1495    /// `ConfigError`. Under `PLAINTEXT` the mechanism is inert, as in Java.
1496    #[test]
1497    fn test_unsupported_sasl_mechanism_rejected() {
1498        let jaas = "org.apache.kafka.common.security.plain.PlainLoginModule required username=\"u\" password=\"p\";";
1499        let build = |extra: &[(&str, &str)]| {
1500            let mut props = HashMap::from([("bootstrap.servers".to_string(), "localhost:9092".to_string())]);
1501            for (k, v) in extra {
1502                props.insert((*k).to_string(), (*v).to_string());
1503            }
1504            AdminClientConfig::new(&props)
1505        };
1506
1507        let err = build(&[
1508            ("security.protocol", "SASL_PLAINTEXT"),
1509            ("sasl.mechanism", "SCRAM-SHA-256"),
1510            ("sasl.jaas.config", jaas),
1511        ])
1512        .unwrap_err();
1513        assert!(err.is_config_error(), "{err:?}");
1514        assert_eq!(
1515            err.to_string(),
1516            "ConfigError: Invalid value SCRAM-SHA-256 for configuration sasl.mechanism: only PLAIN is supported by \
1517             this client"
1518        );
1519
1520        // The default mechanism is Java's `GSSAPI`.
1521        let err = build(&[("security.protocol", "SASL_SSL")]).unwrap_err();
1522        assert!(err.is_config_error(), "{err:?}");
1523        assert_eq!(
1524            err.to_string(),
1525            "ConfigError: Invalid value GSSAPI for configuration sasl.mechanism: only PLAIN is supported by this client"
1526        );
1527
1528        // Case-sensitive, as Java's mechanism names are.
1529        let err = build(&[("security.protocol", "SASL_PLAINTEXT"), ("sasl.mechanism", "plain")]).unwrap_err();
1530        assert!(err.is_config_error(), "{err:?}");
1531
1532        build(&[("security.protocol", "PLAINTEXT")]).unwrap();
1533        build(&[
1534            ("security.protocol", "SASL_PLAINTEXT"),
1535            ("sasl.mechanism", "PLAIN"),
1536            ("sasl.jaas.config", jaas),
1537        ])
1538        .unwrap();
1539
1540        // An empty mechanism fails Java's check first.
1541        let err = build(&[("security.protocol", "SASL_PLAINTEXT"), ("sasl.mechanism", "")]).unwrap_err();
1542        assert!(err.is_config_error(), "{err:?}");
1543        assert_eq!(
1544            err.to_string(),
1545            "ConfigError: Invalid value null for configuration sasl.mechanism: When the security.protocol \
1546             configuration enables SASL, mechanism must be non-null and non-empty string."
1547        );
1548    }
1549
1550    #[test]
1551    fn test_ssl_config_from_properties() {
1552        let mut props = HashMap::new();
1553        props.insert("bootstrap.servers".to_string(), "localhost:9092".to_string());
1554        props.insert("ssl.truststore.location".to_string(), "/path/to/truststore.pem".to_string());
1555        props.insert("ssl.keystore.location".to_string(), "/path/to/keystore.pem".to_string());
1556        props.insert("ssl.endpoint.identification.algorithm".to_string(), String::new());
1557        let config = AdminClientConfig::new(&props).unwrap();
1558        assert_eq!(
1559            config.ssl_config().truststore_location.as_deref(),
1560            Some("/path/to/truststore.pem")
1561        );
1562        assert_eq!(config.ssl_config().keystore_location.as_deref(), Some("/path/to/keystore.pem"));
1563        assert_eq!(config.ssl_config().endpoint_identification_algorithm, "");
1564    }
1565
1566    /// `bootstrap.servers` is a `Type.LIST`: `ConfigDef.parseType` trims the
1567    /// value and splits it on `\\s*,\\s*`, so whitespace around the commas
1568    /// and at the ends never reaches `ClientUtils.parseAndValidateAddresses`
1569    /// (which does not trim, and rejects it).
1570    #[test]
1571    fn test_bootstrap_servers_list_parsing() {
1572        for value in [
1573            "localhost:1,localhost:2",
1574            "localhost:1, localhost:2",
1575            " localhost:1 ,localhost:2 ",
1576        ] {
1577            let props = HashMap::from([("bootstrap.servers".to_string(), value.to_string())]);
1578            let config = AdminClientConfig::new(&props).unwrap();
1579            assert_eq!(
1580                config.bootstrap_servers(),
1581                ["localhost:1".to_string(), "localhost:2".to_string()],
1582                "{value:?}"
1583            );
1584            let addresses = crate::ClientUtils::parse_and_validate_addresses(
1585                config.bootstrap_servers(),
1586                config.client_dns_lookup(),
1587            )
1588            .unwrap();
1589            assert_eq!(addresses.len(), 2, "{value:?}");
1590        }
1591    }
1592
1593    /// `bootstrap.servers` is validated with Java's
1594    /// `ValidList.anyNonDuplicateValues(true, false)`: an empty
1595    /// element is rejected with `ConfigDef`'s exact message and duplicates are removed
1596    /// (single-message `ConfigException`, no `Invalid value` prefix).
1597    #[test]
1598    fn test_bootstrap_servers_valid_list() {
1599        let error_message = |value: &str| {
1600            let props = HashMap::from([("bootstrap.servers".to_string(), value.to_string())]);
1601            match AdminClientConfig::new(&props) {
1602                Err(Error::Config(e)) => e.message().to_string(),
1603                other => panic!("expected a ConfigError for {value:?}, got {other:?}"),
1604            }
1605        };
1606        for value in ["localhost:9092,,localhost:9093", "a:1, ,b:1", "a:1,"] {
1607            assert_eq!(
1608                error_message(value),
1609                "Configuration 'bootstrap.servers' values must not be empty.",
1610                "{value:?}"
1611            );
1612        }
1613        // `ConfigDef.parseValue` removes duplicates (with a warning) before validating.
1614        let props = HashMap::from([("bootstrap.servers".to_string(), "a:1,a:1".to_string())]);
1615        assert_eq!(AdminClientConfig::new(&props).unwrap().bootstrap_servers(), ["a:1".to_string()]);
1616        assert_eq!(
1617            error_message(",,"),
1618            "Configuration 'bootstrap.servers' values must not be empty."
1619        );
1620        // Admin allows an empty list (`isEmptyAllowed = true`), so the
1621        // ValidList message never appears and the configuration builds;
1622        // `KafkaAdminClient.determineBootstrapType` rejects the missing
1623        // bootstrap list when the client is created.
1624        for value in ["", "  "] {
1625            let props = HashMap::from([("bootstrap.servers".to_string(), value.to_string())]);
1626            assert!(
1627                AdminClientConfig::new(&props).unwrap().bootstrap_servers().is_empty(),
1628                "{value:?}"
1629            );
1630        }
1631        let props = HashMap::from([("bootstrap.servers".to_string(), "a:1,b:1".to_string())]);
1632        assert_eq!(
1633            AdminClientConfig::new(&props).unwrap().bootstrap_servers(),
1634            ["a:1".to_string(), "b:1".to_string()]
1635        );
1636    }
1637
1638    /// `{:?}` of a config built from every `Type.PASSWORD` key the client
1639    /// parses (`sasl.jaas.config` and the three SSL keys) renders none of their
1640    /// values. The derived `Debug` is safe because the embedded `SaslConfigs`
1641    /// and `SslConfigs` hold those values as `Password`s. The three SSL
1642    /// password keys this client does not define render as key names only.
1643    #[test]
1644    fn test_debug_redacts_password_configs() {
1645        let secrets = [
1646            (
1647                "sasl.jaas.config",
1648                "org.apache.kafka.common.security.plain.PlainLoginModule required \
1649                 username=\"jaas-user\" password=\"jaas-S3cr3t\";",
1650            ),
1651            ("ssl.truststore.certificates", "TRUSTSTORE-CERTIFICATES-PEM"),
1652            ("ssl.keystore.key", "KEYSTORE-KEY-PEM"),
1653            ("ssl.keystore.certificate.chain", "KEYSTORE-CERTIFICATE-CHAIN-PEM"),
1654        ];
1655        // Not defined (`SslConfigs` module docs), so held only in the originals.
1656        let undefined = [
1657            ("ssl.truststore.password", "truststore-S3cr3t"),
1658            ("ssl.keystore.password", "keystore-S3cr3t"),
1659            ("ssl.key.password", "key-S3cr3t"),
1660        ];
1661        let mut props: HashMap<String, String> = secrets
1662            .iter()
1663            .chain(&undefined)
1664            .map(|(key, value)| (key.to_string(), value.to_string()))
1665            .collect();
1666        props.insert("bootstrap.servers".to_string(), "visible-host:9092".to_string());
1667        props.insert("client.id".to_string(), "visible-admin".to_string());
1668        props.insert("sasl.mechanism".to_string(), "PLAIN".to_string());
1669        props.insert("ssl.truststore.location".to_string(), "/visible/truststore.pem".to_string());
1670        let config = AdminClientConfig::new(&props).unwrap();
1671
1672        // The secrets did reach the config; they are only hidden from `Debug`.
1673        assert_eq!(config.sasl_config().resolve_password().as_deref(), Some("jaas-S3cr3t"));
1674        assert_eq!(
1675            config.ssl_config().keystore_key.as_ref().map(Password::value),
1676            Some("KEYSTORE-KEY-PEM")
1677        );
1678
1679        for rendered in [format!("{config:?}"), format!("{config:#?}")] {
1680            for (key, value) in secrets.iter().chain(&undefined) {
1681                assert!(!rendered.contains(value), "{key} leaked: {rendered}");
1682            }
1683            for fragment in ["jaas-S3cr3t", "jaas-user", "PlainLoginModule", "S3cr3t", "-PEM"] {
1684                assert!(!rendered.contains(fragment), "{fragment:?} leaked: {rendered}");
1685            }
1686            assert_eq!(rendered.matches(Password::HIDDEN).count(), secrets.len(), "{rendered}");
1687            for visible in [
1688                "visible-host:9092",
1689                "visible-admin",
1690                "\"PLAIN\"",
1691                "/visible/truststore.pem",
1692            ] {
1693                assert!(rendered.contains(visible), "{visible} missing: {rendered}");
1694            }
1695        }
1696    }
1697}