EffectCraft: An open-source motion graphics and compositing tool written by scratch in pure Rust
Merge main into #2520; fold the PR's DefaultOutput into main's Lookup::QueueDefault (#2636) for renderQueue.add, render.preRender and file.createProxy, keep #2521's RUNS_SCRIPTS refusal with Vec<Lookup>, keep both tests, blender test expects no lookups, docs/mcp.md names all three
bflatasticb6d4090e4e39
diff --cc crates/automation/src/backend.rsindex f6ad65558,8f7931239..5bba7172a--- a/crates/automation/src/backend.rs+++ b/crates/automation/src/backend.rs@@@ -63,11 -63,12 +63,11 @@@ impl Backendpub fn exec(&mut self, id: &str, params: Value) -> Result<Value> {let params = if params.is_null() { json!({}) } else { params };if let Some(c) = self.confinement.clone() {- let lookup = match c.check_command(id, ¶ms)? {- Some(l @ (crate::confine::Lookup::ProjectFile | crate::confine::Lookup::QueueDefault)) => Some((l, self.run("project.summary", json!({}))?)),- Some(crate::confine::Lookup::RenderOutputs) => Some((crate::confine::Lookup::RenderOutputs, self.run("renderQueue.list", json!({}))?)),- None => None,- };- if let Some((lookup, found)) = lookup {+ for lookup in c.check_command(id, ¶ms)? {+ let found = match lookup {- Lookup::ProjectFile | Lookup::DefaultOutput => self.run("project.summary", json!({}))?,++ Lookup::ProjectFile | Lookup::QueueDefault => self.run("project.summary", json!({}))?,+ Lookup::RenderOutputs => self.run("renderQueue.list", json!({}))?,+ };c.check_lookup(&lookup, &found)?;}}diff --cc crates/automation/src/confine.rsindex 3a4d462e4,9b126bdcb..0e9d79d4b--- a/crates/automation/src/confine.rs+++ b/crates/automation/src/confine.rs@@@ -6,10 -6,10 +6,11 @@@//! `engine.batch`) is checked before it runs: its file parameters must be absolute paths inside//! the roots (symbolic links resolved, no `..`), any other absolute path in its parameters too,//! and commands that write to a file they are not given (Save, Increment and Save, rendering the-//! Render Queue) are checked against where they would write. Commands that run code or open-//! other applications (scripts, ScriptUI panels and the events that reach them, Execute File,-//! Reveal in Finder…) are refused while confined, as is granting scripts the file and network-//! access the user withheld.+//! Render Queue) are checked against where they would write. Queueing a render without naming+//! its output needs a saved project, because the default output of an unsaved one is the home- //! folder. Commands that run code or open other applications (scripts, Execute File, Reveal in- //! Finder…) are refused while confined.++//! folder. Commands that run code or open other applications (scripts, ScriptUI panels and the++//! events that reach them, Execute File, Reveal in Finder…) are refused while confined, as is++//! granting scripts the file and network access the user withheld.use std::path::{Component, Path, PathBuf};@@@ -99,11 -126,11 +130,12 @@@ const QUEUES_AN_OUTPUT: &[&str] = &["repub enum Lookup {/// The open project's file (`project.summary` → `path`).ProjectFile,- /// That the project has a file at all (`project.summary` → `path`), for a queued render whose- /// output the agent did not name: that default is derived from where the project sits.- DefaultOutput,/// Every output of the queued Render Queue items (`renderQueue.list`).RenderOutputs,- /// Whether the open project has a file (`project.summary` → `path`): a Render Queue item- /// added without `output` writes beside it, or to the home folder before the first save.++ /// Whether the open project has a file (`project.summary` → `path`): a render queued without++ /// `output` (Render Queue, Pre-render, Create Proxy) writes beside it, or to the home folder++ /// before the first save.+ QueueDefault,}impl Confinement {@@@ -142,20 -169,30 +174,30 @@@/// Check engine command `id` with `params` before it runs. Returns what must still be looked/// up and passed to [`Confinement::check_lookup`] for commands that write implicitly.- pub fn check_command(&self, id: &str, params: &Value) -> Result<Option<Lookup>> {+ pub fn check_command(&self, id: &str, params: &Value) -> Result<Vec<Lookup>> {- if REFUSED.contains(&id) {+ if REFUSED.contains(&id) || effectcraft_engine::commands::scripts::RUNS_SCRIPTS.contains(&id) {return Err(Error::BadArgs(format!("`{id}` is not available while file access is confined (--automation-read-root/--automation-write-root)")));}+ // Scripts can't grant themselves the access the user withheld+ // (`effectcraft_engine::prefs::Scripting::same_permissions`), and neither may a confined+ // agent: `prefs.set` saves the settings file, so a script run long after this session+ // would still have it. (`prefs.reset` only puts the defaults back, which grant nothing.)+ if id == "prefs.set" && prefs_keys(params).iter().any(|k| is_scripting_pref(k)) {+ return Err(Error::BadArgs(+ "`prefs.set`: the Scripting settings decide what a script may do, so they can't be changed while file access is confined".into(),+ ));+ }if id == "engine.batch" {for step in params.get("steps").and_then(Value::as_array).into_iter().flatten() {let Some(inner) = step.get("command").or_else(|| step.get("id")).and_then(Value::as_str) else { continue };let inner_params = step.get("params").cloned().unwrap_or(Value::Null);let named = keys_of(READS, inner).or_else(|| keys_of(WRITES, inner)).unwrap_or(&[]);+ let mixed = keys_of(MIXED_WRITES, inner).unwrap_or(&[]);// A step's `$N` reference is resolved only as the batch runs: never for a file.- if named.iter().filter_map(|k| inner_params.get(*k)).any(has_reference) {+ if named.iter().chain(mixed).filter_map(|k| inner_params.get(*k)).any(has_reference) {return Err(Error::BadArgs(format!("`{inner}` in a batch: file paths can't be `$N` references while file access is confined")));}- if self.check_command(inner, &inner_params)?.is_some() {+ if !self.check_command(inner, &inner_params)?.is_empty() {return Err(Error::BadArgs(format!("`{inner}` writes to its project's or queue's files: run it on its own while file access is confined")));}}@@@ -182,9 -215,8 +224,9 @@@for p in paths {// A Render Queue output may name a template instead of a file.match p.as_str() {- Some(s) if id == "render.preRender" && !looks_like_path(s) => {}+ Some(s) if matches!(id, "render.preRender" | "file.createProxy") && !looks_like_path(s) => {}Some(s) => {+ gave_a_file |= v.is_string();self.check(s, access)?;}None => return Err(Error::BadArgs(format!("`{id}`: `{key}` must be a path"))),@@@ -201,19 -242,14 +252,19 @@@if matches!(id, "file.openRecent" | "file.importRecent" | "anim.applyRecentPreset") && !given {return Err(Error::BadArgs(format!("`{id}`: give `path` while file access is confined")));}- // Without `output`, an unsaved project's item would write to the home folder (#2479).- if id == "renderQueue.add" && !given {- return Ok(Some(Lookup::QueueDefault));+ let mut lookups = vec![];+ // An output the agent did not name is derived from where the project sits: the Default+ // Output Folder preference when that is set, beside the project file otherwise — and the+ // home folder when the project has never been saved, outside every root (#2479). Only+ // that last case is certainly outside, and reading the preference here would duplicate+ // the engine's precedence, so an unsaved project is told to name its output instead.+ if QUEUES_AN_OUTPUT.contains(&id) && !gave_a_file {- lookups.push(Lookup::DefaultOutput);++ lookups.push(Lookup::QueueDefault);}if IMPLICIT_WRITES.contains(&id) && !(given && id == "file.save") {- return Ok(Some(if id == "file.save" || id == "file.incrementAndSave" { Lookup::ProjectFile } else { Lookup::RenderOutputs }));+ lookups.push(if id == "file.save" || id == "file.incrementAndSave" { Lookup::ProjectFile } else { Lookup::RenderOutputs });}- Ok(None)+ Ok(lookups)}/// Check what a [`Lookup`] found: `project.summary` or `renderQueue.list`'s result.@@@ -224,12 -260,11 +275,11 @@@Some(p) => self.check(p, Access::Write).map(drop),None => Err(Error::BadArgs("the project has no file yet: give `path` (Save As) inside an automation write root".into())),},- Lookup::DefaultOutput => match found.get("path").and_then(Value::as_str) {- // Saved: the default goes beside the project file, inside the roots, and what it- // writes is checked when the queue is rendered.+ // A saved project's default output sits beside it, and rendering checks it then.+ Lookup::QueueDefault => match found.get("path").and_then(Value::as_str) {Some(_) => Ok(()),None => Err(Error::BadArgs(- "the project has no file yet, so this would queue its default output (the home folder) outside the automation write roots: give `output`, or save the project inside a write root first".into(),- "`renderQueue.add`: the project has no file yet, so the default output would go to the home folder: give `output` inside an automation write root".into(),++ "the project has no file yet, so the default output would go to the home folder: give `output` inside an automation write root, or save the project inside one first".into(),)),},Lookup::RenderOutputs => {diff --cc crates/automation/src/tests.rsindex e2acce85f,68376fa46..ff7eedef8--- a/crates/automation/src/tests.rs+++ b/crates/automation/src/tests.rs@@@ -1381,55 -1479,86 +1479,139 @@@ fn automation_roots_confine_file_accesslet _ = std::fs::remove_dir_all(&base);}+/// #2479: a queued output the agent didn't name is derived from where the project sits, so on a+/// project that has never been saved it lands in the home folder, outside every automation root.+/// Queueing it there is refused, rather than leaving an item that can never be rendered.+#[test]+fn automation_roots_refuse_a_queued_output_from_an_unsaved_project() {+ use crate::confine::Confinement;+ let base = std::env::temp_dir().join(format!("ec-mcp-default-out-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&base);+ let write = base.join("out");+ std::fs::create_dir_all(&write).unwrap();+ let p = |f: &str| write.join(f).to_string_lossy().into_owned();+ let mut s = server();+ s.backend().confine(Confinement::new(&[], std::slice::from_ref(&write)).unwrap());+ call_json(&mut s, "execute_command", json!({"command": "comp.new", "params": {"name": "A", "width": 64, "height": 64}}));+ // Never saved: neither way of queueing a render may fall back to the home folder.+ for command in ["renderQueue.add", "render.preRender", "file.createProxy"] {+ let (c, err) = call(&mut s, "execute_command", json!({"command": command, "params": {"comp": "A"}}));+ assert!(err, "`{command}` without an output should be refused: {c:?}");+ let msg = c[0]["text"].as_str().unwrap_or_default();+ assert!(msg.contains("the project has no file yet"), "`{command}`: {msg}");+ }+ // An array where a path goes: the engine reads a scalar, so this is no output either.+ let (c, err) = call(&mut s, "execute_command", json!({"command": "file.createProxy", "params": {"comp": "A", "path": [p("arr.mov")]}}));+ assert!(err, "an array where the output goes should be refused: {c:?}");+ assert!(c[0]["text"].as_str().unwrap_or_default().contains("the project has no file yet"), "{c:?}");+ // Naming an Output Module template instead of a file is the same: its own output is relative.+ let (c, err) = call(&mut s, "execute_command", json!({"command": "render.preRender", "params": {"comp": "A", "output": "Lossless"}}));+ assert!(err, "a template output should be refused too: {c:?}");+ assert!(c[0]["text"].as_str().unwrap_or_default().contains("the project has no file yet"), "{c:?}");+ let queue = call_json(&mut s, "execute_command", json!({"command": "renderQueue.list"}));+ assert_eq!(queue["items"].as_array().map(Vec::len), Some(0), "nothing was queued: {queue}");+ // Naming an output inside a write root is how it is done.+ call_json(&mut s, "execute_command", json!({"command": "renderQueue.add", "params": {"comp": "A", "output": p("named.mp4")}}));+ // A proxy named outside the roots is refused. Whether that reads as a write or a read is+ // #1347's to classify, so this asserts the refusal and not its wording. The path is a sibling+ // of the write root rather than `/elsewhere/…`, which is not absolute on Windows and would be+ // refused for that instead.+ let outside = base.join("elsewhere").join("proxy.mov").to_string_lossy().into_owned();+ let (c, err) = call(&mut s, "execute_command", json!({"command": "file.createProxy", "params": {"comp": "A", "path": outside}}));+ assert!(err, "a proxy outside the roots should be refused: {c:?}");+ assert!(c[0]["text"].as_str().unwrap_or_default().contains("outside the automation roots"), "{c:?}");+ // Once the project is saved there, the default output (beside it) is queued as before.+ call_json(&mut s, "save_project", json!({"path": p("proj.ecproj")}));+ // A name that is not a path is an Output Module template, and the output it resolves to lands+ // beside the saved project: inside the write root, so it is allowed (#1347 relies on this).+ call_json(&mut s, "execute_command", json!({"command": "file.createProxy", "params": {"comp": "A", "path": "ProxyTemplate"}}));+ call_json(&mut s, "execute_command", json!({"command": "renderQueue.add", "params": {"comp": "A"}}));+ let queue = call_json(&mut s, "execute_command", json!({"command": "renderQueue.list"}));+ let out = queue["items"][1]["outputPath"].as_str().unwrap_or_default();+ assert!(out.starts_with(&*write.to_string_lossy()), "{queue}");+ let _ = std::fs::remove_dir_all(&base);+}+++ /// #2131 (audit F-11, "Running code"): `script.run` and the Scripts menu are refused while file+ /// access is confined, but a ScriptUI panel's script runs just as freely — when the panel opens,+ /// when an event reaches one of its controls, or when one of its tasks comes due — and+ /// `prefs.set` could grant every script run afterwards the file and network access the user+ /// withheld, in the settings file, long after the session. All of that is refused too.+ #[test]+ fn automation_roots_refuse_running_script_code() {+ use crate::confine::Confinement;+ let base = std::env::temp_dir().join(format!("ec-mcp-scripts-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&base);+ std::fs::create_dir_all(&base).unwrap();+ let mut s = server();+ s.backend().confine(Confinement::new(&[], std::slice::from_ref(&base)).unwrap());+ let refused = |s: &mut McpServer, name: &str, args: Value| {+ let (c, err) = call(s, name, args.clone());+ assert!(err, "{name} {args} should be refused: {c:?}");+ c[0]["text"].as_str().unwrap_or_default().to_string()+ };+ // Every way a script's code starts.+ for (command, params) in [+ ("window.scriptPanel", json!({"name": "Layer Tools.jsx"})),+ ("window.restoreScriptPanels", json!({})),+ ("script.runTasks", json!({})),+ ("scriptui.click", json!({"window": 1, "widget": 2})),+ ("scriptui.set", json!({"window": 1, "widget": 2, "value": 1})),+ ("scriptui.mouse", json!({"window": 1, "widget": 2, "type": "click"})),+ ("scriptui.close", json!({"window": 1})),+ ] {+ let msg = refused(&mut s, "execute_command", json!({"command": command, "params": params}));+ assert!(msg.contains("not available while file access is confined"), "`{command}`: {msg}");+ }+ // Including as a batch step.+ let msg = refused(&mut s, "batch", json!({"steps": [{"command": "window.scriptPanel", "params": {"name": "x.jsx"}}]}));+ assert!(msg.contains("not available while file access is confined"), "{msg}");+ // What scripts may do stays as the user left it, by either spelling of the setting.+ for params in [+ json!({"key": "scripting.allowScriptsWriteFiles", "value": true}),+ json!({"key": "scripting.allow_scripts_write_files", "value": true}),+ json!({"values": {"scripting.warnExecutingFiles": false}}),+ json!({"values": {"general.showToolTips": false, "scripting.enableJsDebugger": true}}),+ // `Prefs::set` makes a JSON pointer of the key, so this spelling resolves too…+ json!({"key": "scripting/allowScriptsWriteFiles", "value": true}),+ // …and the page on its own replaces every setting on it.+ json!({"key": "scripting", "value": {"allowScriptsWriteFiles": true}}),+ json!({"values": {"scripting": {"warnExecutingFiles": false}}}),+ ] {+ let msg = refused(&mut s, "execute_command", json!({"command": "prefs.set", "params": params}));+ assert!(msg.contains("what a script may do"), "{msg}");+ }+ let got = call_json(&mut s, "execute_command", json!({"command": "prefs.get", "params": {"key": "scripting.allowScriptsWriteFiles"}}));+ assert_eq!(got, json!(false), "{got}");+ // Other settings, and looking at the script windows, still work.+ call_json(&mut s, "execute_command", json!({"command": "prefs.set", "params": {"key": "general.showToolTips", "value": false}}));+ call_json(&mut s, "execute_command", json!({"command": "scriptui.list"}));+ let _ = std::fs::remove_dir_all(&base);+ }++ #[test]+ fn blender_export_requires_an_absolute_path_in_a_write_root() {+ use crate::confine::Confinement;+ let base = std::env::temp_dir().join(format!("ec-blender-confine-{}", std::process::id()));+ let (read, write) = (base.join("read"), base.join("write"));+ for dir in [&read, &write] {+ std::fs::create_dir_all(dir).unwrap();+ }+ let confinement = Confinement::new(std::slice::from_ref(&read), std::slice::from_ref(&write)).unwrap();+ let check = |path: &std::path::Path| confinement.check_command("camera.exportBlender", &json!({"path": path}));- assert_eq!(check(&write.join("scene.py")).unwrap(), None);++ assert!(check(&write.join("scene.py")).unwrap().is_empty());+ for path in [read.join("scene.py"), base.join("outside.py"), write.join("../read/scene.py")] {+ assert!(check(&path).is_err(), "must deny {}", path.display());+ }+ for path in ["scene.py", "./scene.py", "write/scene.py", "../scene.py"] {+ let error = check(std::path::Path::new(path)).unwrap_err().to_string();+ assert!(error.contains("give an absolute path"), "{path}: {error}");+ }+ let read_only = Confinement::new(std::slice::from_ref(&write), &[]).unwrap();+ assert!(read_only.check_command("camera.exportBlender", &json!({"path": write.join("scene.py")})).is_err());+ for path in [json!(read.join("scene.py")), json!("scene.py"), json!("$1.path")] {+ let batch = json!({"steps": [{"command": "camera.exportBlender", "params": {"path": path}}]});+ assert!(confinement.check_command("engine.batch", &batch).is_err());+ }+ std::fs::remove_dir_all(&base).unwrap();+ }diff --cc docs/mcp.mdindex 1104927ac,7685a66e2..686adcb35--- a/docs/mcp.md+++ b/docs/mcp.md@@@ -11,7 -11,9 +11,9 @@@ written only under a write root; with n(`execute_command`, `command_run`, each `batch` step) is checked before it runs: its fileparameters must be absolute paths inside the roots (symbolic links resolved, no `..`), and so mustany other absolute path in its parameters. Save, Increment and Save and rendering the Render- Queue are checked against the files they write (the open project's, the queued outputs). Scripts+ Queue are checked against the files they write (the open project's, the queued outputs);-`renderQueue.add` without `output` needs a saved project, since an unsaved one's default output-would go to the home folder (#2479). Scripts++`renderQueue.add`, `render.preRender` and `file.createProxy` without an output file need a saved++project, since an unsaved one's default output would go to the home folder (#2479). Scripts(`run_script`, `file.runScript`…), Execute File, Reveal in Finder, `$N` references to file pathsin a batch, and the bridge's UI-driving tools (`ui_click`, `ui_key`, `ui_type`, `ui_drag`,`ui_set`, `script_ui`, `control`) are refused while confined. Without the flags nothing changes.