1#[cfg(all(test, feature = "json"))]
38use std::collections::BTreeMap;
39use std::fmt;
40use std::collections::hash_map::DefaultHasher;
44use std::hash::{Hash, Hasher};
45use std::path::Path;
46
47use figment::value::{Dict, Value};
48
49use crate::error::{Error, ErrorKind, Origin};
50use crate::snapshot::Snapshot;
51use crate::source::Format;
52
53const CACHED: &str = "cached";
55
56const MARKER: &str = "__dynamic_config_cache";
65
66const FINGERPRINT: &str = "fingerprint";
68
69const KEYS: &str = "keys";
71
72#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
92#[non_exhaustive]
93pub enum CacheMode {
94 #[default]
100 Full,
101 Redacted,
107 Fingerprint,
113}
114
115impl fmt::Display for CacheMode {
116 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
117 f.write_str(match self {
118 Self::Full => "full",
119 Self::Redacted => "redacted",
120 Self::Fingerprint => "fingerprint",
121 })
122 }
123}
124
125impl CacheMode {
126 #[must_use]
128 pub fn recovers(self) -> bool {
129 !matches!(self, Self::Fingerprint)
130 }
131}
132
133#[derive(Debug)]
135pub enum Recovery {
136 Usable(Snapshot),
138 Drift(Option<Vec<String>>),
145 Absent,
147}
148
149pub(crate) fn write(
158 snapshot: &Snapshot,
159 path: &Path,
160 mode: CacheMode,
161 secrets: &[&str],
162) -> Result<(), Error> {
163 let format = format_of(path)?;
164
165 let mut document = match mode {
166 CacheMode::Full => snapshot.values().clone(),
167 CacheMode::Redacted => without(snapshot.values(), secrets),
168 CacheMode::Fingerprint => fingerprint_document(snapshot),
169 };
170
171 let mut marker = Dict::new();
172 marker.insert("version".to_owned(), Value::from(1));
173 marker.insert(
174 "mode".to_owned(),
175 Value::from(match mode {
176 CacheMode::Full => "full",
177 CacheMode::Redacted => "redacted",
178 CacheMode::Fingerprint => "fingerprint",
179 }),
180 );
181 document.insert(MARKER.to_owned(), Value::from(marker));
182
183 crate::write::save_dict(&document, path, format, CACHED)
184}
185
186#[cfg(feature = "decrypt")]
193pub(crate) fn write_encrypted(
194 snapshot: &Snapshot,
195 path: &Path,
196 encryptor: &dyn crate::Encryptor,
197) -> Result<(), Error> {
198 let format = encrypted_format_of(path)?;
199
200 let mut document = snapshot.values().clone();
201 let mut marker = Dict::new();
202 marker.insert("version".to_owned(), Value::from(1));
203 marker.insert("mode".to_owned(), Value::from("full"));
204 document.insert(MARKER.to_owned(), Value::from(marker));
205
206 crate::write::save_dict_encrypted(&document, path, format, CACHED, encryptor)
207}
208
209#[cfg(feature = "decrypt")]
213pub(crate) fn read_encrypted(path: &Path, current: Option<&Snapshot>) -> Result<Recovery, Error> {
214 let format = encrypted_format_of(path)?;
215
216 let bytes = match std::fs::read(path) {
217 Ok(bytes) => bytes,
218 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Recovery::Absent),
219 Err(error) => {
220 return Err(Error::new(ErrorKind::Io, error.to_string())
221 .with_origin(Origin::File(path.to_owned())))
222 }
223 };
224
225 let plaintext = crate::decrypt::decrypt(&bytes, &path.display().to_string())?;
228
229 parse_cache(plaintext.text(), format, path, current)
230}
231
232#[cfg(feature = "decrypt")]
234fn encrypted_format_of(path: &Path) -> Result<crate::Format, Error> {
235 let name = path
236 .to_str()
237 .ok_or_else(|| Error::new(ErrorKind::Io, "the cache path is not valid UTF-8"))?;
238
239 let Some((inner, _suffix)) = crate::source::inner_name(name) else {
240 return Err(Error::new(
241 ErrorKind::Backend,
242 format!(
243 "an encrypted cache path carries the format under the \
244 encryption suffix — `last.json.{}`, not `{name}`",
245 crate::source::ENCRYPTED_SUFFIX
246 ),
247 ));
248 };
249
250 format_of(Path::new(inner))
251}
252
253pub(crate) fn read(path: &Path, current: Option<&Snapshot>) -> Result<Recovery, Error> {
260 let format = format_of(path)?;
261
262 let text = match std::fs::read_to_string(path) {
263 Ok(text) => text,
264 Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Recovery::Absent),
265 Err(error) => {
266 return Err(Error::new(ErrorKind::Io, error.to_string())
267 .with_origin(Origin::File(path.to_owned())))
268 }
269 };
270
271 parse_cache(&text, format, path, current)
272}
273
274fn parse_cache(
276 text: &str,
277 format: crate::Format,
278 path: &Path,
279 current: Option<&Snapshot>,
280) -> Result<Recovery, Error> {
281 let _ = path;
282 let sources = [crate::Source::inline(text, format)];
283 let cached = crate::loader::snapshot(&crate::LoadSpec::new(CACHED, &sources))?;
284
285 let is_fingerprint = match cached.get::<String>(&format!("{MARKER}.mode")) {
289 Ok(mode) => mode == "fingerprint",
290 Err(_) => cached.contains(FINGERPRINT),
291 };
292
293 if !is_fingerprint {
294 return Ok(Recovery::Usable(cached.without_top_level(MARKER)));
295 }
296
297 Ok(Recovery::Drift(drift(&cached, current)))
298}
299
300fn drift(cached: &Snapshot, current: Option<&Snapshot>) -> Option<Vec<String>> {
307 let current = current?;
308
309 let before: Vec<String> = cached.get(KEYS).unwrap_or_default();
310 let after = current.leaf_paths();
311
312 let mut moved: Vec<String> = before
313 .iter()
314 .filter(|key| !after.contains(key))
315 .map(|key| format!("{key} is gone"))
316 .chain(
317 after
318 .iter()
319 .filter(|key| !before.contains(key))
320 .map(|key| format!("{key} is new")),
321 )
322 .collect();
323
324 moved.sort();
325
326 if moved.is_empty() {
330 let stored: Option<String> = cached.get(FINGERPRINT).ok();
331 let current_hash = fingerprint_of(current);
332
333 if stored.as_deref() == Some(current_hash.as_str()) {
334 return Some(vec!["nothing moved — the sources match the last good \
335 configuration exactly"
336 .to_owned()]);
337 }
338
339 return Some(vec!["the same keys, with different values".to_owned()]);
340 }
341
342 Some(moved)
343}
344
345fn fingerprint_of(snapshot: &Snapshot) -> String {
347 let mut hasher = DefaultHasher::new();
348 format!("{:?}", snapshot.values()).hash(&mut hasher);
349
350 format!("{:016x}", hasher.finish())
351}
352
353fn without(values: &Dict, secrets: &[&str]) -> Dict {
368 let mut document = values.clone();
369
370 for secret in secrets {
371 remove_path(&mut document, secret);
372 }
373
374 document
375}
376
377fn remove_path(document: &mut Dict, path: &str) {
379 match path.split_once('.') {
380 None => {
381 document.remove(path);
382 }
383 Some((head, rest)) => {
384 if let Some(Value::Dict(_, nested)) = document.get_mut(head) {
385 remove_path(nested, rest);
386 }
387 }
388 }
389}
390
391fn fingerprint_document(snapshot: &Snapshot) -> Dict {
393 let keys = snapshot.leaf_paths();
394
395 let mut document = Dict::new();
399 document.insert(
400 FINGERPRINT.to_owned(),
401 Value::from(fingerprint_of(snapshot)),
402 );
403 document.insert(
404 KEYS.to_owned(),
405 Value::from(keys.into_iter().map(Value::from).collect::<Vec<_>>()),
406 );
407
408 document
409}
410
411fn format_of(path: &Path) -> Result<Format, Error> {
412 if path.extension().is_some_and(|extension| extension == "age") {
416 return Err(Error::new(
417 ErrorKind::Backend,
418 format!(
419 "{} ends in `.age`, but the last-known-good cache is written in plaintext; give the cache an unencrypted name",
420 path.display()
421 ),
422 ));
423 }
424
425 path.extension()
426 .and_then(|extension| extension.to_str())
427 .and_then(Format::from_extension)
428 .ok_or_else(|| Error::unsupported(path))
429}
430
431#[cfg(all(test, feature = "json"))]
433fn dict_of(entries: &[(&str, Value)]) -> BTreeMap<String, Value> {
434 entries
435 .iter()
436 .map(|(key, value)| ((*key).to_owned(), value.clone()))
437 .collect()
438}
439
440#[cfg(all(test, feature = "json"))]
441mod tests {
442 use super::*;
443
444 fn scratch(test: &str) -> std::path::PathBuf {
445 let directory = std::env::temp_dir().join("dynamic-config-cache").join(test);
446
447 let _ = std::fs::remove_dir_all(&directory);
448 std::fs::create_dir_all(&directory).expect("the scratch directory should be creatable");
449
450 directory.join("cache.json")
451 }
452
453 fn snapshot() -> Snapshot {
454 Snapshot::new(dict_of(&[
455 ("host", "localhost".into()),
456 ("password", "hunter2".into()),
457 ("pool", Value::from(dict_of(&[("max", 10u16.into())]))),
458 ]))
459 }
460
461 #[test]
462 fn full_keeps_everything_and_recovers() {
463 let path = scratch("full");
464
465 write(&snapshot(), &path, CacheMode::Full, &["password"]).unwrap();
466
467 let Recovery::Usable(recovered) = read(&path, None).unwrap() else {
468 panic!("a full cache must be usable");
469 };
470
471 assert_eq!(recovered.get::<String>("host").unwrap(), "localhost");
472 assert_eq!(recovered.get::<String>("password").unwrap(), "hunter2");
473 assert_eq!(recovered.get::<u16>("pool.max").unwrap(), 10);
474 }
475
476 #[test]
477 fn redacted_drops_the_marked_fields_and_nothing_else() {
478 let path = scratch("redacted");
479
480 write(&snapshot(), &path, CacheMode::Redacted, &["password"]).unwrap();
481
482 let written = std::fs::read_to_string(&path).unwrap();
483 assert!(!written.contains("hunter2"), "{written}");
484
485 let Recovery::Usable(recovered) = read(&path, None).unwrap() else {
486 panic!("a redacted cache is still usable");
487 };
488
489 assert_eq!(recovered.get::<String>("host").unwrap(), "localhost");
490 assert!(
491 !recovered.contains("password"),
492 "the secret must not have survived"
493 );
494 }
495
496 #[test]
497 fn fingerprint_writes_no_value_at_all() {
498 let path = scratch("fingerprint");
499
500 write(&snapshot(), &path, CacheMode::Fingerprint, &[]).unwrap();
501
502 let written = std::fs::read_to_string(&path).unwrap();
503
504 assert!(!written.contains("hunter2"), "{written}");
505 assert!(!written.contains("localhost"), "{written}");
506 assert!(written.contains("host"), "{written}");
508 }
509
510 #[test]
511 fn fingerprint_cannot_recover_but_reports_what_moved() {
512 let path = scratch("drift");
513
514 write(&snapshot(), &path, CacheMode::Fingerprint, &[]).unwrap();
515
516 let now = Snapshot::new(dict_of(&[
517 ("host", "localhost".into()),
518 ("hsot", "typo".into()),
519 ]));
520
521 let Recovery::Drift(Some(moved)) = read(&path, Some(&now)).unwrap() else {
522 panic!("a fingerprint cache cannot be usable");
523 };
524
525 assert!(moved.contains(&"hsot is new".to_owned()), "{moved:?}");
526 assert!(moved.contains(&"password is gone".to_owned()), "{moved:?}");
527 }
528
529 #[test]
530 fn an_age_cache_path_is_refused_because_the_cache_is_plaintext() {
531 let error = write(
532 &snapshot(),
533 Path::new("cache.json.age"),
534 CacheMode::Full,
535 &[],
536 )
537 .unwrap_err();
538
539 assert!(error.to_string().contains("plaintext"), "{error}");
540 }
541
542 #[test]
543 fn a_first_start_has_no_cache_and_that_is_not_a_failure() {
544 let path = scratch("absent").with_file_name("nothing.json");
545
546 assert!(matches!(read(&path, None).unwrap(), Recovery::Absent));
547 }
548
549 #[test]
550 fn only_fingerprint_refuses_to_recover() {
551 assert!(CacheMode::Full.recovers());
552 assert!(CacheMode::Redacted.recovers());
553 assert!(!CacheMode::Fingerprint.recovers());
554 }
555}