GITv

Never leave a half-written keys file, and sync published renames

Browse files

add_key created its temporary keys file with a plain create (which truncates whatever is at that name), left it behind if writing failed, and never synced /etc/gitv after renaming it into place, so a crash could lose a key that was reported as added. The temporary file is now created exclusively under a unique name and removed on any failure, and the directory is synced after the rename. Account and replay-record writes now sync their directory too. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Author
Um9i vulgarmessiah@gmail.com
Date
22 Nov 2026, 16:22
Commit
9d62c182181e
Parent
01924c9

4 files changed +69−9

@@ -271,8 +271,10 @@ fn write_atomically(path: &Path, contents: &[u8], owner: Owner, mode: Publish) -
})();
if written.is_err() {
let _ = fs::remove_file(&temporary);
return written;
}
written
// Published only once the rename survives a crash.
crate::sync_directory_of(path).map_err(write_error)
}
/// Where the account file lives: `$GITV_WEB_AUTH`, or `/var/lib/gitv-web/login`.
@@ -3,7 +3,7 @@
use std::collections::BTreeMap;
use std::fs;
use std::io::Write;
use std::os::unix::fs::PermissionsExt;
use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
use std::path::{Path, PathBuf};
use std::process::{Command, ExitCode, Stdio};
@@ -454,13 +454,29 @@ 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());
let temporary = directory.join(format!(".authorized_keys.{}", std::process::id()));
let mut out = fs::File::create(&temporary).map_err(|e| e.to_string())?;
out.write_all(format!("{old}{line}").as_bytes()).map_err(|e| e.to_string())?;
out.set_permissions(fs::Permissions::from_mode(0o644)).map_err(|e| e.to_string())?;
out.sync_all().map_err(|e| e.to_string())?;
fs::rename(&temporary, &keys).map_err(|e| e.to_string())?;
Ok(())
// 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::sync_directory_of(&keys).map_err(|e| format!("added the key, but couldn't sync {}: {e}", directory.display()))
}
/// The decoded Ed25519 key in an authorized_keys line, wherever it sits: after options, and
@@ -290,6 +290,13 @@ fn run_git<S: AsRef<OsStr>>(
}
}
/// Make a rename or new file in `path`'s directory durable: until the directory itself is
/// synced, a crash can leave the old name, or none, in place of what was just published.
pub fn sync_directory_of(path: &Path) -> std::io::Result<()> {
let directory = path.parent().filter(|d| !d.as_os_str().is_empty()).unwrap_or(Path::new("."));
std::fs::File::open(directory)?.sync_all()
}
/// 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> {
@@ -399,6 +399,41 @@ fn add_key_failure_installs_nothing() {
assert!(out.status.success(), "{}", stderr(&out));
}
#[test]
fn a_failed_key_write_leaves_no_temporary_file() {
use std::os::unix::process::CommandExt;
let host = Host::new("admin-keys-cleanup");
let key = host.dir.join("ada.pub");
fs::write(&key, ed25519_key(4)).unwrap();
let mut command = std::process::Command::new(common::GITV);
command
.args(["add-key", "ada", key.to_str().unwrap()])
.env("GITV_HOST", common::TEST_HOST)
.env("GITV_CONFIG", common::NO_CONFIG)
.env("GITV_REPOS", &host.repos)
.env("GITV_KEYS", &host.keys);
// Files may grow to 16 bytes, so writing the new keys file fails part way. With SIGXFSZ
// ignored the write returns an error instead of killing the process.
// SAFETY: signal and setrlimit are async-signal-safe and the closure does nothing else.
unsafe {
command.pre_exec(|| {
nix::libc::signal(nix::libc::SIGXFSZ, nix::libc::SIG_IGN);
nix::sys::resource::setrlimit(nix::sys::resource::Resource::RLIMIT_FSIZE, 16, 16)
.map_err(std::io::Error::from)
});
}
let out = command.output().unwrap();
assert!(!out.status.success(), "the write should have failed");
assert!(stderr(&out).contains("File too large"), "it failed while writing: {}", stderr(&out));
assert!(!host.keys.exists(), "no keys file was published");
let left: Vec<_> = fs::read_dir(&host.dir)
.unwrap()
.map(|e| e.unwrap().file_name().into_string().unwrap())
.filter(|n| n.starts_with(".authorized_keys"))
.collect();
assert!(left.is_empty(), "temporary files left behind: {left:?}");
}
#[test]
fn add_key_respects_existing_lines() {
let host = Host::new("admin-keys-existing");