Skip to main content

confluent_kafka/admin/
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//! A configuration object containing the configuration entries for a resource.
16
17use std::collections::HashMap;
18
19use crate::admin::ConfigEntry;
20
21/// A configuration object containing the configuration entries for a resource.
22///
23/// # Translation notes
24///
25/// `Debug` redacts sensitive values.
26#[derive(Clone, Debug, PartialEq, Eq)]
27#[doc(alias = "org.apache.kafka.clients.admin.Config")]
28pub struct Config {
29    entries: HashMap<String, ConfigEntry>,
30}
31
32impl Config {
33    /// Create a configuration instance with the provided entries.
34    ///
35    /// # Arguments
36    ///
37    /// - `entries` - the configuration entries.
38    #[doc(alias = "org.apache.kafka.clients.admin.Config#Config")]
39    pub fn new(entries: impl IntoIterator<Item = ConfigEntry>) -> Self {
40        let mut map = HashMap::new();
41        for entry in entries {
42            map.insert(entry.name().to_string(), entry);
43        }
44        Self { entries: map }
45    }
46
47    /// Returns the configuration entries for a resource.
48    #[doc(alias = "org.apache.kafka.clients.admin.Config#entries")]
49    pub fn entries(&self) -> impl Iterator<Item = &ConfigEntry> {
50        self.entries.values()
51    }
52
53    /// Returns the configuration entry with the provided name or `None` if there
54    /// isn't one.
55    ///
56    /// # Arguments
57    ///
58    /// - `name` - the name of the configuration entry.
59    #[doc(alias = "org.apache.kafka.clients.admin.Config#get")]
60    pub fn get(&self, name: &str) -> Option<&ConfigEntry> {
61        self.entries.get(name)
62    }
63}
64
65impl std::hash::Hash for Config {
66    // Java's `Config.hashCode()` is `entries.hashCode()`, the order-independent
67    // sum of a `HashMap`'s entry hashes.
68    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
69        crate::common::utils::Utils::hash_unordered(&self.entries, state);
70    }
71}
72
73impl std::fmt::Display for Config {
74    /// Renders each entry through `ConfigEntry`'s redacting `Display`, as Java's
75    /// `org.apache.kafka.clients.admin.Config#toString` does.
76    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
77        let entries: Vec<String> = self.entries.values().map(|e| e.to_string()).collect();
78        write!(f, "Config(entries=[{}])", entries.join(", "))
79    }
80}
81
82#[cfg(test)]
83mod tests {
84    use super::*;
85    use crate::admin::ConfigEntryOptionsBuilder;
86    use crate::admin::config_entry::ConfigType;
87
88    #[test]
89    fn new_indexes_entries_by_name() {
90        let config = Config::new([
91            ConfigEntry::new("a".to_string(), Some("1".to_string())),
92            ConfigEntry::new("b".to_string(), Some("2".to_string())),
93        ]);
94        assert_eq!(config.get("a").unwrap().value(), Some("1"));
95        assert_eq!(config.get("b").unwrap().value(), Some("2"));
96        assert!(config.get("missing").is_none());
97        assert_eq!(config.entries().count(), 2);
98    }
99
100    #[test]
101    fn equality_is_order_independent() {
102        let a = Config::new([
103            ConfigEntry::new("a".to_string(), Some("1".to_string())),
104            ConfigEntry::new("b".to_string(), Some("2".to_string())),
105        ]);
106        let b = Config::new([
107            ConfigEntry::new("b".to_string(), Some("2".to_string())),
108            ConfigEntry::new("a".to_string(), Some("1".to_string())),
109        ]);
110        assert_eq!(a, b);
111    }
112
113    /// A distinctive secret for the redaction tests.
114    const SECRET: &str = "ssl-truststore-S3cr3t-91c4";
115
116    /// A config holding a sensitive entry with [`SECRET`] and a non-sensitive one.
117    fn config_with_secret() -> Config {
118        Config::new([
119            ConfigEntry::with_options(
120                ConfigEntryOptionsBuilder::new()
121                    .set_name("ssl.truststore.password".to_string())
122                    .set_value(Some(SECRET.to_string()))
123                    .set_is_sensitive(true)
124                    .set_config_type(Some(ConfigType::Password))
125                    .build()
126                    .unwrap(),
127            ),
128            ConfigEntry::new("retention.ms".to_string(), Some("604800000".to_string())),
129        ])
130    }
131
132    /// Translated from `ConfigTest.shouldImplementToStringProperly`: the
133    /// rendering contains each entry's own rendering. Java's fixture holds two plain entries
134    /// (`a=b`, `c=d`); this
135    /// one makes the first entry sensitive, so the test also shows that
136    /// `Display` renders it through the entry's redacting `Display`, as Java's
137    /// `toString()` does, and the secret does not appear.
138    #[test]
139    fn display_redacts_sensitive_values() {
140        let config = config_with_secret();
141        let sensitive = config.get("ssl.truststore.password").unwrap();
142        assert_eq!(sensitive.value(), Some(SECRET));
143        let rendered = config.to_string();
144        // Java's two assertions: the rendering contains each entry's `toString()`.
145        assert!(rendered.contains(&sensitive.to_string()), "{rendered}");
146        assert!(
147            rendered.contains(&config.get("retention.ms").unwrap().to_string()),
148            "{rendered}"
149        );
150        assert!(rendered.starts_with("Config(entries=["), "{rendered}");
151        assert!(rendered.contains("name=ssl.truststore.password, value=Redacted"), "{rendered}");
152        assert!(rendered.contains("name=retention.ms, value=604800000"), "{rendered}");
153        assert!(!rendered.contains(SECRET), "secret leaked: {rendered}");
154    }
155
156    /// The `Debug` counterpart of `ConfigTest.shouldImplementToStringProperly`:
157    /// the derived `Debug` renders each entry through
158    /// its `Debug`, which is the entry's redacting `Display`, so it contains
159    /// each entry's `to_string()`, while a non-sensitive value still prints.
160    #[test]
161    fn debug_redacts_sensitive_values() {
162        let config = config_with_secret();
163        for rendered in [format!("{config:?}"), format!("{config:#?}")] {
164            for entry in config.entries() {
165                assert!(rendered.contains(&entry.to_string()), "{rendered}");
166            }
167            assert!(rendered.starts_with("Config"), "{rendered}");
168            assert!(rendered.contains("name=ssl.truststore.password, value=Redacted"), "{rendered}");
169            assert!(rendered.contains("name=retention.ms, value=604800000"), "{rendered}");
170            assert!(!rendered.contains(SECRET), "secret leaked: {rendered}");
171        }
172    }
173}