Publish files atomically through one core helper
Browse filesadd-key and the web sign-in each wrote a hidden temporary file, synced it, renamed it into place and synced the directory, with their own temporary names (pid and nanoseconds, or pid and a random nonce). gitv_core::publish_file now does it for both: created exclusively, mode applied past the umask, a caller's step (the sign-in's change of owner) before the rename, replace or refuse-if-present, and cleanup on failure. "Already there" is its own error, so a temporary-name clash can never read as an account that's already set up. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Author
- Um9i vulgarmessiah@gmail.com
- Date
- 22 Nov 2026, 22:15
- Commit
- 1a2cc85c32a2
- Parent
- 0414385
3 files changed +106−61
| @@ -312,6 +312,78 @@ pub fn sync_directory_of(path: &Path) -> std::io::Result<()> { | ||
| std::fs::File::open(directory)?.sync_all() | ||
| } | ||
| /// Why [`publish_file`] failed. Nothing was published in any case but a failed final sync. | ||
| #[derive(Debug)] | ||
| pub enum PublishError<E> { | ||
| /// Asked not to replace, and something is already at the path. | ||
| Exists, | ||
| /// Writing, renaming or syncing failed. | ||
| Io(std::io::Error), | ||
| /// The caller's `prepare` step failed. | ||
| Prepare(E), | ||
| } | ||
| impl<E: std::fmt::Display> std::fmt::Display for PublishError<E> { | ||
| fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { | ||
| match self { | ||
| PublishError::Exists => write!(f, "it already exists"), | ||
| PublishError::Io(e) => write!(f, "{e}"), | ||
| PublishError::Prepare(e) => write!(f, "{e}"), | ||
| } | ||
| } | ||
| } | ||
| /// Publish `contents` at `path` in one step, so readers see the old file or the new one, never | ||
| /// part of either, and a crash leaves one of them in place. | ||
| /// | ||
| /// The contents go to a fresh hidden file beside `path`, under a name no other writer uses, | ||
| /// created exclusively (never an existing file opened and truncated) with permissions `mode` | ||
| /// (applied after creation, so the umask doesn't narrow them). `prepare` then sees the | ||
| /// finished file, to change its ownership say, before it is synced and renamed into place, | ||
| /// replacing what's there only if `replace` is set. The directory is synced last, so the | ||
| /// rename survives a crash. On any failure before the rename the hidden file is removed. | ||
| /// | ||
| /// # Errors | ||
| /// [`PublishError::Exists`] if `replace` is unset and `path` exists; [`PublishError::Prepare`] | ||
| /// with `prepare`'s own error; otherwise [`PublishError::Io`]. | ||
| pub fn publish_file<E>( | ||
| path: &Path, | ||
| contents: &[u8], | ||
| mode: u32, | ||
| replace: bool, | ||
| prepare: impl FnOnce(&std::fs::File) -> Result<(), E>, | ||
| ) -> Result<(), PublishError<E>> { | ||
| use std::io::Write as _; | ||
| use std::os::unix::fs::{OpenOptionsExt, PermissionsExt}; | ||
| use std::sync::atomic::{AtomicU64, Ordering}; | ||
| static WRITES: AtomicU64 = AtomicU64::new(0); | ||
| let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); | ||
| let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.subsec_nanos()); | ||
| let serial = WRITES.fetch_add(1, Ordering::Relaxed); | ||
| let temporary = path.with_file_name(format!(".{name}.tmp-{}-{nanos}-{serial}", std::process::id())); | ||
| let mut file = | ||
| std::fs::File::options().write(true).create_new(true).mode(mode).open(&temporary).map_err(PublishError::Io)?; | ||
| let published = (|| { | ||
| file.write_all(contents).map_err(PublishError::Io)?; | ||
| file.set_permissions(std::fs::Permissions::from_mode(mode)).map_err(PublishError::Io)?; | ||
| prepare(&file).map_err(PublishError::Prepare)?; | ||
| file.sync_all().map_err(PublishError::Io)?; | ||
| let flags = if replace { nix::fcntl::RenameFlags::empty() } else { nix::fcntl::RenameFlags::RENAME_NOREPLACE }; | ||
| nix::fcntl::renameat2(nix::fcntl::AT_FDCWD, &temporary, nix::fcntl::AT_FDCWD, path, flags).map_err( | ||
| |e| match e { | ||
| nix::errno::Errno::EEXIST => PublishError::Exists, | ||
| e => PublishError::Io(e.into()), | ||
| }, | ||
| ) | ||
| })(); | ||
| if published.is_err() { | ||
| let _ = std::fs::remove_file(&temporary); | ||
| return published; | ||
| } | ||
| sync_directory_of(path).map_err(PublishError::Io) | ||
| } | ||
| /// Decode `%XX` escapes to raw bytes, as in a URL path or a Markdown link destination. `+` | ||
| /// stays a plus (only query strings use it for a space). A malformed escape is kept as written. | ||
| pub fn percent_decode(text: &str) -> Vec<u8> { | ||
| @@ -510,6 +582,29 @@ mod tests { | ||
| fs::remove_dir_all(&dir.path).unwrap(); | ||
| } | ||
| #[test] | ||
| fn published_files_replace_whole_or_not_at_all() { | ||
| use std::os::unix::fs::PermissionsExt; | ||
| let dir = scratch("publish"); | ||
| let path = dir.join("keys"); | ||
| let none = |_: &fs::File| Ok::<(), String>(()); | ||
| publish_file(&path, b"one\n", 0o644, true, none).unwrap(); | ||
| publish_file(&path, b"two\n", 0o644, true, none).unwrap(); | ||
| assert_eq!(fs::read(&path).unwrap(), b"two\n"); | ||
| assert_eq!(fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o644, "the umask didn't narrow it"); | ||
| // Not replacing: the existing file stays. | ||
| assert!(matches!(publish_file(&path, b"three\n", 0o600, false, none), Err(PublishError::Exists))); | ||
| // A failed preparation publishes nothing and says why. | ||
| let refuse = |_: &fs::File| Err("not today".to_string()); | ||
| assert!( | ||
| matches!(publish_file(&path, b"four\n", 0o600, true, refuse), Err(PublishError::Prepare(e)) if e == "not today") | ||
| ); | ||
| assert_eq!(fs::read(&path).unwrap(), b"two\n"); | ||
| let names: Vec<_> = fs::read_dir(&dir).unwrap().map(|e| e.unwrap().file_name()).collect(); | ||
| assert_eq!(names, ["keys"], "no hidden file was left behind"); | ||
| let _ = fs::remove_dir_all(&dir); | ||
| } | ||
| #[test] | ||
| fn only_well_formed_protocol_requests_pass() { | ||
| assert_eq!(git_protocol("version=2"), Some("version=2")); | ||
| @@ -12,7 +12,6 @@ | ||
| //! [RFC 6238]: https://www.rfc-editor.org/rfc/rfc6238 | ||
| use std::fs; | ||
| use std::io::Write as _; | ||
| use std::os::unix::fs::OpenOptionsExt; | ||
| use std::path::{Path, PathBuf}; | ||
| @@ -121,13 +120,6 @@ enum Publish { | ||
| OnlyIfAbsent, | ||
| } | ||
| /// A hidden name beside `path` that no other writer, in this process or another, will use. | ||
| fn unique_sibling(path: &Path, purpose: &str) -> Result<PathBuf, AuthError> { | ||
| let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); | ||
| let nonce = data_encoding::HEXLOWER.encode(&random_bytes::<8>()?); | ||
| Ok(path.with_file_name(format!(".{name}.{purpose}-{}-{nonce}", std::process::id()))) | ||
| } | ||
| /// Exclusive permission to change the account file, held by every writer (`setup`, | ||
| /// `password`, the web Account page) across processes, so their read-check-write steps can't | ||
| /// interleave. Released when dropped. | ||
| @@ -252,34 +244,13 @@ fn write_replacing(path: &Path, contents: &[u8], owner: Owner) -> Result<(), Aut | ||
| /// Write through a unique temporary file, given to `owner` by handle before it's published, so | ||
| /// the published file is never anyone else's even for a moment. | ||
| fn write_atomically(path: &Path, contents: &[u8], owner: Owner, mode: Publish) -> Result<(), AuthError> { | ||
| let write_error = |source| AuthError::Write { path: path.to_path_buf(), source }; | ||
| let temporary = unique_sibling(path, "tmp")?; | ||
| // Created exclusively under a name no other writer uses; only then is it ours to clean up. | ||
| let mut file = | ||
| fs::File::options().write(true).create_new(true).mode(0o600).open(&temporary).map_err(write_error)?; | ||
| let written = (|| { | ||
| file.write_all(contents).map_err(write_error)?; | ||
| file.sync_all().map_err(write_error)?; | ||
| hand_over(&file, path, owner)?; | ||
| let flags = match mode { | ||
| Publish::Replace => nix::fcntl::RenameFlags::empty(), | ||
| // One atomic step that fails if the name exists, instead of a rename (which would | ||
| // replace it) or a link-then-unlink (whose second step could fail after success). | ||
| Publish::OnlyIfAbsent => nix::fcntl::RenameFlags::RENAME_NOREPLACE, | ||
| }; | ||
| nix::fcntl::renameat2(nix::fcntl::AT_FDCWD, &temporary, nix::fcntl::AT_FDCWD, path, flags).map_err( | ||
| |e| match e { | ||
| nix::errno::Errno::EEXIST => AuthError::AlreadySetUp(path.to_path_buf()), | ||
| e => write_error(e.into()), | ||
| }, | ||
| ) | ||
| })(); | ||
| if written.is_err() { | ||
| let _ = fs::remove_file(&temporary); | ||
| return written; | ||
| } | ||
| // Published only once the rename survives a crash. | ||
| gitv_core::sync_directory_of(path).map_err(write_error) | ||
| let replace = matches!(mode, Publish::Replace); | ||
| gitv_core::publish_file(path, contents, 0o600, replace, |file| hand_over(file, path, owner)).map_err(|e| match e { | ||
| // One atomic step that fails if the name exists, so two first setups can't both win. | ||
| gitv_core::PublishError::Exists => AuthError::AlreadySetUp(path.to_path_buf()), | ||
| gitv_core::PublishError::Io(source) => AuthError::Write { path: path.to_path_buf(), source }, | ||
| gitv_core::PublishError::Prepare(error) => error, | ||
| }) | ||
| } | ||
| /// Where the account file lives: `$GITV_WEB_AUTH`, or `/var/lib/gitv-web/login`. | ||
| @@ -3,7 +3,6 @@ | ||
| use std::collections::BTreeMap; | ||
| use std::fs; | ||
| use std::io::Write; | ||
| use std::os::unix::fs::{OpenOptionsExt, PermissionsExt}; | ||
| use std::path::{Path, PathBuf}; | ||
| use std::process::{Command, ExitCode, Stdio}; | ||
| @@ -451,30 +450,9 @@ fn add_key(owner: &str, file: &Path) -> Result<(), String> { | ||
| } | ||
| let separator = if old.is_empty() || old.ends_with('\n') { "" } else { "\n" }; | ||
| let line = format!("{separator}restrict,command=\"{} serve {owner}\" ssh-ed25519 {token}\n", config::command()); | ||
| // A name no other writer uses, created fresh (never an existing file opened and truncated), | ||
| // and removed again if anything goes wrong before it replaces the keys file. | ||
| let nanos = SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.subsec_nanos()); | ||
| let temporary = directory.join(format!(".authorized_keys.{}.{nanos}", std::process::id())); | ||
| let mut out = fs::File::options() | ||
| .write(true) | ||
| .create_new(true) | ||
| .mode(0o644) | ||
| .open(&temporary) | ||
| .map_err(|e| format!("couldn't create {}: {e}", temporary.display()))?; | ||
| let published = (|| { | ||
| out.write_all(format!("{old}{line}").as_bytes())?; | ||
| // The mode given at creation is masked by the umask; the file must be readable by sshd. | ||
| out.set_permissions(fs::Permissions::from_mode(0o644))?; | ||
| out.sync_all()?; | ||
| fs::rename(&temporary, &keys) | ||
| })(); | ||
| if let Err(e) = published { | ||
| let _ = fs::remove_file(&temporary); | ||
| return Err(e.to_string()); | ||
| } | ||
| // The key counts as added only once the rename itself survives a crash. | ||
| gitv_core::sync_directory_of(&keys) | ||
| .map_err(|e| format!("added the key, but couldn't sync {}: {e}", directory.display()))?; | ||
| // Readable by sshd. The key counts as added only once the rename survives a crash. | ||
| gitv_core::publish_file(&keys, format!("{old}{line}").as_bytes(), 0o644, true, |_| Ok::<(), String>(())) | ||
| .map_err(|e| format!("couldn't write {}: {e}", keys.display()))?; | ||
| relabel(&keys, Path::new("/sys/fs/selinux"), Path::new("/usr/sbin/restorecon")) | ||
| } | ||
| @@ -842,6 +820,7 @@ fn main() -> ExitCode { | ||
| mod tests { | ||
| use super::*; | ||
| use nix::fcntl::{OFlag, open}; | ||
| use std::os::unix::fs::PermissionsExt; | ||
| fn open_path(path: &Path) -> OwnedFd { | ||
| open(path, OFlag::O_DIRECTORY | OFlag::O_CLOEXEC, Mode::empty()).unwrap() | ||