diff --git a/crates/engine/src/cmd/fileio/access.rs b/crates/engine/src/cmd/fileio/access.rs index 84b8bc1a4f..8691ebb1fb 100644 --- a/crates/engine/src/cmd/fileio/access.rs +++ b/crates/engine/src/cmd/fileio/access.rs @@ -1,5 +1,3 @@ -#[cfg(not(target_arch = "wasm32"))] -use super::write_atomic; use super::{EngineError, Result, Session, Value, bad, json}; // ---------- the file system (none on the web, where commands take and return bytes) ---------- @@ -325,8 +323,25 @@ pub(crate) fn write_file(path: &str, bytes: &[u8]) -> Result<()> { // Work that stops early for a cancel can leave a truncated result: none of it is written. vectorcraft_doc::cancel::check()?; may_write(path)?; - // Never a half-written file: see [`write_atomic`]. - write_atomic(std::path::Path::new(path), bytes).map_err(|e| write_error(path, e)) + // Never a half-written file: see [`vectorcraft_format::write_atomic`]. + write_checked(path, |f| std::io::Write::write_all(f, bytes)).map_err(|e| write_error(path, e)) +} + +/// [`vectorcraft_format::write_atomic_with`] for `path`, which [`may_write`] allowed. While writes +/// are checked ([`crate::file_access::writes_checked`]), the folder that receives the file is +/// checked again as it is opened, and the file goes into that open folder +/// ([`vectorcraft_format::write_atomic_checked`]): a folder on the path that is replaced after the +/// check does not redirect the write. +#[cfg(not(target_arch = "wasm32"))] +fn write_checked(path: &str, fill: impl FnOnce(&mut std::fs::File) -> std::io::Result<()>) -> std::io::Result<()> { + let path = std::path::Path::new(path); + if !crate::file_access::writes_checked() { + 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) + }) } /// The error writing `path` failed with: [`EngineError::Cancelled`] for work canceled before the @@ -344,7 +359,7 @@ fn write_error(path: &str, error: std::io::Error) -> EngineError { pub fn write_file_with(path: &str, fill: &mut dyn FnMut(&mut dyn std::io::Write) -> std::io::Result<()>) -> Result<()> { vectorcraft_doc::cancel::check()?; may_write(path)?; - vectorcraft_format::write_atomic_with(std::path::Path::new(path), |f| fill(f)).map_err(|e| write_error(path, e)) + write_checked(path, |f| fill(f)).map_err(|e| write_error(path, e)) } /// The save commands' writer: preserves a filesystem location refusal as a typed error. Other @@ -358,7 +373,7 @@ pub fn write_save_file(path: &str, bytes: &[u8]) -> Result<()> { pub fn write_save_file_with(path: &str, fill: &mut dyn FnMut(&mut dyn std::io::Write) -> std::io::Result<()>) -> Result<()> { vectorcraft_doc::cancel::check()?; may_write(path)?; - vectorcraft_format::write_atomic_with(std::path::Path::new(path), |f| fill(f)).map_err(|e| save_write_error(path, e)) + write_checked(path, |f| fill(f)).map_err(|e| save_write_error(path, e)) } #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index 7daa75e0ae..bc2acda5e6 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -462,8 +462,7 @@ pub fn is_path_key(key: &str) -> bool { /// May `path` be written here? Always, without roots in force and outside a script's command /// ([`with_script_gate`]). pub fn check_write(path: &str) -> Result<(), String> { - current().map_or(Ok(()), |r| r.check(path, Access::Write))?; - check_gate(path, Access::Write)?; + check_write_unrecorded(path)?; WRITES.with(|w| { if let Some(paths) = w.borrow_mut().as_mut() && !paths.iter().any(|(p, _)| p == path) @@ -474,6 +473,17 @@ pub fn check_write(path: &str) -> Result<(), String> { Ok(()) } +/// [`check_write`] without recording `path` as written. +pub(crate) fn check_write_unrecorded(path: &str) -> Result<(), String> { + current().map_or(Ok(()), |r| r.check(path, Access::Write))?; + check_gate(path, 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() +} + /// A file's modification time and length; `None` when there is no file at `path`. type Stamp = Option<(Option, u64)>; diff --git a/crates/format/src/atomic.rs b/crates/format/src/atomic.rs index f314fcdd15..54a0fe0432 100644 --- a/crates/format/src/atomic.rs +++ b/crates/format/src/atomic.rs @@ -82,6 +82,171 @@ fn create_new(path: &Path) -> io::Result { OpenOptions::new().write(true).create_new(true).open(path) } +/// [`write_atomic_with`] for a `path` the caller has allowed by its name. On Unix the folder that +/// holds the file is opened once, and `allowed` is asked again with the path that open folder has +/// then, joined with the file's name. The temporary file, the replacement, a copy over the file +/// where the folder refuses the replacement, and the folder flush all go through that open folder, +/// and none of them looks its path up again. A folder replaced (or swapped for a link) before it is +/// opened fails `allowed`. A folder replaced after it is opened does not receive the file. A link at +/// the final name is followed once before the folder is opened, as [`write_atomic_with`] follows it; +/// a link put there later is replaced, never followed. Elsewhere this is `allowed(path)` followed by +/// [`write_atomic_with`]. +#[cfg(unix)] +pub fn write_atomic_checked( + path: &Path, + fill: impl FnOnce(&mut File) -> io::Result<()>, + allowed: impl FnOnce(&Path) -> io::Result<()>, +) -> io::Result<()> { + use rustix::fs::{AtFlags, Mode, OFlags}; + let resolved = resolve_link(path)?; + let name = resolved + .file_name() + .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); + allowed(&target)?; + let old = rustix::fs::statat(&dir, &name, AtFlags::SYMLINK_NOFOLLOW).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 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() })); + let open_target = |write: bool| -> io::Result { + 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)?)) + }; + match rustix::fs::openat(&dir, &tmp_name, new_file, mode).map(File::from) { + Ok(mut f) => { + let filled = fill(&mut f).and_then(|()| sync_file(&f)).and_then(|()| not_cancelled()); + if let Err(e) = filled { + drop(f); + 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); + } + drop(f); + let Err(refused) = rustix::fs::renameat(&dir, &tmp_name, &dir, &name) else { return synced() }; + let over = Over { + tmp: &tmp, + 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())?)) + }, + remove_tmp: &remove_tmp, + open_target: &open_target, + synced: &synced, + }; + write_over_in(&over, refused.into()) + } + // A folder that isn't there, a full volume: nothing can be saved there. + Err(e) if matches!(io::Error::from(e).kind(), io::ErrorKind::NotFound | io::ErrorKind::StorageFull | io::ErrorKind::QuotaExceeded) => { + Err(e.into()) + } + Err(refused) => { + // The folder takes no temporary file: it is written in the system's folder and copied in. + let elsewhere = std::env::temp_dir().join(&tmp_name); + let mut f = create_private(&elsewhere).map_err(|_| io::Error::from(refused))?; + let filled = fill(&mut f).and_then(|()| sync_file(&f)).and_then(|()| not_cancelled()); + drop(f); + let remove = || { + // Best effort: the temporary file is all there is to clean up. + let _ = std::fs::remove_file(&elsewhere); + }; + if let Err(e) = filled { + remove(); + return Err(e); + } + let over = Over { + tmp: &elsewhere, + old: elsewhere.with_extension("old"), + open_tmp: &|| File::open(&elsewhere), + remove_tmp: &remove, + open_target: &open_target, + synced: &synced, + }; + write_over_in(&over, refused.into()) + } + } +} + +/// See the Unix version. +#[cfg(not(unix))] +pub fn write_atomic_checked( + path: &Path, + fill: impl FnOnce(&mut File) -> io::Result<()>, + allowed: impl FnOnce(&Path) -> io::Result<()>, +) -> io::Result<()> { + allowed(path)?; + write_atomic_with(path, fill) +} + +/// The path folder `dir` has now, which `parent` named when it was opened: `parent` with its links +/// followed, when that is still the folder `dir` holds (the same device and inode). A folder +/// replaced in between is an error. +#[cfg(unix)] +fn opened_folder_path(dir: &std::os::fd::OwnedFd, parent: &Path) -> io::Result { + 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()))); + } + Ok(real) +} + +/// [`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. +#[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}; + if FileType::from_raw_mode(old.st_mode) != FileType::RegularFile { + return Ok(()); + } + 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) { + 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. +#[cfg(target_os = "linux")] +fn keep_acl_at(dir: &std::os::fd::OwnedFd, name: &std::ffi::OsStr, 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; + }; + 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()), + Err(e) if e == Errno::NODATA => match rustix::fs::fremovexattr(tmp, ACL) { + Ok(()) => true, + Err(e) => e == Errno::NODATA || e == Errno::NOTSUP, + }, + Err(e) => e == Errno::NOTSUP, + } +} + +#[cfg(all(unix, not(target_os = "linux")))] +fn keep_acl_at(_: &std::os::fd::OwnedFd, _: &std::ffi::OsStr, _: &File) -> bool { + true +} + /// [`write_atomic_with`], with `create` making the temporary file beside the target and `rename` /// moving it over the target. fn write_atomic_stepping( @@ -130,16 +295,49 @@ fn write_atomic_stepping( /// the copy into `target` fails it is damaged: `tmp` and the copy of the old content stay and the /// error says where they are. fn write_over(tmp: &Path, target: &Path, refused: io::Error) -> io::Result<()> { - let opened = File::open(tmp).and_then(|from| Ok((from, OpenOptions::new().write(true).create(true).truncate(false).open(target)?))); + let over = Over { + tmp, + old: tmp.with_extension("old"), + open_tmp: &|| File::open(tmp), + remove_tmp: &|| { + let _ = std::fs::remove_file(tmp); + }, + open_target: &|write| if write { OpenOptions::new().write(true).create(true).truncate(false).open(target) } else { File::open(target) }, + synced: &|| sync_written_parent(target), + }; + write_over_in(&over, refused) +} + +/// 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 file as it was is copied aside. + old: PathBuf, + open_tmp: &'a dyn Fn() -> io::Result, + /// Best effort. + remove_tmp: &'a dyn Fn(), + /// The target for writing (created when missing, not truncated) when `true`, for reading when + /// `false`. + open_target: &'a dyn Fn(bool) -> io::Result, + /// The target's folder flushed, after the target is written. + synced: &'a dyn Fn() -> io::Result<()>, +} + +/// [`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. - let _ = std::fs::remove_file(tmp); + (over.remove_tmp)(); return Err(refused); }; // Nothing to keep of a file that is new or empty. - let old = to.metadata().map_or(true, |m| m.len() > 0).then(|| tmp.with_extension("old")); + let old = to.metadata().map_or(true, |m| m.len() > 0).then(|| over.old.clone()); if let Some(old) = &old - && let Err(e) = keep_old(target, 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); @@ -152,11 +350,11 @@ fn write_over(tmp: &Path, target: &Path, refused: io::Error) -> io::Result<()> { match (copied, old) { (Ok(()), old) => { // Best effort: the file is saved, so the copies are no longer needed. - let _ = std::fs::remove_file(tmp); + (over.remove_tmp)(); if let Some(old) = old { let _ = std::fs::remove_file(old); } - sync_written_parent(target) + (over.synced)() } (Err(e), Some(old)) => Err(io::Error::new( e.kind(), @@ -166,10 +364,10 @@ fn write_over(tmp: &Path, target: &Path, refused: io::Error) -> io::Result<()> { } } -/// A flushed copy of `target` as it is, at `old` (for its owner only). -fn keep_old(target: &Path, old: &Path) -> io::Result<()> { +/// A flushed copy of what `target` holds, at `old` (for its owner only). +fn keep_old(target: &mut File, old: &Path) -> io::Result<()> { let mut to = create_private(old)?; - io::copy(&mut File::open(target)?, &mut to)?; + io::copy(target, &mut to)?; sync_file(&to) } @@ -466,6 +664,81 @@ mod tests { true } + /// A folder `root/inside` and a folder `outside` beside `root`, by their real paths, and a check + /// that allows paths under `root` only. + #[cfg(unix)] + fn checked_folders(name: &str) -> (PathBuf, PathBuf, PathBuf) { + let d = std::fs::canonicalize(dir(name)).unwrap(); + let (root, outside) = (d.join("root"), d.join("outside")); + std::fs::create_dir_all(root.join("inside")).unwrap(); + std::fs::create_dir_all(&outside).unwrap(); + (d, root, outside) + } + + #[cfg(unix)] + fn under(root: &Path) -> impl FnOnce(&Path) -> io::Result<()> + '_ { + move |p: &Path| if p.starts_with(root) { Ok(()) } else { Err(io::Error::other(format!("{} is outside", p.display()))) } + } + + /// A folder on the path that is a link to a folder outside when the write starts fails the check + /// made on the folder that is opened, and nothing is written outside. + #[cfg(unix)] + #[test] + fn a_checked_write_refuses_a_folder_replaced_before_it_is_opened() { + let (d, root, outside) = checked_folders("checked-before"); + std::fs::remove_dir(root.join("inside")).unwrap(); + std::os::unix::fs::symlink(&outside, root.join("inside")).unwrap(); + let r = write_atomic_checked(&root.join("inside/doc.txt"), |f| f.write_all(b"new"), under(&root)); + assert!(r.as_ref().is_err_and(|e| e.to_string().contains("is outside")), "{r:?}"); + assert!(std::fs::read_dir(&outside).unwrap().next().is_none(), "nothing is left outside"); + let _ = std::fs::remove_dir_all(d); + } + + /// A folder on the path replaced by a link to a folder outside after it is checked and opened + /// does not redirect the write: the file goes into the folder that was opened. + #[cfg(unix)] + #[test] + fn a_checked_write_stays_in_the_folder_it_opened() { + let (d, root, outside) = checked_folders("checked-after"); + 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"))?; + std::os::unix::fs::symlink(&outside, root.join("inside")) + }, + ); + r.unwrap(); + assert!(!outside.join("doc.txt").exists(), "the write followed the replaced folder"); + assert_eq!(std::fs::read(root.join("moved/doc.txt")).unwrap(), b"new"); + let _ = std::fs::remove_dir_all(d); + } + + /// A link put at the file's name after the check is replaced by the file, not followed. + #[cfg(unix)] + #[test] + fn a_checked_write_replaces_a_link_put_at_its_name() { + let (d, root, outside) = checked_folders("checked-link"); + std::fs::write(outside.join("other.txt"), b"keep").unwrap(); + let path = root.join("inside/doc.txt"); + let check = under(&root); + write_atomic_checked( + &path, + |f| f.write_all(b"new"), + |p| { + check(p)?; + std::os::unix::fs::symlink(outside.join("other.txt"), &path) + }, + ) + .unwrap(); + assert_eq!(std::fs::read(outside.join("other.txt")).unwrap(), b"keep"); + assert!(std::fs::symlink_metadata(&path).unwrap().is_file()); + assert_eq!(std::fs::read(&path).unwrap(), b"new"); + let _ = std::fs::remove_dir_all(d); + } + /// The other files in `d` besides `keep`. fn leftovers(d: &Path, keep: &str) -> Vec { std::fs::read_dir(d).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().to_string()).filter(|n| n != keep).collect() diff --git a/crates/format/src/lib.rs b/crates/format/src/lib.rs index 654f0ac065..9975527f78 100644 --- a/crates/format/src/lib.rs +++ b/crates/format/src/lib.rs @@ -58,7 +58,7 @@ use vectorcraft_doc::{Document, ImageBlob}; #[cfg(all(unix, not(target_arch = "wasm32")))] pub use atomic::sync_parent; #[cfg(not(target_arch = "wasm32"))] -pub use atomic::{keep_permissions, read_only_location, sync_file, write_atomic, write_atomic_with, write_new_with}; +pub use atomic::{keep_permissions, read_only_location, sync_file, write_atomic, write_atomic_checked, write_atomic_with, write_new_with}; use craft_gzip::Gz; pub use craft_vectorcraft_format::base64::{decode as base64_decode, decoded_len as base64_decoded_len, encode as base64_encode}; use craft_vectorcraft_format::stream::{FileHeader, Indent, KeyScan, write_file_json};