返回 CodeWhale
display_redaction.rs
根目录 / crates / config / src / display_redaction.rs
1 use crate::config_toml::ConfigToml;
2 use crate::settings_schema::{SettingDef, SettingKind};
3 use anyhow::Context as _;
4 use anyhow::{Result, bail};
5 use std::collections::BTreeMap;
6
7 /// `value` as the TOML value a [`SettingDef`] declares, or an error naming
8 /// the key and what it accepts. No partial write happens on error.
9 pub(crate) fn schema_toml_value(key: &str, def: &SettingDef, value: &str) -> Result<toml::Value> {
10 let trimmed = value.trim();
11 Ok(match def.kind {
12 SettingKind::Bool(_) => toml::Value::Boolean(
13 parse_bool(value).with_context(|| format!("invalid value for '{key}'"))?,
14 ),
15 SettingKind::Int => toml::Value::Integer(trimmed.parse().map_err(|_| {
16 anyhow::anyhow!("invalid value '{value}' for '{key}': expected an integer")
17 })?),
18 SettingKind::Float => toml::Value::Float(
19 trimmed
20 .parse::<f64>()
21 .ok()
22 .filter(|number| number.is_finite())
23 .ok_or_else(|| {
24 anyhow::anyhow!("invalid value '{value}' for '{key}': expected a number")
25 })?,
26 ),
27 SettingKind::Enum(options) => {
28 let Some(option) = options
29 .iter()
30 .find(|option| option.value.eq_ignore_ascii_case(trimmed))
31 else {
32 let expected: Vec<&str> = options.iter().map(|option| option.value).collect();
33 bail!(
34 "invalid value '{value}' for '{key}': expected one of {}",
35 expected.join(", ")
36 );
37 };
38 toml::Value::String(option.value.to_string())
39 }
40 SettingKind::String => toml::Value::String(value.to_string()),
41 })
42 }
43
44 pub(crate) fn parse_bool(raw: &str) -> Result<bool> {
45 match raw.trim().to_ascii_lowercase().as_str() {
46 "1" | "true" | "yes" | "on" | "enabled" => Ok(true),
47 "0" | "false" | "no" | "off" | "disabled" => Ok(false),
48 _ => bail!("invalid boolean '{raw}'"),
49 }
50 }
51
52 pub(crate) fn parse_http_headers(raw: &str) -> Result<BTreeMap<String, String>> {
53 let mut headers = BTreeMap::new();
54 for pair in raw.trim().split(',') {
55 let pair = pair.trim();
56 if pair.is_empty() {
57 continue;
58 }
59 let Some((name, value)) = pair.split_once('=') else {
60 bail!("invalid header pair '{pair}', expected name=value");
61 };
62 let name = name.trim();
63 let value = value.trim();
64 if name.is_empty() {
65 bail!("header name cannot be empty");
66 }
67 if value.is_empty() {
68 continue;
69 }
70 headers.insert(name.to_string(), value.to_string());
71 }
72 Ok(headers)
73 }
74
75 pub(crate) fn serialize_http_headers(headers: &BTreeMap<String, String>) -> Option<String> {
76 if headers.is_empty() {
77 return None;
78 }
79 Some(
80 headers
81 .iter()
82 .map(|(name, value)| format!("{name}={value}"))
83 .collect::<Vec<_>>()
84 .join(","),
85 )
86 }
87
88 pub(crate) fn serialize_http_headers_for_display(
89 headers: &BTreeMap<String, String>,
90 ) -> Option<String> {
91 if headers.is_empty() {
92 return None;
93 }
94 Some(
95 headers
96 .iter()
97 .map(|(name, value)| {
98 let display_value = if is_sensitive_config_key(name) {
99 redact_secret(value)
100 } else {
101 value.clone()
102 };
103 format!("{name}={display_value}")
104 })
105 .collect::<Vec<_>>()
106 .join(","),
107 )
108 }
109
110 pub(crate) fn redact_secret(secret: &str) -> String {
111 let chars: Vec<char> = secret.chars().collect();
112 if chars.len() <= 16 {
113 return "********".to_string();
114 }
115 let prefix: String = chars.iter().take(4).collect();
116 let suffix: String = chars
117 .iter()
118 .rev()
119 .take(4)
120 .collect::<Vec<_>>()
121 .into_iter()
122 .rev()
123 .collect();
124 format!("{prefix}***{suffix}")
125 }
126
127 #[must_use]
128 pub fn is_sensitive_config_key(key: &str) -> bool {
129 key.rsplit('.')
130 .next()
131 .is_some_and(codewhale_sanitize::sanitize::is_sensitive_key_name)
132 }
133
134 /// Resolve dotted paths without treating a dotted key as a top-level literal.
135 pub(crate) fn config_value_at_path<'a>(
136 value: &'a toml::Value,
137 key: &str,
138 ) -> Option<&'a toml::Value> {
139 key.split('.')
140 .try_fold(value, |value, part| value.get(part))
141 }
142
143 pub(crate) fn redact_toml_value_for_display(key: &str, value: &toml::Value) -> String {
144 redact_toml_value_for_display_inner(key, false, value).to_string()
145 }
146
147 impl ConfigToml {
148 /// Redacted TOML rendering of the effective config for `config dump`.
149 /// Structure is preserved; strings under sensitive key names (api_key,
150 /// token, secret, … — see `is_sensitive_config_key`, nested tables
151 /// inherit sensitivity from their ancestors) are redacted. Redaction is
152 /// name-based: an unrecognized key holding a secret-looking value would
153 /// pass through, so pasting dump output still deserves a glance.
154 #[must_use]
155 pub fn redacted_toml_value(&self) -> toml::Value {
156 let value =
157 toml::Value::try_from(self).expect("ConfigToml derives Serialize, so this holds");
158 match value {
159 toml::Value::Table(table) => toml::Value::Table(
160 table
161 .into_iter()
162 .map(|(key, value)| {
163 let redacted = redact_toml_value_for_display_inner(&key, false, &value);
164 (key, redacted)
165 })
166 .collect(),
167 ),
168 other => other,
169 }
170 }
171 }
172
173 pub(crate) fn toml_value_as_u64(value: &toml::Value) -> Option<u64> {
174 match value {
175 toml::Value::Integer(value) => u64::try_from(*value).ok(),
176 toml::Value::String(value) => value.trim().parse().ok(),
177 _ => None,
178 }
179 }
180
181 pub(crate) fn redact_toml_value_for_display_inner(
182 key: &str,
183 sensitive_ancestor: bool,
184 value: &toml::Value,
185 ) -> toml::Value {
186 let sensitive = sensitive_ancestor || is_sensitive_config_key(key);
187 match value {
188 toml::Value::String(value) if sensitive => toml::Value::String(redact_secret(value)),
189 toml::Value::Array(values) => toml::Value::Array(
190 values
191 .iter()
192 .map(|value| redact_toml_value_for_display_inner(key, sensitive, value))
193 .collect(),
194 ),
195 toml::Value::Table(table) => {
196 let mut redacted = toml::map::Map::new();
197 for (child_key, child_value) in table {
198 let path = if key.is_empty() {
199 child_key.clone()
200 } else {
201 format!("{key}.{child_key}")
202 };
203 redacted.insert(
204 child_key.clone(),
205 redact_toml_value_for_display_inner(&path, sensitive, child_value),
206 );
207 }
208 toml::Value::Table(redacted)
209 }
210 _ if sensitive => toml::Value::String("********".to_string()),
211 _ => value.clone(),
212 }
213 }
214
214 lines RUST