aidaemon_tools/
config_file.rs1use std::path::{Path, PathBuf};
7use std::sync::Arc;
8
9use tracing::{info, warn};
10
11pub trait ConfigCheck: Send + Sync {
14 fn check(&self, content: &str) -> Result<(), String>;
15}
16
17impl<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
27pub 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#[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 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 pub async fn backup(&self) -> anyhow::Result<()> {
78 rotate_backups(&self.path).await
79 }
80
81 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 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 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 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
121pub use aidaemon_secrets::write_owner_only;
124
125pub use aidaemon_secrets::daemon_home;
127
128#[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
143pub 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 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}