Skip to main content

sapphire_framework_server/
settings.rs

1//! The app server's settings (#314): the framework's keys and the application's, in one
2//! registry.
3//!
4//! The framework owns `http.*` and `update.check`, all on the device and all read once at
5//! start. The application owns the keys under its own name, on the device or in the
6//! workspace; it says what they are ([`AppSettings`]) and the framework says where they
7//! live:
8//!
9//! | Scope | File |
10//! |---|---|
11//! | Device | `<config dir>/config.toml` |
12//! | Workspace | `{root}/.{app}/config.toml`, of the workspace selected at the time |
13//! | Secrets | `<config dir>/secrets/<key>`, owner-only |
14//!
15//! The device's file is the application's own `config.toml` too: the framework reads and
16//! checks only its own tables (`[http]`, `[update]`) and the application's keys, and a
17//! write changes only the keys it names, leaving everything else in the file as it was.
18//!
19//! `config.toml` replaces `server.toml`, whose layout it keeps: [`migrate`] moves the old
20//! file's tables over once.
21
22use std::collections::BTreeMap;
23use std::path::{Path, PathBuf};
24use std::sync::{Arc, RwLock};
25
26use sapphire_framework_settings::{
27    Apply, FieldError, Kind, Process, Registry, Scope, SettingDef, SettingsOwner, Staged,
28    StartState, Value,
29};
30use sapphire_workspace::AppContext;
31use tokio::sync::watch;
32
33use crate::config::{MCP_MOVED, SERVER_CONFIG_FILE};
34use crate::error::{Error, Result};
35use crate::selection::SelectionFile;
36
37/// The file `config.toml` replaces, and what it is renamed to once migrated.
38const OLD_CONFIG_FILE: &str = "server.toml";
39const OLD_CONFIG_BACKUP: &str = "server.toml.v1";
40
41/// What `workspace()` says with no workspace to put the file in.
42const NO_WORKSPACE: &str = "no workspace is selected";
43
44/// Top-level names the framework keeps for itself, whether or not it defines keys there.
45const FRAMEWORK_NAMES: [&str; 5] = ["http", "update", "sync", "retrieve", "workspace"];
46
47/// The framework's tables the device file is checked under: the names it defines keys in.
48/// Every other name in the file is the application's business (an application keeps its
49/// own `[workspace]` there, say).
50const CHECKED_NAMES: [&str; 2] = ["http", "update"];
51
52/// The bridge's top-level names: owned by no one here, so no key of this server takes them.
53pub(crate) const BRIDGE_NAMES: [&str; 3] = ["net", "embed", "gui"];
54
55/// An application's own settings: what they are, and a check of the edited files as a
56/// whole.
57///
58/// Every key starts with the application's name and a dot, lives on the device or in the
59/// workspace (not in the workgroup), and a secret lives on the device only. Where the files
60/// are is the framework's business. `()` is an application with no settings of its own.
61pub trait AppSettings: Send + Sync + 'static {
62    /// The application's settings, in the order a listing shows them.
63    fn defs(&self) -> Vec<SettingDef>;
64
65    /// Check the edited files as a whole, before anything is written; also run once when
66    /// the server starts, against the files as they are.
67    ///
68    /// `files` says where the application's files are; `staged.read(path)` gives a file as
69    /// the write would leave it, falling back to what is on disk for a file the write does
70    /// not touch.
71    fn validate(
72        &self,
73        _files: &AppFiles,
74        _staged: &Staged,
75    ) -> std::result::Result<(), Vec<FieldError>> {
76        Ok(())
77    }
78}
79
80/// Where an application's settings files are, for [`AppSettings::validate`].
81#[derive(Clone, Debug, PartialEq, Eq)]
82pub struct AppFiles {
83    device: PathBuf,
84    workspace: Option<PathBuf>,
85}
86
87impl AppFiles {
88    /// The device's file, `<config dir>/config.toml`.
89    pub fn device(&self) -> &Path {
90        &self.device
91    }
92
93    /// The selected workspace's file, `{root}/.{app}/config.toml`; `None` when no
94    /// workspace is selected.
95    pub fn workspace(&self) -> Option<&Path> {
96        self.workspace.as_deref()
97    }
98}
99
100impl AppSettings for () {
101    fn defs(&self) -> Vec<SettingDef> {
102        Vec::new()
103    }
104}
105
106/// Where the app server's settings live.
107#[derive(Clone, Debug)]
108pub(crate) struct SettingsFiles {
109    config_dir: PathBuf,
110    app_name: &'static str,
111    selection: SelectionFile,
112}
113
114impl SettingsFiles {
115    /// `ctx`'s application's files; an error while its config directory is unresolved.
116    #[cfg(test)]
117    pub(crate) fn for_app(ctx: &AppContext) -> Result<SettingsFiles> {
118        SettingsFiles::with_selection(ctx, SelectionFile::for_app(ctx))
119    }
120
121    /// [`for_app`](Self::for_app), with the selected workspace read from `selection`: the
122    /// server's own, where a fixture moved it.
123    pub(crate) fn with_selection(
124        ctx: &AppContext,
125        selection: SelectionFile,
126    ) -> Result<SettingsFiles> {
127        let config_dir = ctx.try_config_dir().ok_or_else(|| {
128            Error::Config(format!(
129                "{} has no config directory, so no settings",
130                ctx.app_name
131            ))
132        })?;
133        Ok(SettingsFiles {
134            config_dir: config_dir.to_path_buf(),
135            app_name: ctx.app_name,
136            selection,
137        })
138    }
139
140    /// The device's file.
141    pub(crate) fn device(&self) -> PathBuf {
142        self.config_dir.join(SERVER_CONFIG_FILE)
143    }
144
145    /// The selected workspace's file, as the selection is now: a selection that changes
146    /// moves the workspace scope with it.
147    pub(crate) fn workspace(&self) -> Result<PathBuf> {
148        match self.selection.load(self.app_name)? {
149            Some(selection) => Ok(selection
150                .root
151                .join(format!(".{}", self.app_name))
152                .join("config.toml")),
153            None => Err(Error::Config(NO_WORKSPACE.to_owned())),
154        }
155    }
156
157    /// The application's files, as its `validate` is told them now.
158    fn app_files(&self) -> AppFiles {
159        AppFiles {
160            device: self.device(),
161            workspace: self.workspace().ok(),
162        }
163    }
164
165    /// The owner-only file of the secret `key`.
166    pub(crate) fn secret(&self, key: &str) -> PathBuf {
167        self.config_dir.join("secrets").join(key)
168    }
169
170    /// The file of `scope`, as an owner answers it.
171    fn scope_file(&self, scope: Scope) -> sapphire_framework_settings::Result<PathBuf> {
172        match scope {
173            Scope::Device => Ok(self.device()),
174            Scope::Workspace => self
175                .workspace()
176                .map_err(|e| std::io::Error::other(e.to_string()).into()),
177            Scope::Workgroup => Err(std::io::Error::other(format!(
178                "the {} server has no workgroup scope",
179                self.app_name
180            ))
181            .into()),
182        }
183    }
184}
185
186/// The framework's settings, in the order a listing shows them.
187fn framework_defs() -> Vec<SettingDef> {
188    let def = |key: &str, kind: Kind, default: Option<Value>, doc: &str| SettingDef {
189        key: key.into(),
190        kind,
191        scopes: vec![Scope::Device],
192        overridable: false,
193        apply: Apply::Restart,
194        default,
195        section: "Server".into(),
196        doc: doc.into(),
197        process: Process::App,
198    };
199    vec![
200        def(
201            "http.listen",
202            Kind::SocketAddr,
203            None,
204            "Where the HTTP listener binds; unset = the application's default address",
205        ),
206        def(
207            "http.allowed_hosts",
208            Kind::List {
209                item: Box::new(Kind::String { non_empty: true }),
210            },
211            None,
212            "The Host names clients reach the server by, beyond loopback",
213        ),
214        def(
215            "http.mcp.enabled",
216            Kind::Bool,
217            Some(Value::Bool(false)),
218            "Serve the application's MCP tools at /mcp, behind an external device's token",
219        ),
220        def(
221            "http.metrics.enabled",
222            Kind::Bool,
223            Some(Value::Bool(false)),
224            "Serve Prometheus metrics at /metrics, without a token",
225        ),
226        def(
227            "update.check",
228            Kind::Bool,
229            Some(Value::Bool(true)),
230            "Look for newer releases of the application, at start and once a day",
231        ),
232    ]
233}
234
235/// The framework as a settings owner.
236struct FrameworkOwner {
237    files: SettingsFiles,
238}
239
240impl SettingsOwner for FrameworkOwner {
241    fn defs(&self) -> Vec<SettingDef> {
242        framework_defs()
243    }
244
245    fn file(&self, scope: Scope) -> sapphire_framework_settings::Result<PathBuf> {
246        self.files.scope_file(scope)
247    }
248
249    fn secret_file(&self, key: &str) -> sapphire_framework_settings::Result<PathBuf> {
250        Ok(self.files.secret(key))
251    }
252
253    fn validate(&self, staged: &Staged) -> std::result::Result<(), Vec<FieldError>> {
254        check_device_file(&self.files, staged)
255    }
256}
257
258/// The application as a settings owner, in the framework's files.
259struct AppOwner {
260    files: SettingsFiles,
261    app: Arc<dyn AppSettings>,
262}
263
264impl SettingsOwner for AppOwner {
265    fn defs(&self) -> Vec<SettingDef> {
266        self.app
267            .defs()
268            .into_iter()
269            .map(|def| SettingDef {
270                process: Process::App,
271                ..def
272            })
273            .collect()
274    }
275
276    fn file(&self, scope: Scope) -> sapphire_framework_settings::Result<PathBuf> {
277        self.files.scope_file(scope)
278    }
279
280    fn secret_file(&self, key: &str) -> sapphire_framework_settings::Result<PathBuf> {
281        Ok(self.files.secret(key))
282    }
283
284    fn validate(&self, staged: &Staged) -> std::result::Result<(), Vec<FieldError>> {
285        self.app.validate(&self.files.app_files(), staged)
286    }
287}
288
289/// The app server's registry: the framework (owner 0) and the application (owner 1).
290///
291/// An application key outside `<app_name>.`, or one the workgroup may hold, is
292/// [`InvalidDef`](sapphire_framework_settings::Error::InvalidDef).
293pub(crate) fn registry(
294    ctx: &AppContext,
295    files: &SettingsFiles,
296    app: Arc<dyn AppSettings>,
297) -> sapphire_framework_settings::Result<Registry> {
298    let prefix = format!("{}.", ctx.app_name);
299    for def in app.defs() {
300        let invalid = |message: String| sapphire_framework_settings::Error::InvalidDef {
301            key: def.key.clone(),
302            message,
303        };
304        if !def.key.starts_with(&prefix) {
305            return Err(invalid(format!(
306                "an application's key starts with `{prefix}`"
307            )));
308        }
309        if def.scopes.contains(&Scope::Workgroup) {
310            return Err(invalid(
311                "an application's key lives on the device or in the workspace, not in the workgroup"
312                    .to_owned(),
313            ));
314        }
315    }
316    // No owner has this index: the bridge's names are reserved against both.
317    const NO_OWNER: usize = usize::MAX;
318    let mut reserved: Vec<(&str, usize)> = FRAMEWORK_NAMES.iter().map(|n| (*n, 0)).collect();
319    reserved.push((ctx.app_name, 1));
320    reserved.extend(BRIDGE_NAMES.iter().map(|n| (*n, NO_OWNER)));
321    Registry::new(
322        vec![
323            Arc::new(FrameworkOwner {
324                files: files.clone(),
325            }),
326            Arc::new(AppOwner {
327                files: files.clone(),
328                app,
329            }),
330        ],
331        &reserved,
332    )
333}
334
335/// The device file's framework part: the old `[mcp]` table, unknown keys under `[http]` and
336/// `[update]`, and framework values of the wrong kind. Every other table — the
337/// application's own config shares the file — is left alone.
338///
339/// Values are never quoted back: the message names the key and the file only.
340fn check_device_file(
341    files: &SettingsFiles,
342    staged: &Staged,
343) -> std::result::Result<(), Vec<FieldError>> {
344    let path = files.device();
345    let failure = |key: Option<String>, message: String| FieldError {
346        key,
347        file: Some(path.clone()),
348        message,
349    };
350    let text = match staged.read(&path) {
351        Ok(Some(text)) => text,
352        Ok(None) => return Ok(()),
353        Err(e) => return Err(vec![failure(None, e.to_string())]),
354    };
355    let table = match text.parse::<toml::Table>() {
356        Ok(table) => table,
357        Err(e) => {
358            return Err(vec![failure(
359                None,
360                sapphire_framework_settings::describe_toml_error(&text, e.span(), e.message()),
361            )]);
362        }
363    };
364    let defs = framework_defs();
365    let mut errors = Vec::new();
366    for (name, item) in &table {
367        if name == "mcp" {
368            errors.push(failure(None, MCP_MOVED.to_owned()));
369        } else if CHECKED_NAMES.contains(&name.as_str()) {
370            let mut leaves = Vec::new();
371            leaves_of(name.clone(), item, &mut leaves);
372            for (key, value) in leaves {
373                let in_file = format!("in {}", path.display());
374                match defs.iter().find(|d| d.key == key) {
375                    None => errors.push(failure(Some(key), format!("unknown setting {in_file}"))),
376                    Some(def) => {
377                        if !accepts(&def.kind, value) {
378                            errors.push(failure(
379                                Some(key),
380                                format!("the value {in_file} is not a valid one"),
381                            ));
382                        }
383                    }
384                }
385            }
386        }
387    }
388    if errors.is_empty() {
389        Ok(())
390    } else {
391        Err(errors)
392    }
393}
394
395/// Every non-table value under `item`, by its dotted path.
396fn leaves_of<'a>(path: String, item: &'a toml::Value, out: &mut Vec<(String, &'a toml::Value)>) {
397    match item {
398        toml::Value::Table(table) => {
399            for (name, child) in table {
400                leaves_of(format!("{path}.{name}"), child, out);
401            }
402        }
403        other => out.push((path, other)),
404    }
405}
406
407/// Whether a TOML value is one `kind` accepts.
408fn accepts(kind: &Kind, value: &toml::Value) -> bool {
409    to_value(value).is_some_and(|v| kind.check(&v).is_ok())
410}
411
412/// A TOML value as a setting value; floats, datetimes and tables are none.
413fn to_value(value: &toml::Value) -> Option<Value> {
414    match value {
415        toml::Value::String(s) => Some(Value::String(s.clone())),
416        toml::Value::Integer(i) => Some(Value::Int(*i)),
417        toml::Value::Boolean(b) => Some(Value::Bool(*b)),
418        toml::Value::Array(items) => items
419            .iter()
420            .map(to_value)
421            .collect::<Option<_>>()
422            .map(Value::List),
423        _ => None,
424    }
425}
426
427/// Move `<config_dir>/server.toml` into `config.toml`, keeping the old file as
428/// `server.toml.v1`.
429///
430/// With no `config.toml`, the old file's text becomes it unchanged. With one — the
431/// application's own config shares the file — the old file's tables are merged in, the
432/// existing file's comments and content kept: a key it already has wins, with a warning
433/// naming the key. A rename that fails once the new file is written is a warning (the old
434/// file may be held open); the next start merges it again, changing nothing.
435pub(crate) fn migrate(config_dir: &Path) -> Result<()> {
436    let new = config_dir.join(SERVER_CONFIG_FILE);
437    let old = config_dir.join(OLD_CONFIG_FILE);
438    let text = match std::fs::read_to_string(&old) {
439        Ok(text) => text,
440        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
441        Err(e) => return Err(Error::Io(e)),
442    };
443    let merged = match std::fs::read_to_string(&new) {
444        Ok(existing) => {
445            let mut doc = parse_doc(&new, &existing)?;
446            let from = parse_doc(&old, &text)?;
447            let mut kept = Vec::new();
448            merge_tables(doc.as_table_mut(), from.as_table(), "", &mut kept);
449            for key in kept {
450                tracing::warn!(
451                    "{key} is in both {} and {}; the value in {} is kept",
452                    old.display(),
453                    new.display(),
454                    new.display()
455                );
456            }
457            doc.to_string()
458        }
459        Err(e) if e.kind() == std::io::ErrorKind::NotFound => text,
460        Err(e) => return Err(Error::Io(e)),
461    };
462    sapphire_framework_settings::write_atomic(&new, &merged)?;
463    let backup = config_dir.join(OLD_CONFIG_BACKUP);
464    match std::fs::rename(&old, &backup) {
465        Ok(()) => tracing::info!(
466            "{} moved to {}; the old file is kept as {OLD_CONFIG_BACKUP}",
467            old.display(),
468            new.display()
469        ),
470        Err(e) => tracing::warn!(
471            "{} moved to {}, but it could not be renamed to {OLD_CONFIG_BACKUP}: {e}",
472            old.display(),
473            new.display()
474        ),
475    }
476    Ok(())
477}
478
479/// `text`, the content of `path`, as an editable document.
480fn parse_doc(path: &Path, text: &str) -> Result<toml_edit::DocumentMut> {
481    text.parse::<toml_edit::DocumentMut>().map_err(|e| {
482        sapphire_framework_settings::Error::Unparsable {
483            file: path.to_path_buf(),
484            message: sapphire_framework_settings::describe_toml_error(text, e.span(), e.message()),
485        }
486        .into()
487    })
488}
489
490/// Add to `into` what `from` holds and it does not, table by table; a key both hold keeps
491/// `into`'s value and is pushed, dotted under `prefix`, to `kept`.
492fn merge_tables(
493    into: &mut dyn toml_edit::TableLike,
494    from: &dyn toml_edit::TableLike,
495    prefix: &str,
496    kept: &mut Vec<String>,
497) {
498    for (name, item) in from.iter() {
499        let key = if prefix.is_empty() {
500            name.to_owned()
501        } else {
502            format!("{prefix}.{name}")
503        };
504        match into.get_mut(name) {
505            None => {
506                let mut item = item.clone();
507                unplace(&mut item);
508                into.insert(name, item);
509            }
510            Some(existing) => match (existing.as_table_like_mut(), item.as_table_like()) {
511                (Some(existing), Some(item)) => merge_tables(existing, item, &key, kept),
512                _ => kept.push(key),
513            },
514        }
515    }
516}
517
518/// Clear the positions a table brought from its own document, so it is written after what
519/// the document it joins already holds.
520fn unplace(item: &mut toml_edit::Item) {
521    fn table(table: &mut toml_edit::Table) {
522        table.set_position(None);
523        for (_, child) in table.iter_mut() {
524            unplace(child);
525        }
526    }
527    match item {
528        toml_edit::Item::Table(t) => table(t),
529        toml_edit::Item::ArrayOfTables(array) => array.iter_mut().for_each(table),
530        _ => {}
531    }
532}
533
534/// A Rust type a setting's value reads as, for [`Settings::get_as`].
535pub trait FromValue: Sized {
536    /// `value` as this type, or `None` when it is of another kind.
537    fn from_value(value: Value) -> Option<Self>;
538}
539
540impl FromValue for bool {
541    fn from_value(value: Value) -> Option<Self> {
542        match value {
543            Value::Bool(b) => Some(b),
544            _ => None,
545        }
546    }
547}
548
549impl FromValue for i64 {
550    fn from_value(value: Value) -> Option<Self> {
551        match value {
552            Value::Int(i) => Some(i),
553            _ => None,
554        }
555    }
556}
557
558impl FromValue for String {
559    fn from_value(value: Value) -> Option<Self> {
560        match value {
561            Value::String(s) => Some(s),
562            _ => None,
563        }
564    }
565}
566
567impl FromValue for Vec<String> {
568    fn from_value(value: Value) -> Option<Self> {
569        match value {
570            Value::List(items) => items.into_iter().map(String::from_value).collect(),
571            _ => None,
572        }
573    }
574}
575
576/// The app server's settings as the running server sees them: a cheap, clonable handle.
577///
578/// Keys that apply on a restart keep the values they had when the server started; keys
579/// that apply live follow every write, a change of the selected workspace and a change sync
580/// or an edit makes to its `config.toml`, and [`changed`](Self::changed) announces it.
581///
582/// A key that applies on a restart is pending while its value differs from the one the
583/// server started with, so switching to a workspace whose file holds another value for a
584/// workspace key of that kind makes it pending too.
585#[derive(Clone)]
586pub struct Settings {
587    inner: Arc<Inner>,
588}
589
590struct Inner {
591    registry: Registry,
592    start: StartState,
593    /// Effective values, secrets and unset keys left out.
594    values: RwLock<BTreeMap<String, Value>>,
595    changed: watch::Sender<u64>,
596}
597
598impl std::fmt::Debug for Settings {
599    // Never the values: they are the user's.
600    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
601        f.debug_struct("Settings").finish_non_exhaustive()
602    }
603}
604
605impl Settings {
606    /// Read `ctx`'s application's settings: migrate `server.toml`, build the registry,
607    /// check the device file and the application's files, and read every value.
608    pub(crate) fn load(ctx: &AppContext, app: Arc<dyn AppSettings>) -> Result<Settings> {
609        Settings::load_with(ctx, app, SelectionFile::for_app(ctx))
610    }
611
612    /// [`load`](Self::load), with the selected workspace — and so the workspace scope's
613    /// file — read from `selection`.
614    pub(crate) fn load_with(
615        ctx: &AppContext,
616        app: Arc<dyn AppSettings>,
617        selection: SelectionFile,
618    ) -> Result<Settings> {
619        let files = SettingsFiles::with_selection(ctx, selection)?;
620        migrate(&files.config_dir)?;
621        let registry = registry(ctx, &files, Arc::clone(&app))?;
622        startup_check(&files, &*app)?;
623        let values = read(&registry)?;
624        let start = StartState::capture(&registry)?;
625        Ok(Settings {
626            inner: Arc::new(Inner {
627                registry,
628                start,
629                values: RwLock::new(values),
630                changed: watch::channel(0).0,
631            }),
632        })
633    }
634
635    /// Every key at its default, with no file read, migrated or checked: for the commands
636    /// that must work whatever the files hold (`update`, `service`, `mcp`).
637    ///
638    /// The registry still points at the usual files, but nothing here opens them. An error
639    /// only when the application's own definitions break the registry's rules.
640    pub(crate) fn defaults(ctx: &AppContext, app: Arc<dyn AppSettings>) -> Result<Settings> {
641        let config_dir = ctx
642            .try_config_dir()
643            .map(Path::to_path_buf)
644            .unwrap_or_default();
645        let files = SettingsFiles {
646            selection: SelectionFile::at(config_dir.join(crate::selection::SELECTION_FILE)),
647            config_dir,
648            app_name: ctx.app_name,
649        };
650        let registry = registry(ctx, &files, app)?;
651        let values = registry
652            .schema()
653            .into_iter()
654            .filter(|def| def.kind != Kind::Secret)
655            .filter_map(|def| def.default.map(|value| (def.key, value)))
656            .collect();
657        Ok(Settings {
658            inner: Arc::new(Inner {
659                registry,
660                start: StartState::default(),
661                values: RwLock::new(values),
662                changed: watch::channel(0).0,
663            }),
664        })
665    }
666
667    /// The config directory's `config.toml`, where the device's settings are: for a message
668    /// about them. `None` while the directory is unresolved.
669    pub(crate) fn device_file(ctx: &AppContext) -> Option<PathBuf> {
670        ctx.try_config_dir().map(|dir| dir.join(SERVER_CONFIG_FILE))
671    }
672
673    /// The effective value of `key`: `None` for a secret, an unset key or an unknown one.
674    pub fn get(&self, key: &str) -> Option<Value> {
675        self.inner
676            .values
677            .read()
678            .unwrap_or_else(|e| e.into_inner())
679            .get(key)
680            .cloned()
681    }
682
683    /// The effective value of `key` as `T`; `None` as for [`get`](Self::get), or when the
684    /// value is of another kind.
685    pub fn get_as<T: FromValue>(&self, key: &str) -> Option<T> {
686        self.get(key).and_then(T::from_value)
687    }
688
689    /// Bumped whenever the effective value of a key that applies live changes: after a
690    /// write, a change of the selected workspace, or a change to its `config.toml`.
691    pub fn changed(&self) -> watch::Receiver<u64> {
692        self.inner.changed.subscribe()
693    }
694
695    /// Read the files again after a write, a change of selection or a change to the
696    /// workspace's file: live keys take their new values, and [`changed`](Self::changed)
697    /// is bumped if any did; restart keys keep their start values. Synchronous, and holding
698    /// its lock only while it swaps the values in, so any caller may run it.
699    pub(crate) fn refresh(&self) -> Result<()> {
700        let new = read(&self.inner.registry)?;
701        let mut values = self.inner.values.write().unwrap_or_else(|e| e.into_inner());
702        let mut any = false;
703        for def in self.inner.registry.schema() {
704            if def.apply != Apply::Live || values.get(&def.key) == new.get(&def.key) {
705                continue;
706            }
707            any = true;
708            match new.get(&def.key) {
709                Some(value) => values.insert(def.key, value.clone()),
710                None => values.remove(&def.key),
711            };
712        }
713        drop(values);
714        if any {
715            self.inner.changed.send_modify(|n| *n = n.wrapping_add(1));
716        }
717        Ok(())
718    }
719
720    /// The registry the server reads and writes through.
721    pub(crate) fn registry(&self) -> &Registry {
722        &self.inner.registry
723    }
724
725    /// The restart keys' values at start, to tell which writes wait for a restart.
726    pub(crate) fn start(&self) -> &StartState {
727        &self.inner.start
728    }
729}
730
731/// The checks a server runs on the files as they are before it starts: the device file's
732/// framework part and the application's `validate`.
733fn startup_check(files: &SettingsFiles, app: &dyn AppSettings) -> Result<()> {
734    let mut errors = Vec::new();
735    for result in [
736        check_device_file(files, &Staged::default()),
737        app.validate(&files.app_files(), &Staged::default()),
738    ] {
739        if let Err(e) = result {
740            errors.extend(e);
741        }
742    }
743    if errors.is_empty() {
744        Ok(())
745    } else {
746        Err(sapphire_framework_settings::Error::Rejected(errors).into())
747    }
748}
749
750/// `ctx`'s registry, `server.toml` migrated, with the outcome of the checks a starting
751/// server runs kept apart rather than failing: for the offline `config`, which must be able
752/// to repair a file those checks refuse. A write still goes through the owners' checks of
753/// the edited files.
754pub(crate) fn open_unchecked(
755    ctx: &AppContext,
756    app: Arc<dyn AppSettings>,
757) -> Result<(Registry, Result<()>)> {
758    let files = SettingsFiles::with_selection(ctx, SelectionFile::for_app(ctx))?;
759    migrate(&files.config_dir)?;
760    let registry = registry(ctx, &files, Arc::clone(&app))?;
761    let checked = startup_check(&files, &*app);
762    Ok((registry, checked))
763}
764
765/// Every key's effective value, secrets and unset keys left out.
766fn read(registry: &Registry) -> Result<BTreeMap<String, Value>> {
767    Ok(sapphire_framework_settings::list(registry, None, None)?
768        .into_iter()
769        .filter_map(|entry| match entry.value {
770            sapphire_framework_settings::EntryValue::Value(value) => Some((entry.key, value)),
771            _ => None,
772        })
773        .collect())
774}
775
776#[cfg(test)]
777mod tests {
778    use super::*;
779    use crate::config::ServerConfig;
780    use crate::selection::Selection;
781    use sapphire_framework_settings::{Op, apply};
782    use sapphire_workspace::AppContext;
783    use std::path::Path;
784    use std::sync::Arc;
785
786    const APP: &str = "settingstest";
787
788    /// A context of its own for each test, its config directory in `tmp`.
789    fn context(tmp: &Path) -> AppContext {
790        let ctx = AppContext::new(APP);
791        let dir = tmp.join("config");
792        std::fs::create_dir_all(&dir).unwrap();
793        ctx.set_config_dir(dir);
794        ctx
795    }
796
797    struct TestApp(Vec<SettingDef>);
798
799    impl AppSettings for TestApp {
800        fn defs(&self) -> Vec<SettingDef> {
801            self.0.clone()
802        }
803    }
804
805    fn app_def(key: &str, kind: Kind, scopes: Vec<Scope>, apply: Apply) -> SettingDef {
806        SettingDef {
807            key: key.into(),
808            kind,
809            scopes,
810            overridable: false,
811            apply,
812            default: None,
813            section: "Test".into(),
814            doc: "test".into(),
815            // Left as the default on purpose: the framework marks the app's defs.
816            process: Process::Bridge,
817        }
818    }
819
820    fn one(def: SettingDef) -> Arc<dyn AppSettings> {
821        Arc::new(TestApp(vec![def]))
822    }
823
824    fn set(key: &str, value: Value) -> Op {
825        Op::Set {
826            key: key.into(),
827            value,
828        }
829    }
830
831    fn select(ctx: &AppContext, root: &Path) {
832        std::fs::create_dir_all(root).unwrap();
833        SelectionFile::for_app(ctx)
834            .save(&Selection {
835                root: root.to_path_buf(),
836                sync: false,
837            })
838            .unwrap();
839    }
840
841    #[test]
842    fn server_toml_becomes_config_toml() {
843        let tmp = tempfile::tempdir().unwrap();
844        let text = "# mine\n[update]\ncheck = false\n";
845        std::fs::write(tmp.path().join("server.toml"), text).unwrap();
846        migrate(tmp.path()).unwrap();
847        assert_eq!(
848            std::fs::read_to_string(tmp.path().join("config.toml")).unwrap(),
849            text
850        );
851        assert_eq!(
852            std::fs::read_to_string(tmp.path().join("server.toml.v1")).unwrap(),
853            text
854        );
855        assert!(!tmp.path().join("server.toml").exists());
856        // Once done, it is done.
857        migrate(tmp.path()).unwrap();
858        assert!(!tmp.path().join("server.toml").exists());
859    }
860
861    /// Every log line `f` writes, at any level.
862    fn logged(f: impl FnOnce()) -> String {
863        use std::sync::Mutex;
864        #[derive(Clone, Default)]
865        struct Captured(Arc<Mutex<Vec<u8>>>);
866        impl std::io::Write for Captured {
867            fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
868                self.0.lock().unwrap().extend_from_slice(buf);
869                Ok(buf.len())
870            }
871            fn flush(&mut self) -> std::io::Result<()> {
872                Ok(())
873            }
874        }
875        let captured = Captured::default();
876        let writer = captured.clone();
877        let subscriber = tracing_subscriber::fmt()
878            .with_writer(move || writer.clone())
879            .with_ansi(false)
880            .finish();
881        tracing::subscriber::with_default(subscriber, f);
882        String::from_utf8(captured.0.lock().unwrap().clone()).unwrap()
883    }
884
885    #[test]
886    fn server_toml_merges_into_an_existing_config_toml() {
887        let tmp = tempfile::tempdir().unwrap();
888        let old = "# old\n[update]\ncheck = false\n\n[http.mcp]\n# mine\nenabled = true\n";
889        std::fs::write(tmp.path().join("server.toml"), old).unwrap();
890        let app =
891            "# the app's own\nsync_interval_minutes = 5\n\n[anthropic]\napi_key = \"x\" # keep\n";
892        std::fs::write(tmp.path().join("config.toml"), app).unwrap();
893        let log = logged(|| migrate(tmp.path()).unwrap());
894        let merged = std::fs::read_to_string(tmp.path().join("config.toml")).unwrap();
895        assert!(merged.starts_with(app), "{merged}");
896        let table: toml::Table = merged.parse().unwrap();
897        assert_eq!(table["update"]["check"].as_bool(), Some(false));
898        assert_eq!(table["http"]["mcp"]["enabled"].as_bool(), Some(true));
899        assert_eq!(table["anthropic"]["api_key"].as_str(), Some("x"));
900        assert!(merged.contains("# mine"), "{merged}");
901        assert_eq!(
902            std::fs::read_to_string(tmp.path().join("server.toml.v1")).unwrap(),
903            old
904        );
905        assert!(!tmp.path().join("server.toml").exists());
906        assert!(!log.contains("WARN"), "{log}");
907        // Once done, it is done.
908        migrate(tmp.path()).unwrap();
909        assert_eq!(
910            std::fs::read_to_string(tmp.path().join("config.toml")).unwrap(),
911            merged
912        );
913    }
914
915    #[test]
916    fn a_key_config_toml_already_has_wins_with_a_warning() {
917        let tmp = tempfile::tempdir().unwrap();
918        std::fs::write(
919            tmp.path().join("server.toml"),
920            "[update]\ncheck = false\n[http]\nlisten = \"10.9.8.7:1\"\n",
921        )
922        .unwrap();
923        std::fs::write(tmp.path().join("config.toml"), "[update]\ncheck = true\n").unwrap();
924        let log = logged(|| migrate(tmp.path()).unwrap());
925        let table: toml::Table = std::fs::read_to_string(tmp.path().join("config.toml"))
926            .unwrap()
927            .parse()
928            .unwrap();
929        assert_eq!(table["update"]["check"].as_bool(), Some(true));
930        assert_eq!(table["http"]["listen"].as_str(), Some("10.9.8.7:1"));
931        assert!(
932            log.contains("WARN") && log.contains("update.check"),
933            "{log}"
934        );
935        // The key, never the value.
936        assert!(!log.contains("false"), "{log}");
937        assert!(tmp.path().join("server.toml.v1").exists());
938        assert!(!tmp.path().join("server.toml").exists());
939    }
940
941    #[cfg(unix)]
942    #[test]
943    fn a_merge_keeps_config_tomls_permissions() {
944        use std::os::unix::fs::PermissionsExt;
945        let tmp = tempfile::tempdir().unwrap();
946        std::fs::write(tmp.path().join("server.toml"), "[update]\ncheck = false\n").unwrap();
947        let path = tmp.path().join("config.toml");
948        std::fs::write(&path, "[anthropic]\napi_key = \"x\"\n").unwrap();
949        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap();
950        migrate(tmp.path()).unwrap();
951        let mode = std::fs::metadata(&path).unwrap().permissions().mode();
952        assert_eq!(mode & 0o777, 0o600);
953    }
954
955    #[test]
956    fn the_apps_own_tables_are_left_alone() {
957        let tmp = tempfile::tempdir().unwrap();
958        let ctx = context(tmp.path());
959        std::fs::write(
960            ctx.config_dir().join("config.toml"),
961            "sync_interval_minutes = 5\n\n[anthropic]\napi_key = \"x\"\n\n\
962             [workspace]\ndefault = \"a\"\n\n[sync]\nwhatever = true\n\n\
963             [retrieve]\nk = 1\n\n[cache]\ndir = \"/c\"\n",
964        )
965        .unwrap();
966        let settings = Settings::load(&ctx, Arc::new(())).unwrap();
967        assert_eq!(settings.get_as::<bool>("update.check"), Some(true));
968    }
969
970    #[test]
971    fn a_framework_write_keeps_the_apps_own_tables_byte_for_byte() {
972        let tmp = tempfile::tempdir().unwrap();
973        let ctx = context(tmp.path());
974        let path = ctx.config_dir().join("config.toml");
975        let before = "# sapphire-agent\nsync_interval_minutes = 5 # minutes\n\n\
976                      [anthropic]\n# the key\napi_key = \"x\"\n\n\
977                      [http]\n# where\nlisten = \"127.0.0.1:1\"\n\n\
978                      [matrix]\nhomeserver = \"https://m\" # mine\n";
979        std::fs::write(&path, before).unwrap();
980        let settings = Settings::load(&ctx, Arc::new(())).unwrap();
981        apply(
982            settings.registry(),
983            None,
984            vec![set("http.listen", Value::String("127.0.0.1:2".into()))],
985        )
986        .unwrap();
987        assert_eq!(
988            std::fs::read_to_string(&path).unwrap(),
989            before.replace("127.0.0.1:1", "127.0.0.1:2")
990        );
991    }
992
993    #[test]
994    fn an_unknown_key_under_http_or_update_is_still_an_error() {
995        for text in ["[http]\nlisn = 1\n", "[update]\nchekc = true\n"] {
996            let tmp = tempfile::tempdir().unwrap();
997            let ctx = context(tmp.path());
998            std::fs::write(ctx.config_dir().join("config.toml"), text).unwrap();
999            assert!(Settings::load(&ctx, Arc::new(())).is_err(), "{text}");
1000        }
1001    }
1002
1003    #[test]
1004    fn a_missing_server_toml_migrates_nothing() {
1005        let tmp = tempfile::tempdir().unwrap();
1006        migrate(tmp.path()).unwrap();
1007        assert!(!tmp.path().join("config.toml").exists());
1008    }
1009
1010    #[test]
1011    fn the_old_mcp_table_still_says_where_it_went() {
1012        let tmp = tempfile::tempdir().unwrap();
1013        let ctx = context(tmp.path());
1014        std::fs::write(ctx.config_dir().join("server.toml"), "[mcp]\nhttp = true\n").unwrap();
1015        let err = Settings::load(&ctx, Arc::new(()))
1016            .err()
1017            .unwrap()
1018            .to_string();
1019        assert!(
1020            err.contains("[mcp] http moved to [http.mcp] enabled"),
1021            "{err}"
1022        );
1023        assert!(
1024            err.contains(&ctx.config_dir().join("config.toml").display().to_string()),
1025            "{err}"
1026        );
1027    }
1028
1029    #[test]
1030    fn server_config_comes_from_the_settings() {
1031        let tmp = tempfile::tempdir().unwrap();
1032        let ctx = context(tmp.path());
1033        std::fs::write(
1034            ctx.config_dir().join("config.toml"),
1035            "[http]\nlisten = \"127.0.0.1:9000\"\nallowed_hosts = [\"box.example\"]\n\n\
1036             [http.mcp]\nenabled = true\n\n[update]\ncheck = false\n",
1037        )
1038        .unwrap();
1039        let settings = Settings::load(&ctx, Arc::new(())).unwrap();
1040        let config = ServerConfig::from_settings(&settings).unwrap();
1041        assert_eq!(config.http.listen, Some("127.0.0.1:9000".parse().unwrap()));
1042        assert_eq!(config.http.allowed_hosts, vec!["box.example".to_owned()]);
1043        assert!(config.http.mcp.enabled);
1044        assert!(!config.http.metrics.enabled);
1045        assert!(!config.update.check);
1046    }
1047
1048    #[test]
1049    fn a_misspelt_framework_setting_is_an_error_not_a_default() {
1050        let tmp = tempfile::tempdir().unwrap();
1051        let ctx = context(tmp.path());
1052        std::fs::write(
1053            ctx.config_dir().join("config.toml"),
1054            "[http.mcp]\nenabeld = true\n",
1055        )
1056        .unwrap();
1057        let err = Settings::load(&ctx, Arc::new(()))
1058            .err()
1059            .unwrap()
1060            .to_string();
1061        assert!(err.contains("http.mcp.enabeld"), "{err}");
1062    }
1063
1064    #[test]
1065    fn a_framework_value_of_the_wrong_kind_is_an_error() {
1066        let tmp = tempfile::tempdir().unwrap();
1067        let ctx = context(tmp.path());
1068        std::fs::write(
1069            ctx.config_dir().join("config.toml"),
1070            "[http]\nlisten = \"nowhere\"\n",
1071        )
1072        .unwrap();
1073        let err = Settings::load(&ctx, Arc::new(()))
1074            .err()
1075            .unwrap()
1076            .to_string();
1077        assert!(err.contains("http.listen"), "{err}");
1078    }
1079
1080    #[test]
1081    fn an_app_key_outside_its_name_is_refused() {
1082        let tmp = tempfile::tempdir().unwrap();
1083        let ctx = context(tmp.path());
1084        let files = SettingsFiles::for_app(&ctx).unwrap();
1085        let def = app_def("other.x", Kind::Bool, vec![Scope::Device], Apply::Live);
1086        let err = registry(&ctx, &files, one(def)).err().unwrap();
1087        assert!(
1088            matches!(&err, sapphire_framework_settings::Error::InvalidDef { key, .. } if key == "other.x"),
1089            "{err}"
1090        );
1091    }
1092
1093    #[test]
1094    fn an_app_key_in_the_workgroup_is_refused() {
1095        let tmp = tempfile::tempdir().unwrap();
1096        let ctx = context(tmp.path());
1097        let files = SettingsFiles::for_app(&ctx).unwrap();
1098        for scopes in [
1099            vec![Scope::Workgroup],
1100            vec![Scope::Workspace, Scope::Workgroup],
1101        ] {
1102            let def = app_def("settingstest.x", Kind::Bool, scopes, Apply::Live);
1103            let err = registry(&ctx, &files, one(def)).err().unwrap();
1104            assert!(
1105                matches!(&err, sapphire_framework_settings::Error::InvalidDef { key, .. } if key == "settingstest.x"),
1106                "{err}"
1107            );
1108        }
1109    }
1110
1111    #[test]
1112    fn an_app_key_named_http_is_refused() {
1113        let tmp = tempfile::tempdir().unwrap();
1114        let ctx = context(tmp.path());
1115        let files = SettingsFiles::for_app(&ctx).unwrap();
1116        let def = app_def("http.port", Kind::Bool, vec![Scope::Device], Apply::Live);
1117        assert!(registry(&ctx, &files, one(def)).is_err());
1118    }
1119
1120    #[test]
1121    fn every_def_is_the_app_servers() {
1122        let tmp = tempfile::tempdir().unwrap();
1123        let ctx = context(tmp.path());
1124        let files = SettingsFiles::for_app(&ctx).unwrap();
1125        let def = app_def(
1126            "settingstest.x",
1127            Kind::Bool,
1128            vec![Scope::Device],
1129            Apply::Live,
1130        );
1131        let reg = registry(&ctx, &files, one(def)).unwrap();
1132        let schema = reg.schema();
1133        assert_eq!(
1134            schema.iter().map(|d| d.key.as_str()).collect::<Vec<_>>(),
1135            vec![
1136                "http.listen",
1137                "http.allowed_hosts",
1138                "http.mcp.enabled",
1139                "http.metrics.enabled",
1140                "update.check",
1141                "settingstest.x",
1142            ]
1143        );
1144        assert!(schema.iter().all(|d| d.process == Process::App));
1145    }
1146
1147    #[test]
1148    fn the_workspace_scope_follows_the_selection() {
1149        let tmp = tempfile::tempdir().unwrap();
1150        let ctx = context(tmp.path());
1151        let def = app_def(
1152            "settingstest.note",
1153            Kind::String { non_empty: false },
1154            vec![Scope::Workspace],
1155            Apply::Live,
1156        );
1157        let settings = Settings::load(&ctx, one(def)).unwrap();
1158        let (a, b) = (tmp.path().join("a"), tmp.path().join("b"));
1159        let file = |root: &Path| root.join(format!(".{APP}")).join("config.toml");
1160
1161        select(&ctx, &a);
1162        apply(
1163            settings.registry(),
1164            None,
1165            vec![set("settingstest.note", Value::String("first".into()))],
1166        )
1167        .unwrap();
1168        select(&ctx, &b);
1169        apply(
1170            settings.registry(),
1171            None,
1172            vec![set("settingstest.note", Value::String("second".into()))],
1173        )
1174        .unwrap();
1175
1176        let a_text = std::fs::read_to_string(file(&a)).unwrap();
1177        let b_text = std::fs::read_to_string(file(&b)).unwrap();
1178        assert!(
1179            a_text.contains("first") && !a_text.contains("second"),
1180            "{a_text}"
1181        );
1182        assert!(b_text.contains("second"), "{b_text}");
1183    }
1184
1185    #[test]
1186    fn no_selection_means_no_workspace_scope() {
1187        let tmp = tempfile::tempdir().unwrap();
1188        let ctx = context(tmp.path());
1189        let files = SettingsFiles::for_app(&ctx).unwrap();
1190        let err = files.workspace().unwrap_err().to_string();
1191        assert_eq!(err, "no workspace is selected");
1192
1193        let def = app_def(
1194            "settingstest.note",
1195            Kind::String { non_empty: false },
1196            vec![Scope::Workspace],
1197            Apply::Live,
1198        );
1199        let settings = Settings::load(&ctx, one(def)).unwrap();
1200        // Reading falls back to the default; writing says why it cannot.
1201        assert_eq!(settings.get("settingstest.note"), None);
1202        let err = apply(
1203            settings.registry(),
1204            None,
1205            vec![set("settingstest.note", Value::String("x".into()))],
1206        )
1207        .unwrap_err()
1208        .to_string();
1209        assert!(err.contains("no workspace is selected"), "{err}");
1210    }
1211
1212    #[test]
1213    fn a_live_change_fires_changed_and_a_restart_change_does_not() {
1214        let tmp = tempfile::tempdir().unwrap();
1215        let ctx = context(tmp.path());
1216        let app = TestApp(vec![
1217            app_def(
1218                "settingstest.live",
1219                Kind::Int { min: 0, max: 10 },
1220                vec![Scope::Device],
1221                Apply::Live,
1222            ),
1223            app_def(
1224                "settingstest.slow",
1225                Kind::Int { min: 0, max: 10 },
1226                vec![Scope::Device],
1227                Apply::Restart,
1228            ),
1229        ]);
1230        let settings = Settings::load(&ctx, Arc::new(app)).unwrap();
1231        let mut changed = settings.changed();
1232
1233        apply(
1234            settings.registry(),
1235            None,
1236            vec![set("settingstest.slow", Value::Int(3))],
1237        )
1238        .unwrap();
1239        settings.refresh().unwrap();
1240        assert!(!changed.has_changed().unwrap());
1241        assert_eq!(
1242            settings.get("settingstest.slow"),
1243            None,
1244            "kept until restart"
1245        );
1246
1247        apply(
1248            settings.registry(),
1249            None,
1250            vec![set("settingstest.live", Value::Int(4))],
1251        )
1252        .unwrap();
1253        settings.refresh().unwrap();
1254        assert!(changed.has_changed().unwrap());
1255        changed.mark_unchanged();
1256        assert_eq!(settings.get_as::<i64>("settingstest.live"), Some(4));
1257        // A clone is the same handle.
1258        assert_eq!(
1259            settings.clone().get("settingstest.live"),
1260            Some(Value::Int(4))
1261        );
1262
1263        // Nothing changed, nothing announced.
1264        settings.refresh().unwrap();
1265        assert!(!changed.has_changed().unwrap());
1266    }
1267
1268    /// `settingstest.a` needs `settingstest.b`: a cross-key rule over the device file.
1269    struct Paired;
1270
1271    impl AppSettings for Paired {
1272        fn defs(&self) -> Vec<SettingDef> {
1273            ["settingstest.a", "settingstest.b"]
1274                .map(|key| app_def(key, Kind::Bool, vec![Scope::Device], Apply::Live))
1275                .into()
1276        }
1277
1278        fn validate(
1279            &self,
1280            files: &AppFiles,
1281            staged: &Staged,
1282        ) -> std::result::Result<(), Vec<FieldError>> {
1283            assert_eq!(files.workspace(), None, "no workspace is selected");
1284            let text = staged.read(files.device()).unwrap().unwrap_or_default();
1285            let table: toml::Table = text.parse().unwrap();
1286            let has = |k: &str| table.get("settingstest").and_then(|t| t.get(k)).is_some();
1287            if has("a") && !has("b") {
1288                return Err(vec![FieldError {
1289                    key: Some("settingstest.a".into()),
1290                    file: Some(files.device().to_path_buf()),
1291                    message: "needs settingstest.b".into(),
1292                }]);
1293            }
1294            Ok(())
1295        }
1296    }
1297
1298    #[test]
1299    fn an_apps_validate_sees_the_files_whole() {
1300        let tmp = tempfile::tempdir().unwrap();
1301        let ctx = context(tmp.path());
1302        let settings = Settings::load(&ctx, Arc::new(Paired)).unwrap();
1303        let reg = settings.registry();
1304
1305        let err = apply(reg, None, vec![set("settingstest.a", Value::Bool(true))])
1306            .unwrap_err()
1307            .to_string();
1308        assert!(err.contains("needs settingstest.b"), "{err}");
1309        assert!(!ctx.config_dir().join("config.toml").exists());
1310
1311        apply(reg, None, vec![set("settingstest.b", Value::Bool(true))]).unwrap();
1312        // `b` is read from the file on disk, untouched by this batch.
1313        apply(reg, None, vec![set("settingstest.a", Value::Bool(true))]).unwrap();
1314        let err = apply(
1315            reg,
1316            None,
1317            vec![Op::Unset {
1318                key: "settingstest.b".into(),
1319            }],
1320        )
1321        .unwrap_err()
1322        .to_string();
1323        assert!(err.contains("needs settingstest.b"), "{err}");
1324    }
1325
1326    #[test]
1327    fn an_unparsable_config_names_the_file() {
1328        let tmp = tempfile::tempdir().unwrap();
1329        let ctx = context(tmp.path());
1330        let path = ctx.config_dir().join("config.toml");
1331        std::fs::write(&path, "this is = = not toml").unwrap();
1332        let err = Settings::load(&ctx, Arc::new(()))
1333            .err()
1334            .unwrap()
1335            .to_string();
1336        assert!(err.contains(&path.display().to_string()), "{err}");
1337    }
1338
1339    #[test]
1340    fn an_unparsable_config_is_never_quoted() {
1341        let tmp = tempfile::tempdir().unwrap();
1342        let ctx = context(tmp.path());
1343        std::fs::write(
1344            ctx.config_dir().join("config.toml"),
1345            "[anthropic]\napi_key = \"hunter2\" x\n",
1346        )
1347        .unwrap();
1348        let err = Settings::load(&ctx, Arc::new(()))
1349            .err()
1350            .unwrap()
1351            .to_string();
1352        assert!(err.contains("line 2"), "{err}");
1353        assert!(!err.contains("hunter2"), "{err}");
1354        // Merging `server.toml` into it says no more.
1355        std::fs::write(
1356            ctx.config_dir().join("server.toml"),
1357            "[update]\ncheck = false\n",
1358        )
1359        .unwrap();
1360        let err = migrate(ctx.config_dir()).unwrap_err().to_string();
1361        assert!(err.contains("line 2") && !err.contains("hunter2"), "{err}");
1362    }
1363
1364    #[test]
1365    fn a_secret_is_never_read_back_and_lives_under_secrets() {
1366        let tmp = tempfile::tempdir().unwrap();
1367        let ctx = context(tmp.path());
1368        let def = app_def(
1369            "settingstest.token",
1370            Kind::Secret,
1371            vec![Scope::Device],
1372            Apply::Live,
1373        );
1374        let settings = Settings::load(&ctx, one(def)).unwrap();
1375        apply(
1376            settings.registry(),
1377            None,
1378            vec![set("settingstest.token", Value::String("hunter2".into()))],
1379        )
1380        .unwrap();
1381        let path = ctx.config_dir().join("secrets").join("settingstest.token");
1382        assert_eq!(std::fs::read_to_string(&path).unwrap(), "hunter2");
1383        #[cfg(unix)]
1384        {
1385            use std::os::unix::fs::PermissionsExt;
1386            let mode = std::fs::metadata(&path).unwrap().permissions().mode();
1387            assert_eq!(mode & 0o777, 0o600);
1388        }
1389        settings.refresh().unwrap();
1390        assert_eq!(settings.get("settingstest.token"), None);
1391    }
1392
1393    #[test]
1394    fn values_convert_to_their_rust_types() {
1395        let tmp = tempfile::tempdir().unwrap();
1396        let ctx = context(tmp.path());
1397        std::fs::write(
1398            ctx.config_dir().join("config.toml"),
1399            "[http]\nallowed_hosts = [\"a\", \"b\"]\n",
1400        )
1401        .unwrap();
1402        let settings = Settings::load(&ctx, Arc::new(())).unwrap();
1403        assert_eq!(settings.get_as::<bool>("update.check"), Some(true));
1404        assert_eq!(
1405            settings.get_as::<Vec<String>>("http.allowed_hosts"),
1406            Some(vec!["a".to_owned(), "b".to_owned()])
1407        );
1408        assert_eq!(
1409            settings.get_as::<String>("update.check"),
1410            None,
1411            "wrong type"
1412        );
1413        assert_eq!(settings.get_as::<i64>("http.listen"), None, "unset");
1414        assert_eq!(settings.get("no.such.key"), None);
1415    }
1416}