Merge pull request #10260 from dotCooCoo/fix/plugins-tree-audit-in-checks

CI: the plug-in grant call-site audit runs in the checks shard
This commit is contained in:
.CooCoo
2026-12-02 07:13:43 -08:00
committed by GitHub
8 changed files with 195 additions and 100 deletions
+13
View File
@@ -47,6 +47,19 @@ jobs:
test-shards: 6
shard-command: cargo xtask ci shard
warm-command: cargo xtask ci warm
# A pull request runs only the test shards whose crates its changes reach: the crates that
# own a changed file or declare a read of it (`[package.metadata.craft] reads`), and every
# crate that depends on them. Shard 6 runs on every event. The `select legs` log lists the
# shards left out and why; pushes to main, the nightly run and the `full-ci` label run all
# six. `shard-members` names each shard's crates, as xtask/src/shards.rs › GROUPS does.
select-tests: true
shard-members: |
vectorcraft-ui-egui
vectorcraft-ui-egui
vectorcraft-engine
vectorcraft vectorcraft-web vectorcraft-cli vectorcraft-mcp xtask
(rest)
(always)
# The warm build runs as one `cache warm <k>/6` leg per shard, in parallel (each builds what
# its shard builds), and `cache warm` puts their files into the one entry it saves.
warm-split: true
-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)),
+27 -1
View File
@@ -70,7 +70,8 @@ pub static UI_EGUI: Split = Split {
],
};
/// The shards in order; `test-shards` in `.github/workflows/ci.yml` is its length.
/// The shards in order; `test-shards` in `.github/workflows/ci.yml` is its length, and its
/// `shard-members` names each shard's crates.
pub const GROUPS: &[Group] = &[
Group::Part(&UI_EGUI, 1),
Group::Part(&UI_EGUI, 2),
@@ -683,4 +684,29 @@ geom v0.1.0 (/w/geom)|
["lib: features absent in shard 4, [default,synth] with the whole workspace"]
);
}
/// The lines of the `shard-members: |` block in `workflow`, trimmed.
fn shard_members(workflow: &str) -> Vec<&str> {
let mut lines = workflow.lines().skip_while(|l| l.trim() != "shard-members: |");
let Some(key) = lines.next() else { return Vec::new() };
let indent = |l: &str| l.len() - l.trim_start().len();
lines.take_while(|l| !l.trim().is_empty() && indent(l) > indent(key)).map(str::trim).collect()
}
#[test]
fn ci_names_the_crates_of_every_shard_for_test_selection() {
// The shared gate runs only the shards that test a crate a pull request reaches, by these lines.
let expected: Vec<String> = GROUPS
.iter()
.map(|g| match g {
Group::Crates(crates) => crates.join(" "),
Group::Part(split, _) => split.crates.join(" "),
Group::Rest => "(rest)".to_owned(),
Group::Checks => "(always)".to_owned(),
})
.collect();
assert_eq!(shard_members(include_str!("../../.github/workflows/ci.yml")), expected, "shard-members in .github/workflows/ci.yml");
assert_eq!(shard_members(" shard-members: |\n a b\n (rest)\n next: 1\n"), ["a b", "(rest)"]);
assert!(shard_members("test-shards: 6\n").is_empty());
}
}