Skip to main content

rushls_common/config/
secret.rs

1use crate::config::ConfigError;
2use std::{fmt, path::PathBuf, str::FromStr};
3
4/// Configuration credentials stay redacted even when the whole schema is logged.
5#[derive(Clone)]
6pub struct SecretString(String);
7
8/// Serde type errors normally quote the rejected value. Secret fields must
9/// replace that diagnostic before the configuration parser sees it.
10pub fn deserialize_secret<'de, D, T>(deserializer: D) -> Result<T, D::Error>
11where
12    D: serde::Deserializer<'de>,
13    T: serde::Deserialize<'de>,
14{
15    T::deserialize(deserializer).map_err(|_| serde::de::Error::custom("invalid secret value"))
16}
17
18impl<'de> serde::Deserialize<'de> for SecretString {
19    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
20        deserialize_secret(deserializer).map(Self)
21    }
22}
23
24impl SecretString {
25    pub fn new(value: String) -> Self {
26        Self(value)
27    }
28}
29impl std::ops::Deref for SecretString {
30    type Target = str;
31    fn deref(&self) -> &str {
32        &self.0
33    }
34}
35impl fmt::Debug for SecretString {
36    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37        f.write_str("[REDACTED]")
38    }
39}
40impl FromStr for SecretString {
41    type Err = std::convert::Infallible;
42    fn from_str(value: &str) -> Result<Self, Self::Err> {
43        Ok(Self(value.to_owned()))
44    }
45}
46
47/// Text written inline or read from a file: `"value"` or `{ file = "/path" }`.
48///
49/// One field per credential, rather than an inline field and a `_file` twin
50/// that must not both be set: the value's shape makes the choice, so it can
51/// never be ambiguous. Environment values use the same two spellings; a value
52/// that parses as `{ file = "..." }` names a file, anything else is literal.
53#[derive(Clone)]
54pub enum TextSource {
55    Inline(SecretString),
56    File(PathBuf),
57}
58
59impl TextSource {
60    /// Reads the text. Mounted files commonly end with a newline from a shell
61    /// or secret projection, so trailing CR/LF is removed from files only;
62    /// spaces can be part of a real credential and inline values are untouched.
63    pub fn read(&self, label: &str) -> Result<String, ConfigError> {
64        match self {
65            Self::Inline(value) => Ok(value.to_string()),
66            Self::File(path) => std::fs::read_to_string(path)
67                .map(|value| value.trim_end_matches(['\r', '\n']).to_owned())
68                .map_err(|source| ConfigError::SecretRead {
69                    secret: label.to_owned(),
70                    path: path.clone(),
71                    source,
72                }),
73        }
74    }
75}
76
77/// The table form, kept strict so a typo such as `{ path = ... }` is refused
78/// rather than read as some other credential.
79#[derive(serde::Deserialize)]
80#[serde(deny_unknown_fields)]
81struct FileReference {
82    file: PathBuf,
83}
84
85impl<'de> serde::Deserialize<'de> for TextSource {
86    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
87        #[derive(serde::Deserialize)]
88        #[serde(untagged)]
89        enum Shape {
90            Inline(String),
91            File(FileReference),
92        }
93        // Redacted like every secret: the rejected value may be the credential.
94        match Shape::deserialize(deserializer)
95            .map_err(|_| serde::de::Error::custom("expected a string or { file = \"/path\" }"))?
96        {
97            Shape::Inline(value) => Ok(Self::Inline(SecretString(value))),
98            Shape::File(reference) => Ok(Self::File(reference.file)),
99        }
100    }
101}
102
103impl FromStr for TextSource {
104    type Err = String;
105
106    fn from_str(value: &str) -> Result<Self, Self::Err> {
107        if value.trim_start().starts_with('{') {
108            #[derive(serde::Deserialize)]
109            struct Wrapper {
110                value: FileReference,
111            }
112            return toml::from_str::<Wrapper>(&format!("value = {value}"))
113                .map(|wrapper| Self::File(wrapper.value.file))
114                .map_err(|_| "expected { file = \"/path\" }".to_owned());
115        }
116        Ok(Self::Inline(SecretString(value.to_owned())))
117    }
118}
119
120impl fmt::Debug for TextSource {
121    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
122        match self {
123            Self::Inline(_) => f.write_str("Inline([REDACTED])"),
124            Self::File(path) => f.debug_tuple("File").field(path).finish(),
125        }
126    }
127}