1use 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
53static 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 .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 .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 .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 });
233
234#[doc(alias = "org.apache.kafka.clients.admin.AdminClientConfig")]
237pub struct AdminClientConfig {
238 config: AbstractConfig,
240 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_protocol: SecurityProtocol,
269
270 sasl_config: SaslConfigs,
272
273 ssl_config: SslConfigs,
275}
276
277impl fmt::Debug for AdminClientConfig {
278 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
283 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 fn eq(&self, other: &Self) -> bool {
351 self.config == other.config
352 }
353}
354
355impl Eq for AdminClientConfig {}
356
357impl Hash for AdminClientConfig {
358 fn hash<H: Hasher>(&self, state: &mut H) {
360 self.config.hash(state);
361 }
362}
363
364impl AdminClientConfig {
365 pub const BOOTSTRAP_SERVERS_CONFIG: &'static str = "bootstrap.servers";
367 pub const BOOTSTRAP_CONTROLLERS_CONFIG: &'static str = "bootstrap.controllers";
376 pub const CLIENT_DNS_LOOKUP_CONFIG: &'static str = CommonClientConfigs::CLIENT_DNS_LOOKUP_CONFIG;
378 pub const CLIENT_ID_CONFIG: &'static str = "client.id";
380 pub const REQUEST_TIMEOUT_MS_CONFIG: &'static str = "request.timeout.ms";
382 pub const DEFAULT_API_TIMEOUT_MS_CONFIG: &'static str = "default.api.timeout.ms";
384 pub const RETRIES_CONFIG: &'static str = "retries";
386 pub const RETRY_BACKOFF_MS_CONFIG: &'static str = "retry.backoff.ms";
388 pub const RETRY_BACKOFF_MAX_MS_CONFIG: &'static str = "retry.backoff.max.ms";
390 pub const BOOTSTRAP_RESOLVE_TIMEOUT_MS_CONFIG: &'static str =
394 CommonClientConfigs::BOOTSTRAP_RESOLVE_TIMEOUT_MS_CONFIG;
395 pub const RECONNECT_BACKOFF_MS_CONFIG: &'static str = "reconnect.backoff.ms";
397 pub const RECONNECT_BACKOFF_MAX_MS_CONFIG: &'static str = "reconnect.backoff.max.ms";
399 pub const CONNECTIONS_MAX_IDLE_MS_CONFIG: &'static str = "connections.max.idle.ms";
401 pub const METADATA_MAX_AGE_CONFIG: &'static str = "metadata.max.age.ms";
403 pub const SOCKET_CONNECTION_SETUP_TIMEOUT_MS_CONFIG: &'static str = "socket.connection.setup.timeout.ms";
405 pub const METADATA_CLUSTER_CHECK_ENABLE_CONFIG: &'static str =
414 CommonClientConfigs::METADATA_CLUSTER_CHECK_ENABLE_CONFIG;
415 pub const SECURITY_PROTOCOL_CONFIG: &'static str = CommonClientConfigs::SECURITY_PROTOCOL_CONFIG;
417
418 #[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 #[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 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 |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 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 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 let security_protocol = SecurityProtocol::for_name(protocol)
524 .ok_or_else(|| Error::local_illegal_state(format!("Unknown security protocol {protocol}")))?;
525
526 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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[doc(alias = "org.apache.kafka.common.config.AbstractConfig#unused")]
730 pub fn unused(&self) -> HashSet<String> {
731 self.config.unused()
732 }
733
734 #[doc(alias = "org.apache.kafka.common.config.AbstractConfig#ignore")]
740 pub fn ignore(&self, key: &str) {
741 self.config.ignore(key);
742 }
743
744 #[doc(alias = "org.apache.kafka.common.config.AbstractConfig#logUnused")]
748 pub fn log_unused(&self) {
749 self.config.log_unused();
750 }
751
752 #[doc(alias = "org.apache.kafka.clients.admin.AdminClientConfig#configNames")]
758 pub fn config_names() -> HashSet<String> {
759 CONFIG.names()
760 }
761
762 pub(crate) fn mark_read_keys_used(&self) {
765 for key in &self.read_keys {
766 self.config.ignore(key);
767 }
768 }
769
770 pub(crate) fn log_values(&self) {
773 self.config.log_all("AdminClientConfig");
774 }
775
776 pub(crate) fn bootstrap_servers(&self) -> &[String] {
778 &self.bootstrap_servers
779 }
780
781 pub(crate) fn bootstrap_controllers(&self) -> &[String] {
783 &self.bootstrap_controllers
784 }
785
786 pub(crate) fn client_dns_lookup(&self) -> ClientDnsLookup {
788 self.client_dns_lookup
789 }
790
791 pub(crate) fn client_id(&self) -> &str {
793 &self.client_id
794 }
795
796 pub(crate) fn request_timeout_ms(&self) -> i32 {
798 self.request_timeout_ms
799 }
800
801 pub(crate) fn default_api_timeout_ms(&self) -> i32 {
803 self.default_api_timeout_ms
804 }
805
806 pub(crate) fn user_configured(&self, key: &str) -> bool {
812 self.config.originals_map().contains_key(key)
813 }
814
815 pub(crate) fn retries(&self) -> i32 {
817 self.retries
818 }
819
820 pub(crate) fn retry_backoff_ms(&self) -> i64 {
822 self.retry_backoff_ms
823 }
824
825 pub(crate) fn retry_backoff_max_ms(&self) -> i64 {
827 self.retry_backoff_max_ms
828 }
829
830 pub(crate) fn bootstrap_resolve_timeout_ms(&self) -> i64 {
841 self.bootstrap_resolve_timeout_ms
842 }
843
844 pub(crate) fn reconnect_backoff_ms(&self) -> i64 {
846 self.reconnect_backoff_ms
847 }
848
849 pub(crate) fn reconnect_backoff_max_ms(&self) -> i64 {
851 self.reconnect_backoff_max_ms
852 }
853
854 pub(crate) fn connections_max_idle_ms(&self) -> i64 {
856 self.connections_max_idle_ms
857 }
858
859 pub(crate) fn send_buffer_bytes(&self) -> i32 {
861 self.send_buffer_bytes
862 }
863
864 pub(crate) fn receive_buffer_bytes(&self) -> i32 {
867 self.receive_buffer_bytes
868 }
869
870 pub(crate) fn metadata_max_age_ms(&self) -> i64 {
872 self.metadata_max_age_ms
873 }
874
875 pub(crate) fn socket_connection_setup_timeout_ms(&self) -> i64 {
877 self.socket_connection_setup_timeout_ms
878 }
879
880 pub(crate) fn socket_connection_setup_timeout_max_ms(&self) -> i64 {
882 self.socket_connection_setup_timeout_max_ms
883 }
884
885 pub(crate) fn metadata_recovery_strategy(&self) -> MetadataRecoveryStrategy {
889 self.metadata_recovery_strategy
890 }
891
892 pub(crate) fn metadata_recovery_rebootstrap_trigger_ms(&self) -> i64 {
895 self.metadata_recovery_rebootstrap_trigger_ms
896 }
897
898 pub(crate) fn metadata_cluster_check_enable(&self) -> bool {
908 self.metadata_cluster_check_enable
909 }
910
911 pub(crate) fn security_protocol(&self) -> SecurityProtocol {
913 self.security_protocol
914 }
915
916 pub(crate) fn sasl_config(&self) -> &SaslConfigs {
918 &self.sasl_config
919 }
920
921 pub(crate) fn ssl_config(&self) -> &SslConfigs {
923 &self.ssl_config
924 }
925}
926
927#[cfg(test)]
928mod tests {
929 #[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 #[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 #[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 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 #[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 #[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 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 #[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 #[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 #[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 #[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 #[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 config.mark_read_keys_used();
1205 assert!(config.unused().is_empty(), "{:?}", config.unused());
1206 }
1207
1208 #[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 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 #[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 #[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 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 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 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 #[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 assert_eq!(config.unused(), new_unused);
1424 }
1425
1426 #[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 #[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 #[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 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 #[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 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 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 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 #[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 #[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 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 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 #[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 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 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}