Save: checked writes check the open folder's path as it is

The second check of a checked write passed the open folder's path as
text and looked it up again. A path that was not valid UTF-8 was refused,
and a folder on that path replaced by a link into an allowed folder
between the two lookups could let a place outside pass.
check_write_real compares the open folder's real path with the write
roots and the script's grants as it is, without looking it up again.

- The folder is opened with O_PATH on Linux, Android and FreeBSD, so a
  folder that can be written and searched but not listed takes the file.
  The folder flush opens it for reading, and an error there still
  reports the completed write.
- The replaced file's permissions are read after the new content is
  written, as write_atomic_with reads them, so permissions taken away
  meanwhile stay taken away. Its ACL is read only from the same file.
- A folder that changed while it was opened is no longer reported as a
  read-only location.
- Errors name the kept temporary file where its folder is now, after
  the folder moved.
- A file already at the name the old content is copied to is left as it
  is: only a copy this save made and could not finish is removed.
This commit is contained in:
dotCooCoo
2026-12-01 23:24:20 -08:00
parent 4cb6f8f152
commit 6cf9145890
3 changed files with 318 additions and 61 deletions
+46 -2
View File
@@ -339,8 +339,13 @@ fn write_checked(path: &str, fill: impl FnOnce(&mut std::fs::File) -> std::io::R
return vectorcraft_format::write_atomic_with(path, fill);
}
vectorcraft_format::write_atomic_checked(path, fill, |opened| {
let opened = opened.to_str().ok_or_else(|| std::io::Error::other(format!("{}: path is not valid UTF-8", opened.display())))?;
crate::file_access::check_write_unrecorded(opened).map_err(std::io::Error::other)
// On Unix `opened` is the open folder's real path with the file's name: compared as it is,
// without looking the folder up again. Elsewhere it is `path` itself.
#[cfg(unix)]
let checked = crate::file_access::check_write_real(opened);
#[cfg(not(unix))]
let checked = crate::file_access::check_write_unrecorded(&opened.to_string_lossy());
checked.map_err(std::io::Error::other)
})
}
@@ -766,4 +771,43 @@ mod tests {
assert_eq!(naming_in_error(EngineError::Other(raw.clone()), &file).to_string(), raw);
let _ = std::fs::remove_dir_all(base);
}
/// The second check of a checked write compares the open folder's real path as it is: a folder
/// on that path replaced afterwards by a link into the write root does not make a place outside
/// the root pass.
#[cfg(unix)]
#[test]
fn a_checked_write_compares_the_open_folder_without_looking_it_up_again() {
let base = std::fs::canonicalize(std::env::temp_dir()).unwrap().join(format!("vc-access-real-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&base);
let (root, out) = (base.join("root"), base.join("out"));
std::fs::create_dir_all(&root).unwrap();
std::fs::create_dir_all(out.join("x")).unwrap();
let real = out.join("x/doc.svg");
std::fs::remove_dir(out.join("x")).unwrap();
std::os::unix::fs::symlink(&root, out.join("x")).unwrap();
let roots = AutomationRoots::new(&[], &[root.as_path()]).unwrap();
assert!(confine(roots.as_ref(), || crate::file_access::check_write_unrecorded(&real.to_string_lossy())).is_ok(), "looked up, it passes");
let checked = confine(roots.as_ref(), || crate::file_access::check_write_real(&real));
assert!(checked.is_err_and(|e| e.contains("outside the write root")));
let _ = std::fs::remove_dir_all(base);
}
/// A checked write through a link to a folder whose name is not valid UTF-8, inside the write
/// root, is saved.
#[cfg(target_os = "linux")]
#[test]
fn a_checked_write_saves_into_a_folder_whose_name_is_not_text() {
use std::os::unix::ffi::OsStrExt;
let base = std::fs::canonicalize(std::env::temp_dir()).unwrap().join(format!("vc-access-bytes-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&base);
let bytes = base.join(std::ffi::OsStr::from_bytes(b"folder-\xff"));
std::fs::create_dir_all(&bytes).unwrap();
std::os::unix::fs::symlink(&bytes, base.join("text")).unwrap();
let roots = AutomationRoots::new(&[], &[base.as_path()]).unwrap();
let path = base.join("text/doc.svg").to_string_lossy().into_owned();
confine(roots.as_ref(), || write_file(&path, b"new")).unwrap();
assert_eq!(std::fs::read(bytes.join("doc.svg")).unwrap(), b"new");
let _ = std::fs::remove_dir_all(base);
}
}
+73 -27
View File
@@ -100,16 +100,9 @@ impl AutomationRoots {
/// May the file or folder at `path` be read (or written)? It must lie inside one of the roots
/// of that kind. `Err` says why not.
pub fn check(&self, path: &str, access: Access) -> Result<(), String> {
let roots = match access {
Access::Read => &self.read,
Access::Write => &self.write,
};
// The messages are spelled out whole, as the translation catalogs match them.
let roots = self.of(access);
if roots.is_empty() {
return match access {
Access::Read => Err(format!("automation filesystem access is not granted: read authority is absent: {path}")),
Access::Write => Err(format!("automation filesystem access is not granted: write authority is absent: {path}")),
};
return Err(refused(roots, path, access));
}
// Resolving a path on another computer connects to it: unless a root is on a network
// share, such a path is refused by its name before anything is looked up.
@@ -120,12 +113,22 @@ impl AutomationRoots {
return Ok(());
}
}
let shown: Vec<String> = roots.iter().map(|r| r.shown.display().to_string()).collect();
match (shown.as_slice(), access) {
([root], Access::Read) => Err(format!("automation path rejected: outside the read root {root}: {path}")),
([root], Access::Write) => Err(format!("automation path rejected: outside the write root {root}: {path}")),
(_, Access::Read) => Err(format!("automation path rejected: outside the read roots {roots}: {path}", roots = shown.join(", "))),
(_, Access::Write) => Err(format!("automation path rejected: outside the write roots {roots}: {path}", roots = shown.join(", "))),
Err(refused(roots, path, access))
}
/// [`AutomationRoots::check`] for `real`, a path whose links have been followed already: it is
/// compared with the roots as it is, and not looked up again.
#[cfg(unix)]
pub(crate) fn check_real(&self, real: &Path, access: Access) -> Result<(), String> {
let roots = self.of(access);
if roots.iter().any(|r| inside(real, &r.resolved)) { Ok(()) } else { Err(refused(roots, &real.display().to_string(), access)) }
}
/// The roots of the kind `access`.
fn of(&self, access: Access) -> &[Root] {
match access {
Access::Read => &self.read,
Access::Write => &self.write,
}
}
@@ -157,6 +160,24 @@ impl AutomationRoots {
}
}
/// Why `path` is refused `access` under `roots`, the roots of that kind.
fn refused(roots: &[Root], path: &str, access: Access) -> String {
// The messages are spelled out whole, as the translation catalogs match them.
if roots.is_empty() {
return match access {
Access::Read => format!("automation filesystem access is not granted: read authority is absent: {path}"),
Access::Write => format!("automation filesystem access is not granted: write authority is absent: {path}"),
};
}
let shown: Vec<String> = roots.iter().map(|r| r.shown.display().to_string()).collect();
match (shown.as_slice(), access) {
([root], Access::Read) => format!("automation path rejected: outside the read root {root}: {path}"),
([root], Access::Write) => format!("automation path rejected: outside the write root {root}: {path}"),
(_, Access::Read) => format!("automation path rejected: outside the read roots {roots}: {path}", roots = shown.join(", ")),
(_, Access::Write) => format!("automation path rejected: outside the write roots {roots}: {path}", roots = shown.join(", ")),
}
}
/// Where the roots are in force on a thread ([`confine`], [`unconfined`]).
#[derive(Clone, Debug)]
enum Scope {
@@ -371,18 +392,34 @@ impl ScriptGate {
also.check(path, access)?;
}
let real = if ScriptScope::refused_by_name(Path::new(path)) { None } else { resolve(path).ok() };
let allowed = real.is_some_and(|real| {
let scoped = match access {
Access::Read => self.read.allows(&real) || self.write.allows(&real),
Access::Write => self.write.allows(&real),
};
// A read-only file is not written over, also where a rename could replace it.
let read_only = matches!(access, Access::Write) && std::fs::metadata(&real).is_ok_and(|m| m.is_file() && m.permissions().readonly());
let held = matches!(access, Access::Write) && self.held.contains(&real);
let linked = matches!(access, Access::Read) && self.linked.has(&real) && !self.read.keeps_out(&real);
!read_only && !held && (scoped || self.documents.iter().any(|d| resolve(d).is_ok_and(|d| d == real)) || linked)
});
if allowed { Ok(()) } else { Err(format!("Script file access denied: {path}")) }
if real.is_some_and(|real| self.allows_real(&real, access)) { Ok(()) } else { Err(format!("Script file access denied: {path}")) }
}
/// [`ScriptGate::check`] for `real`, a path whose links have been followed already: it is
/// compared as it is, and not looked up again.
#[cfg(unix)]
pub(crate) fn check_real(&self, real: &Path, access: Access) -> Result<(), String> {
if let Some(also) = &self.also {
also.check_real(real, access)?;
}
if !ScriptScope::refused_by_name(real) && self.allows_real(real, access) {
Ok(())
} else {
Err(format!("Script file access denied: {}", real.display()))
}
}
/// May the place at the real path `real` be read (or written) through this gate alone?
fn allows_real(&self, real: &Path, access: Access) -> bool {
let scoped = match access {
Access::Read => self.read.allows(real) || self.write.allows(real),
Access::Write => self.write.allows(real),
};
// A read-only file is not written over, also where a rename could replace it.
let read_only = matches!(access, Access::Write) && std::fs::metadata(real).is_ok_and(|m| m.is_file() && m.permissions().readonly());
let held = matches!(access, Access::Write) && self.held.iter().any(|h| h == real);
let linked = matches!(access, Access::Read) && self.linked.has(real) && !self.read.keeps_out(real);
!read_only && !held && (scoped || self.documents.iter().any(|d| resolve(d).is_ok_and(|d| d == real)) || linked)
}
}
@@ -479,6 +516,15 @@ pub(crate) fn check_write_unrecorded(path: &str) -> Result<(), String> {
check_gate(path, Access::Write)
}
/// [`check_write_unrecorded`] for `real`, the path of a file in a folder whose links have been
/// followed already (the folder a checked write has opened): it is compared as it is, so the folder
/// is not looked up again by its path.
#[cfg(unix)]
pub(crate) fn check_write_real(real: &Path) -> Result<(), String> {
current().map_or(Ok(()), |r| r.check_real(real, Access::Write))?;
GATE.with(|g| g.borrow().clone()).map_or(Ok(()), |g| g.check_real(real, Access::Write))
}
/// Whether a write here is checked: roots are in force, or a script's command runs.
pub(crate) fn writes_checked() -> bool {
current().is_some() || in_script_command()
+199 -32
View File
@@ -104,21 +104,28 @@ pub fn write_atomic_checked(
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, format!("{}: not a file path", resolved.display())))?
.to_os_string();
let parent = resolved.parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or_else(|| Path::new("."));
let dir = rustix::fs::open(parent, OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC, Mode::empty())?;
let target = opened_folder_path(&dir, parent)?.join(&name);
let dir = open_folder(parent)?;
let real = opened_folder_path(&dir, parent)?;
let target = real.join(&name);
allowed(&target)?;
let old = rustix::fs::statat(&dir, &name, AtFlags::SYMLINK_NOFOLLOW).ok();
// Only whether a file is there: its permissions are read again once it is about to be replaced.
let replacing = rustix::fs::statat(&dir, &name, AtFlags::SYMLINK_NOFOLLOW).is_ok();
let tmp_name = temp_path(&target)?.file_name().map(std::ffi::OsStr::to_os_string).unwrap_or_default();
let tmp = target.with_file_name(&tmp_name);
// Replacing a file: owner-only while it is written, as in `write_atomic_with`.
let mode = if old.is_some() { Mode::RUSR | Mode::WUSR } else { Mode::RUSR | Mode::WUSR | Mode::RGRP | Mode::WGRP | Mode::ROTH | Mode::WOTH };
let mode = if replacing { Mode::RUSR | Mode::WUSR } else { Mode::RUSR | Mode::WUSR | Mode::RGRP | Mode::WGRP | Mode::ROTH | Mode::WOTH };
let new_file = OFlags::WRONLY | OFlags::CREATE | OFlags::EXCL | OFlags::NOFOLLOW | OFlags::CLOEXEC;
let remove_tmp = || {
// Best effort: the temporary file is all there is to clean up.
let _ = rustix::fs::unlinkat(&dir, &tmp_name, AtFlags::empty());
};
let synced =
|| rustix::fs::fsync(&dir).map_err(|e| io::Error::new(io::Error::from(e).kind(), WrittenError { path: target.clone(), error: e.into() }));
// The folder may have moved since it was opened: messages name it where it is now.
let now = |file: &std::ffi::OsStr| folder_now(&dir, &real).join(file);
let synced = || {
// Opened for reading here: the folder handle above may allow name lookups only.
let flushed =
rustix::fs::openat(&dir, ".", OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC, Mode::empty()).and_then(|d| rustix::fs::fsync(&d));
flushed.map_err(|e| io::Error::new(io::Error::from(e).kind(), WrittenError { path: now(&name), error: e.into() }))
};
let open_target = |write: bool| -> io::Result<File> {
let flags = if write { OFlags::WRONLY | OFlags::CREATE } else { OFlags::RDONLY };
Ok(File::from(rustix::fs::openat(&dir, &name, flags | OFlags::NOFOLLOW | OFlags::CLOEXEC, mode)?))
@@ -131,14 +138,21 @@ pub fn write_atomic_checked(
remove_tmp();
return Err(e);
}
if let Some(old) = &old {
// Best effort, as in `write_atomic_with`.
let _ = keep_permissions_at(&dir, &name, old, &f);
// The file's permissions as they are now, after `fill`, as in `write_atomic_with`: a
// change made to them meanwhile is kept. Best effort; a file that can't be looked at
// leaves the replacement owner-only.
if let Ok(old) = rustix::fs::statat(&dir, &name, AtFlags::SYMLINK_NOFOLLOW) {
let _ = keep_permissions_at(&dir, &name, &old, &f);
}
drop(f);
let Err(refused) = rustix::fs::renameat(&dir, &tmp_name, &dir, &name) else { return synced() };
#[cfg(test)]
let refuse = RENAME_REFUSED.with(std::cell::Cell::get);
#[cfg(not(test))]
let refuse = false;
let renamed = if refuse { Err(rustix::io::Errno::ACCESS) } else { rustix::fs::renameat(&dir, &tmp_name, &dir, &name) };
let Err(refused) = renamed else { return synced() };
let over = Over {
tmp: &tmp,
tmp: &|| now(&tmp_name),
old: std::env::temp_dir().join(&tmp_name).with_extension("old"),
open_tmp: &|| {
Ok(File::from(rustix::fs::openat(&dir, &tmp_name, OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::CLOEXEC, Mode::empty())?))
@@ -168,7 +182,7 @@ pub fn write_atomic_checked(
return Err(e);
}
let over = Over {
tmp: &elsewhere,
tmp: &|| elsewhere.clone(),
old: elsewhere.with_extension("old"),
open_tmp: &|| File::open(&elsewhere),
remove_tmp: &remove,
@@ -199,13 +213,47 @@ fn opened_folder_path(dir: &std::os::fd::OwnedFd, parent: &Path) -> io::Result<P
let real = std::fs::canonicalize(parent)?;
let (open, now) = (rustix::fs::fstat(dir)?, rustix::fs::stat(&real)?);
if (open.st_dev, open.st_ino) != (now.st_dev, now.st_ino) {
return Err(io::Error::new(io::ErrorKind::PermissionDenied, format!("{}: the folder changed while it was opened", parent.display())));
// Not a permission the file system refused: [`read_only_location`] does not take it for one.
return Err(io::Error::other(format!("{}: the folder changed while it was opened", parent.display())));
}
Ok(real)
}
/// The folder at `parent`, opened for looking names up in it. On Linux, Android and FreeBSD that
/// is `O_PATH`, which needs no permission to list the folder, so a folder that can be written and
/// searched but not listed still takes the file.
#[cfg(unix)]
fn open_folder(parent: &Path) -> io::Result<std::os::fd::OwnedFd> {
use rustix::fs::{Mode, OFlags};
#[cfg(any(target_os = "linux", target_os = "android", target_os = "freebsd"))]
let access = OFlags::PATH;
#[cfg(not(any(target_os = "linux", target_os = "android", target_os = "freebsd")))]
let access = OFlags::RDONLY;
Ok(rustix::fs::open(parent, access | OFlags::DIRECTORY | OFlags::CLOEXEC, Mode::empty())?)
}
/// The path the open folder `dir` has now, which may differ from `opened`, its real path when it
/// was opened, after it moved. `opened` where the system does not say.
#[cfg(unix)]
fn folder_now(dir: &std::os::fd::OwnedFd, opened: &Path) -> PathBuf {
#[cfg(any(target_os = "linux", target_os = "android"))]
if let Ok(now) = std::fs::read_link(format!("/proc/self/fd/{}", std::os::fd::AsRawFd::as_raw_fd(dir)))
&& now.is_absolute()
{
return now;
}
#[cfg(target_vendor = "apple")]
if let Ok(now) = rustix::fs::getpath(dir) {
return PathBuf::from(<std::ffi::OsString as std::os::unix::ffi::OsStringExt>::from_vec(now.into_bytes()));
}
let _ = dir;
opened.to_path_buf()
}
/// [`keep_permissions`] for the temporary file `tmp`, about to replace `name` in folder `dir`, whose
/// file had the status `old`. A name that does not hold a plain file has none to keep.
/// file has the status `old`. A name that does not hold a plain file has none to keep. The ACL is
/// read only from that same file (the same device and inode); when it can't be, the replacement
/// keeps no group or other permissions.
#[cfg(unix)]
fn keep_permissions_at(dir: &std::os::fd::OwnedFd, name: &std::ffi::OsStr, old: &rustix::fs::Stat, tmp: &File) -> io::Result<()> {
use rustix::fs::{FileType, Mode};
@@ -215,22 +263,25 @@ fn keep_permissions_at(dir: &std::os::fd::OwnedFd, name: &std::ffi::OsStr, old:
let mut mode = Mode::from_raw_mode(old.st_mode);
let gid = rustix::fs::Gid::from_raw(old.st_gid);
let kept_group = rustix::fs::fstat(tmp).is_ok_and(|t| t.st_gid == old.st_gid) || rustix::fs::fchown(tmp, None, Some(gid)).is_ok();
if !kept_group || !keep_acl_at(dir, name, tmp) {
if !kept_group || !keep_acl_at(dir, name, old, tmp) {
mode.remove(Mode::RWXG | Mode::RWXO);
}
rustix::fs::fchmod(tmp, mode).map_err(io::Error::from)
}
/// [`keep_acl`] for `name` in folder `dir`, opened without following a link and without waiting on
/// a pipe put in its place.
/// a pipe put in its place, when it is still the file with the status `old`.
#[cfg(target_os = "linux")]
fn keep_acl_at(dir: &std::os::fd::OwnedFd, name: &std::ffi::OsStr, tmp: &File) -> bool {
fn keep_acl_at(dir: &std::os::fd::OwnedFd, name: &std::ffi::OsStr, old: &rustix::fs::Stat, tmp: &File) -> bool {
use rustix::fs::{Mode, OFlags};
use rustix::io::Errno;
const ACL: &str = "system.posix_acl_access";
let Ok(target) = rustix::fs::openat(dir, name, OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::NONBLOCK | OFlags::CLOEXEC, Mode::empty()) else {
return false;
};
if !rustix::fs::fstat(&target).is_ok_and(|t| (t.st_dev, t.st_ino) == (old.st_dev, old.st_ino)) {
return false;
}
let mut buf = vec![0u8; 64 << 10];
match rustix::fs::fgetxattr(&target, ACL, &mut buf[..]) {
Ok(n) => buf.get(..n).is_some_and(|acl| rustix::fs::fsetxattr(tmp, ACL, acl, rustix::fs::XattrFlags::empty()).is_ok()),
@@ -243,7 +294,7 @@ fn keep_acl_at(dir: &std::os::fd::OwnedFd, name: &std::ffi::OsStr, tmp: &File) -
}
#[cfg(all(unix, not(target_os = "linux")))]
fn keep_acl_at(_: &std::os::fd::OwnedFd, _: &std::ffi::OsStr, _: &File) -> bool {
fn keep_acl_at(_: &std::os::fd::OwnedFd, _: &std::ffi::OsStr, _: &rustix::fs::Stat, _: &File) -> bool {
true
}
@@ -296,7 +347,7 @@ fn write_atomic_stepping(
/// error says where they are.
fn write_over(tmp: &Path, target: &Path, refused: io::Error) -> io::Result<()> {
let over = Over {
tmp,
tmp: &|| tmp.to_path_buf(),
old: tmp.with_extension("old"),
open_tmp: &|| File::open(tmp),
remove_tmp: &|| {
@@ -311,8 +362,8 @@ fn write_over(tmp: &Path, target: &Path, refused: io::Error) -> io::Result<()> {
/// How [`write_over_in`] reaches its files: by their paths, or through a folder opened once
/// ([`write_atomic_checked`]).
struct Over<'a> {
/// The temporary file, as error messages name it.
tmp: &'a Path,
/// Where the temporary file is when an error message names it (its folder may have moved).
tmp: &'a dyn Fn() -> PathBuf,
/// Where the file as it was is copied aside.
old: PathBuf,
open_tmp: &'a dyn Fn() -> io::Result<File>,
@@ -327,7 +378,6 @@ struct Over<'a> {
/// [`write_over`] through `over`.
fn write_over_in(over: &Over<'_>, refused: io::Error) -> io::Result<()> {
let tmp = over.tmp;
let opened = (over.open_tmp)().and_then(|from| Ok((from, (over.open_target)(true)?)));
let Ok((mut from, mut to)) = opened else {
// Best effort: the temporary file is all there is to clean up.
@@ -339,10 +389,10 @@ fn write_over_in(over: &Over<'_>, refused: io::Error) -> io::Result<()> {
if let Some(old) = &old
&& let Err(e) = (over.open_target)(false).and_then(|mut target| keep_old(&mut target, old))
{
// Best effort: a partial copy is of no use.
let _ = std::fs::remove_file(old);
let why =
format!("{refused}, and the file can't be copied aside before it is overwritten ({e}); the new content is kept in {}", tmp.display());
let why = format!(
"{refused}, and the file can't be copied aside before it is overwritten ({e}); the new content is kept in {}",
(over.tmp)().display()
);
return Err(io::Error::new(refused.kind(), RecoveryError(why)));
}
let copied = to.set_len(0).and_then(|()| io::copy(&mut from, &mut to)).and_then(|_| sync_file(&to));
@@ -358,17 +408,23 @@ fn write_over_in(over: &Over<'_>, refused: io::Error) -> io::Result<()> {
}
(Err(e), Some(old)) => Err(io::Error::new(
e.kind(),
RecoveryError(format!("{e} (the new content is kept in {}, the file as it was in {})", tmp.display(), old.display())),
RecoveryError(format!("{e} (the new content is kept in {}, the file as it was in {})", (over.tmp)().display(), old.display())),
)),
(Err(e), None) => Err(io::Error::new(e.kind(), RecoveryError(format!("{e} (the new content is kept in {})", tmp.display())))),
(Err(e), None) => Err(io::Error::new(e.kind(), RecoveryError(format!("{e} (the new content is kept in {})", (over.tmp)().display())))),
}
}
/// A flushed copy of what `target` holds, at `old` (for its owner only).
/// A flushed copy of what `target` holds, at `old` (for its owner only). A copy this call made and
/// could not finish is removed; a file already at `old` is left as it is.
fn keep_old(target: &mut File, old: &Path) -> io::Result<()> {
let mut to = create_private(old)?;
io::copy(target, &mut to)?;
sync_file(&to)
let copied = io::copy(target, &mut to).and_then(|_| sync_file(&to));
if copied.is_err() {
drop(to);
// Best effort: a partial copy is of no use.
let _ = std::fs::remove_file(old);
}
copied
}
/// A new file for its owner only (Unix): the system's temporary folder is shared.
@@ -523,6 +579,9 @@ thread_local! {
static FLUSHES_LEFT: std::cell::Cell<Option<u32>> = const { std::cell::Cell::new(None) };
/// Tests: how many plain `fsync` fallbacks were made on this thread.
static PLAIN_FSYNCS: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
/// Tests: [`write_atomic_checked`]'s folder refuses the rename.
#[cfg(unix)]
static RENAME_REFUSED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
/// A symbolic link keeps pointing at its file: write the file it names.
@@ -739,6 +798,87 @@ mod tests {
let _ = std::fs::remove_dir_all(d);
}
/// Permissions taken away from the file while the new content is written stay taken away.
#[cfg(unix)]
#[test]
fn a_checked_write_keeps_permissions_changed_while_it_fills() {
use std::os::unix::fs::PermissionsExt;
let (d, root, _) = checked_folders("checked-mode");
let path = root.join("inside/doc.txt");
std::fs::write(&path, b"old").unwrap();
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();
let fill = |f: &mut File| {
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))?;
f.write_all(b"new")
};
write_atomic_checked(&path, fill, under(&root)).unwrap();
assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
assert_eq!(std::fs::read(&path).unwrap(), b"new");
let _ = std::fs::remove_dir_all(d);
}
/// A folder that changed between being opened and being looked up by its path is not reported
/// as a read-only location.
#[cfg(unix)]
#[test]
fn a_changed_folder_is_not_a_read_only_location() {
let (d, root, outside) = checked_folders("checked-identity");
let opened = open_folder(&root.join("inside")).unwrap();
let e = opened_folder_path(&opened, &outside).unwrap_err();
assert!(e.to_string().contains("the folder changed while it was opened"), "{e}");
assert!(!read_only_location(&e), "{e:?}");
let _ = std::fs::remove_dir_all(d);
}
/// A checked write whose folder moved after it was opened, refused the rename, and failed to
/// copy into the file: the error names the temporary file where it is now.
#[cfg(unix)]
#[test]
fn a_checked_write_names_the_kept_file_where_its_folder_moved() {
let (d, root, _) = checked_folders("checked-moved");
std::fs::write(root.join("inside/doc.txt"), b"original").unwrap();
let check = under(&root);
let r = write_atomic_checked(
&root.join("inside/doc.txt"),
|f| f.write_all(b"new"),
|p| {
check(p)?;
std::fs::rename(root.join("inside"), root.join("moved"))?;
RENAME_REFUSED.with(|c| c.set(true));
// The temporary file's flush and the copy of the old content work, the next doesn't.
FLUSHES_LEFT.with(|c| c.set(Some(2)));
Ok(())
},
);
RENAME_REFUSED.with(|c| c.set(false));
FLUSHES_LEFT.with(|c| c.set(None));
let message = r.unwrap_err().to_string();
let kept: Vec<_> =
std::fs::read_dir(root.join("moved")).unwrap().map(|e| e.unwrap().path()).filter(|p| p.extension().is_some_and(|x| x == "tmp")).collect();
let [kept] = kept.as_slice() else { panic!("one temporary file: {kept:?}") };
let kept = std::fs::canonicalize(kept).unwrap();
assert!(message.contains(&kept.display().to_string()), "{message}");
assert_eq!(std::fs::read(&kept).unwrap(), b"new");
let _ = std::fs::remove_dir_all(d);
}
/// A folder that can be written and searched but not listed takes the file. (The permission
/// does not hold for root, which can list any folder.)
#[cfg(target_os = "linux")]
#[test]
fn a_checked_write_saves_into_a_folder_that_cannot_be_listed() {
use std::os::unix::fs::PermissionsExt;
let (d, root, _) = checked_folders("checked-search-only");
let folder = root.join("inside");
std::fs::set_permissions(&folder, std::fs::Permissions::from_mode(0o300)).unwrap();
let r = write_atomic_checked(&folder.join("doc.txt"), |f| f.write_all(b"new"), under(&root));
std::fs::set_permissions(&folder, std::fs::Permissions::from_mode(0o755)).unwrap();
// The folder flush needs it opened for reading: the file is written, and the error says so.
assert!(r.as_ref().map_or_else(|e| e.get_ref().is_some_and(|e| e.is::<WrittenError>()), |()| true), "{r:?}");
assert_eq!(std::fs::read(folder.join("doc.txt")).unwrap(), b"new");
let _ = std::fs::remove_dir_all(d);
}
/// The other files in `d` besides `keep`.
fn leftovers(d: &Path, keep: &str) -> Vec<String> {
std::fs::read_dir(d).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().to_string()).filter(|n| n != keep).collect()
@@ -995,6 +1135,33 @@ mod tests {
let _ = std::fs::remove_dir_all(&d);
}
/// A refused rename where a file is already at the name the old content would be copied to:
/// that file is left as it is, and the temporary file with the new content stays.
#[test]
fn a_refused_rename_leaves_a_file_already_at_the_backup_name() {
let d = dir("no-rename-backup-taken");
let path = d.join("doc.vectorcraft");
std::fs::write(&path, b"original").unwrap();
let r = write_atomic_stepping(
&path,
|f| f.write_all(b"new"),
create_new,
|tmp, _| {
std::fs::write(tmp.with_extension("old"), b"an earlier copy")?;
denied()
},
);
let message = r.unwrap_err().to_string();
let mut left = leftovers(&d, "doc.vectorcraft");
left.sort();
let [old, tmp] = left.as_slice() else { panic!("the earlier copy and the new content: {left:?}") };
assert!(message.contains(tmp.as_str()), "{message}");
assert_eq!(std::fs::read(d.join(old)).unwrap(), b"an earlier copy");
assert_eq!(std::fs::read(d.join(tmp)).unwrap(), b"new");
assert_eq!(std::fs::read(&path).unwrap(), b"original");
let _ = std::fs::remove_dir_all(&d);
}
/// A refused rename where the old content can't be copied aside (here: no flush works): the
/// file is left as it was, the temporary file with the whole new content stays and the error
/// names it.