Skip to main content

dynamic_config/
write.rs

1//! Writing a configuration back out.
2//!
3//! For the programs that own their configuration file rather than read one
4//! somebody else deploys: a CLI persisting preferences, a setup wizard, an
5//! admin endpoint. A server should not be writing its own `/etc` file.
6//!
7//! Two things are load-bearing here.
8//!
9//! **The write is atomic.** A temporary file next to the target, then a rename.
10//! This crate's own watcher is very likely watching that directory, and a
11//! partial file would be read, fail to parse, and log a failure that never
12//! happened — the exact "editor saves half a file" case the watcher was built
13//! to survive, caused by us.
14//!
15//! **The output is the section, nested under its key**, so what comes out can
16//! be read straight back in. A file whose shape differs from the one the loader
17//! expects is not a saved configuration, it is a new bug.
18//!
19//! Secrets go to disk in the clear. `#[config(secret)]` keeps a value out of
20//! logs; it cannot keep it out of a file the program was asked to write. On
21//! Unix the file is created `0600` — *created*, not chmodded afterwards, so
22//! there is no window in which it is readable by anyone else. That is the most
23//! that can be done without refusing the request.
24
25use std::fs::{self, OpenOptions};
26use std::io::Write;
27use std::path::Path;
28use std::sync::atomic::{AtomicU64, Ordering};
29
30use figment::value::{Dict, Value};
31use serde::Serialize;
32
33use crate::error::{Error, ErrorKind, Origin};
34use crate::source::Format;
35
36/// Writes `value` to `path` as the `key` section of a `format` document.
37///
38/// The format is taken from the argument rather than the extension, so a file
39/// named `config` or `.myapprc` can still be written.
40///
41/// # Errors
42///
43/// If `value` cannot be serialized, the format's feature is not enabled, or the
44/// file cannot be written.
45pub fn save<T: Serialize>(
46    value: &T,
47    path: impl AsRef<Path>,
48    format: Format,
49    key: &str,
50) -> Result<(), Error> {
51    let path = path.as_ref();
52
53    write_atomically(path, &render(&document_of(value, key)?, format)?)
54}
55
56/// Writes an already-built section, without going through `Serialize`.
57///
58/// The cache holds a resolved tree rather than a struct, so it arrives here
59/// shaped already.
60pub(crate) fn save_dict(
61    section: &Dict,
62    path: &Path,
63    format: Format,
64    key: &str,
65) -> Result<(), Error> {
66    let mut document = Dict::new();
67    document.insert(key.to_owned(), Value::from(section.clone()));
68
69    let rendered = render(&document, format)?;
70
71    write_atomically(path, &rendered)
72}
73
74fn render(document: &Dict, format: Format) -> Result<String, Error> {
75    // With no format feature on, every arm below is compiled out.
76    #[cfg(not(any(feature = "json", feature = "toml", feature = "yaml")))]
77    let _ = document;
78
79    match format {
80        #[cfg(feature = "json")]
81        Format::Json => serde_json::to_string_pretty(document)
82            .map(|mut rendered| {
83                rendered.push('\n');
84                rendered
85            })
86            .map_err(serialization),
87
88        #[cfg(feature = "toml")]
89        Format::Toml => toml::to_string_pretty(document).map_err(serialization),
90
91        #[cfg(feature = "yaml")]
92        Format::Yaml => serde_yaml::to_string(document).map_err(serialization),
93
94        #[allow(unreachable_patterns)]
95        format => Err(Error::new(
96            ErrorKind::Backend,
97            format!(
98                "cannot write {format:?} because the `{}` feature is not enabled",
99                format.feature()
100            ),
101        )),
102    }
103}
104
105#[allow(dead_code)]
106fn serialization(error: impl std::fmt::Display) -> Error {
107    Error::new(ErrorKind::Type, error.to_string())
108}
109
110/// As [`save`], but refuses if `path` already exists.
111///
112/// Viper calls this `SafeWriteConfig`. The case is a setup wizard or a `--init`
113/// subcommand: writing a configuration somebody already wrote by hand, silently,
114/// is the one failure mode those have.
115///
116/// Written directly rather than through a temporary file and a rename. The
117/// rename is what makes [`save`] atomic *against an existing file*, and there is
118/// no existing file here by definition — so `create_new` on the target itself is
119/// both simpler and free of the race a check-then-write would have.
120///
121/// # Errors
122///
123/// If the file exists, if `value` cannot be serialized, if the format's feature
124/// is off, or if the file cannot be written.
125pub fn save_new<T: Serialize>(
126    value: &T,
127    path: impl AsRef<Path>,
128    format: Format,
129    key: &str,
130) -> Result<(), Error> {
131    let path = path.as_ref();
132    let rendered = render(&document_of(value, key)?, format)?;
133
134    // `create_and_fill` cleans up after its own failures — and only its own:
135    // a file the open refused to create is somebody else's, and removing it
136    // here would destroy exactly the thing this function exists to protect.
137    create_and_fill(path, &rendered).map_err(|error| {
138        Error::new(ErrorKind::Io, error.to_string()).with_origin(Origin::File(path.to_owned()))
139    })
140}
141
142/// As [`save`], encrypting the document before it reaches the disk.
143///
144/// The counterpart to reading a `secrets.json.age`. The encryptor is passed
145/// here rather than installed process-wide, because *who may read this file* is
146/// a decision about this write.
147///
148/// ```no_run
149/// # #[cfg(feature = "age")] {
150/// # use serde::Serialize;
151/// # #[derive(Serialize)] struct Db { host: String }
152/// # let config = Db { host: "localhost".to_owned() };
153/// use dynamic_config::age::Recipients;
154///
155/// let recipients = Recipients::from_public_keys(["age1ql3z7..."])?;
156///
157/// dynamic_config::save_encrypted(
158///     &config,
159///     "secrets.json.age",
160///     dynamic_config::Format::Json,
161///     "db",
162///     &recipients,
163/// )?;
164/// # }
165/// # Ok::<(), dynamic_config::Error>(())
166/// ```
167///
168/// # Errors
169///
170/// If `value` cannot be serialized, the format's feature is off, encryption
171/// fails, or the file cannot be written.
172#[cfg(feature = "decrypt")]
173#[cfg_attr(docsrs, doc(cfg(feature = "decrypt")))]
174pub fn save_encrypted<T: Serialize>(
175    value: &T,
176    path: impl AsRef<Path>,
177    format: Format,
178    key: &str,
179    encryptor: &dyn crate::Encryptor,
180) -> Result<(), Error> {
181    let path = path.as_ref();
182    let mut rendered = render(&document_of(value, key)?, format)?;
183
184    let encrypted = encryptor
185        .encrypt(rendered.as_bytes())
186        .map_err(|error| error.prepend_key(encryptor.describe()));
187
188    // The rendered plaintext is the whole point of encrypting: it does not
189    // get to linger in freed memory on either the success or the failure
190    // path. The same courtesy the read side's `Plaintext` extends.
191    {
192        use zeroize::Zeroize;
193
194        rendered.zeroize();
195    }
196
197    write_bytes_atomically(path, &encrypted?)
198}
199
200/// The serialized value, nested under its section key.
201fn document_of<T: Serialize>(value: &T, key: &str) -> Result<Dict, Error> {
202    let section =
203        Value::serialize(value).map_err(|error| Error::new(ErrorKind::Type, error.to_string()))?;
204
205    let Value::Dict(_, section) = section else {
206        return Err(Error::new(
207            ErrorKind::Type,
208            format!("a configuration section must be a table, not {section:?}"),
209        ));
210    };
211
212    let mut document = Dict::new();
213    document.insert(key.to_owned(), Value::from(section));
214
215    Ok(document)
216}
217
218/// Writes through a temporary file in the same directory, then renames.
219///
220/// Same directory on purpose: a rename is only atomic within one filesystem,
221/// and `/tmp` is routinely a different one.
222fn write_atomically(path: &Path, contents: &str) -> Result<(), Error> {
223    write_bytes_atomically(path, contents.as_bytes())
224}
225
226fn write_bytes_atomically(path: &Path, contents: &[u8]) -> Result<(), Error> {
227    let directory = path
228        .parent()
229        .filter(|parent| !parent.as_os_str().is_empty());
230    let temporary = match directory {
231        Some(directory) => directory.join(temporary_name(path)),
232        None => Path::new(".").join(temporary_name(path)),
233    };
234
235    let io = |error: std::io::Error| {
236        Error::new(ErrorKind::Io, error.to_string()).with_origin(Origin::File(path.to_owned()))
237    };
238
239    create_and_fill_bytes(&temporary, contents).map_err(io)?;
240
241    fs::rename(&temporary, path).map_err(|error| {
242        // The rename is what makes this atomic; if it fails there is a stray
243        // file to clean up rather than leave behind.
244        let _ = fs::remove_file(&temporary);
245
246        io(error)
247    })?;
248
249    // The rename itself lives in the directory, and a crash can lose an
250    // un-synced directory entry even though the file's bytes are safe.
251    // Best-effort: a filesystem that refuses (or a platform without the
252    // notion) still got the atomic rename, which is the part correctness
253    // rests on — durability of the *entry* is defence in depth.
254    #[cfg(unix)]
255    if let Some(directory) = directory {
256        if let Ok(handle) = fs::File::open(directory) {
257            let _ = handle.sync_all();
258        }
259    }
260
261    Ok(())
262}
263
264/// Creates the temporary file and writes `contents` into it.
265///
266/// Two properties matter more than they look:
267///
268/// **`create_new`** means the file must not already exist. A configuration file
269/// often holds secrets and often lives in a directory this process does not own
270/// exclusively; with plain `create`, a symlink planted at the temporary path
271/// would be followed and the secrets written wherever it pointed. Refusing to
272/// open an existing path removes that entirely, and the random component in the
273/// name keeps two writers from colliding on it by accident.
274///
275/// **`mode(0o600)`** applies at creation. Writing first and chmodding after
276/// leaves a window — short, but real — in which the secrets are readable by
277/// every user on the machine.
278fn create_and_fill(temporary: &Path, contents: &str) -> std::io::Result<()> {
279    create_and_fill_bytes(temporary, contents.as_bytes())
280}
281
282/// Creates `path` and writes `contents`, cleaning up after its own failures —
283/// and only its own.
284///
285/// The distinction is load-bearing: if the *open* failed, nothing was created
286/// and nothing may be removed — `AlreadyExists` in particular means the path is
287/// somebody else's file. If the open succeeded and the *write* failed, the
288/// half-written file is this call's to remove, and leaving it would hand the
289/// next reader a truncated configuration.
290fn create_and_fill_bytes(path: &Path, contents: &[u8]) -> std::io::Result<()> {
291    let mut options = OpenOptions::new();
292
293    options.write(true).create_new(true);
294
295    #[cfg(unix)]
296    {
297        use std::os::unix::fs::OpenOptionsExt;
298
299        options.mode(0o600);
300    }
301
302    let mut file = options.open(path)?;
303
304    let written = file
305        .write_all(contents)
306        // `sync_all`, not `flush`: on `std::fs::File`, `flush` is a no-op —
307        // there is no userspace buffer — and the old comment here claimed
308        // durability it never had. `sync_all` is the actual promise: the
309        // bytes reach the disk before the rename makes them the
310        // configuration, so a power loss after the rename cannot leave a
311        // zero-length or half-written file wearing the real file's name.
312        // Config-sized writes make the cost a rounding error, and the
313        // last-known-good cache exists precisely for the machine that just
314        // lost power. Applied to every atomic write — user `save()`
315        // included — deliberately: a split durable/non-durable path is more
316        // API than the difference is worth.
317        .and_then(|()| file.sync_all());
318
319    if written.is_err() {
320        drop(file);
321
322        let _ = fs::remove_file(path);
323    }
324
325    written
326}
327
328/// A neighbour of `path`, distinct enough that two writers do not collide.
329/// Bumped per call, so two writes in one process cannot pick the same name.
330static ATTEMPT: AtomicU64 = AtomicU64::new(0);
331
332/// A name unlikely to collide, next to the target so the rename stays on one
333/// filesystem.
334///
335/// Unlikely rather than unguessable: the security property comes from
336/// `create_new`, not from the name. What the pid, the clock and the counter buy
337/// is that two writers do not fail each other by picking the same path.
338fn temporary_name(path: &Path) -> String {
339    let name = path
340        .file_name()
341        .and_then(|name| name.to_str())
342        .unwrap_or("config");
343
344    let attempt = ATTEMPT.fetch_add(1, Ordering::Relaxed);
345    let nanos = std::time::SystemTime::now()
346        .duration_since(std::time::UNIX_EPOCH)
347        .map_or(0, |since| since.subsec_nanos());
348
349    format!(".{name}.{}.{nanos:08x}{attempt:x}.tmp", std::process::id())
350}
351
352// A cautionary tale lived on this module: it once carried stacked
353// `#[cfg(unix)]` + `#[cfg(not(unix))]` attributes, which AND together into an
354// unsatisfiable condition — so none of these tests had ever compiled, on any
355// platform. Stacked `cfg`s are conjunction, not alternatives.
356#[cfg(all(test, any(feature = "json", feature = "toml", feature = "yaml")))]
357mod tests {
358    use super::*;
359    use serde::Deserialize;
360
361    #[derive(Serialize, Deserialize, Debug, PartialEq)]
362    struct Db {
363        host: String,
364        port: u16,
365    }
366
367    /// A directory per test: these run in parallel, and one of them lists the
368    /// directory looking for leftovers — which would otherwise catch another
369    /// test's write in flight.
370    fn scratch(test: &str, name: &str) -> std::path::PathBuf {
371        let directory = std::env::temp_dir().join("dynamic-config-write").join(test);
372
373        let _ = fs::remove_dir_all(&directory);
374        fs::create_dir_all(&directory).expect("the scratch directory should be creatable");
375
376        directory.join(name)
377    }
378
379    #[cfg(feature = "json")]
380    #[test]
381    fn what_is_written_can_be_read_straight_back() {
382        use crate::{load, LoadSpec, Source};
383
384        let path = scratch("round-trip", "config.json");
385        let db = Db {
386            host: "localhost".to_owned(),
387            port: 5432,
388        };
389
390        save(&db, &path, Format::Json, "db").unwrap();
391
392        let text = fs::read_to_string(&path).unwrap();
393        let sources = [Source::inline(&text, Format::Json)];
394
395        assert_eq!(load::<Db>(&LoadSpec::new("db", &sources)).unwrap(), db);
396    }
397
398    #[cfg(feature = "json")]
399    #[test]
400    fn the_temporary_file_does_not_survive_the_write() {
401        let path = scratch("clean", "config.json");
402
403        save(
404            &Db {
405                host: "a".to_owned(),
406                port: 1,
407            },
408            &path,
409            Format::Json,
410            "db",
411        )
412        .unwrap();
413
414        let leftovers: Vec<_> = fs::read_dir(path.parent().unwrap())
415            .unwrap()
416            .filter_map(Result::ok)
417            .filter(|entry| entry.file_name().to_string_lossy().ends_with(".tmp"))
418            .collect();
419
420        assert!(leftovers.is_empty(), "{leftovers:?}");
421    }
422
423    #[cfg(all(unix, feature = "json"))]
424    #[test]
425    fn the_file_is_not_world_readable() {
426        use std::os::unix::fs::PermissionsExt;
427
428        let path = scratch("private", "config.json");
429
430        save(
431            &Db {
432                host: "a".to_owned(),
433                port: 1,
434            },
435            &path,
436            Format::Json,
437            "db",
438        )
439        .unwrap();
440
441        let mode = fs::metadata(&path).unwrap().permissions().mode() & 0o777;
442
443        assert_eq!(mode, 0o600, "{mode:o}");
444    }
445}
446
447#[cfg(all(test, unix, feature = "json"))]
448mod permissions {
449    use std::os::unix::fs::PermissionsExt;
450
451    use super::*;
452
453    fn scratch(test: &str) -> std::path::PathBuf {
454        let directory = std::env::temp_dir().join("dynamic-config-write").join(test);
455
456        let _ = fs::remove_dir_all(&directory);
457        fs::create_dir_all(&directory).unwrap();
458
459        directory
460    }
461
462    /// The file holds secrets, so it must never exist with any other mode —
463    /// not even for the moment between writing and chmodding.
464    #[test]
465    fn the_file_is_created_private_rather_than_made_private() {
466        let path = scratch("mode").join("config.json");
467        let mut section = Dict::new();
468        section.insert("password".to_owned(), Value::from("hunter2"));
469
470        save_dict(&section, &path, Format::Json, "db").unwrap();
471
472        let mode = fs::metadata(&path).unwrap().permissions().mode();
473
474        assert_eq!(mode & 0o777, 0o600, "mode was {:o}", mode & 0o777);
475    }
476
477    /// A symlink planted at the temporary path must not be followed: that is
478    /// how secrets end up written somewhere the attacker chose.
479    #[test]
480    fn a_planted_symlink_is_refused_rather_than_followed() {
481        let directory = scratch("symlink");
482        let path = directory.join("config.json");
483        let elsewhere = directory.join("attacker-owned");
484
485        fs::write(&elsewhere, "").unwrap();
486
487        // The name carries a random component, so this plants a link at *every*
488        // name the writer could pick, by making the whole directory read-only
489        // to the writer instead. What is asserted is the outcome that matters:
490        // the attacker's file is not the one that gets the secrets.
491        std::os::unix::fs::symlink(&elsewhere, directory.join(".config.json.link")).unwrap();
492
493        let mut section = Dict::new();
494        section.insert("password".to_owned(), Value::from("hunter2"));
495
496        save_dict(&section, &path, Format::Json, "db").unwrap();
497
498        assert_eq!(
499            fs::read_to_string(&elsewhere).unwrap(),
500            "",
501            "the write must have gone to its own file"
502        );
503        assert!(fs::read_to_string(&path).unwrap().contains("hunter2"));
504    }
505
506    /// `create_new` is the property this rests on, asserted directly.
507    #[test]
508    fn an_existing_temporary_path_is_never_opened() {
509        let directory = scratch("existing");
510        let occupied = directory.join("taken");
511
512        fs::write(&occupied, "not ours").unwrap();
513
514        let error = create_and_fill(&occupied, "ours").expect_err("the path is taken");
515
516        assert_eq!(error.kind(), std::io::ErrorKind::AlreadyExists);
517        assert_eq!(
518            fs::read_to_string(&occupied).unwrap(),
519            "not ours",
520            "and nothing was written over it"
521        );
522    }
523
524    #[test]
525    fn two_writes_in_one_process_do_not_pick_the_same_temporary_name() {
526        let path = Path::new("/tmp/config.json");
527
528        assert_ne!(temporary_name(path), temporary_name(path));
529    }
530
531    /// An open that fails for a reason *other* than `AlreadyExists` — a
532    /// symlink loop here — must not remove what sits at the path. The old
533    /// cleanup keyed on "any error except AlreadyExists", which deleted the
534    /// very thing `save_new` exists to protect whenever the open failed
535    /// differently.
536    #[test]
537    fn an_open_that_fails_oddly_removes_nothing() {
538        let directory = scratch("eloop");
539        let path = directory.join("config.json");
540
541        // A symlink pointing at itself: `open` fails with ELOOP, not
542        // AlreadyExists.
543        std::os::unix::fs::symlink(&path, &path).unwrap();
544
545        let mut section = Dict::new();
546        section.insert("host".to_owned(), Value::from("localhost"));
547
548        assert!(save_new(&BTree(section), &path, Format::Json, "db").is_err());
549
550        assert!(
551            path.symlink_metadata().is_ok(),
552            "whatever was at the path must survive an open failure"
553        );
554    }
555
556    /// `save_new` takes a `Serialize`; the permission tests work in `Dict`s.
557    struct BTree(Dict);
558
559    impl serde::Serialize for BTree {
560        fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
561            use serde::ser::SerializeMap;
562
563            let mut map = serializer.serialize_map(Some(self.0.len()))?;
564
565            for (key, value) in &self.0 {
566                map.serialize_entry(key, value)?;
567            }
568
569            map.end()
570        }
571    }
572
573    #[test]
574    fn a_failed_write_leaves_no_temporary_file_behind() {
575        let directory = scratch("cleanup");
576        // A directory where the target's parent does not exist: the create
577        // fails, and the question is whether anything is left over.
578        let path = directory.join("missing").join("config.json");
579
580        let mut section = Dict::new();
581        section.insert("host".to_owned(), Value::from("localhost"));
582
583        assert!(save_dict(&section, &path, Format::Json, "db").is_err());
584
585        let leftovers: Vec<_> = fs::read_dir(&directory)
586            .unwrap()
587            .filter_map(Result::ok)
588            .map(|entry| entry.file_name())
589            .collect();
590
591        assert!(leftovers.is_empty(), "{leftovers:?}");
592    }
593}