use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use base64::Engine as _;
use serde::{Deserialize, Serialize};
use std::fs;
use std::io::{self, Read, Write};
use std::path::{Component, Path, PathBuf};
use uuid::{Uuid, Version};
use zeroize::Zeroizing;
const LEGACY_PROFILE_SCHEMA: u32 = 1;
const POLICY_PROFILE_SCHEMA: u32 = 2;
const PROFILE_BYTES_LIMIT: u64 = 16 * 1024;
const PROFILE_LIMIT: usize = 128;
const PROFILE_DIRECTORY_ENTRY_LIMIT: usize = 4096;
const KEY_BYTES: usize = 32;
#[derive(Clone)]
pub struct Profile {
id: Uuid,
root: PathBuf,
key: Zeroizing<Vec<u8>>,
policy_required: bool,
}
#[derive(Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
struct StoredProfile {
schema: u32,
id: Uuid,
root: String,
key: Zeroizing<String>,
}
impl Profile {
pub fn id(&self) -> Uuid {
self.id
}
pub fn root(&self) -> &Path {
&self.root
}
pub fn create(root: &Path) -> io::Result<Self> {
let lock = ConfigLock::acquire()?;
let mut key = Zeroizing::new(vec![0_u8; KEY_BYTES]);
getrandom::fill(&mut key).map_err(|error| io::Error::other(error.to_string()))?;
let id = Uuid::now_v7();
let policy = crate::policy::AccessPolicy::load_locked(&lock)?;
let profile = Self {
id,
root: validate_root(root)?,
key,
policy_required: policy.requires_profile_marker(id),
};
profile.persist_new_locked(&lock)?;
Ok(profile)
}
pub fn join(root: &Path, pairing_code: &str) -> io::Result<Self> {
let lock = ConfigLock::acquire()?;
let (id, encoded_key) = pairing_code
.trim()
.split_once('.')
.ok_or_else(|| invalid_input("pairing code has an invalid format"))?;
let id = parse_profile_id(id)?;
let key = Zeroizing::new(
URL_SAFE_NO_PAD
.decode(encoded_key)
.map_err(|_| invalid_input("pairing code has an invalid key"))?,
);
if key.len() != KEY_BYTES || URL_SAFE_NO_PAD.encode(key.as_slice()) != encoded_key {
return Err(invalid_input("pairing code has an invalid key"));
}
let policy = crate::policy::AccessPolicy::load_locked(&lock)?;
let profile = Self {
id,
root: validate_root(root)?,
key,
policy_required: policy.requires_profile_marker(id),
};
profile.persist_new_locked(&lock)?;
Ok(profile)
}
pub fn load(id: Uuid) -> io::Result<Self> {
validate_profile_id(id)?;
let path = profile_path(id);
let owned_fd = rustix::fs::open(
&path,
rustix::fs::OFlags::RDONLY | rustix::fs::OFlags::CLOEXEC | rustix::fs::OFlags::NOFOLLOW,
rustix::fs::Mode::empty(),
)
.map_err(errno_error)?;
let file = fs::File::from(owned_fd);
let metadata = file.metadata()?;
validate_profile_metadata(&metadata)?;
if metadata.len() > PROFILE_BYTES_LIMIT {
return Err(invalid_data("profile file is too large"));
}
let mut bytes = Zeroizing::new(Vec::with_capacity(metadata.len() as usize));
file.take(PROFILE_BYTES_LIMIT + 1).read_to_end(&mut bytes)?;
let stored: StoredProfile = serde_json::from_slice(&bytes)
.map_err(|error| invalid_data(format!("invalid profile: {error}")))?;
if !matches!(stored.schema, LEGACY_PROFILE_SCHEMA | POLICY_PROFILE_SCHEMA)
|| stored.id != id
{
return Err(invalid_data("profile identity does not match its file"));
}
validate_profile_id(stored.id)?;
let key = Zeroizing::new(
URL_SAFE_NO_PAD
.decode(stored.key.as_bytes())
.map_err(|_| invalid_data("profile key is invalid"))?,
);
if key.len() != KEY_BYTES || URL_SAFE_NO_PAD.encode(key.as_slice()) != *stored.key {
return Err(invalid_data("profile key is invalid"));
}
let root = validate_root(Path::new(&stored.root))?;
Ok(Self {
id,
root,
key,
policy_required: stored.schema == POLICY_PROFILE_SCHEMA,
})
}
pub fn list() -> io::Result<Vec<(Uuid, PathBuf, bool)>> {
let directory = profiles_dir();
let entries = match fs::read_dir(directory) {
Ok(entries) => entries,
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()),
Err(error) => return Err(error),
};
let mut profile_ids = Vec::new();
for (index, entry) in entries.enumerate() {
if index >= PROFILE_DIRECTORY_ENTRY_LIMIT {
return Err(invalid_data("profile directory entry limit exceeded"));
}
let entry = entry?;
let path = entry.path();
if path.extension().is_none_or(|extension| extension != "json") {
continue;
}
let Some(stem) = path.file_stem().and_then(|stem| stem.to_str()) else {
continue;
};
let Ok(id) = parse_profile_id(stem) else {
continue;
};
if id.to_string() != stem {
continue;
}
profile_ids.push(id);
if profile_ids.len() > PROFILE_LIMIT {
return Err(invalid_data("profile limit exceeded"));
}
}
profile_ids.sort();
profile_ids.dedup();
let mut profiles = Vec::with_capacity(profile_ids.len());
for id in profile_ids {
let profile = Self::load(id)?;
profiles.push((profile.id, profile.root, profile.policy_required));
}
Ok(profiles)
}
pub fn policy_required(&self) -> bool {
self.policy_required
}
pub(crate) fn require_policy_locked(&mut self, _lock: &ConfigLock) -> io::Result<()> {
if !self.policy_required {
self.policy_required = true;
self.persist(false)?;
}
Ok(())
}
pub fn pairing_code(&self) -> Zeroizing<String> {
Zeroizing::new(format!(
"{}.{}",
self.id,
URL_SAFE_NO_PAD.encode(self.key.as_slice())
))
}
pub(crate) fn key_text(&self) -> Zeroizing<String> {
Zeroizing::new(URL_SAFE_NO_PAD.encode(self.key.as_slice()))
}
fn persist_new_locked(&self, _lock: &ConfigLock) -> io::Result<()> {
self.persist(true)
}
fn persist(&self, create_new: bool) -> io::Result<()> {
create_private_dir(&config_dir())?;
let directory = profiles_dir();
create_private_dir(&directory)?;
if create_new {
let profiles = Self::list()?;
if profiles.len() >= PROFILE_LIMIT {
return Err(invalid_data("profile limit reached"));
}
if profiles.iter().any(|(_, root, _)| root == &self.root) {
return Err(io::Error::new(
io::ErrorKind::AlreadyExists,
"a Guth Sync profile already uses this root",
));
}
}
let stored = StoredProfile {
schema: if self.policy_required {
POLICY_PROFILE_SCHEMA
} else {
LEGACY_PROFILE_SCHEMA
},
id: self.id,
root: path_text(&self.root)?,
key: Zeroizing::new(URL_SAFE_NO_PAD.encode(self.key.as_slice())),
};
let content = Zeroizing::new(
serde_json::to_vec_pretty(&stored)
.map_err(|error| invalid_data(format!("could not encode profile: {error}")))?,
);
let path = profile_path(self.id);
let temporary = directory.join(format!(".{}.{}.tmp", self.id, Uuid::now_v7()));
let mut guard = TemporaryFile::create(temporary)?;
let result = (|| {
guard.file.write_all(&content)?;
guard.file.write_all(b"\n")?;
guard.file.sync_all()?;
if create_new {
rustix::fs::renameat_with(
rustix::fs::CWD,
guard.path(),
rustix::fs::CWD,
&path,
rustix::fs::RenameFlags::NOREPLACE,
)
.map_err(errno_error)
} else {
rustix::fs::renameat(rustix::fs::CWD, guard.path(), rustix::fs::CWD, &path)
.map_err(errno_error)
}
})();
if result.is_ok() {
guard.disarm();
fs::File::open(&directory)?.sync_all()?;
}
result
}
}
pub fn parse_profile_id(value: &str) -> io::Result<Uuid> {
let id = Uuid::parse_str(value).map_err(|_| invalid_input("invalid profile UUID"))?;
if id.to_string() != value {
return Err(invalid_input(
"profile UUID must use canonical lowercase text",
));
}
validate_profile_id(id)?;
Ok(id)
}
pub fn validate_relative_path(path: &Path) -> io::Result<()> {
if path.as_os_str().is_empty() || path.is_absolute() {
return Err(invalid_input("transfer paths must be relative"));
}
if path.components().any(|component| {
matches!(
component,
Component::ParentDir | Component::RootDir | Component::Prefix(_)
)
}) {
return Err(invalid_input(
"transfer paths cannot leave the profile root",
));
}
Ok(())
}
pub fn runtime_dir() -> io::Result<PathBuf> {
let base = std::env::var_os("XDG_RUNTIME_DIR")
.map(PathBuf::from)
.unwrap_or_else(|| home_dir().join(".cache"));
let directory = base.join("guth-sync");
create_private_dir(&directory)?;
Ok(directory)
}
pub fn private_new_file(path: &Path) -> io::Result<fs::File> {
let mut options = fs::OpenOptions::new();
options.write(true).create_new(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600);
}
options.open(path)
}
pub(crate) fn config_dir() -> PathBuf {
std::env::var_os("XDG_CONFIG_HOME")
.map(PathBuf::from)
.unwrap_or_else(|| home_dir().join(".config"))
.join("guth-sync")
}
pub(crate) struct ConfigLock {
directory: fs::File,
}
impl ConfigLock {
pub(crate) fn acquire() -> io::Result<Self> {
let path = config_dir();
create_private_dir(&path)?;
let owned_fd = rustix::fs::open(
&path,
rustix::fs::OFlags::RDONLY
| rustix::fs::OFlags::DIRECTORY
| rustix::fs::OFlags::NOFOLLOW
| rustix::fs::OFlags::CLOEXEC,
rustix::fs::Mode::empty(),
)
.map_err(errno_error)?;
let directory = fs::File::from(owned_fd);
rustix::fs::flock(
&directory,
rustix::fs::FlockOperation::NonBlockingLockExclusive,
)
.map_err(|error| {
if error == rustix::io::Errno::WOULDBLOCK {
io::Error::new(
io::ErrorKind::WouldBlock,
"another Guth Sync configuration update is running",
)
} else {
errno_error(error)
}
})?;
Ok(Self { directory })
}
pub(crate) fn directory(&self) -> &fs::File {
&self.directory
}
}
fn profiles_dir() -> PathBuf {
config_dir().join("profiles")
}
fn profile_path(id: Uuid) -> PathBuf {
profiles_dir().join(format!("{id}.json"))
}
fn validate_profile_id(id: Uuid) -> io::Result<()> {
if id.get_version() != Some(Version::SortRand) {
return Err(invalid_input("profile ID must be a UUIDv7"));
}
Ok(())
}
fn validate_root(root: &Path) -> io::Result<PathBuf> {
let canonical = fs::canonicalize(root)?;
if !canonical.is_dir() {
return Err(invalid_input("profile root must be a folder"));
}
let text = path_text(&canonical)?;
if text.chars().any(char::is_control)
|| text.contains(['%', '\\'])
|| text.trim_end().len() != text.len()
{
return Err(invalid_input(
"profile root contains characters unsupported by rsync configuration",
));
}
Ok(canonical)
}
fn path_text(path: &Path) -> io::Result<String> {
path.to_str()
.map(str::to_owned)
.ok_or_else(|| invalid_input("profile roots must be valid UTF-8"))
}
fn create_private_dir(path: &Path) -> io::Result<()> {
if !path.is_absolute() {
return Err(invalid_input("configuration paths must be absolute"));
}
let text = path
.to_str()
.ok_or_else(|| invalid_input("configuration paths must be valid UTF-8"))?;
if text.chars().any(char::is_control)
|| text.contains(['%', '\\'])
|| text.trim_end().len() != text.len()
{
return Err(invalid_input(
"configuration path contains characters unsupported by rsync",
));
}
fs::create_dir_all(path)?;
#[cfg(unix)]
{
use std::os::unix::fs::{MetadataExt, PermissionsExt};
let metadata = fs::symlink_metadata(path)?;
if metadata.file_type().is_symlink() || !metadata.is_dir() {
return Err(io::Error::new(
io::ErrorKind::PermissionDenied,
"private path must be a real directory",
));
}
if metadata.uid() != rustix::process::geteuid().as_raw() {
return Err(io::Error::new(
io::ErrorKind::PermissionDenied,
"private directory has an unexpected owner",
));
}
fs::set_permissions(path, fs::Permissions::from_mode(0o700))?;
}
Ok(())
}
fn validate_profile_metadata(metadata: &fs::Metadata) -> io::Result<()> {
if metadata.file_type().is_symlink() || !metadata.is_file() {
return Err(invalid_data("profile must be a regular file"));
}
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt;
if metadata.uid() != rustix::process::geteuid().as_raw() {
return Err(io::Error::new(
io::ErrorKind::PermissionDenied,
"profile has an unexpected owner",
));
}
if metadata.mode() & 0o077 != 0 {
return Err(io::Error::new(
io::ErrorKind::PermissionDenied,
"profile permissions must be 0600",
));
}
if metadata.nlink() != 1 {
return Err(io::Error::new(
io::ErrorKind::PermissionDenied,
"profile cannot have hard links",
));
}
}
Ok(())
}
struct TemporaryFile {
path: PathBuf,
file: fs::File,
}
impl TemporaryFile {
fn create(path: PathBuf) -> io::Result<Self> {
let file = private_new_file(&path)?;
Ok(Self { path, file })
}
fn path(&self) -> &Path {
&self.path
}
fn disarm(mut self) {
self.path.clear();
}
}
impl Drop for TemporaryFile {
fn drop(&mut self) {
if !self.path.as_os_str().is_empty() {
let _ = fs::remove_file(&self.path);
}
}
}
fn errno_error(error: rustix::io::Errno) -> io::Error {
io::Error::from_raw_os_error(error.raw_os_error())
}
fn home_dir() -> PathBuf {
std::env::var_os("HOME")
.map(PathBuf::from)
.unwrap_or_else(|| PathBuf::from("/"))
}
fn invalid_input(message: impl Into<String>) -> io::Error {
io::Error::new(io::ErrorKind::InvalidInput, message.into())
}
fn invalid_data(message: impl Into<String>) -> io::Error {
io::Error::new(io::ErrorKind::InvalidData, message.into())
}
#[cfg(test)]
mod tests {
use super::*;
use std::time::{SystemTime, UNIX_EPOCH};
fn test_dir(label: &str) -> PathBuf {
let nonce = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos();
let path =
std::env::temp_dir().join(format!("guth-sync-{label}-{}-{nonce}", std::process::id()));
fs::create_dir(&path).unwrap();
path
}
#[test]
fn transfer_paths_cannot_escape_the_profile() {
assert!(validate_relative_path(Path::new("Documents/report.txt")).is_ok());
assert!(validate_relative_path(Path::new("../secret")).is_err());
assert!(validate_relative_path(Path::new("/etc/passwd")).is_err());
}
#[test]
fn profile_ids_must_be_canonical_uuid_v7() {
let id = Uuid::now_v7();
assert_eq!(parse_profile_id(&id.to_string()).unwrap(), id);
assert!(parse_profile_id(&id.to_string().to_uppercase()).is_err());
assert!(parse_profile_id(&Uuid::nil().to_string()).is_err());
}
#[test]
fn rsync_configuration_metacharacters_are_rejected() {
let root = test_dir("percent%root");
assert!(validate_root(&root).is_err());
fs::remove_dir(root).unwrap();
}
}