use std::path::{Path, PathBuf};
use std::sync::Arc;
use tracing::{info, warn};
pub trait ConfigCheck: Send + Sync {
fn check(&self, content: &str) -> Result<(), String>;
}
impl<F> ConfigCheck for F
where
F: Fn(&str) -> Result<(), String> + Send + Sync,
{
fn check(&self, content: &str) -> Result<(), String> {
self(content)
}
}
pub fn toml_only(content: &str) -> Result<(), String> {
content
.parse::<toml::Table>()
.map(|_| ())
.map_err(|e| format!("Invalid TOML syntax: {}", e))
}
#[derive(Clone)]
pub struct ConfigFile {
path: PathBuf,
check: Arc<dyn ConfigCheck>,
}
impl std::fmt::Debug for ConfigFile {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ConfigFile")
.field("path", &self.path)
.finish_non_exhaustive()
}
}
impl ConfigFile {
pub fn new(path: impl Into<PathBuf>, check: Arc<dyn ConfigCheck>) -> Self {
Self {
path: path.into(),
check,
}
}
pub fn path(&self) -> &Path {
&self.path
}
pub fn validate(&self, content: &str) -> Result<(), String> {
self.check.check(content)
}
pub async fn read(&self) -> std::io::Result<String> {
tokio::fs::read_to_string(&self.path).await
}
pub async fn load_table(&self) -> anyhow::Result<toml::Table> {
Ok(self.read().await?.parse()?)
}
pub async fn backup(&self) -> anyhow::Result<()> {
rotate_backups(&self.path).await
}
pub async fn write_checked(&self, content: &str) -> anyhow::Result<()> {
let path = self.path.clone();
let content = content.to_string();
tokio::task::spawn_blocking(move || write_owner_only(&path, &content)).await??;
Ok(())
}
pub async fn save(&self, content: &str) -> anyhow::Result<()> {
if let Err(err) = self.validate(content) {
anyhow::bail!("Refused to save invalid config: {}", err);
}
if let Err(err) = self.backup().await {
warn!(error = %err, "Failed to create config backup before a config change");
}
self.write_checked(content).await
}
pub async fn save_table(&self, doc: &toml::Table) -> anyhow::Result<()> {
let rendered = toml::to_string_pretty(&toml::Value::Table(doc.clone()))?;
self.save(&rendered).await
}
pub fn backups(&self) -> [PathBuf; 3] {
backup_paths(&self.path)
}
}
fn backup_paths(path: &Path) -> [PathBuf; 3] {
[
path.with_extension("toml.bak"),
path.with_extension("toml.bak.1"),
path.with_extension("toml.bak.2"),
]
}
pub fn write_owner_only(path: &Path, content: &str) -> std::io::Result<()> {
use std::io::Write;
let parent = path.parent().filter(|p| !p.as_os_str().is_empty());
let name = path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| "config".to_string());
let tmp = parent
.map(Path::to_path_buf)
.unwrap_or_default()
.join(format!(".{name}.{}.tmp", uuid::Uuid::new_v4().simple()));
let mut options = std::fs::OpenOptions::new();
options.write(true).create_new(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600);
}
let written = (|| {
let mut file = options.open(&tmp)?;
file.write_all(content.as_bytes())?;
file.sync_all()?;
std::fs::rename(&tmp, path)
})();
if written.is_err() {
let _ = std::fs::remove_file(&tmp);
}
written
}
#[cfg(unix)]
pub fn set_owner_only_permissions(path: &Path) {
use std::os::unix::fs::PermissionsExt;
if !path.exists() {
return;
}
if let Err(e) = std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)) {
warn!(path = %path.display(), "Failed to set 0600 permissions: {}", e);
}
}
#[cfg(not(unix))]
pub fn set_owner_only_permissions(_path: &Path) {}
pub async fn rotate_backups(path: &Path) -> anyhow::Result<()> {
let [bak, bak1, bak2] = backup_paths(path);
if bak1.exists() {
let _ = tokio::fs::rename(&bak1, &bak2).await;
}
if bak.exists() {
let _ = tokio::fs::rename(&bak, &bak1).await;
}
tokio::fs::copy(path, &bak).await?;
set_owner_only_permissions(&bak);
set_owner_only_permissions(&bak1);
set_owner_only_permissions(&bak2);
info!(backup = %bak.display(), "Config backup created (3-deep rotation)");
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn an_owner_only_write_replaces_the_file_and_leaves_no_temp() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("config.toml");
std::fs::write(&path, "old = 1\n").unwrap();
write_owner_only(&path, "token = \"synthetic\"\n").unwrap();
assert_eq!(
std::fs::read_to_string(&path).unwrap(),
"token = \"synthetic\"\n"
);
assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1);
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mode = std::fs::metadata(&path).unwrap().permissions().mode();
assert_eq!(mode & 0o777, 0o600);
}
}
#[tokio::test]
async fn save_refuses_what_the_check_refuses_and_keeps_backups() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("config.toml");
std::fs::write(&path, "a = 1\n").unwrap();
let file = ConfigFile::new(
&path,
Arc::new(|content: &str| {
toml_only(content)?;
if content.contains("bad") {
return Err("bad key".to_string());
}
Ok(())
}),
);
let err = file.save("bad = 1\n").await.unwrap_err();
assert!(err.to_string().contains("bad key"));
assert_eq!(std::fs::read_to_string(&path).unwrap(), "a = 1\n");
file.save("a = 2\n").await.unwrap();
file.save("a = 3\n").await.unwrap();
assert_eq!(std::fs::read_to_string(&path).unwrap(), "a = 3\n");
let [bak, bak1, _] = file.backups();
assert_eq!(std::fs::read_to_string(bak).unwrap(), "a = 2\n");
assert_eq!(std::fs::read_to_string(bak1).unwrap(), "a = 1\n");
}
}