Skip to main content

sapphire_framework_settings/
store.rs

1//! Writing settings: validated, all-or-nothing batches that keep the files' comments.
2
3use std::collections::BTreeMap;
4use std::io::Write;
5use std::path::{Path, PathBuf};
6use std::sync::atomic::{AtomicU64, Ordering};
7
8use sapphire_bridge_api::settings::{Apply, Kind, Scope, SettingDef, Value};
9use toml_edit::DocumentMut;
10
11use crate::owner::{SettingsOwner, Staged};
12use crate::{Error, Registry, Result};
13
14/// One change in a batch.
15#[derive(Clone, Debug, PartialEq)]
16pub enum Op {
17    /// Set `key` to `value`.
18    Set {
19        /// The key.
20        key: String,
21        /// The new value.
22        value: Value,
23    },
24    /// Remove `key`; a prefix removes every key under it that the target scope allows.
25    Unset {
26        /// The key, or a prefix of several keys.
27        key: String,
28    },
29}
30
31/// What a batch changed.
32#[derive(Clone, Debug, Default, PartialEq, Eq)]
33pub struct Applied {
34    /// The concrete keys the batch touched (prefixes expanded).
35    pub keys: Vec<String>,
36    /// Whether any touched key only takes effect after a restart.
37    pub restart: bool,
38    /// Whether any touched key takes effect live.
39    pub live: bool,
40}
41
42/// What to do with a secret's file once the batch is validated.
43enum SecretEdit {
44    Write(String),
45    Remove,
46}
47
48/// A batch that passed every check: the edited files and secrets, not yet written.
49struct Checks {
50    applied: Applied,
51    staged: Staged,
52    secrets: BTreeMap<PathBuf, SecretEdit>,
53}
54
55/// Apply `ops` to the scope files, all or nothing.
56///
57/// `scope: None` targets each key's home scope; `Some(s)` must be allowed for every key.
58/// Every op is checked and every touched owner validates the edited files before anything
59/// is written; then the files are written atomically, then the secrets.
60pub fn apply(reg: &Registry, scope: Option<Scope>, ops: Vec<Op>) -> Result<Applied> {
61    let Checks {
62        applied,
63        staged,
64        secrets,
65    } = run_checks(reg, scope, ops)?;
66    for (path, text) in &staged.files {
67        write_atomic(path, text)?;
68    }
69    for (path, edit) in &secrets {
70        match edit {
71            SecretEdit::Write(text) => write_private(path, text)?,
72            SecretEdit::Remove => match std::fs::remove_file(path) {
73                Err(e) if e.kind() != std::io::ErrorKind::NotFound => return Err(e.into()),
74                _ => {}
75            },
76        }
77    }
78    Ok(applied)
79}
80
81/// Everything [`apply`] does up to and including the owners' `validate`, writing nothing:
82/// the same `Applied`, or the same error, that `apply` would produce.
83pub fn check(reg: &Registry, scope: Option<Scope>, ops: Vec<Op>) -> Result<Applied> {
84    run_checks(reg, scope, ops).map(|checked| checked.applied)
85}
86
87/// The shared part of [`apply`] and [`check`].
88fn run_checks(reg: &Registry, scope: Option<Scope>, ops: Vec<Op>) -> Result<Checks> {
89    let mut applied = Applied::default();
90    let mut docs: BTreeMap<PathBuf, DocumentMut> = BTreeMap::new();
91    let mut secrets: BTreeMap<PathBuf, SecretEdit> = BTreeMap::new();
92    let mut owners: Vec<&dyn SettingsOwner> = Vec::new();
93
94    for op in ops {
95        let targets: Vec<(&SettingDef, &dyn SettingsOwner, Scope)> = match &op {
96            Op::Set { key, .. } => {
97                let (def, owner) = reg.def(key)?;
98                vec![(def, owner, target_scope(def, scope)?)]
99            }
100            Op::Unset { key } => expand(reg, scope, key)?,
101        };
102        for (def, owner, target) in targets {
103            if !owners.iter().any(|o| std::ptr::addr_eq(*o, owner)) {
104                owners.push(owner);
105            }
106            match &op {
107                Op::Set { value, .. } => {
108                    def.kind
109                        .check(value)
110                        .map_err(|message| Error::InvalidValue {
111                            key: def.key.clone(),
112                            message,
113                        })?;
114                    if def.kind == Kind::Secret {
115                        let text = match value {
116                            Value::String(s) if !s.trim().is_empty() => s.clone(),
117                            _ => {
118                                return Err(Error::InvalidValue {
119                                    key: def.key.clone(),
120                                    message: "a secret must be a non-empty string".into(),
121                                });
122                            }
123                        };
124                        secrets.insert(owner.secret_file(&def.key)?, SecretEdit::Write(text));
125                    } else {
126                        let doc = load(&mut docs, &owner.file(target)?, true)?.expect("created");
127                        set(doc, &def.key, value)?;
128                    }
129                }
130                Op::Unset { .. } => {
131                    if def.kind == Kind::Secret {
132                        secrets.insert(owner.secret_file(&def.key)?, SecretEdit::Remove);
133                    } else if let Some(doc) = load(&mut docs, &owner.file(target)?, false)? {
134                        unset(doc, &def.key);
135                    }
136                }
137            }
138            if !applied.keys.contains(&def.key) {
139                applied.keys.push(def.key.clone());
140            }
141            match def.apply {
142                Apply::Restart => applied.restart = true,
143                Apply::Live => applied.live = true,
144            }
145        }
146    }
147
148    let staged = Staged {
149        files: docs
150            .iter()
151            .map(|(p, d)| (p.clone(), d.to_string()))
152            .collect(),
153    };
154    for owner in owners {
155        owner.validate(&staged).map_err(Error::Rejected)?;
156    }
157
158    Ok(Checks {
159        applied,
160        staged,
161        secrets,
162    })
163}
164
165/// The scope a key is written in: the requested one if the key allows it, else (with none
166/// requested) its home.
167fn target_scope(def: &SettingDef, scope: Option<Scope>) -> Result<Scope> {
168    let target = scope.unwrap_or_else(|| def.home());
169    if def.allows(target) {
170        Ok(target)
171    } else {
172        Err(Error::ScopeNotAllowed {
173            key: def.key.clone(),
174            scope: target,
175            allowed: def.scopes.clone(),
176        })
177    }
178}
179
180/// The keys an `Unset` of `key` removes, each with its owner and target scope.
181fn expand<'a>(
182    reg: &'a Registry,
183    scope: Option<Scope>,
184    key: &str,
185) -> Result<Vec<(&'a SettingDef, &'a dyn SettingsOwner, Scope)>> {
186    if let Ok((def, owner)) = reg.def(key) {
187        return Ok(vec![(def, owner, target_scope(def, scope)?)]);
188    }
189    let under = reg.under(key);
190    if under.is_empty() {
191        return Err(Error::UnknownKey(key.to_string()));
192    }
193    let chosen: Vec<&SettingDef> = match scope {
194        Some(s) => under.into_iter().filter(|d| d.allows(s)).collect(),
195        None => under,
196    };
197    if chosen.is_empty() {
198        // Nothing under the prefix may live in that scope; name the scopes that could.
199        let first = reg.under(key)[0];
200        return Err(Error::ScopeNotAllowed {
201            key: key.to_string(),
202            scope: scope.unwrap_or_else(|| first.home()),
203            allowed: first.scopes.clone(),
204        });
205    }
206    let target = match scope {
207        Some(s) => s,
208        None => {
209            let home = chosen[0].home();
210            if chosen.iter().any(|d| d.home() != home) {
211                return Err(Error::InvalidValue {
212                    key: key.to_string(),
213                    message: "keys under it live in more than one scope; \
214                              name one with --device or --workgroup"
215                        .into(),
216                });
217            }
218            home
219        }
220    };
221    chosen
222        .into_iter()
223        .map(|def| Ok((def, reg.def(&def.key)?.1, target)))
224        .collect()
225}
226
227/// The editable document of `path`, loaded once. An absent file is an empty document if
228/// `create`, else `None`.
229fn load<'a>(
230    docs: &'a mut BTreeMap<PathBuf, DocumentMut>,
231    path: &Path,
232    create: bool,
233) -> Result<Option<&'a mut DocumentMut>> {
234    if !docs.contains_key(path) {
235        let doc = match std::fs::read_to_string(path) {
236            Ok(text) => text.parse::<DocumentMut>().map_err(|e| Error::Unparsable {
237                file: path.to_path_buf(),
238                message: crate::describe_toml_error(&text, e.span(), e.message()),
239            })?,
240            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
241                if !create {
242                    return Ok(None);
243                }
244                DocumentMut::new()
245            }
246            Err(e) => return Err(e.into()),
247        };
248        docs.insert(path.to_path_buf(), doc);
249    }
250    Ok(docs.get_mut(path))
251}
252
253fn to_edit(value: &Value) -> toml_edit::Value {
254    match value {
255        Value::Bool(b) => (*b).into(),
256        Value::Int(i) => (*i).into(),
257        Value::String(s) => s.as_str().into(),
258        Value::List(items) => items
259            .iter()
260            .map(to_edit)
261            .collect::<toml_edit::Array>()
262            .into(),
263    }
264}
265
266/// Set `key` in `doc`, creating the tables on its path and keeping an old value's
267/// surrounding comments and spacing.
268fn set(doc: &mut DocumentMut, key: &str, value: &Value) -> Result<()> {
269    let mut segments: Vec<&str> = key.split('.').collect();
270    let last = segments.pop().unwrap_or_default();
271    let mut table: &mut dyn toml_edit::TableLike = doc.as_table_mut();
272    for segment in segments {
273        if !table.contains_key(segment) {
274            let mut new = toml_edit::Table::new();
275            new.set_implicit(true);
276            table.insert(segment, toml_edit::Item::Table(new));
277        }
278        table = table
279            .get_mut(segment)
280            .and_then(toml_edit::Item::as_table_like_mut)
281            .ok_or_else(|| Error::InvalidValue {
282                key: key.to_string(),
283                message: format!("`{segment}` is already a value, not a table"),
284            })?;
285    }
286    let mut new = to_edit(value);
287    // Replaced in place, so the key keeps its own decor (a comment above it) too.
288    if let Some(old) = table.get_mut(last).and_then(toml_edit::Item::as_value_mut) {
289        *new.decor_mut() = old.decor().clone();
290        *old = new;
291    } else {
292        table.insert(last, toml_edit::Item::Value(new));
293    }
294    Ok(())
295}
296
297/// Remove `key` from `doc` and the tables it leaves empty.
298fn unset(doc: &mut DocumentMut, key: &str) {
299    fn go(table: &mut dyn toml_edit::TableLike, segments: &[&str]) {
300        match segments {
301            [] => {}
302            [last] => {
303                table.remove(last);
304            }
305            [head, rest @ ..] => {
306                if let Some(child) = table
307                    .get_mut(head)
308                    .and_then(toml_edit::Item::as_table_like_mut)
309                {
310                    go(child, rest);
311                    if child.is_empty() {
312                        table.remove(head);
313                    }
314                }
315            }
316        }
317    }
318    let segments: Vec<&str> = key.split('.').collect();
319    go(doc.as_table_mut(), &segments);
320}
321
322/// Write `text` to `path` through a temp file and a rename, creating the directory.
323///
324/// A file already at `path` keeps its permissions (its mode on unix, its read-only flag
325/// elsewhere): the file may be shared with what an application keeps there, tokens
326/// included.
327pub fn write_atomic(path: &Path, text: &str) -> std::io::Result<()> {
328    write_file(path, text, false)
329}
330
331/// Like [`write_atomic`], but the file is readable by its owner only (0600 on unix).
332pub fn write_private(path: &Path, text: &str) -> std::io::Result<()> {
333    write_file(path, text, true)
334}
335
336/// The temp file a write of `path` goes through, beside it: its own for every call, so two
337/// writes never share one, and a stale one left by a crash is never reopened — its mode
338/// would otherwise carry over to the file it replaces.
339fn temp_path(path: &Path) -> PathBuf {
340    static NEXT: AtomicU64 = AtomicU64::new(0);
341    let parent = path.parent().unwrap_or_else(|| Path::new("."));
342    parent.join(format!(
343        "{}.tmp.{}.{}",
344        path.file_name().and_then(|n| n.to_str()).unwrap_or("file"),
345        std::process::id(),
346        NEXT.fetch_add(1, Ordering::Relaxed)
347    ))
348}
349
350fn write_file(path: &Path, text: &str, private: bool) -> std::io::Result<()> {
351    let parent = path.parent().unwrap_or_else(|| Path::new("."));
352    std::fs::create_dir_all(parent)?;
353    // A private file is owner-only whatever it was; any other keeps what it had.
354    let keep = if private {
355        None
356    } else {
357        match std::fs::metadata(path) {
358            Ok(meta) => Some(meta.permissions()),
359            Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
360            Err(e) => return Err(e),
361        }
362    };
363    let tmp = temp_path(path);
364    let written = (|| {
365        let mut options = std::fs::OpenOptions::new();
366        options.write(true).create_new(true);
367        #[cfg(unix)]
368        if private {
369            use std::os::unix::fs::OpenOptionsExt;
370            options.mode(0o600);
371        }
372        let mut file = options.open(&tmp)?;
373        // On unix before the text goes in, so it is never readable more widely than the
374        // file it replaces.
375        #[cfg(unix)]
376        if let Some(perms) = &keep {
377            file.set_permissions(perms.clone())?;
378        }
379        file.write_all(text.as_bytes())?;
380        file.sync_all()?;
381        drop(file);
382        // Elsewhere after it is closed: a read-only flag set first would refuse the write.
383        #[cfg(not(unix))]
384        if let Some(perms) = keep {
385            std::fs::set_permissions(&tmp, perms)?;
386        }
387        std::fs::rename(&tmp, path)
388    })();
389    written.inspect_err(|_| {
390        let _ = std::fs::remove_file(&tmp);
391    })
392}
393
394#[cfg(test)]
395mod tests {
396    use super::*;
397    use crate::owner::FieldError;
398    use crate::owner::test_support::{TestOwner, def};
399    use std::sync::Arc;
400
401    #[test]
402    fn every_write_gets_its_own_temp_file() {
403        let path = Path::new("/x/config.toml");
404        let (a, b) = (temp_path(path), temp_path(path));
405        assert_ne!(a, b);
406        assert_eq!(a.parent(), path.parent());
407        let name = a.file_name().unwrap().to_str().unwrap();
408        assert!(name.starts_with("config.toml.tmp."), "{name}");
409    }
410
411    #[cfg(unix)]
412    #[test]
413    fn a_write_keeps_the_files_permissions() {
414        use std::os::unix::fs::PermissionsExt;
415        let dir = tempfile::tempdir().unwrap();
416        let path = dir.path().join("config.toml");
417        std::fs::write(&path, "a = 1\n").unwrap();
418        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap();
419        write_atomic(&path, "a = 2\n").unwrap();
420        assert_eq!(std::fs::read_to_string(&path).unwrap(), "a = 2\n");
421        let mode = std::fs::metadata(&path).unwrap().permissions().mode();
422        assert_eq!(mode & 0o777, 0o600);
423        // A new file takes the usual mode, not the last one's.
424        let fresh = dir.path().join("fresh.toml");
425        write_atomic(&fresh, "").unwrap();
426        let mode = std::fs::metadata(&fresh).unwrap().permissions().mode();
427        assert_ne!(mode & 0o777, 0o600, "{mode:o}");
428    }
429
430    #[test]
431    fn a_write_keeps_a_readonly_flag() {
432        let dir = tempfile::tempdir().unwrap();
433        let path = dir.path().join("config.toml");
434        std::fs::write(&path, "a = 1\n").unwrap();
435        let mut perms = std::fs::metadata(&path).unwrap().permissions();
436        perms.set_readonly(true);
437        std::fs::set_permissions(&path, perms).unwrap();
438        // Unix replaces a read-only file through its directory; Windows refuses to.
439        if write_atomic(&path, "a = 2\n").is_ok() {
440            assert!(std::fs::metadata(&path).unwrap().permissions().readonly());
441        }
442        let mut perms = std::fs::metadata(&path).unwrap().permissions();
443        #[allow(clippy::permissions_set_readonly_false)]
444        perms.set_readonly(false);
445        std::fs::set_permissions(&path, perms).unwrap();
446    }
447
448    /// A test owner whose `validate` rejects `a.max < a.min` in the workgroup file.
449    struct Checked(TestOwner);
450
451    impl SettingsOwner for Checked {
452        fn defs(&self) -> Vec<SettingDef> {
453            self.0.defs()
454        }
455        fn file(&self, scope: Scope) -> Result<PathBuf> {
456            self.0.file(scope)
457        }
458        fn secret_file(&self, key: &str) -> Result<PathBuf> {
459            self.0.secret_file(key)
460        }
461        fn validate(&self, staged: &Staged) -> std::result::Result<(), Vec<FieldError>> {
462            let path = self.0.file(Scope::Workgroup).unwrap();
463            let text = staged.read(&path).unwrap().unwrap_or_default();
464            let table: toml::Table = text.parse().unwrap();
465            let get = |k: &str| table.get("a")?.get(k)?.as_integer();
466            match (get("min"), get("max")) {
467                (Some(min), Some(max)) if max < min => Err(vec![FieldError {
468                    key: Some("a.max".into()),
469                    file: None,
470                    message: "max is below min".into(),
471                }]),
472                _ => Ok(()),
473            }
474        }
475    }
476
477    fn int() -> Kind {
478        Kind::Int { min: 0, max: 100 }
479    }
480
481    fn setup(defs: Vec<SettingDef>) -> (Arc<Checked>, Registry) {
482        let owner = Arc::new(Checked(TestOwner::new(defs)));
483        let reg = Registry::new(vec![owner.clone() as Arc<dyn SettingsOwner>], &[]).unwrap();
484        (owner, reg)
485    }
486
487    fn set_op(key: &str, value: Value) -> Op {
488        Op::Set {
489            key: key.into(),
490            value,
491        }
492    }
493
494    fn unset_op(key: &str) -> Op {
495        Op::Unset { key: key.into() }
496    }
497
498    fn wg(owner: &Checked) -> PathBuf {
499        owner.0.dir.path().join("wg.toml")
500    }
501
502    fn dev(owner: &Checked) -> PathBuf {
503        owner.0.dir.path().join("dev.toml")
504    }
505
506    #[test]
507    fn set_keeps_comments_and_order() {
508        let (owner, reg) = setup(vec![def("net.discovery", Kind::Bool)]);
509        let before = "# mine\n[net]\n# relays\nrelays = []\n# found\ndiscovery = true # on\n";
510        owner.0.write("wg.toml", before);
511        apply(
512            &reg,
513            None,
514            vec![set_op("net.discovery", Value::Bool(false))],
515        )
516        .unwrap();
517        let after = std::fs::read_to_string(wg(&owner)).unwrap();
518        assert_eq!(after, before.replace("true", "false"));
519    }
520
521    #[test]
522    fn set_creates_missing_tables_and_the_file() {
523        let (owner, reg) = setup(vec![def("a.b.c", int())]);
524        apply(&reg, None, vec![set_op("a.b.c", Value::Int(3))]).unwrap();
525        let table: toml::Table = std::fs::read_to_string(wg(&owner))
526            .unwrap()
527            .parse()
528            .unwrap();
529        assert_eq!(table["a"]["b"]["c"].as_integer(), Some(3));
530    }
531
532    #[test]
533    fn lists_are_written_as_inline_arrays() {
534        let kind = Kind::List {
535            item: Box::new(Kind::Url),
536        };
537        let (owner, reg) = setup(vec![def("net.relays", kind)]);
538        let list = Value::List(vec![Value::String("https://r".into())]);
539        apply(&reg, None, vec![set_op("net.relays", list)]).unwrap();
540        let text = std::fs::read_to_string(wg(&owner)).unwrap();
541        assert!(text.contains("relays = [\"https://r\"]"), "{text}");
542    }
543
544    #[test]
545    fn unset_removes_the_key_and_empty_tables() {
546        let (owner, reg) = setup(vec![def("a.b.c", int())]);
547        owner.0.write("wg.toml", "[a.b]\nc = 1\n");
548        apply(&reg, None, vec![unset_op("a.b.c")]).unwrap();
549        assert_eq!(std::fs::read_to_string(wg(&owner)).unwrap().trim(), "");
550    }
551
552    #[test]
553    fn unsetting_in_an_absent_file_creates_nothing() {
554        let (owner, reg) = setup(vec![def("a.b", int())]);
555        apply(&reg, None, vec![unset_op("a.b")]).unwrap();
556        assert!(!wg(&owner).exists());
557    }
558
559    fn remote_defs() -> Vec<SettingDef> {
560        let mut enabled = def("embed.remote.enabled", Kind::Bool);
561        enabled.scopes = vec![Scope::Device];
562        vec![enabled, def("embed.remote.endpoint", Kind::Url)]
563    }
564
565    #[test]
566    fn a_prefix_unset_removes_only_the_target_scopes_keys() {
567        let (owner, reg) = setup(remote_defs());
568        owner
569            .0
570            .write("dev.toml", "[embed.remote]\nenabled = false\n");
571        owner
572            .0
573            .write("wg.toml", "[embed.remote]\nendpoint = \"https://x\"\n");
574        let applied = apply(&reg, Some(Scope::Workgroup), vec![unset_op("embed.remote")]).unwrap();
575        assert_eq!(applied.keys, ["embed.remote.endpoint"]);
576        assert_eq!(
577            std::fs::read_to_string(dev(&owner)).unwrap(),
578            "[embed.remote]\nenabled = false\n"
579        );
580        assert_eq!(std::fs::read_to_string(wg(&owner)).unwrap().trim(), "");
581    }
582
583    #[test]
584    fn a_prefix_unset_across_scopes_needs_a_scope() {
585        let (owner, reg) = setup(remote_defs());
586        owner
587            .0
588            .write("dev.toml", "[embed.remote]\nenabled = false\n");
589        let err = apply(&reg, None, vec![unset_op("embed.remote")]).unwrap_err();
590        assert!(matches!(err, Error::InvalidValue { .. }), "{err:?}");
591        assert!(err.to_string().contains("--workgroup"));
592        assert_eq!(
593            std::fs::read_to_string(dev(&owner)).unwrap(),
594            "[embed.remote]\nenabled = false\n"
595        );
596    }
597
598    #[test]
599    fn an_unknown_prefix_is_an_unknown_key() {
600        let (_owner, reg) = setup(remote_defs());
601        let err = apply(&reg, None, vec![unset_op("nope")]).unwrap_err();
602        assert!(matches!(err, Error::UnknownKey(_)));
603    }
604
605    #[test]
606    fn a_rejected_batch_writes_nothing() {
607        let (owner, reg) = setup(vec![def("a.min", int()), def("a.max", int())]);
608        let before = "# keep\n[a]\nmin = 1\nmax = 9\n";
609        owner.0.write("wg.toml", before);
610        let err = apply(
611            &reg,
612            None,
613            vec![
614                set_op("a.min", Value::Int(10)),
615                set_op("a.max", Value::Int(5)),
616            ],
617        )
618        .unwrap_err();
619        assert!(matches!(err, Error::Rejected(_)), "{err:?}");
620        assert_eq!(std::fs::read_to_string(wg(&owner)).unwrap(), before);
621        assert!(!dev(&owner).exists());
622    }
623
624    #[test]
625    fn a_disallowed_scope_names_the_allowed_ones() {
626        let (_owner, reg) = setup(vec![def("a.min", int())]);
627        let err = apply(
628            &reg,
629            Some(Scope::Device),
630            vec![set_op("a.min", Value::Int(1))],
631        )
632        .unwrap_err();
633        match &err {
634            Error::ScopeNotAllowed { allowed, .. } => {
635                assert_eq!(allowed, &[Scope::Workgroup]);
636            }
637            other => panic!("{other:?}"),
638        }
639        assert!(err.to_string().contains("workgroup"));
640    }
641
642    #[test]
643    fn a_value_of_the_wrong_kind_is_refused() {
644        let (_owner, reg) = setup(vec![def("a.min", int())]);
645        let err = apply(&reg, None, vec![set_op("a.min", Value::String("x".into()))]).unwrap_err();
646        assert!(matches!(err, Error::InvalidValue { .. }));
647    }
648
649    #[test]
650    fn an_unparsable_file_is_named_by_line_not_quoted() {
651        let (owner, reg) = setup(vec![def("a.min", int())]);
652        owner.0.write("wg.toml", "a = 1\ntoken = \"hunter2\" x\n");
653        let err = apply(&reg, None, vec![set_op("a.min", Value::Int(1))])
654            .unwrap_err()
655            .to_string();
656        assert!(err.contains("line 2"), "{err}");
657        assert!(!err.contains("hunter2"), "{err}");
658    }
659
660    #[test]
661    fn an_unparsable_file_is_not_overwritten() {
662        let (owner, reg) = setup(vec![def("a.min", int())]);
663        owner.0.write("wg.toml", "[[[");
664        let err = apply(&reg, None, vec![set_op("a.min", Value::Int(1))]).unwrap_err();
665        assert!(matches!(err, Error::Unparsable { .. }));
666        assert_eq!(std::fs::read_to_string(wg(&owner)).unwrap(), "[[[");
667    }
668
669    #[test]
670    fn secrets_are_written_private_and_deleted_on_unset() {
671        let mut secret = def("embed.remote.token", Kind::Secret);
672        secret.scopes = vec![Scope::Device];
673        let (owner, reg) = setup(vec![secret]);
674        let path = owner.0.dir.path().join("secret-embed.remote.token");
675
676        // Unsetting an absent secret is fine.
677        apply(&reg, None, vec![unset_op("embed.remote.token")]).unwrap();
678
679        let empty = apply(
680            &reg,
681            None,
682            vec![set_op("embed.remote.token", Value::String(" ".into()))],
683        );
684        assert!(matches!(empty, Err(Error::InvalidValue { .. })));
685        assert!(!path.exists());
686
687        apply(
688            &reg,
689            None,
690            vec![set_op(
691                "embed.remote.token",
692                Value::String("hunter2".into()),
693            )],
694        )
695        .unwrap();
696        assert_eq!(std::fs::read_to_string(&path).unwrap(), "hunter2");
697        #[cfg(unix)]
698        {
699            use std::os::unix::fs::PermissionsExt;
700            let mode = std::fs::metadata(&path).unwrap().permissions().mode();
701            assert_eq!(mode & 0o777, 0o600);
702        }
703
704        apply(&reg, None, vec![unset_op("embed.remote.token")]).unwrap();
705        assert!(!path.exists());
706    }
707
708    #[test]
709    fn check_writes_nothing_and_reports_what_apply_would() {
710        let (owner, reg) = setup(vec![def("a.min", int())]);
711        let ops = || vec![set_op("a.min", Value::Int(3))];
712        let checked = check(&reg, None, ops()).unwrap();
713        assert!(!wg(&owner).exists());
714        let applied = apply(&reg, None, ops()).unwrap();
715        assert_eq!(checked, applied);
716        assert!(wg(&owner).exists());
717    }
718
719    #[test]
720    fn check_reports_the_same_errors() {
721        let (owner, reg) = setup(vec![def("a.min", int()), def("a.max", int())]);
722        let wrong = || vec![set_op("a.min", Value::String("x".into()))];
723        let (c, a) = (
724            check(&reg, None, wrong()).unwrap_err(),
725            apply(&reg, None, wrong()).unwrap_err(),
726        );
727        assert_eq!(c.to_string(), a.to_string());
728        let rejected = || {
729            vec![
730                set_op("a.min", Value::Int(10)),
731                set_op("a.max", Value::Int(5)),
732            ]
733        };
734        let (c, a) = (
735            check(&reg, None, rejected()).unwrap_err(),
736            apply(&reg, None, rejected()).unwrap_err(),
737        );
738        assert!(matches!(c, Error::Rejected(_)));
739        assert_eq!(c.to_string(), a.to_string());
740        assert!(!wg(&owner).exists());
741    }
742
743    #[test]
744    fn applied_reports_restart_and_live() {
745        let mut restart = def("a.r", int());
746        restart.apply = Apply::Restart;
747        let (_owner, reg) = setup(vec![restart, def("a.l", int())]);
748        let live = apply(&reg, None, vec![set_op("a.l", Value::Int(1))]).unwrap();
749        assert_eq!((live.restart, live.live), (false, true));
750        let both = apply(
751            &reg,
752            None,
753            vec![set_op("a.l", Value::Int(1)), set_op("a.r", Value::Int(2))],
754        )
755        .unwrap();
756        assert_eq!(both.keys, ["a.l", "a.r"]);
757        assert_eq!((both.restart, both.live), (true, true));
758    }
759}