use std::fs::{self, OpenOptions};
use std::io::Write;
use std::path::Path;
use anyhow::{Context, Result};
use super::DeviceKeys;
use super::device::sync_dir;
pub const DEVICE_PUB_FILE: &str = "device.pub";
const PUBLIC_FILE_MODE: u32 = 0o644;
pub fn publish_device_pub(data_dir: &Path, keys: &DeviceKeys) -> Result<bool> {
let path = data_dir.join(DEVICE_PUB_FILE);
let line = format!("{}\n", keys.age_recipient());
if is_current(&path, &line) {
return Ok(false);
}
let temp = data_dir.join(format!(
".{DEVICE_PUB_FILE}.{}.tmp",
uuid::Uuid::new_v4().simple()
));
let written = write_public_file(&temp, line.as_bytes())
.and_then(|()| fs::rename(&temp, &path).context("installing the device recipient"));
if let Err(e) = written {
if let Err(cleanup) = fs::remove_file(&temp)
&& cleanup.kind() != std::io::ErrorKind::NotFound
{
return Err(e.context(format!(
"also failed to remove {}: {cleanup}",
temp.display()
)));
}
return Err(e).with_context(|| format!("publishing {}", path.display()));
}
sync_dir(data_dir)?;
Ok(true)
}
fn is_current(path: &Path, line: &str) -> bool {
let same_text = fs::read_to_string(path).is_ok_and(|text| text == line);
#[cfg(unix)]
let same_mode = {
use std::os::unix::fs::PermissionsExt;
fs::metadata(path).is_ok_and(|m| m.permissions().mode() & 0o777 == PUBLIC_FILE_MODE)
};
#[cfg(not(unix))]
let same_mode = true;
same_text && same_mode
}
fn write_public_file(path: &Path, bytes: &[u8]) -> Result<()> {
let mut options = OpenOptions::new();
options.write(true).create_new(true);
#[cfg(unix)]
std::os::unix::fs::OpenOptionsExt::mode(&mut options, PUBLIC_FILE_MODE);
let mut file = options
.open(path)
.with_context(|| format!("creating {}", path.display()))?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
file.set_permissions(fs::Permissions::from_mode(PUBLIC_FILE_MODE))?;
}
file.write_all(bytes)
.and_then(|()| file.sync_all())
.with_context(|| format!("writing {}", path.display()))
}
#[cfg(test)]
mod tests {
use std::os::unix::fs::PermissionsExt;
use std::str::FromStr;
use age::x25519::Recipient;
use super::*;
fn mode(path: &Path) -> u32 {
fs::metadata(path).unwrap().permissions().mode() & 0o777
}
#[test]
fn publishes_the_recipient_world_readable_once() {
let dir = tempfile::tempdir().unwrap();
let keys = DeviceKeys::generate().unwrap();
assert!(publish_device_pub(dir.path(), &keys).unwrap());
let path = dir.path().join(DEVICE_PUB_FILE);
assert_eq!(mode(&path), 0o644);
let text = fs::read_to_string(&path).unwrap();
assert_eq!(
Recipient::from_str(text.trim()).unwrap(),
keys.age_recipient()
);
assert!(!publish_device_pub(dir.path(), &keys).unwrap());
let leftovers: Vec<_> = fs::read_dir(dir.path())
.unwrap()
.flatten()
.filter(|e| e.file_name().to_string_lossy().ends_with(".tmp"))
.collect();
assert!(leftovers.is_empty());
}
#[test]
fn replaces_a_stale_or_private_file() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join(DEVICE_PUB_FILE);
let old = DeviceKeys::generate().unwrap();
publish_device_pub(dir.path(), &old).unwrap();
let keys = DeviceKeys::generate().unwrap();
assert!(publish_device_pub(dir.path(), &keys).unwrap());
assert_eq!(
fs::read_to_string(&path).unwrap(),
format!("{}\n", keys.age_recipient())
);
fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).unwrap();
assert!(publish_device_pub(dir.path(), &keys).unwrap());
assert_eq!(mode(&path), 0o644);
}
}