Merge main into fix/ci-select-tests

This commit is contained in:
dotCooCoo committed 2026-12-02 07:27:01 -08:00
commit aee21d8bb7
7 files changed
+505 -127

No files matched your search

+350 -28
View File
@@ -89,13 +89,15 @@ fn create_new(path: &Path) -> io::Result<File> {
/// 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
/// a link put there later is replaced, never followed. A folder that moved after it was opened is
/// checked with `allowed` again at its new path right before the file is put in place, and a folder
/// whose new path the system does not report fails. 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<()>,
allowed: impl Fn(&Path) -> io::Result<()>,
) -> io::Result<()> {
use rustix::fs::{AtFlags, Mode, OFlags};
// A path written as a folder (`draft.svg/`, `draft.svg/.`) is not a file path: `file_name`
@@ -126,6 +128,24 @@ pub fn write_atomic_checked(
};
// 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);
// Right before the file is put in place: a folder that moved since it was opened is checked
// again where it is now, so a move out of the allowed folders does not receive the file.
let still_allowed = || -> io::Result<()> {
let here = folder_now(&dir, &real);
let open = rustix::fs::fstat(&dir)?;
// The path itself, not a link that leads to the folder from elsewhere.
let same = |p: &Path| {
std::fs::canonicalize(p).is_ok_and(|c| c == p) && rustix::fs::stat(p).is_ok_and(|s| (s.st_dev, s.st_ino) == (open.st_dev, open.st_ino))
};
if here == real && same(&real) {
return Ok(());
}
if here == real || !same(&here) {
return Err(io::Error::other(format!("{}: the folder moved while the file was written", target.display())));
}
allowed(&here.join(stored_name(&dir, &here, &name)))
.map_err(|_| io::Error::other(format!("{}: the folder moved while the file was written", target.display())))
};
let synced = || {
// Opened for reading here: the folder handle above may allow name lookups only.
let flushed =
@@ -133,13 +153,21 @@ pub fn write_atomic_checked(
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> {
// A missing target is created by `create_target`, after the last check. An existing one is
// opened with `O_CREAT` as before, so Linux's `fs.protected_regular` still applies to it.
if write && matches!(rustix::fs::statat(&dir, &name, AtFlags::SYMLINK_NOFOLLOW), Err(e) if e == rustix::io::Errno::NOENT) {
return Err(io::ErrorKind::NotFound.into());
}
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)?))
};
let create_target = || -> io::Result<File> { Ok(File::from(rustix::fs::openat(&dir, &name, new_file, 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 {
// Checked before the temporary file takes the old file's wider permissions, and again
// right before the rename.
if let Err(e) = filled.and_then(|()| still_allowed()) {
drop(f);
remove_tmp();
return Err(e);
@@ -151,6 +179,10 @@ pub fn write_atomic_checked(
let _ = keep_permissions_at(&dir, &name, &old, &f);
}
drop(f);
if let Err(e) = still_allowed() {
remove_tmp();
return Err(e);
}
#[cfg(test)]
let refuse = RENAME_REFUSED.with(std::cell::Cell::get);
#[cfg(not(test))]
@@ -189,7 +221,9 @@ pub fn write_atomic_checked(
},
remove_tmp: &remove_tmp,
open_target: &open_target,
create_target: &create_target,
synced: &synced,
still_allowed: &still_allowed,
};
write_over_in(&over, refused.into())
}
@@ -207,7 +241,7 @@ pub fn write_atomic_checked(
// Best effort: the temporary file is all there is to clean up.
let _ = std::fs::remove_file(&elsewhere);
};
if let Err(e) = filled {
if let Err(e) = filled.and_then(|()| still_allowed()) {
remove();
return Err(e);
}
@@ -222,7 +256,9 @@ pub fn write_atomic_checked(
open_tmp: &|| File::open(&elsewhere),
remove_tmp: &remove,
open_target: &open_target,
create_target: &create_target,
synced: &synced,
still_allowed: &still_allowed,
};
write_over_in(&over, refused.into())
}
@@ -422,7 +458,10 @@ fn write_over(tmp: &Path, target: &Path, refused: io::Error) -> io::Result<()> {
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) },
#[cfg(unix)]
create_target: &|| create_new(target),
synced: &|| sync_written_parent(target),
still_allowed: &|| Ok(()),
};
write_over_in(&over, refused)
}
@@ -441,38 +480,92 @@ struct Over<'a> {
open_tmp: &'a dyn Fn() -> io::Result<File>,
/// Best effort.
remove_tmp: &'a dyn Fn(),
/// The target for writing (created when missing, not truncated) when `true`, for reading when
/// `false`.
/// Opens the target without truncating it for writing when `true`, or for reading when `false`.
/// Checked Unix writes defer creation of a missing target to `create_target`.
open_target: &'a dyn Fn(bool) -> io::Result<File>,
/// Creates a missing target after the final check and fails if its name is taken.
#[cfg(unix)]
create_target: &'a dyn Fn() -> io::Result<File>,
/// The target's folder flushed, after the target is written.
synced: &'a dyn Fn() -> io::Result<()>,
/// Asked right before the target is overwritten: an error leaves it as it was.
still_allowed: &'a dyn Fn() -> io::Result<()>,
}
/// [`write_over`] through `over`.
fn write_over_in(over: &Over<'_>, refused: io::Error) -> io::Result<()> {
let opened = (over.open_tmp)().and_then(|from| Ok((from, (over.open_target)(true)?)));
let Ok((mut from, mut to)) = opened else {
// Checked Unix writes create a missing target only after the final check.
if let Err(e) = (over.still_allowed)() {
(over.remove_tmp)();
return Err(e);
}
let opened = (over.open_tmp)().and_then(|from| {
let to = match (over.open_target)(true) {
Ok(to) => Some(to),
#[cfg(unix)]
Err(e) if e.kind() == io::ErrorKind::NotFound => None,
Err(e) => return Err(e),
};
Ok((from, to))
});
let Ok((mut from, to)) = opened else {
// Best effort: the temporary file is all there is to clean up.
(over.remove_tmp)();
return Err(refused);
};
// Nothing to keep of a file that is new or empty. The copy is read from the file `to` writes
// into: one put at its name meanwhile is not copied in its place.
let kept = to.metadata().map_or(true, |m| m.len() > 0);
let kept = to.as_ref().is_some_and(|to| to.metadata().map_or(true, |m| m.len() > 0));
if kept
&& let Err(e) = (over.open_target)(false).and_then(|mut target| {
if !same_file(&target, &to) {
if !to.as_ref().is_some_and(|to| same_file(&target, to)) {
return Err(io::Error::other("the file was replaced while it was opened"));
}
keep_old(&mut target, over)
})
{
#[cfg(unix)]
if let Err(e) = (over.still_allowed)() {
drop((from, to));
(over.remove_tmp)();
return Err(e);
}
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)));
}
if let Err(e) = (over.still_allowed)() {
// Nothing was overwritten: neither copy is needed.
drop((from, to));
(over.remove_tmp)();
if kept {
(over.remove_old)();
}
return Err(e);
}
let mut to = match to {
Some(to) => to,
#[cfg(unix)]
None => match (over.create_target)() {
Ok(to) => to,
// A file put at the name meanwhile is left alone, and reported as there.
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {
(over.remove_tmp)();
return Err(e);
}
Err(_) => {
(over.remove_tmp)();
return Err(refused);
}
},
#[cfg(not(unix))]
None => {
(over.remove_tmp)();
return Err(refused);
}
};
let copied = to.set_len(0).and_then(|()| io::copy(&mut from, &mut to)).and_then(|_| sync_file(&to));
drop((from, to));
match (copied, kept) {
@@ -826,8 +919,18 @@ mod tests {
(d, root, outside)
}
/// Whether this system says where an open folder is now: macOS always, Linux and Android through
/// `/proc/self/fd`, which a chroot may lack. Decided without `folder_now`.
#[cfg(unix)]
fn under(root: &Path) -> impl FnOnce(&Path) -> io::Result<()> + '_ {
fn reports_open_folder_paths() -> bool {
if cfg!(target_vendor = "apple") {
return true;
}
cfg!(any(target_os = "linux", target_os = "android")) && Path::new("/proc/self/fd").is_dir()
}
#[cfg(unix)]
fn under(root: &Path) -> impl Fn(&Path) -> io::Result<()> + '_ {
move |p: &Path| if p.starts_with(root) { Ok(()) } else { Err(io::Error::other(format!("{} is outside", p.display()))) }
}
@@ -851,22 +954,51 @@ mod tests {
#[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)?;
|f| {
std::fs::rename(root.join("inside"), root.join("moved"))?;
std::os::unix::fs::symlink(&outside, root.join("inside"))
std::os::unix::fs::symlink(&outside, root.join("inside"))?;
f.write_all(b"new")
},
under(&root),
);
if !reports_open_folder_paths() {
assert!(r.as_ref().is_err_and(|e| e.to_string().contains("the folder moved")), "{r:?}");
assert!(!outside.join("doc.txt").exists() && !root.join("moved/doc.txt").exists());
assert!(std::fs::read_dir(root.join("moved")).unwrap().next().is_none());
let _ = std::fs::remove_dir_all(d);
return;
}
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 folder moved out of the allowed root while the file is written receives nothing: the move is
/// caught before the file is put in place, and the temporary file is removed.
#[cfg(unix)]
#[test]
fn a_checked_write_refuses_a_folder_moved_outside_while_it_fills() {
let (d, root, outside) = checked_folders("checked-moved-out");
let r = write_atomic_checked(
&root.join("inside/doc.txt"),
|f| {
f.write_all(b"new")?;
std::fs::rename(root.join("inside"), outside.join("inside"))
},
under(&root),
);
assert!(r.as_ref().is_err_and(|e| !read_only_location(e)), "{r:?}");
let message = r.unwrap_err().to_string();
assert!(message.contains(&root.join("inside/doc.txt").display().to_string()), "{message}");
assert!(message.contains("the folder moved"), "{message}");
assert!(!message.contains(&outside.display().to_string()), "{message}");
assert!(std::fs::read_dir(outside.join("inside")).unwrap().next().is_none(), "nothing is left outside");
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]
@@ -922,31 +1054,34 @@ mod tests {
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 temporary file and the copy of the old content stay in that folder,
/// and the error names them where they are now. (FreeBSD does not say where an open folder is
/// now: there the error names them where the folder was opened.)
/// A failed fallback names the recovery files in the folder's current location when available.
/// A move is refused when the system cannot resolve the open folder's current path.
#[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)?;
|f| {
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(())
f.write_all(b"new")
},
under(&root),
);
RENAME_REFUSED.with(|c| c.set(false));
FLUSHES_LEFT.with(|c| c.set(None));
let message = r.unwrap_err().to_string();
if !reports_open_folder_paths() {
assert!(message.contains("the folder moved"), "{message}");
assert_eq!(std::fs::read(root.join("moved/doc.txt")).unwrap(), b"original");
assert_eq!(std::fs::read_dir(root.join("moved")).unwrap().count(), 1);
let _ = std::fs::remove_dir_all(d);
return;
}
let kept = |ext: &str| -> PathBuf {
let found: Vec<_> = std::fs::read_dir(root.join("moved"))
.unwrap()
@@ -958,15 +1093,200 @@ mod tests {
};
let (tmp, old) = (kept("tmp"), kept("old"));
assert_eq!((std::fs::read(&tmp).unwrap(), std::fs::read(&old).unwrap()), (b"new".to_vec(), b"original".to_vec()));
let named_in =
if cfg!(any(target_os = "linux", target_os = "android", target_vendor = "apple")) { root.join("moved") } else { root.join("inside") };
for file in [&tmp, &old] {
let named = named_in.join(file.file_name().unwrap());
let named = root.join("moved").join(file.file_name().unwrap());
assert!(message.contains(&named.display().to_string()), "{} in {message}", named.display());
}
let _ = std::fs::remove_dir_all(d);
}
/// A refused rename whose folder is no longer allowed by the time the file would be overwritten
/// leaves the file as it was, and neither copy stays behind.
#[test]
fn a_refused_rename_does_not_overwrite_once_no_longer_allowed() {
let d = dir("no-rename-disallowed");
let (path, tmp, old) = (d.join("doc.txt"), d.join("doc.tmp"), d.join("doc.old"));
std::fs::write(&path, b"original").unwrap();
std::fs::write(&tmp, b"new").unwrap();
let checks = std::cell::Cell::new(0);
let over = Over {
tmp: &|| tmp.clone(),
create_old: &|| create_private(&old),
old: &|| old.clone(),
remove_old: &|| {
let _ = std::fs::remove_file(&old);
},
open_tmp: &|| File::open(&tmp),
remove_tmp: &|| {
let _ = std::fs::remove_file(&tmp);
},
open_target: &|write| if write { OpenOptions::new().write(true).open(&path) } else { File::open(&path) },
#[cfg(unix)]
create_target: &|| create_new(&path),
synced: &|| Ok(()),
still_allowed: &|| {
checks.set(checks.get() + 1);
if checks.get() == 1 {
Ok(())
} else {
assert_eq!(std::fs::read(&old).unwrap(), b"original");
Err(io::Error::other("moved outside"))
}
},
};
let e = write_over_in(&over, denied::<()>().unwrap_err()).unwrap_err();
assert_eq!(checks.get(), 2);
assert!(e.to_string().contains("moved outside"), "{e}");
assert_eq!(std::fs::read(&path).unwrap(), b"original");
assert!(!tmp.exists() && !old.exists());
let _ = std::fs::remove_dir_all(d);
}
/// A backup failure after a folder moves outside removes the new content and reports the refusal.
#[cfg(unix)]
#[test]
fn a_refused_rename_rechecks_authorization_after_a_backup_error() {
let (d, root, outside) = checked_folders("no-rename-backup-moved");
let inside = root.join("inside");
let moved = outside.join("inside");
let path = inside.join("doc.txt");
std::fs::write(&path, b"original").unwrap();
std::fs::write(inside.join("doc.tmp"), b"new").unwrap();
let checks = std::cell::Cell::new(0);
let over = Over {
tmp: &|| moved.join("doc.tmp"),
create_old: &|| {
std::fs::rename(&inside, &moved)?;
Err(io::Error::other("backup failed"))
},
old: &|| moved.join("doc.old"),
remove_old: &|| {},
open_tmp: &|| File::open(inside.join("doc.tmp")),
remove_tmp: &|| {
let _ = std::fs::remove_file(moved.join("doc.tmp"));
},
open_target: &|write| if write { OpenOptions::new().write(true).open(&path) } else { File::open(&path) },
create_target: &|| create_new(&path),
synced: &|| Ok(()),
still_allowed: &|| {
checks.set(checks.get() + 1);
if inside.exists() { Ok(()) } else { Err(io::Error::other("moved outside")) }
},
};
let e = write_over_in(&over, denied::<()>().unwrap_err()).unwrap_err();
assert_eq!(checks.get(), 2);
assert!(e.to_string().contains("moved outside"), "{e}");
assert!(!e.to_string().contains(&outside.display().to_string()), "{e}");
assert!(!e.get_ref().is_some_and(|e| e.is::<RecoveryError>()));
assert_eq!(std::fs::read(moved.join("doc.txt")).unwrap(), b"original");
assert_eq!(std::fs::read_dir(&moved).unwrap().count(), 1);
let _ = std::fs::remove_dir_all(d);
}
/// A refused fallback leaves a missing target absent when the final check fails.
#[cfg(unix)]
#[test]
fn a_refused_rename_leaves_a_missing_target_absent_once_no_longer_allowed() {
let d = dir("no-rename-disallowed-new");
let (path, tmp, old) = (d.join("doc.txt"), d.join("doc.tmp"), d.join("doc.old"));
std::fs::write(&tmp, b"new").unwrap();
let checks = std::cell::Cell::new(0);
let created = std::cell::Cell::new(false);
let over = Over {
tmp: &|| tmp.clone(),
create_old: &|| create_private(&old),
old: &|| old.clone(),
remove_old: &|| {
let _ = std::fs::remove_file(&old);
},
open_tmp: &|| File::open(&tmp),
remove_tmp: &|| {
let _ = std::fs::remove_file(&tmp);
},
open_target: &|write| {
if write { OpenOptions::new().write(true).open(&path) } else { File::open(&path) }
},
create_target: &|| {
created.set(true);
create_new(&path)
},
synced: &|| Ok(()),
still_allowed: &|| {
checks.set(checks.get() + 1);
if checks.get() == 1 {
assert!(!path.exists());
Ok(())
} else {
assert!(!created.get() && !path.exists());
Err(io::Error::other("moved outside"))
}
},
};
let e = write_over_in(&over, denied::<()>().unwrap_err()).unwrap_err();
assert_eq!(checks.get(), 2);
assert!(e.to_string().contains("moved outside"), "{e}");
assert!(!created.get());
assert!(!path.exists());
assert!(!tmp.exists() && !old.exists());
let _ = std::fs::remove_dir_all(d);
}
/// A checked fallback creates a missing target after authorization succeeds.
#[cfg(unix)]
#[test]
fn a_checked_write_creates_a_missing_target_when_the_rename_is_refused() {
let (d, root, _) = checked_folders("checked-new-no-rename");
let path = root.join("inside/doc.txt");
RENAME_REFUSED.with(|c| c.set(true));
let r = write_atomic_checked(&path, |f| f.write_all(b"new"), under(&root));
RENAME_REFUSED.with(|c| c.set(false));
r.unwrap();
assert_eq!(std::fs::read(&path).unwrap(), b"new");
assert_eq!(std::fs::read_dir(root.join("inside")).unwrap().count(), 1);
let _ = std::fs::remove_dir_all(d);
}
/// A file created by another writer at the final check is preserved whether that check succeeds or fails.
#[cfg(unix)]
#[test]
fn a_refused_rename_preserves_a_target_created_at_the_final_check() {
for allowed in [false, true] {
let d = dir("no-rename-new-target-taken");
let (path, tmp) = (d.join("doc.txt"), d.join("doc.tmp"));
std::fs::write(&tmp, b"new").unwrap();
let checks = std::cell::Cell::new(0);
let over = Over {
tmp: &|| tmp.clone(),
create_old: &|| Err(io::Error::other("no backup expected")),
old: &|| d.join("doc.old"),
remove_old: &|| {},
open_tmp: &|| File::open(&tmp),
remove_tmp: &|| {
let _ = std::fs::remove_file(&tmp);
},
open_target: &|write| if write { OpenOptions::new().write(true).open(&path) } else { File::open(&path) },
create_target: &|| create_new(&path),
synced: &|| Ok(()),
still_allowed: &|| {
checks.set(checks.get() + 1);
if checks.get() == 1 {
return Ok(());
}
std::fs::write(&path, b"someone else's")?;
if allowed { Ok(()) } else { Err(io::Error::other("moved outside")) }
},
};
let e = write_over_in(&over, denied::<()>().unwrap_err()).unwrap_err();
assert_eq!(checks.get(), 2);
if !allowed {
assert!(e.to_string().contains("moved outside"), "{e}");
}
assert_eq!(std::fs::read(&path).unwrap(), b"someone else's");
assert!(!tmp.exists() && !d.join("doc.old").exists());
let _ = std::fs::remove_dir_all(d);
}
}
/// A refused rename copies the old content through the file handle it then overwrites: when a
/// different file is at the name by the time it is opened for reading, nothing is overwritten and
/// the new content stays in the temporary file.
@@ -991,7 +1311,9 @@ mod tests {
let _ = std::fs::remove_file(&tmp);
},
open_target: &|write| if write { OpenOptions::new().write(true).open(&path) } else { File::open(&other) },
create_target: &|| create_new(&path),
synced: &|| Ok(()),
still_allowed: &|| Ok(()),
};
let e = write_over_in(&over, denied::<()>().unwrap_err()).unwrap_err();
assert!(e.to_string().contains("the file was replaced while it was opened"), "{e}");
-4
View File
@@ -44,7 +44,3 @@ vectorcraft-plugins = { path = ".", features = ["test-steady"] }
[features]
# `vectorcraft_plugins::steady` for other crates' tests (dev-dependencies only).
test-steady = []
# For CI's test selection: `tests/grant_sites.rs` reads the sources of every crate.
[package.metadata.craft]
reads-every-member = true
+1 -1
View File
@@ -301,7 +301,7 @@ impl Grant {
/// A [`Grant`] that [`crate::registry::grant`] records. The engine makes one where it records what
/// a person approved and where it loads the grants kept in its plug-in folder; tests that set up a
/// grant use the same constructors. `tests/grant_sites.rs` fails when other shipped code makes one.
/// grant use the same constructors. `cargo xtask grant-sites` fails when other shipped code makes one.
/// Native code linked into the app can still call these constructors, so the token does not
/// protect against such code.
#[derive(Debug)]
-92
View File
@@ -1,92 +0,0 @@
//! The shipped code that records a plug-in grant: only the engine's install approval and its load
//! of the plug-in folder's grants file make a `GrantToken` and call `registry::grant`,
//! `registry::install_checked` or `registry::install_for_load`. A new call site fails this test until
//! it is added to the list. It checks the source, not what native code can do at run time.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
/// `(text, file, how many times)` for every place shipped code may name it.
const EXPECTED: &[(&str, &str, usize)] = &[
("GrantToken::after_engine_approval", "crates/engine/src/cmd/plugin.rs", 1),
("GrantToken::from_engine_grants_file", "crates/engine/src/store.rs", 2),
("registry::grant", "crates/engine/src/store.rs", 1),
("registry::install_checked", "crates/engine/src/cmd/plugin.rs", 1),
("registry::install_for_load", "crates/engine/src/store.rs", 2),
];
/// The names the audit counts.
const NAMES: [&str; 5] = [
"GrantToken::after_engine_approval",
"GrantToken::from_engine_grants_file",
"registry::grant",
"registry::install_checked",
"registry::install_for_load",
];
/// Every `.rs` file under `dir`, without test files and folders.
fn sources(dir: &Path, out: &mut Vec<PathBuf>) {
let Ok(entries) = std::fs::read_dir(dir) else { return };
for entry in entries.flatten() {
let path = entry.path();
let name = entry.file_name().to_string_lossy().to_string();
if path.is_dir() {
if !matches!(name.as_str(), "tests" | "benches" | "examples" | "target" | "fuzz") {
sources(&path, out);
}
} else if name.ends_with(".rs") && name != "tests.rs" && !name.starts_with("tests_") && !name.ends_with("_tests.rs") {
out.push(path);
}
}
}
/// The lines of `text` that ship: not comments, and nothing from a top-level `#[cfg(test)] mod x {`
/// on.
fn shipped(text: &str) -> Vec<&str> {
let lines: Vec<&str> = text.lines().collect();
let opens_test_module = |i: usize| {
lines[i] == "#[cfg(test)]"
&& lines[i + 1..].iter().find(|l| !l.trim().is_empty()).is_some_and(|l| l.starts_with("mod ") && l.trim_end().ends_with('{'))
};
let end = (0..lines.len()).find(|&i| opens_test_module(i)).unwrap_or(lines.len());
lines[..end].iter().copied().filter(|l| !l.trim_start().starts_with("//")).collect()
}
/// How many times `name` occurs in `line` as a whole path (`registry::grant`, not `registry::granted`).
fn count(line: &str, name: &str) -> usize {
line.match_indices(name).filter(|(at, _)| !line[at + name.len()..].starts_with(|c: char| c.is_alphanumeric() || c == '_')).count()
}
#[test]
fn grant_token_call_sites_are_limited() {
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
let mut files = Vec::new();
for top in ["crates", "apps", "xtask"] {
sources(&root.join(top), &mut files);
}
assert!(files.len() > 100, "found only {} source files under {}", files.len(), root.display());
let mut found: BTreeMap<(&str, String), usize> = BTreeMap::new();
for file in &files {
let text = std::fs::read_to_string(file).unwrap();
let rel = file.strip_prefix(&root).unwrap().to_string_lossy().replace('\\', "/");
for line in shipped(&text) {
for name in NAMES {
let n = count(line, name);
if n > 0 {
*found.entry((name, rel.clone())).or_default() += n;
}
}
}
}
let expected: BTreeMap<(&str, String), usize> = EXPECTED.iter().map(|&(name, file, n)| ((name, file.to_string()), n)).collect();
assert_eq!(found, expected, "shipped code that makes a grant token or records a grant");
}
/// The audit's own filters: a test module and comments are left out, a longer name isn't counted.
#[test]
fn the_audit_skips_test_code_and_comments() {
let text = "fn a() { registry::grant(t); }\n// registry::grant(t)\nfn b() { registry::granted(id); }\n\n#[cfg(test)]\n\nmod tests {\n registry::grant(t);\n}\n";
let lines = shipped(text);
assert_eq!(lines.iter().map(|l| count(l, "registry::grant")).sum::<usize>(), 1, "{lines:?}");
}
+1 -1
View File
@@ -2858,7 +2858,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- **Plug-in grants cover one module (G17):** a grant counts only for the module with the id and SHA-256 it records. A module that lists permissions and has other bytes under the same id needs a new approval, even with the same permissions: `plugin.inspect` reports `needsApproval`, `plugin.install` refuses it without `grant`, Install Plug-in… and File › Open ask again, and the plug-in store and plug-in folders skip it. A module with a missing or empty permissions list needs no grant; without the list, it gets its kind's implied permissions. A grant with a malformed hash covers nothing. Regressions: `crates/plugins/src/permissions.rs`, `crates/engine/src/tests/plugins.rs`, `crates/ui-egui/src/tests/plugins.rs`. Scores and hours unchanged.
- **Plug-in approval needs a person (G17):** a plug-in's permissions and heavy budget are approved in a dialog that only a person can confirm: the control channel, MCP and injected input are refused, and `plugin.install` takes `grant` or `allowHeavy` only with that approval. `vectorcraft-cli mcp` and `run` refuse them unless started with `--allow-plugin-grants`. Regressions: `crates/engine/src/tests/plugins.rs`, `crates/ui-egui/src/tests/automation.rs`, `apps/vectorcraft-cli/tests/it/cli.rs`. Scores and hours unchanged.
- **A dialog's OK runs what it was opened for:** `ui.dialog.set`, and MCP's `answer_dialog` through it, can set a `__` field only when it is a control of that kind of dialog (a section or tab shown, a link between two fields, a name or search being typed). Every other `__` field, such as the `__command` and `__params` of a confirmation or the generic parameter dialog, a plug-in command dialog's `__command` and `__plugin`, or the paste a swatch conflict waits to finish, is refused with "the `<kind>` dialog cannot set protected field `<field>`"; the request sets no field, and with `action: "confirm"` OK does not run. Regressions: `crates/ui-egui/src/tests/automation.rs`, `crates/ui-egui/src/control/tests.rs`. Scores and hours unchanged.
- **Only an approval records a plug-in grant (G17):** `vectorcraft_plugins::registry::grant` takes a `GrantToken`, which the engine makes after an approval and when it loads `grants.json`, and `registry::install`, `install_bytes` and folder loads refuse a module that lists permissions no recorded grant gives this very module (`Error::NeedsApproval`), leaving the plug-in under its id and the revision as they were. A module without `permissions`, or with an empty list, installs as before. `docs/plugins.md` says what the approval does not protect against (native code linked into the app, another program running as the same user). Regressions: `crates/plugins/src/registry.rs`, `crates/plugins/tests/grant_sites.rs`, `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged.
- **Only an approval records a plug-in grant (G17):** `vectorcraft_plugins::registry::grant` takes a `GrantToken`, which the engine makes after an approval and when it loads `grants.json`, and `registry::install`, `install_bytes` and folder loads refuse a module that lists permissions no recorded grant gives this very module (`Error::NeedsApproval`), leaving the plug-in under its id and the revision as they were. A module without `permissions`, or with an empty list, installs as before. `docs/plugins.md` says what the approval does not protect against (native code linked into the app, another program running as the same user). Regressions: `crates/plugins/src/registry.rs`, `xtask/src/grant_sites.rs` (`cargo xtask grant-sites`), `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged.
- **A refused plug-in install writes nothing (G17):** `plugin.install` checks the plug-in installed under the module's id and its grant again while it records the grant and installs the module (`registry::install_checked`), and only then writes the module and its grant to the `Plug-ins` folder, attaches its settings and cache and turns a disabled plug-in on. When another session installed a plug-in with the id that would need `replace: true`, or changed the grant the checks relied on, the install is refused and the folder, `grants.json`, the disabled list and the installed plug-in stay as they were. Without a plug-in store, the approval comes from the grant the install checks again. A `plugin.remove`, or a load of the folder or of a plug-ins folder, in another session waits until the install has written the folder. VectorCraft's own rule. Regressions: `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged.
- **A plug-in's manifest from a custom section (G17):** a module that carries its manifest in a `vc_manifest` custom section, with `"abi": 1`, is inspected, installed and loaded at startup without being instantiated, so none of its code runs (its start function, data segments, `vc_abi_version` and `vc_manifest`); the host checks its imports against the manifest's permissions, its `memory`, `vc_alloc` and `vc_run` exports by type, and its initial memory and tables against the limits its runs have. A repeated section, one over 64 KiB, or one that is not a valid manifest or gives another `abi` is refused. Such a module whose start function traps installs and fails at each run. Modules without the section load as before. The example plug-in carries the section. Regressions: `crates/plugins/tests/abi.rs`, `crates/engine/src/tests/plugins.rs`, `crates/engine/tests/plugin_fuzz.rs`. Scores and hours unchanged.
- **Windows and processes take turns on the Plug-ins folder:** each one locks `disabled.lock` in the `Plug-ins` folder while it reads and changes the stored modules, `grants.json`, `disabled.json` and the plug-ins' settings and caches, so two installs of one id keep each module with its own grant, and grants or settings written by two processes are all kept. When the file can't be locked, `plugin.install` and `plugin.remove` fail and change nothing. VectorCraft's own rule. Regressions: `crates/engine/src/tests/plugins.rs`. Scores and hours unchanged.
+148
View File
@@ -0,0 +1,148 @@
//! `cargo xtask grant-sites`: the shipped code that records a plug-in grant. Only the engine's
//! install approval and its load of the plug-in folder's grants file make a `GrantToken` and call
//! `registry::grant`, `registry::install_checked` or `registry::install_for_load`. A new call site
//! fails this check until it is added to the list. It checks the source, not what native code can
//! do at run time.
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
/// `(text, file, how many times)` for every place shipped code may name it.
const EXPECTED: &[(&str, &str, usize)] = &[
("GrantToken::after_engine_approval", "crates/engine/src/cmd/plugin.rs", 1),
("GrantToken::from_engine_grants_file", "crates/engine/src/store.rs", 2),
("registry::grant", "crates/engine/src/store.rs", 1),
("registry::install_checked", "crates/engine/src/cmd/plugin.rs", 1),
("registry::install_for_load", "crates/engine/src/store.rs", 2),
];
/// This file lists the names it counts.
const SELF: &str = "xtask/src/grant_sites.rs";
/// The names the audit counts.
const NAMES: [&str; 5] = [
"GrantToken::after_engine_approval",
"GrantToken::from_engine_grants_file",
"registry::grant",
"registry::install_checked",
"registry::install_for_load",
];
pub fn run(root: &Path) -> Result<(), String> {
let mut files = Vec::new();
for top in ["crates", "apps", "xtask"] {
sources(&root.join(top), &mut files);
}
if files.len() <= 100 {
return Err(format!("grant-sites: found only {} source files under {}", files.len(), root.display()));
}
let found = scan(root, &files)?;
let expected: BTreeMap<(&str, String), usize> = EXPECTED.iter().map(|&(name, file, n)| ((name, file.to_string()), n)).collect();
if found == expected {
println!("grant-sites: only the listed shipped code makes a grant token or records a grant");
return Ok(());
}
let list =
|m: &BTreeMap<(&str, String), usize>| m.iter().map(|((name, file), n)| format!("{file}: {name} x{n}")).collect::<Vec<_>>().join("\n ");
Err(format!(
"shipped code that makes a grant token or records a grant differs from EXPECTED in xtask/src/grant_sites.rs\nfound:\n {}\nexpected:\n {}",
list(&found),
list(&expected)
))
}
/// How many times each name occurs in the shipped lines of each of `files`, keyed by the file's
/// path relative to `root`. This file is left out.
fn scan(root: &Path, files: &[PathBuf]) -> Result<BTreeMap<(&'static str, String), usize>, String> {
let mut found = BTreeMap::new();
for file in files {
let rel = file.strip_prefix(root).unwrap_or(file).to_string_lossy().replace('\\', "/");
if rel == SELF {
continue;
}
let text = std::fs::read_to_string(file).map_err(|e| format!("grant-sites: {}: {e}", file.display()))?;
for line in shipped(&text) {
for name in NAMES {
let n = count(line, name);
if n > 0 {
*found.entry((name, rel.clone())).or_default() += n;
}
}
}
}
Ok(found)
}
/// Every `.rs` file under `dir`, without test files and folders.
fn sources(dir: &Path, out: &mut Vec<PathBuf>) {
let Ok(entries) = std::fs::read_dir(dir) else { return };
for entry in entries.flatten() {
let path = entry.path();
let name = entry.file_name().to_string_lossy().to_string();
if path.is_dir() {
if !matches!(name.as_str(), "tests" | "benches" | "examples" | "target" | "fuzz") {
sources(&path, out);
}
} else if name.ends_with(".rs") && name != "tests.rs" && !name.starts_with("tests_") && !name.ends_with("_tests.rs") {
out.push(path);
}
}
}
/// The lines of `text` that ship: not comments, and nothing from a top-level `#[cfg(test)] mod x {`
/// on.
fn shipped(text: &str) -> Vec<&str> {
let lines: Vec<&str> = text.lines().collect();
let opens_test_module = |i: usize| {
lines[i] == "#[cfg(test)]"
&& lines[i + 1..].iter().find(|l| !l.trim().is_empty()).is_some_and(|l| l.starts_with("mod ") && l.trim_end().ends_with('{'))
};
let end = (0..lines.len()).find(|&i| opens_test_module(i)).unwrap_or(lines.len());
lines[..end].iter().copied().filter(|l| !l.trim_start().starts_with("//")).collect()
}
/// How many times `name` occurs in `line` as a whole path (`registry::grant`, not `registry::granted`).
fn count(line: &str, name: &str) -> usize {
line.match_indices(name).filter(|(at, _)| !line[at + name.len()..].starts_with(|c: char| c.is_alphanumeric() || c == '_')).count()
}
#[cfg(test)]
mod tests {
use super::*;
/// The audit's own filters: a test module and comments are left out, a longer name isn't counted.
#[test]
fn the_audit_skips_test_code_and_comments() {
let text = "fn a() { registry::grant(t); }\n// registry::grant(t)\nfn b() { registry::granted(id); }\n\n#[cfg(test)]\n\nmod tests {\n registry::grant(t);\n}\n";
let lines = shipped(text);
assert_eq!(lines.iter().map(|l| count(l, "registry::grant")).sum::<usize>(), 1, "{lines:?}");
}
/// The walk leaves out test files and folders and this file; a shipped call site is counted.
#[test]
fn the_audit_counts_shipped_files_only() {
let dir = std::env::temp_dir().join(format!("vc-grant-sites-{}", std::process::id()));
let file = |p: &str| {
let path = dir.join(p);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(path, "fn f() { registry::grant(t); }\n").unwrap();
};
for p in [
"crates/x/src/lib.rs",
"crates/x/src/tests.rs",
"crates/x/src/a_tests.rs",
"crates/x/tests/it.rs",
"crates/x/benches/b.rs",
"xtask/src/grant_sites.rs",
] {
file(p);
}
let mut files = Vec::new();
for top in ["crates", "apps", "xtask"] {
sources(&dir.join(top), &mut files);
}
let found = scan(&dir, &files);
let _ = std::fs::remove_dir_all(&dir);
assert_eq!(found.unwrap(), BTreeMap::from([(("registry::grant", "crates/x/src/lib.rs".to_owned()), 1)]));
}
}
+5 -1
View File
@@ -9,6 +9,7 @@ mod brands;
mod bundle;
mod cache_units;
mod cursors;
mod grant_sites;
mod ico;
mod layers;
mod pdf_deps;
@@ -33,6 +34,7 @@ commands:
assets check that every icon/image/font/asset is attributed in ASSETS.md
brands check that user-visible text (labels, params docs, MCP, docs, packaging) names no other vendor's products
cursors warn about Cursor values with no entry in crates/tools/src/cursors.toml (never fails)
grant-sites check that only the listed shipped code makes a plug-in grant token or records a grant
test-lint [--base <rev>] [--all]
weak tests in the lines changed since the base: fail on self-compares, reasonless
#[ignore], sleeps, reads of Rust source and tests no CI target runs; list only
@@ -46,7 +48,7 @@ commands:
layers enforce the crate dependency layering (plan/architecture.md §3)
wasm cargo check --target wasm32-unknown-unknown for the wasm-safe crates, the web app and its plug-in worker
test the workspace tests (cargo nextest when installed, else cargo test), then the doctests
ci fmt --check, clippy -D warnings, test, doctests, no-bundled-fonts, pdf-deps, assets, brands, cursors (warnings only), test-lint, ui-commands --check, layers, wasm (stops at first failure)
ci fmt --check, clippy -D warnings, test, doctests, no-bundled-fonts, pdf-deps, assets, brands, grant-sites, cursors (warnings only), test-lint, ui-commands --check, layers, wasm (stops at first failure)
ci shard shard $GATE_SHARD of $GATE_SHARDS of ci (xtask/src/shards.rs): a test shard runs
the tests and doctests of its crates, the last shard the other steps
ci warm build what every shard builds, without running it (fills the gate's cache); with
@@ -82,6 +84,7 @@ fn main() -> ExitCode {
Some("assets") => assets::run(&root()),
Some("brands") => brands::run(&root()),
Some("cursors") => cursors::run(&root()),
Some("grant-sites") => grant_sites::run(&root()),
Some("test-lint") => test_lint::run(&root(), &rest),
Some("i18n-report") => cmd_i18n_report(),
Some("ui-commands") => ui_commands::run(&root(), rest.contains(&"--check")),
@@ -548,6 +551,7 @@ fn ci_steps() -> Vec<Step> {
("pdf-deps", Box::new(|| pdf_deps::run(&root()))),
("assets", Box::new(|| assets::run(&root()))),
("brands", Box::new(|| brands::run(&root()))),
("grant-sites", Box::new(|| grant_sites::run(&root()))),
("cursors", Box::new(|| cursors::run(&root()))),
("test-lint", Box::new(|| test_lint::run(&root(), &[]))),
("i18n-report", Box::new(cmd_ci_i18n_report)),