1use std::collections::{BTreeMap, BTreeSet, HashSet};
20use std::fmt;
21use std::ops::Range;
22use std::sync::{Mutex, PoisonError};
23
24use hmac::{Hmac, KeyInit, Mac};
25use sha2::{Digest, Sha256};
26use toml_edit::{Item, TableLike, Value};
27
28use crate::error::{CoreError, ErrorCode};
29use crate::secrets::classify::{self, Reason};
30
31pub const ALLOWLIST_FILE: &str = ".loadout-allow";
33const ALLOW_PREFIX: &str = "sha256:";
35const ALLOW_DOMAIN: &[u8] = b"loadout-allow\0";
37pub const MIN_TRACKED_LEN: usize = 8;
40
41pub struct SecretMemory {
45 key: [u8; 32],
46 by_len: Mutex<BTreeMap<usize, HashSet<[u8; 32]>>>,
47}
48
49impl fmt::Debug for SecretMemory {
50 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
51 f.debug_struct("SecretMemory")
52 .field("tracked", &self.len())
53 .finish_non_exhaustive()
54 }
55}
56
57impl SecretMemory {
58 pub fn new() -> Result<Self, CoreError> {
59 let mut key = [0u8; 32];
60 getrandom::fill(&mut key).map_err(|err| {
61 CoreError::new(
62 ErrorCode::IoError,
63 format!("cannot read random bytes for the secret memory key: {err}"),
64 )
65 })?;
66 Ok(Self {
67 key,
68 by_len: Mutex::new(BTreeMap::new()),
69 })
70 }
71
72 pub fn record(&self, value: &str) {
76 self.record_here(value);
77 crate::diagnostics::redact::remember(value);
78 }
79
80 pub(crate) fn record_here(&self, value: &str) {
82 let mut by_len = self.by_len.lock().unwrap_or_else(PoisonError::into_inner);
83 for form in [value, value.trim()] {
84 if form.len() >= MIN_TRACKED_LEN {
85 by_len
86 .entry(form.len())
87 .or_default()
88 .insert(self.digest(form.as_bytes()));
89 }
90 }
91 }
92
93 pub fn len(&self) -> usize {
95 self.by_len
96 .lock()
97 .unwrap_or_else(PoisonError::into_inner)
98 .values()
99 .map(HashSet::len)
100 .sum()
101 }
102
103 pub fn is_empty(&self) -> bool {
104 self.len() == 0
105 }
106
107 pub fn find(&self, haystack: &[u8]) -> Option<Range<usize>> {
109 let by_len = self.by_len.lock().unwrap_or_else(PoisonError::into_inner);
110 let mut first: Option<Range<usize>> = None;
111 for (&len, digests) in by_len.iter() {
112 if len > haystack.len() {
113 break;
114 }
115 let limit = first.as_ref().map_or(haystack.len(), |found| found.start);
116 let hit = (0..=haystack.len() - len)
117 .take_while(|start| *start < limit)
118 .find(|&start| digests.contains(&self.digest(&haystack[start..start + len])));
119 if let Some(start) = hit {
120 first = Some(start..start + len);
121 }
122 }
123 first
124 }
125
126 fn digest(&self, bytes: &[u8]) -> [u8; 32] {
127 let mut mac = <Hmac<Sha256> as KeyInit>::new_from_slice(&self.key)
128 .expect("HMAC accepts any key length");
129 mac.update(bytes);
130 mac.finalize().into_bytes().into()
131 }
132}
133
134pub fn allow_hash(text: &str) -> String {
136 let mut hasher = Sha256::new();
137 hasher.update(ALLOW_DOMAIN);
138 hasher.update(text.as_bytes());
139 let digest = hasher.finalize();
140 let mut out = String::with_capacity(ALLOW_PREFIX.len() + 64);
141 out.push_str(ALLOW_PREFIX);
142 for byte in digest {
143 out.push_str(&format!("{byte:02x}"));
144 }
145 out
146}
147
148#[derive(Debug, Clone, Default, PartialEq, Eq)]
150pub struct Allowlist(BTreeSet<String>);
151
152impl Allowlist {
153 pub fn parse(text: &str) -> Self {
154 Self(
155 text.lines()
156 .map(|line| line.split('#').next().unwrap_or("").trim())
157 .filter(|line| line.starts_with(ALLOW_PREFIX))
158 .map(str::to_owned)
159 .collect(),
160 )
161 }
162
163 pub fn contains(&self, hash: &str) -> bool {
164 self.0.contains(hash)
165 }
166
167 pub fn append(existing: Option<&str>, hash: &str) -> String {
169 let mut text = existing.unwrap_or_default().to_owned();
170 if Self::parse(&text).contains(hash) {
171 return text;
172 }
173 if text.is_empty() {
174 text.push_str("# Values marked as not secret (SPEC 11.7); hashes only.\n");
175 } else if !text.ends_with('\n') {
176 text.push('\n');
177 }
178 text.push_str(hash);
179 text.push('\n');
180 text
181 }
182}
183
184#[derive(Debug, Clone, Copy, PartialEq, Eq)]
186pub enum LeakKind {
187 Classified(Reason),
189 ResolvedValue,
191}
192
193impl LeakKind {
194 pub const fn as_str(self) -> &'static str {
197 match self {
198 LeakKind::Classified(reason) => reason.as_str(),
199 LeakKind::ResolvedValue => "resolved_value",
200 }
201 }
202}
203
204#[derive(Debug, Clone, PartialEq, Eq)]
206pub struct LeakFinding {
207 pub file: String,
209 pub line: Option<usize>,
211 pub key: Option<String>,
213 pub kind: LeakKind,
214}
215
216impl fmt::Display for LeakFinding {
217 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
218 f.write_str(&self.file)?;
219 if let Some(line) = self.line {
220 write!(f, " line {line}")?;
221 }
222 if let Some(key) = &self.key {
223 write!(f, " ({key})")?;
224 }
225 match self.kind {
226 LeakKind::Classified(reason) => write!(f, ": {}", reason.describe()),
227 LeakKind::ResolvedValue => f.write_str(": holds a secret value resolved by Surjection"),
228 }
229 }
230}
231
232pub fn scan_text(
235 file: &str,
236 bytes: &[u8],
237 toml: bool,
238 memory: &SecretMemory,
239 allow: &Allowlist,
240) -> Vec<LeakFinding> {
241 let mut findings = Vec::new();
242 if let Some(range) = memory.find(bytes) {
243 findings.push(LeakFinding {
244 file: file.to_owned(),
245 line: Some(line_of(bytes, range.start)),
246 key: None,
247 kind: LeakKind::ResolvedValue,
248 });
249 }
250 let text = String::from_utf8_lossy(bytes);
251 for hit in classify::find_in_text(&text) {
252 if allow.contains(&allow_hash(&text[hit.range.clone()])) {
253 continue;
254 }
255 findings.push(LeakFinding {
256 file: file.to_owned(),
257 line: Some(line_of(text.as_bytes(), hit.range.start)),
258 key: None,
259 kind: LeakKind::Classified(hit.reason),
260 });
261 }
262 if toml && let Ok(doc) = toml_edit::Document::parse(text.as_ref()) {
263 let mut keyed = Vec::new();
264 walk_table(doc.as_table(), "", &mut keyed);
265 for (key, value, span) in keyed {
266 if allow.contains(&allow_hash(&value)) {
267 continue;
268 }
269 findings.push(LeakFinding {
270 file: file.to_owned(),
271 line: span.map(|span| line_of(text.as_bytes(), span.start)),
272 key: Some(key),
273 kind: LeakKind::Classified(Reason::HighEntropy),
274 });
275 }
276 }
277 findings
278}
279
280pub fn leak_error(findings: &[LeakFinding]) -> Option<CoreError> {
282 if findings.is_empty() {
283 return None;
284 }
285 let listed: Vec<String> = findings.iter().map(ToString::to_string).collect();
286 Some(CoreError::new(
287 ErrorCode::LeakDetected,
288 format!(
289 "refusing to commit a possible secret: {}. Store files hold references \
290 (`${{secret:ALIAS}}`), never values; mark text that is not secret in {ALLOWLIST_FILE}",
291 listed.join("; ")
292 ),
293 ))
294}
295
296fn line_of(bytes: &[u8], offset: usize) -> usize {
297 bytes[..offset.min(bytes.len())]
298 .iter()
299 .filter(|b| **b == b'\n')
300 .count()
301 + 1
302}
303
304type Keyed = Vec<(String, String, Option<Range<usize>>)>;
305
306fn walk_table(table: &dyn TableLike, prefix: &str, out: &mut Keyed) {
310 for (key, item) in table.iter() {
311 let path = if prefix.is_empty() {
312 key.to_owned()
313 } else {
314 format!("{prefix}.{key}")
315 };
316 match item {
317 Item::Value(value) => walk_value(key, value, &path, out),
318 Item::Table(table) => walk_table(table, &path, out),
319 Item::ArrayOfTables(array) => {
320 for (index, table) in array.iter().enumerate() {
321 walk_table(table, &format!("{path}[{index}]"), out);
322 }
323 }
324 Item::None => {}
325 }
326 }
327}
328
329fn walk_value(key: &str, value: &Value, path: &str, out: &mut Keyed) {
330 match value {
331 Value::String(text) => {
332 if classify::classify_stored(Some(key), text.value()) == Some(Reason::HighEntropy) {
333 out.push((path.to_owned(), text.value().clone(), value.span()));
334 }
335 }
336 Value::Array(array) => {
337 let strings: Vec<(usize, &Value)> = array
338 .iter()
339 .enumerate()
340 .filter(|(_, item)| item.is_str())
341 .collect();
342 let args: Vec<String> = strings
343 .iter()
344 .filter_map(|(_, item)| item.as_str().map(str::to_owned))
345 .collect();
346 for ((index, item), reason) in strings.iter().zip(classify::classify_args_stored(&args))
347 {
348 if reason == Some(Reason::HighEntropy) {
349 let text = item.as_str().unwrap_or_default().to_owned();
350 out.push((format!("{path}[{index}]"), text, item.span()));
351 }
352 }
353 for (index, item) in array.iter().enumerate() {
354 if !item.is_str() {
355 walk_value(key, item, &format!("{path}[{index}]"), out);
356 }
357 }
358 }
359 Value::InlineTable(table) => walk_table(table, path, out),
360 Value::Integer(_) | Value::Float(_) | Value::Boolean(_) | Value::Datetime(_) => {}
361 }
362}