Skip to main content

aidaemon_tools/
config_file.rs

1//! The host's config file, as the tools that edit it see it: where it is,
2//! how a new text is checked before it is written, and the backups kept
3//! beside it. The host owns what a valid config is ([`ConfigCheck`]); the
4//! tools only read, change and save the TOML.
5
6use std::path::{Path, PathBuf};
7use std::sync::Arc;
8
9use tracing::{info, warn};
10
11/// The host's check of a whole config text before it is written: TOML
12/// syntax, environment references and the host's own config structure.
13pub trait ConfigCheck: Send + Sync {
14    fn check(&self, content: &str) -> Result<(), String>;
15}
16
17/// Any `Fn(&str) -> Result<(), String>` is a check.
18impl<F> ConfigCheck for F
19where
20    F: Fn(&str) -> Result<(), String> + Send + Sync,
21{
22    fn check(&self, content: &str) -> Result<(), String> {
23        self(content)
24    }
25}
26
27/// A check that accepts any valid TOML: for tests and hosts with no
28/// config structure of their own.
29pub fn toml_only(content: &str) -> Result<(), String> {
30    content
31        .parse::<toml::Table>()
32        .map(|_| ())
33        .map_err(|e| format!("Invalid TOML syntax: {}", e))
34}
35
36/// The config file a tool edits.
37#[derive(Clone)]
38pub struct ConfigFile {
39    path: PathBuf,
40    check: Arc<dyn ConfigCheck>,
41}
42
43impl std::fmt::Debug for ConfigFile {
44    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
45        f.debug_struct("ConfigFile")
46            .field("path", &self.path)
47            .finish_non_exhaustive()
48    }
49}
50
51impl ConfigFile {
52    pub fn new(path: impl Into<PathBuf>, check: Arc<dyn ConfigCheck>) -> Self {
53        Self {
54            path: path.into(),
55            check,
56        }
57    }
58
59    pub fn path(&self) -> &Path {
60        &self.path
61    }
62
63    /// The host's check of a whole config text.
64    pub fn validate(&self, content: &str) -> Result<(), String> {
65        self.check.check(content)
66    }
67
68    pub async fn read(&self) -> std::io::Result<String> {
69        tokio::fs::read_to_string(&self.path).await
70    }
71
72    pub async fn load_table(&self) -> anyhow::Result<toml::Table> {
73        Ok(self.read().await?.parse()?)
74    }
75
76    /// Rotates the backups and copies the current file to `.bak`.
77    pub async fn backup(&self) -> anyhow::Result<()> {
78        rotate_backups(&self.path).await
79    }
80
81    /// Writes a text already checked, owner-only.
82    pub async fn write_checked(&self, content: &str) -> anyhow::Result<()> {
83        let path = self.path.clone();
84        let content = content.to_string();
85        tokio::task::spawn_blocking(move || write_owner_only(&path, &content)).await??;
86        Ok(())
87    }
88
89    /// Checks a text, backs the file up and writes it. A failed backup is
90    /// logged, not fatal.
91    pub async fn save(&self, content: &str) -> anyhow::Result<()> {
92        if let Err(err) = self.validate(content) {
93            anyhow::bail!("Refused to save invalid config: {}", err);
94        }
95        if let Err(err) = self.backup().await {
96            warn!(error = %err, "Failed to create config backup before a config change");
97        }
98        self.write_checked(content).await
99    }
100
101    /// [`ConfigFile::save`] for a parsed table.
102    pub async fn save_table(&self, doc: &toml::Table) -> anyhow::Result<()> {
103        let rendered = toml::to_string_pretty(&toml::Value::Table(doc.clone()))?;
104        self.save(&rendered).await
105    }
106
107    /// The backups, newest first.
108    pub fn backups(&self) -> [PathBuf; 3] {
109        backup_paths(&self.path)
110    }
111}
112
113fn backup_paths(path: &Path) -> [PathBuf; 3] {
114    [
115        path.with_extension("toml.bak"),
116        path.with_extension("toml.bak.1"),
117        path.with_extension("toml.bak.2"),
118    ]
119}
120
121/// Write `content` to `path`, owner-only (0600) from the first byte and
122/// atomically (a fresh sibling file renamed over `path`).
123pub use aidaemon_secrets::write_owner_only;
124
125/// The daemon's own folder: `AIDAEMON_HOME`, else `~/.aidaemon`.
126pub use aidaemon_secrets::daemon_home;
127
128/// Owner-only read/write (0600) on Unix, best effort.
129#[cfg(unix)]
130pub fn set_owner_only_permissions(path: &Path) {
131    use std::os::unix::fs::PermissionsExt;
132    if !path.exists() {
133        return;
134    }
135    if let Err(e) = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)) {
136        warn!(path = %path.display(), "Failed to set 0600 permissions: {}", e);
137    }
138}
139
140#[cfg(not(unix))]
141pub fn set_owner_only_permissions(_path: &Path) {}
142
143/// Rotates the 3-deep backup ring and copies the current file to `.bak`:
144/// `.bak.1` -> `.bak.2`, `.bak` -> `.bak.1`, current -> `.bak`.
145pub async fn rotate_backups(path: &Path) -> anyhow::Result<()> {
146    let [bak, bak1, bak2] = backup_paths(path);
147    if bak1.exists() {
148        let _ = tokio::fs::rename(&bak1, &bak2).await;
149    }
150    if bak.exists() {
151        let _ = tokio::fs::rename(&bak, &bak1).await;
152    }
153    tokio::fs::copy(path, &bak).await?;
154    // Backups hold secrets too.
155    set_owner_only_permissions(&bak);
156    set_owner_only_permissions(&bak1);
157    set_owner_only_permissions(&bak2);
158    info!(backup = %bak.display(), "Config backup created (3-deep rotation)");
159    Ok(())
160}
161
162#[cfg(test)]
163mod tests {
164    use super::*;
165
166    #[test]
167    fn an_owner_only_write_replaces_the_file_and_leaves_no_temp() {
168        let dir = tempfile::tempdir().unwrap();
169        let path = dir.path().join("config.toml");
170        std::fs::write(&path, "old = 1\n").unwrap();
171        write_owner_only(&path, "token = \"synthetic\"\n").unwrap();
172        assert_eq!(
173            std::fs::read_to_string(&path).unwrap(),
174            "token = \"synthetic\"\n"
175        );
176        assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1);
177        #[cfg(unix)]
178        {
179            use std::os::unix::fs::PermissionsExt;
180            let mode = std::fs::metadata(&path).unwrap().permissions().mode();
181            assert_eq!(mode & 0o777, 0o600);
182        }
183    }
184
185    #[tokio::test]
186    async fn save_refuses_what_the_check_refuses_and_keeps_backups() {
187        let dir = tempfile::tempdir().unwrap();
188        let path = dir.path().join("config.toml");
189        std::fs::write(&path, "a = 1\n").unwrap();
190        let file = ConfigFile::new(
191            &path,
192            Arc::new(|content: &str| {
193                toml_only(content)?;
194                if content.contains("bad") {
195                    return Err("bad key".to_string());
196                }
197                Ok(())
198            }),
199        );
200        let err = file.save("bad = 1\n").await.unwrap_err();
201        assert!(err.to_string().contains("bad key"));
202        assert_eq!(std::fs::read_to_string(&path).unwrap(), "a = 1\n");
203
204        file.save("a = 2\n").await.unwrap();
205        file.save("a = 3\n").await.unwrap();
206        assert_eq!(std::fs::read_to_string(&path).unwrap(), "a = 3\n");
207        let [bak, bak1, _] = file.backups();
208        assert_eq!(std::fs::read_to_string(bak).unwrap(), "a = 2\n");
209        assert_eq!(std::fs::read_to_string(bak1).unwrap(), "a = 1\n");
210    }
211}