vector_common/
sensitive_string.rs

1use vector_config::{configurable_component, ConfigurableString};
2
3/// Wrapper for sensitive strings containing credentials
4#[configurable_component(no_deser, no_ser)]
5#[derive(::serde::Deserialize, ::serde::Serialize)]
6#[serde(from = "String", into = "String")]
7#[configurable(metadata(sensitive))]
8#[derive(Clone, Default, PartialEq, Eq)]
9pub struct SensitiveString(String);
10
11impl From<String> for SensitiveString {
12    fn from(value: String) -> Self {
13        Self(value)
14    }
15}
16
17impl From<SensitiveString> for String {
18    fn from(value: SensitiveString) -> Self {
19        value.0
20    }
21}
22
23impl ConfigurableString for SensitiveString {}
24
25impl std::fmt::Display for SensitiveString {
26    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
27        write!(f, "**REDACTED**")
28    }
29}
30
31impl std::fmt::Debug for SensitiveString {
32    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
33        // we keep the double quotes here to keep the String behavior
34        write!(f, "\"**REDACTED**\"")
35    }
36}
37
38impl SensitiveString {
39    #[must_use]
40    pub fn inner(&self) -> &str {
41        self.0.as_str()
42    }
43}
44
45#[cfg(test)]
46mod tests {
47    use super::*;
48
49    #[test]
50    fn serialization() {
51        let json_value = "\"foo\"";
52        let value: SensitiveString = serde_json::from_str(json_value).unwrap();
53        let result: String = serde_json::to_string(&value).unwrap();
54        assert_eq!(result, json_value);
55    }
56
57    #[test]
58    fn hide_content() {
59        let value = SensitiveString("hello world".to_string());
60        let display = format!("{value}");
61        assert_eq!(display, "**REDACTED**");
62        let debug = format!("{value:?}");
63        assert_eq!(debug, "\"**REDACTED**\"");
64    }
65}