mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
Support ordered automation read roots with safe save provenance (#3023)
* fix(cli): reject repeated automation read roots * feat(automation): add ordered read roots with isolated saves Stage source and regression tests for GGEO-AI02 validation before updating PR #3023. Repeated reads accumulate; writes remain single-root and implicit saves retain their selected capability provenance. * style: format multi-root automation extension * test: use fixed pixel chunks in read-root regression * docs: reconcile control protocol with upstream TGA options * docs: state multi-root capabilities directly in API summaries * test: construct regression actions through upstream defaults * Clarify headless and desktop directory automation reads * Format the shared root parser and relocated service regressions * test: adapt automation import callback to ImportOptions * test: expect read-root diagnostic for denied smart-object input * test: reject repeated write roots while allowing ordered read roots * test: assert explicit empty-root parser diagnostic * test: exercise leaf-link save using a supported image filename --------- Co-authored-by: FredApps <[email protected]> Co-authored-by: Codex <[email protected]>
This commit is contained in:
21 files changed
+996
-75
No files matched your search
@@ -508,7 +508,7 @@ pub(crate) fn parse(args: &[OsString]) -> Result<Cli, clap::Error> {
|
||||
conflict(sub, m, "automation_read_root", "bridge")?;
|
||||
conflict(sub, m, "automation_write_root", "bridge")?;
|
||||
}
|
||||
if a.bridge.is_some() && (a.automation.automation_read_root.is_some() || a.automation.automation_write_root.is_some()) {
|
||||
if a.bridge.is_some() && (!a.automation.automation_read_root.is_empty() || a.automation.automation_write_root.is_some()) {
|
||||
return Err(ServerOptionError::BridgeRoots.into_clap(sub));
|
||||
}
|
||||
if a.bridge.is_some() && (m.value_source("gpu") == Some(ValueSource::CommandLine) || m.value_source("no_gpu") == Some(ValueSource::CommandLine))
|
||||
|
||||
@@ -167,9 +167,9 @@ fn server_modes_reject_ignored_or_conflicting_options() {
|
||||
for flag in ["--control-token", "--control-token-file"] {
|
||||
server_usage_error(&[sub, flag, "unused"], if sub == "mcp" { "requires --bridge" } else { "requires --port" });
|
||||
}
|
||||
server_usage_error(&[sub, "--automation-write-root", ".", "--automation-write-root", "."], "cannot be used multiple times");
|
||||
for flag in ["--automation-read-root", "--automation-write-root"] {
|
||||
server_usage_error(&[sub, flag, ".", flag, "."], "cannot be used multiple times");
|
||||
server_usage_error(&[sub, &format!("{flag}=")], &format!("a value is required for '{flag} "));
|
||||
server_usage_error(&[sub, &format!("{flag}=")], "root needs a non-empty directory");
|
||||
server_usage_error(&[sub, flag, "--automation-write-root", "."], &format!("a value is required for '{flag} "));
|
||||
}
|
||||
let transport = if sub == "mcp" { "--bridge" } else { "--port" };
|
||||
@@ -193,7 +193,7 @@ fn server_validation_does_not_consume_stdio_or_create_files() {
|
||||
let other = d.join("other.token");
|
||||
let token_flag = format!("--control-token-file={}", token.display());
|
||||
let other_flag = format!("--control-token-file={}", other.display());
|
||||
for tail in [&["stray"][..], &["--automation-read-root", ".", "--automation-read-root", "."], &["--port", "0"], &[&other_flag]] {
|
||||
for tail in [&["stray"][..], &["--automation-write-root", ".", "--automation-write-root", "."], &["--port", "0"], &[&other_flag]] {
|
||||
let mut child = bin()
|
||||
.current_dir(&d)
|
||||
.args(["serve", "--port", "0", &token_flag])
|
||||
@@ -1857,6 +1857,120 @@ fn batch_skips_deselect_with_nothing_selected() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_configured_read_root_must_be_a_valid_directory() {
|
||||
let d = tmp("invalid-read-roots");
|
||||
let good = d.join("good");
|
||||
std::fs::create_dir_all(&good).unwrap();
|
||||
let file = d.join("file");
|
||||
std::fs::write(&file, b"not a directory").unwrap();
|
||||
for sub in ["mcp", "serve"] {
|
||||
for invalid in [d.join("missing"), file.clone()] {
|
||||
for roots in [[&good, &invalid], [&invalid, &good]] {
|
||||
let o = bin()
|
||||
.arg(sub)
|
||||
.arg("--automation-read-root")
|
||||
.arg(roots[0])
|
||||
.arg(format!("--automation-read-root={}", roots[1].display()))
|
||||
.stdin(Stdio::null())
|
||||
.output()
|
||||
.unwrap();
|
||||
assert_eq!(o.status.code(), Some(1), "{sub}: {}", String::from_utf8_lossy(&o.stderr));
|
||||
assert!(String::from_utf8_lossy(&o.stderr).contains("automation read root"));
|
||||
assert!(o.stdout.is_empty(), "invalid roots must fail before the server starts");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serve_reads_roots_in_order_and_supports_absolute_paths_in_each_root() {
|
||||
let d = tmp("serve-read-roots");
|
||||
let first = d.join("first");
|
||||
let second = d.join("second");
|
||||
std::fs::create_dir_all(&first).unwrap();
|
||||
std::fs::create_dir_all(&second).unwrap();
|
||||
write_png(&first.join("shared.png"), 3, 2, 3);
|
||||
write_png(&second.join("shared.png"), 7, 4, 5);
|
||||
write_png(&second.join("fallback.png"), 6, 5, 7);
|
||||
let mut child = bin()
|
||||
.args(["serve", "--automation-read-root"])
|
||||
.arg(&first)
|
||||
.arg(format!("--automation-read-root={}", second.display()))
|
||||
.arg("--automation-read-root")
|
||||
.arg(&first)
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let mut stdin = child.stdin.take().unwrap();
|
||||
for (id, path) in [(1, "shared.png".into()), (2, "fallback.png".into()), (3, second.join("shared.png").to_string_lossy().into_owned())] {
|
||||
writeln!(stdin, "{}", json!({"id": id, "method": "doc.open", "params": {"path": path}})).unwrap();
|
||||
}
|
||||
drop(stdin);
|
||||
let output = child.wait_with_output().unwrap();
|
||||
assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr));
|
||||
let replies: Vec<Value> = String::from_utf8(output.stdout).unwrap().lines().map(|line| serde_json::from_str(line).unwrap()).collect();
|
||||
assert_eq!(replies.len(), 3);
|
||||
for (reply, (width, height)) in replies.iter().zip([(3, 2), (6, 5), (7, 4)]) {
|
||||
assert_eq!(reply["ok"], true, "{reply}");
|
||||
assert_eq!(reply["result"]["width"], width, "{reply}");
|
||||
assert_eq!(reply["result"]["height"], height, "{reply}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mcp_reads_roots_in_order_with_fallback() {
|
||||
let d = tmp("mcp-read-roots");
|
||||
let first = d.join("first");
|
||||
let second = d.join("second");
|
||||
std::fs::create_dir_all(&first).unwrap();
|
||||
std::fs::create_dir_all(&second).unwrap();
|
||||
write_png(&first.join("shared.png"), 3, 2, 3);
|
||||
write_png(&second.join("shared.png"), 7, 4, 5);
|
||||
write_png(&second.join("fallback.png"), 6, 5, 7);
|
||||
let mut child = bin()
|
||||
.arg("mcp")
|
||||
.arg(format!("--automation-read-root={}", first.display()))
|
||||
.arg("--automation-read-root")
|
||||
.arg(&second)
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let mut stdin = child.stdin.take().unwrap();
|
||||
let mut stdout = BufReader::new(child.stdout.take().unwrap());
|
||||
let mut send = |value: Value| {
|
||||
writeln!(stdin, "{value}").unwrap();
|
||||
stdin.flush().unwrap();
|
||||
};
|
||||
let mut recv = |id: u64| -> Value {
|
||||
loop {
|
||||
let mut line = String::new();
|
||||
assert!(stdout.read_line(&mut line).unwrap() > 0, "server closed");
|
||||
let value: Value = serde_json::from_str(&line).unwrap();
|
||||
if value["id"] == id {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
};
|
||||
send(json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{
|
||||
"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"test","version":"0"}}}));
|
||||
assert_eq!(recv(1)["result"]["serverInfo"]["name"], "photocraft");
|
||||
send(json!({"jsonrpc":"2.0","method":"notifications/initialized"}));
|
||||
for (id, path, width) in [(2, "shared.png", 3), (3, "fallback.png", 6)] {
|
||||
send(json!({"jsonrpc":"2.0","id":id,"method":"tools/call","params":{"name":"doc_open","arguments":{"path":path}}}));
|
||||
let reply = recv(id);
|
||||
assert_ne!(reply["result"]["isError"], true, "{reply}");
|
||||
let opened: Value = serde_json::from_str(reply["result"]["content"][0]["text"].as_str().unwrap()).unwrap();
|
||||
assert_eq!(opened["width"], width, "{reply}");
|
||||
}
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
}
|
||||
|
||||
/// TIFF Options from the command line (#8827): `--tiff-compression`, `--tiff-transparency on|off`
|
||||
/// and `--tiff-pyramid`; a bad value is a usage error that writes nothing.
|
||||
#[test]
|
||||
|
||||
@@ -286,7 +286,7 @@ mod tests {
|
||||
assert_eq!(parsed.control, Some(50494));
|
||||
assert_eq!(parsed.auth.control_token.as_deref(), Some("abcd"));
|
||||
assert_eq!(parsed.auth.control_token_file, None);
|
||||
assert_eq!(parsed.automation.automation_read_root.as_deref(), Some(std::path::Path::new("/r")));
|
||||
assert_eq!(parsed.automation.automation_read_root, vec![std::path::PathBuf::from("/r")]);
|
||||
assert_eq!(parsed.automation.automation_write_root.as_deref(), Some(std::path::Path::new("/w")));
|
||||
assert!(parsed.safe_gpu && parsed.in_window_menus && parsed.new_instance);
|
||||
assert_eq!(parsed.present_mode, Some(PresentMode::AutoNoVsync));
|
||||
|
||||
@@ -703,9 +703,9 @@ pub fn native(automation: Option<photocraft_automation::AuthorizedWorkspace>) ->
|
||||
let clip_unreadable: Rc<Cell<bool>> = Rc::default();
|
||||
let automation_read = automation.clone().map(|workspace| {
|
||||
Box::new(move |path: &str| {
|
||||
let bytes = workspace.read(path).map_err(|error| error.to_string())?;
|
||||
let (bytes, save_path) = workspace.read_with_save_path(path).map_err(|error| error.to_string())?;
|
||||
let name = Path::new(path).file_name().and_then(|name| name.to_str()).unwrap_or(path).to_string();
|
||||
Ok((name, bytes))
|
||||
Ok(photocraft_ui_egui::AutomationReadResult { name, bytes, save_path })
|
||||
}) as photocraft_ui_egui::AutomationReadFn
|
||||
});
|
||||
let automation_write = automation.clone().map(|workspace| {
|
||||
|
||||
@@ -120,3 +120,49 @@ fn automation_roots_come_from_the_environment_too() {
|
||||
assert!(stderr.contains("cannot configure automation workspace"), "{var}: stderr: {stderr}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_read_root_is_not_hidden_by_another_valid_root() {
|
||||
let dir = std::env::temp_dir().join(format!("photocraft-control-roots-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let good = dir.to_str().unwrap();
|
||||
let missing = dir.join("missing");
|
||||
let file = dir.join("not-a-directory");
|
||||
std::fs::write(&file, b"not a directory").unwrap();
|
||||
for invalid in [&missing, &file] {
|
||||
for roots in [[good, invalid.to_str().unwrap()], [invalid.to_str().unwrap(), good]] {
|
||||
let Run { status, stderr } = run_photocraft(&[
|
||||
"--control",
|
||||
"0",
|
||||
"--control-token",
|
||||
VALID_TOKEN,
|
||||
"--automation-read-root",
|
||||
roots[0],
|
||||
&format!("--automation-read-root={}", roots[1]),
|
||||
]);
|
||||
assert_eq!(status.code(), Some(2), "every configured read root must be valid: {stderr}");
|
||||
assert!(stderr.contains("cannot configure automation workspace"), "stderr: {stderr}");
|
||||
}
|
||||
}
|
||||
std::fs::remove_dir_all(&dir).ok();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_missing_and_repeated_write_root_flags_are_usage_errors() {
|
||||
for flags in [
|
||||
vec!["--automation-read-root"],
|
||||
vec!["--automation-read-root", ""],
|
||||
vec!["--automation-read-root="],
|
||||
vec!["--automation-read-root", "--safe-gpu"],
|
||||
vec!["--automation-write-root"],
|
||||
vec!["--automation-write-root="],
|
||||
vec!["--automation-write-root", "work", "--automation-write-root=work"],
|
||||
vec!["--automation-write-root=", "--automation-write-root=work"],
|
||||
] {
|
||||
let args: Vec<&str> = ["--control", "0", "--control-token", VALID_TOKEN].into_iter().chain(flags).collect();
|
||||
let Run { status, stderr } = run_photocraft(&args);
|
||||
assert_eq!(status.code(), Some(2), "{args:?}: {stderr}");
|
||||
assert!(stderr.contains("--automation-"), "stderr: {stderr}");
|
||||
assert!(!stderr.contains("cannot configure automation workspace"), "parse errors must fail before opening roots: {stderr}");
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,7 @@
|
||||
use std::ffi::OsString;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use clap::builder::NonEmptyStringValueParser;
|
||||
use clap::builder::{NonEmptyStringValueParser, OsStringValueParser, TypedValueParser};
|
||||
use clap::error::{ContextKind, ContextValue, ErrorKind};
|
||||
use clap::parser::ValueSource;
|
||||
use clap::{Arg, ArgMatches, Args, Command};
|
||||
@@ -34,18 +34,22 @@ pub struct ControlArgs {
|
||||
/// `photocraft-cli` access (#1551); the desktop app adds its own.
|
||||
#[derive(Args)]
|
||||
pub struct AutomationArgs {
|
||||
/// The folder automation may read from (none without it)
|
||||
#[arg(long, value_name = "DIR")]
|
||||
pub automation_read_root: Option<PathBuf>,
|
||||
/// Ordered folders automation may read from; repeat for more roots (none without it)
|
||||
#[arg(long, value_name = "DIR", value_parser = root_path())]
|
||||
pub automation_read_root: Vec<PathBuf>,
|
||||
/// The folder automation may write to (none without it)
|
||||
#[arg(long, value_name = "DIR")]
|
||||
#[arg(long, value_name = "DIR", value_parser = root_path())]
|
||||
pub automation_write_root: Option<PathBuf>,
|
||||
}
|
||||
|
||||
fn root_path() -> impl TypedValueParser<Value = PathBuf> {
|
||||
OsStringValueParser::new().try_map(|value: OsString| if value.is_empty() { Err("root needs a non-empty directory") } else { Ok(PathBuf::from(value)) })
|
||||
}
|
||||
|
||||
impl AutomationArgs {
|
||||
/// The roots, opened as capabilities.
|
||||
pub fn workspace(&self) -> Result<AuthorizedWorkspace, AutomationError> {
|
||||
AuthorizedWorkspace::new(self.automation_read_root.as_deref(), self.automation_write_root.as_deref())
|
||||
AuthorizedWorkspace::with_read_roots(self.automation_read_root.iter().map(PathBuf::as_path), self.automation_write_root.as_deref())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -120,4 +124,40 @@ mod tests {
|
||||
assert_eq!(control_port(bad), Err(NotAPort), "{bad:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(clap::Parser)]
|
||||
struct RootCli {
|
||||
#[command(flatten)]
|
||||
automation: AutomationArgs,
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeated_read_roots_preserve_order_and_write_roots_stay_single() {
|
||||
use clap::Parser;
|
||||
let parsed = RootCli::try_parse_from(["test", "--automation-read-root", "first", "--automation-read-root=second"]).unwrap();
|
||||
assert_eq!(parsed.automation.automation_read_root, vec![PathBuf::from("first"), PathBuf::from("second")]);
|
||||
for args in [
|
||||
vec!["test", "--automation-write-root", "one", "--automation-write-root=two"],
|
||||
vec!["test", "--automation-write-root=one", "--automation-write-root", "one"],
|
||||
vec!["test", "--automation-read-root="],
|
||||
vec!["test", "--automation-read-root", "--automation-write-root=work"],
|
||||
vec!["test", "--automation-write-root="],
|
||||
] {
|
||||
assert!(RootCli::try_parse_from(args.clone()).is_err(), "accepted {args:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn non_unicode_root_paths_are_preserved_without_lossy_conversion() {
|
||||
use clap::Parser;
|
||||
use std::os::unix::ffi::OsStringExt;
|
||||
let value = OsString::from_vec(b"library-\xff".to_vec());
|
||||
let parsed = RootCli::try_parse_from([OsString::from("test"), OsString::from("--automation-read-root"), value.clone()]).unwrap();
|
||||
assert_eq!(parsed.automation.automation_read_root, vec![PathBuf::from(value.clone())]);
|
||||
let mut inline = OsString::from("--automation-read-root=");
|
||||
inline.push(&value);
|
||||
let parsed = RootCli::try_parse_from([OsString::from("test"), inline]).unwrap();
|
||||
assert_eq!(parsed.automation.automation_read_root, vec![PathBuf::from(value)]);
|
||||
}
|
||||
}
|
||||
@@ -181,13 +181,13 @@ impl Headless {
|
||||
/// Open a file with custom import options and make it the active document.
|
||||
pub fn open_with_options(&mut self, path: &Path, opts: &photocraft_io::ImportOptions) -> Result<Value, AutomationError> {
|
||||
let requested = path.to_str().ok_or_else(|| AutomationError::BadRequest("automation paths must be valid UTF-8".into()))?;
|
||||
let mut o = match &self.filesystem {
|
||||
let (mut o, save_path) = match &self.filesystem {
|
||||
Filesystem::Denied => return Err(AutomationError::BadRequest("automation filesystem access is not granted: read authority is absent".into())),
|
||||
Filesystem::TrustedLocal => files::open_with_options(path, opts)?,
|
||||
Filesystem::TrustedLocal => (files::open_with_options(path, opts)?, Some(requested.to_string())),
|
||||
Filesystem::Workspace(workspace) => {
|
||||
let bytes = workspace.read(requested)?;
|
||||
let (bytes, save_path) = workspace.read_with_save_path(requested)?;
|
||||
let name = path.file_name().and_then(|name| name.to_str()).unwrap_or(requested);
|
||||
files::open_bytes_with_options(name, &bytes, opts)?
|
||||
(files::open_bytes_with_options(name, &bytes, opts)?, save_path)
|
||||
}
|
||||
};
|
||||
// Preferences › Raw Defaults › Resolution, as the app's File › Open applies it.
|
||||
@@ -197,7 +197,7 @@ impl Headless {
|
||||
o.document.name = untitled;
|
||||
None
|
||||
}
|
||||
None => Some(requested.to_string()),
|
||||
None => save_path,
|
||||
};
|
||||
let index = self.session.add_document(o.document, path.filter(|_| !o.source_read_only));
|
||||
if let Some(st) = self.session.active_mut() {
|
||||
|
||||
@@ -413,7 +413,7 @@ fn doc_place_reads_through_the_read_root_and_never_outside_it() {
|
||||
let inspected = h.handle("doc.inspect", json!({})).unwrap();
|
||||
assert_eq!(inspected["layers"].as_array().map(Vec::len), Some(2), "the placed layer is in the document: {inspected}");
|
||||
// A path outside the read root is refused the way the ambient command is (#2810).
|
||||
for (path, reason) in [("../outside/logo.png", "parent traversal"), (absolute.as_str(), "must be inside the automation root")] {
|
||||
for (path, reason) in [("../outside/logo.png", "parent traversal"), (absolute.as_str(), "must be inside an automation read root")] {
|
||||
let refused = h.handle("doc.place", json!({"path": path})).unwrap_err().to_string();
|
||||
assert!(refused.contains(reason), "{refused}");
|
||||
let inspected = h.handle("doc.inspect", json!({})).unwrap();
|
||||
@@ -513,7 +513,7 @@ fn doc_replace_smart_object_reads_through_the_read_root_and_never_outside_it() {
|
||||
// Outside the read root, a bad layer, a missing path or a file that is no image: refused, nothing changed.
|
||||
for (params, reason) in [
|
||||
(json!({"path": "../outside/red.png"}), "parent traversal"),
|
||||
(json!({"path": absolute}), "must be inside the automation root"),
|
||||
(json!({"path": absolute}), "must be inside an automation read root"),
|
||||
(json!({"path": "logo.png", "layer": 999_999}), "no such layer"),
|
||||
(json!({}), "needs `path`"),
|
||||
] {
|
||||
@@ -660,7 +660,7 @@ fn doc_export_data_sets_refuse_collisions_and_import_reads_the_root() {
|
||||
assert_eq!(imported["imported"].as_u64(), Some(2), "{imported}");
|
||||
std::fs::write(base.join("outside.csv"), "Data Set,show\none,true\n").unwrap();
|
||||
let outside = h.handle("doc.importDataSets", json!({"path": base.join("outside.csv").to_string_lossy()})).unwrap_err().to_string();
|
||||
assert!(outside.contains("must be inside the automation root"), "{outside}");
|
||||
assert!(outside.contains("must be inside an automation read root"), "{outside}");
|
||||
// Release directory capabilities before cleanup on Windows.
|
||||
drop(h);
|
||||
std::fs::remove_dir_all(base).unwrap();
|
||||
|
||||
@@ -50,7 +50,8 @@ pub struct DocIndex {
|
||||
#[derive(Debug, Deserialize, JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct OpenParams {
|
||||
/// Path beneath the configured automation read root: relative (forward slashes) or absolute.
|
||||
/// Path beneath the configured automation read roots: relative (forward slashes, searched
|
||||
/// in launch order) or absolute. Only a missing file tries the next root.
|
||||
pub path: String,
|
||||
/// Explicitly approve high-memory PSD/PSB imports that fit within the hard memory budget.
|
||||
#[serde(default)]
|
||||
@@ -179,6 +180,7 @@ pub struct SaveParams {
|
||||
/// The extension selects the format. Omit to write back to the document's own file, which
|
||||
/// works only for a PSD, PSB or .pcraft file kept in its own format; any other save needs
|
||||
/// `path`, so a flattened or converted copy never replaces the opened file.
|
||||
/// A document opened from a different read capability needs an explicit path first.
|
||||
#[serde(default)]
|
||||
pub path: Option<String>,
|
||||
/// Format override as an extension (pcraft, psd, png, jpg, tif, webp, exr, …).
|
||||
|
||||
@@ -33,7 +33,7 @@ struct RootCapability {
|
||||
/// before I/O.
|
||||
#[derive(Clone, Default)]
|
||||
pub struct AuthorizedWorkspace {
|
||||
read: Option<RootCapability>,
|
||||
read: Vec<RootCapability>,
|
||||
write: Option<RootCapability>,
|
||||
}
|
||||
|
||||
@@ -41,34 +41,90 @@ impl AuthorizedWorkspace {
|
||||
/// Open the configured roots as capabilities. Either authority may be
|
||||
/// omitted; omitted authority fails closed.
|
||||
pub fn new(read_root: Option<&Path>, write_root: Option<&Path>) -> Result<Self, AutomationError> {
|
||||
Ok(Self { read: open_root(read_root, "read")?, write: open_root(write_root, "write")? })
|
||||
Self::with_read_roots(read_root, write_root)
|
||||
}
|
||||
|
||||
/// Read one regular file below the configured read root.
|
||||
/// Open ordered read capabilities and an independent, optional write capability.
|
||||
/// Every configured root must be valid; a write root does not also grant reads.
|
||||
pub fn with_read_roots<'a>(read_roots: impl IntoIterator<Item = &'a Path>, write_root: Option<&Path>) -> Result<Self, AutomationError> {
|
||||
let mut read = Vec::new();
|
||||
for path in read_roots {
|
||||
let root = open_root(path, "read", &read)?;
|
||||
read.push(root);
|
||||
}
|
||||
let write = write_root.map(|path| open_root(path, "write", &read)).transpose()?;
|
||||
Ok(Self { read, write })
|
||||
}
|
||||
|
||||
/// Read the first matching regular file, trying roots in their configured order.
|
||||
/// Only an open that reports NotFound tries the next root. Once opened, errors
|
||||
/// (including a non-regular file or a failed bounded read) never select another file.
|
||||
pub fn read(&self, path: &str) -> Result<Vec<u8>, AutomationError> {
|
||||
let relative = request_path(path, self.read.as_ref())?;
|
||||
let root = self.read.as_ref().ok_or_else(|| AutomationError::BadRequest(format!("{DENIED}: read authority is absent")))?;
|
||||
let mut file = root.dir.open(&relative).map_err(|e| file_error("read", path, e))?;
|
||||
self.read_with_save_path(path).map(|(bytes, _)| bytes)
|
||||
}
|
||||
|
||||
/// Read bytes and derive a conservative implicit-save request from the same
|
||||
/// selected capability. A different read root must never redirect an implicit
|
||||
/// save to a same-named file in the write root. Aliases and nested roots need an
|
||||
/// explicit Save As; this is not canonical desktop document identity.
|
||||
pub fn read_with_save_path(&self, path: &str) -> Result<(Vec<u8>, Option<String>), AutomationError> {
|
||||
let (mut file, root) = self.open_read(path)?;
|
||||
let metadata = file.metadata().map_err(|e| file_error("read", path, e))?;
|
||||
if !metadata.is_file() {
|
||||
return Err(AutomationError::BadRequest(format!("automation read path is not a regular file: `{path}`")));
|
||||
}
|
||||
read_to_observed_length(&mut file, metadata.len())
|
||||
// Retain main's bounded, growth-checked reads while keeping save provenance.
|
||||
let bytes = read_to_observed_length(&mut file, metadata.len())?;
|
||||
let save_path = self.write.as_ref().filter(|write| Arc::ptr_eq(&root.dir, &write.dir)).map(|_| path.to_owned());
|
||||
Ok((bytes, save_path))
|
||||
}
|
||||
|
||||
fn open_read(&self, path: &str) -> Result<(cap_std::fs::File, &RootCapability), AutomationError> {
|
||||
if self.read.is_empty() {
|
||||
return Err(AutomationError::BadRequest(format!("{DENIED}: read authority is absent")));
|
||||
}
|
||||
let mut not_found = None;
|
||||
for root in &self.read {
|
||||
let Some(relative) = scoped_path(path, root)? else { continue };
|
||||
match root.dir.open(&relative) {
|
||||
Ok(file) => return Ok((file, root)),
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => not_found = Some(error),
|
||||
Err(error) => return Err(file_error("read", path, error)),
|
||||
}
|
||||
}
|
||||
match not_found {
|
||||
Some(error) => Err(file_error("read", path, error)),
|
||||
None => Err(path_error(path, "absolute paths must be inside an automation read root")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Load one `.pcraft` document in directory form — the native on-disk layout — below the
|
||||
/// read root. `read` serves regular files only (the zip form), so a regular file at the
|
||||
/// first matching read root. Directory opens never establish an implicit save target.
|
||||
/// `read` serves regular files only (the zip form), so a regular file at the
|
||||
/// path is reported as `Ok(None)` for the caller to fall back to.
|
||||
pub fn open_pcraft(&self, path: &str) -> Result<Option<photocraft_doc::Document>, AutomationError> {
|
||||
let relative = request_path(path, self.read.as_ref())?;
|
||||
let root = self.read.as_ref().ok_or_else(|| AutomationError::BadRequest(format!("{DENIED}: read authority is absent")))?;
|
||||
let dir = match root.dir.open_dir(&relative) {
|
||||
Ok(dir) => dir,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotADirectory => return Ok(None),
|
||||
Err(e) => return Err(file_error("read", path, e)),
|
||||
};
|
||||
let source = DirHandle { dir };
|
||||
Ok(Some(photocraft_format::load_bytes_source(&source, &photocraft_format::LoadOptions::default())?))
|
||||
if self.read.is_empty() {
|
||||
return Err(AutomationError::BadRequest(format!("{DENIED}: read authority is absent")));
|
||||
}
|
||||
let mut not_found = None;
|
||||
for root in &self.read {
|
||||
let Some(relative) = scoped_path(path, root)? else { continue };
|
||||
let dir = match root.dir.open_dir(&relative) {
|
||||
Ok(dir) => dir,
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
|
||||
not_found = Some(error);
|
||||
continue;
|
||||
}
|
||||
Err(error) if error.kind() == std::io::ErrorKind::NotADirectory => return Ok(None),
|
||||
Err(error) => return Err(file_error("read", path, error)),
|
||||
};
|
||||
let source = DirHandle { dir };
|
||||
return Ok(Some(photocraft_format::load_bytes_source(&source, &photocraft_format::LoadOptions::default())?));
|
||||
}
|
||||
match not_found {
|
||||
Some(error) => Err(file_error("read", path, error)),
|
||||
None => Err(path_error(path, "absolute paths must be inside an automation read root")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Create or replace one file below the configured write root, crash-safely: the bytes go to
|
||||
@@ -216,8 +272,7 @@ fn read_to_observed_length(reader: &mut impl Read, observed_length: u64) -> Resu
|
||||
}
|
||||
}
|
||||
|
||||
fn open_root(path: Option<&Path>, authority: &str) -> Result<Option<RootCapability>, AutomationError> {
|
||||
let Some(path) = path else { return Ok(None) };
|
||||
fn open_root(path: &Path, authority: &str, opened: &[RootCapability]) -> Result<RootCapability, AutomationError> {
|
||||
if path.as_os_str().is_empty() {
|
||||
return Err(AutomationError::BadRequest(format!("automation {authority} root is empty")));
|
||||
}
|
||||
@@ -228,27 +283,42 @@ fn open_root(path: Option<&Path>, authority: &str) -> Result<Option<RootCapabili
|
||||
} else {
|
||||
std::path::absolute(path).map_err(|e| AutomationError::Io(format!("cannot resolve automation {authority} root `{}`: {e}", path.display())))?
|
||||
};
|
||||
// Reuse the held handle for the same launch spelling, not a second open of it: a root
|
||||
// symlink could otherwise change between the two opens. Only a shared handle lets an
|
||||
// implicit save write where the bytes were read (`read_with_save_path`); aliases do not.
|
||||
if let Some(root) = opened.iter().find(|root| root.configured_path == configured_path) {
|
||||
return Ok(root.clone());
|
||||
}
|
||||
// Resolve trusted configuration once, before opening that exact directory as a capability.
|
||||
let absolute =
|
||||
std::fs::canonicalize(path).map_err(|e| AutomationError::Io(format!("cannot resolve automation {authority} root `{}`: {e}", path.display())))?;
|
||||
let dir = Dir::open_ambient_dir(&absolute, ambient_authority())
|
||||
.map_err(|e| AutomationError::Io(format!("cannot open automation {authority} root `{}`: {e}", path.display())))?;
|
||||
Ok(Some(RootCapability { dir: Arc::new(dir), path: absolute, configured_path }))
|
||||
Ok(RootCapability { dir: Arc::new(dir), path: absolute, configured_path })
|
||||
}
|
||||
|
||||
/// Both root spellings refer to the capability opened at startup. Do not resolve an untrusted
|
||||
/// absolute request using ambient filesystem access: strip a known root first and let cap-std
|
||||
/// resolve the remaining name. New targets and nested export directories need not exist yet.
|
||||
fn request_path(raw: &str, root: Option<&RootCapability>) -> Result<PathBuf, AutomationError> {
|
||||
let Some(root) = root else { return relative_path(raw) };
|
||||
scoped_path(raw, root)?.ok_or_else(|| path_error(raw, "absolute paths must be inside the automation root"))
|
||||
}
|
||||
|
||||
/// An absolute prefix mismatch is a noncandidate, whereas a malformed path
|
||||
/// beneath a matching root is an error. Never turn either into a relative lookup.
|
||||
fn scoped_path(raw: &str, root: &RootCapability) -> Result<Option<PathBuf>, AutomationError> {
|
||||
let path = Path::new(raw);
|
||||
let Some(root) = root.filter(|_| path.is_absolute()) else { return relative_path(raw) };
|
||||
if !path.is_absolute() {
|
||||
return relative_path(raw).map(Some);
|
||||
}
|
||||
// Prefer the trusted launch spelling: it can itself contain `..`. Only that
|
||||
// exact granted prefix is exempt; traversal in the remaining request still fails below.
|
||||
let request = path_beneath_root(path, &root.configured_path)
|
||||
.or_else(|| path_beneath_root(path, &root.path))
|
||||
.ok_or_else(|| path_error(raw, "absolute paths must be inside the automation root"))?;
|
||||
let Some(request) = path_beneath_root(path, &root.configured_path).or_else(|| path_beneath_root(path, &root.path)) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let rest = request.map(|c| c.as_os_str().to_str().ok_or_else(|| path_error(raw, "path is not UTF-8"))).collect::<Result<Vec<_>, _>>()?;
|
||||
relative_path(&rest.join("/"))
|
||||
relative_path(&rest.join("/")).map(Some)
|
||||
}
|
||||
|
||||
/// Strip a granted root prefix without resolving the client path with ambient authority.
|
||||
|
||||
@@ -1075,6 +1075,149 @@ fn absolute_paths_are_checked_against_the_authority_s_own_root() {
|
||||
assert!(none.read(&target.to_string_lossy()).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ordered_read_roots_keep_write_authority_and_save_provenance_separate() {
|
||||
let (library, work, _) = roots("multiple-roots");
|
||||
std::fs::write(library.join("photo.txt"), b"library").unwrap();
|
||||
std::fs::write(work.join("draft.txt"), b"draft").unwrap();
|
||||
std::fs::write(library.join("same.txt"), b"first").unwrap();
|
||||
std::fs::write(work.join("same.txt"), b"second").unwrap();
|
||||
let workspace = AuthorizedWorkspace::with_read_roots([library.as_path(), work.as_path(), library.as_path()], Some(&work)).unwrap();
|
||||
assert_eq!(workspace.read_with_save_path("photo.txt").unwrap(), (b"library".to_vec(), None));
|
||||
assert_eq!(workspace.read_with_save_path("draft.txt").unwrap(), (b"draft".to_vec(), Some("draft.txt".into())));
|
||||
assert_eq!(workspace.read("same.txt").unwrap(), b"first");
|
||||
let absolute = work.join("same.txt").to_string_lossy().into_owned();
|
||||
assert_eq!(workspace.read_with_save_path(&absolute).unwrap(), (b"second".to_vec(), Some(absolute)));
|
||||
let reverse = AuthorizedWorkspace::with_read_roots([work.as_path(), library.as_path()], Some(&work)).unwrap();
|
||||
assert_eq!(reverse.read("same.txt").unwrap(), b"second");
|
||||
// Identical configured spellings share the held handle, including the write grant.
|
||||
assert!(Arc::ptr_eq(&workspace.read[0].dir, &workspace.read[2].dir));
|
||||
assert!(Arc::ptr_eq(&workspace.read[1].dir, &workspace.write.as_ref().unwrap().dir));
|
||||
workspace.write("result.txt", b"output").unwrap();
|
||||
assert_eq!(std::fs::read(work.join("result.txt")).unwrap(), b"output");
|
||||
assert!(!library.join("result.txt").exists());
|
||||
assert!(workspace.write(&library.join("photo.txt").to_string_lossy(), b"blocked").is_err());
|
||||
assert_eq!(std::fs::read(library.join("photo.txt")).unwrap(), b"library");
|
||||
let error = workspace.read("missing.txt").unwrap_err().to_string();
|
||||
assert!(error.contains("NotFound"), "{error}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn streamed_save_follows_read_provenance_across_ordered_roots() {
|
||||
let (library, work, _) = roots("stream-provenance");
|
||||
std::fs::write(library.join("same.png"), b"library").unwrap();
|
||||
std::fs::write(work.join("same.png"), b"work").unwrap();
|
||||
std::fs::write(work.join("draft.png"), b"draft").unwrap();
|
||||
let workspace = AuthorizedWorkspace::with_read_roots([library.as_path(), work.as_path()], Some(&work)).unwrap();
|
||||
// Read from the library root: no implicit save, so a streamed save needs an explicit target.
|
||||
assert_eq!(workspace.read_with_save_path("same.png").unwrap(), (b"library".to_vec(), None));
|
||||
// Read from the root that shares the write handle: the streamed save replaces that file only.
|
||||
let (_, save_path) = workspace.read_with_save_path("draft.png").unwrap();
|
||||
let save_path = save_path.unwrap();
|
||||
workspace.write_stream(&save_path, &mut |w| w.write_all(b"streamed")).unwrap();
|
||||
assert_eq!(std::fs::read(work.join("draft.png")).unwrap(), b"streamed");
|
||||
assert!(!library.join("draft.png").exists());
|
||||
// An absolute library path never reaches the write root, streamed or not.
|
||||
assert!(workspace.write_stream(&library.join("same.png").to_string_lossy(), &mut |w| w.write_all(b"blocked")).is_err());
|
||||
assert_eq!(std::fs::read(library.join("same.png")).unwrap(), b"library");
|
||||
assert_eq!(std::fs::read(work.join("same.png")).unwrap(), b"work");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_read_root_is_validated_and_write_roots_never_imply_reads() {
|
||||
let (library, work, _) = roots("root-validation");
|
||||
std::fs::write(work.join("file.txt"), b"work").unwrap();
|
||||
for invalid in [library.join("missing"), work.join("file.txt"), PathBuf::new()] {
|
||||
assert!(AuthorizedWorkspace::with_read_roots([library.as_path(), invalid.as_path(), work.as_path()], Some(&work)).is_err());
|
||||
}
|
||||
let write_only = AuthorizedWorkspace::with_read_roots(std::iter::empty(), Some(&work)).unwrap();
|
||||
assert!(write_only.read("file.txt").is_err());
|
||||
assert!(write_only.read(&work.join("file.txt").to_string_lossy()).is_err());
|
||||
let read_only = AuthorizedWorkspace::with_read_roots([library.as_path(), work.as_path()], None).unwrap();
|
||||
assert_eq!(read_only.read_with_save_path("file.txt").unwrap(), (b"work".to_vec(), None));
|
||||
assert!(read_only.write("file.txt", b"blocked").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_earlier_directory_or_invalid_path_never_falls_back_to_a_later_file() {
|
||||
let (library, work, _) = roots("root-errors");
|
||||
std::fs::create_dir(library.join("same.txt")).unwrap();
|
||||
std::fs::write(work.join("same.txt"), b"later").unwrap();
|
||||
let workspace = AuthorizedWorkspace::with_read_roots([library.as_path(), work.as_path()], Some(&work)).unwrap();
|
||||
assert!(workspace.read("same.txt").is_err());
|
||||
for invalid in ["", "../same.txt", "a/../same.txt", "a\\same.txt", "a//same.txt", "NUL", "same.txt:stream"] {
|
||||
assert!(workspace.read(invalid).is_err(), "accepted {invalid:?}");
|
||||
assert!(workspace.write(invalid, b"blocked").is_err(), "wrote {invalid:?}");
|
||||
}
|
||||
let traversal = library.join("../outside/same.txt");
|
||||
assert!(workspace.read(&traversal.to_string_lossy()).is_err());
|
||||
assert_eq!(std::fs::read(work.join("same.txt")).unwrap(), b"later");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn multiple_roots_do_not_allow_link_escapes_or_alias_save_back() {
|
||||
use std::os::unix::fs::symlink;
|
||||
let (library, work, _) = roots("multi-root-links");
|
||||
std::fs::write(work.join("photo.txt"), b"work").unwrap();
|
||||
symlink(&work, library.join("escape")).unwrap();
|
||||
std::fs::create_dir(work.join("escape")).unwrap();
|
||||
std::fs::write(work.join("escape/photo.txt"), b"later").unwrap();
|
||||
let workspace = AuthorizedWorkspace::with_read_roots([library.as_path(), work.as_path()], Some(&work)).unwrap();
|
||||
// Being separately granted does not allow following a link out of the selected root.
|
||||
assert!(workspace.read("escape/photo.txt").is_err());
|
||||
assert_eq!(workspace.read("photo.txt").unwrap(), b"work");
|
||||
let alias = library.join("alias");
|
||||
symlink(&work, &alias).unwrap();
|
||||
let aliased = AuthorizedWorkspace::new(Some(&alias), Some(&work)).unwrap();
|
||||
assert_eq!(aliased.read_with_save_path("photo.txt").unwrap(), (b"work".to_vec(), None));
|
||||
let nested = AuthorizedWorkspace::new(Some(&work.join("escape")), Some(&work)).unwrap();
|
||||
assert_eq!(nested.read_with_save_path("photo.txt").unwrap(), (b"later".to_vec(), None));
|
||||
symlink(&library, work.join("escape-write")).unwrap();
|
||||
assert!(workspace.write("escape-write/output.txt", b"blocked").is_err());
|
||||
assert!(!library.join("output.txt").exists());
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn same_root_leaf_link_save_replaces_the_link_without_writing_its_target() {
|
||||
let (inside, _, workspace) = roots("leaf-link");
|
||||
std::fs::write(inside.join("target.txt"), b"target").unwrap();
|
||||
std::os::unix::fs::symlink("target.txt", inside.join("link.png")).unwrap();
|
||||
let (bytes, save_path) = workspace.read_with_save_path("link.png").unwrap();
|
||||
assert_eq!(bytes, b"target");
|
||||
workspace.write(&save_path.unwrap(), b"replacement").unwrap();
|
||||
assert_eq!(std::fs::read(inside.join("target.txt")).unwrap(), b"target");
|
||||
assert_eq!(std::fs::read(inside.join("link.png")).unwrap(), b"replacement");
|
||||
assert!(!std::fs::symlink_metadata(inside.join("link.png")).unwrap().file_type().is_symlink());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn directory_pcraft_uses_ordered_roots_without_falling_back_after_selection() {
|
||||
let (library, work, _) = roots("pcraft-ordered");
|
||||
let save = |root: &Path, name: &str| {
|
||||
let doc = photocraft_doc::Document::new(name, photocraft_doc::Size::new(4, 4), photocraft_doc::ColorMode::Rgb, photocraft_doc::SampleType::U8);
|
||||
photocraft_format::PcraftWriter::new().save_dir(&doc, &root.join("native.pcraft"), &photocraft_format::SaveOptions::default()).unwrap();
|
||||
};
|
||||
save(&work, "Later");
|
||||
let workspace = AuthorizedWorkspace::with_read_roots([library.as_path(), work.as_path()], Some(&work)).unwrap();
|
||||
assert_eq!(workspace.open_pcraft("native.pcraft").unwrap().unwrap().name, "Later");
|
||||
save(&library, "First");
|
||||
assert_eq!(workspace.open_pcraft("native.pcraft").unwrap().unwrap().name, "First");
|
||||
assert_eq!(workspace.open_pcraft(&work.join("native.pcraft").to_string_lossy()).unwrap().unwrap().name, "Later");
|
||||
std::fs::remove_dir_all(library.join("native.pcraft")).unwrap();
|
||||
std::fs::write(library.join("native.pcraft"), b"zip placeholder").unwrap();
|
||||
assert!(workspace.open_pcraft("native.pcraft").unwrap().is_none());
|
||||
std::fs::remove_file(library.join("native.pcraft")).unwrap();
|
||||
std::fs::create_dir(library.join("native.pcraft")).unwrap();
|
||||
assert!(workspace.open_pcraft("native.pcraft").is_err());
|
||||
for invalid in ["../native.pcraft", "a//native.pcraft", "a\\native.pcraft"] {
|
||||
assert!(workspace.open_pcraft(invalid).is_err());
|
||||
}
|
||||
let write_only = AuthorizedWorkspace::with_read_roots(std::iter::empty(), Some(&work)).unwrap();
|
||||
assert!(write_only.open_pcraft("native.pcraft").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn csh_import_requires_inline_data_in_automation() {
|
||||
let id = "shape.presets.importCsh";
|
||||
|
||||
@@ -15,5 +15,6 @@ mod native_full_composite;
|
||||
mod native_save_name;
|
||||
mod openraster;
|
||||
mod raw_defaults;
|
||||
mod read_roots;
|
||||
mod renderer_save;
|
||||
mod smart_filter_authorization;
|
||||
@@ -749,6 +749,49 @@ async fn save_without_path_never_flattens_over_the_opened_file() {
|
||||
cleanup(&dir);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn ordered_read_roots_preserve_save_identity_over_mcp() {
|
||||
let base = tmp("ordered-read-roots");
|
||||
let library = base.join("library");
|
||||
let work = base.join("work");
|
||||
for (root, width, background) in [(&library, 11, "white"), (&work, 7, "black")] {
|
||||
std::fs::create_dir_all(root).unwrap();
|
||||
let mut fixture = photocraft_automation::Headless::new();
|
||||
fixture.command_run("file.new", json!({"width": width, "height": 5, "background": background})).unwrap();
|
||||
fixture.command_run("layer.new.layer", json!({"name": "Source marker"})).unwrap();
|
||||
let bytes = photocraft_automation::files::save_bytes(&fixture.session.active().unwrap().doc, "same.pcraft", None, &Default::default()).unwrap().0;
|
||||
std::fs::write(root.join("same.pcraft"), bytes).unwrap();
|
||||
}
|
||||
let original_library = std::fs::read(library.join("same.pcraft")).unwrap();
|
||||
let original_work = std::fs::read(work.join("same.pcraft")).unwrap();
|
||||
let workspace = AuthorizedWorkspace::with_read_roots([library.as_path(), work.as_path()], Some(work.as_path())).unwrap();
|
||||
let client = connect(PhotocraftMcp::headless_with_workspace(workspace)).await;
|
||||
|
||||
assert_eq!(json_of(&call(&client, "doc_open", json!({"path": "same.pcraft"})).await)["width"], 11);
|
||||
json_of(&call(&client, "command_run", json!({"id": "layer.new.layer", "params": {"name": "Library edit"}})).await);
|
||||
let before = json_of(&call(&client, "session_list", json!({})).await);
|
||||
assert!(before["documents"][0]["path"].is_null());
|
||||
assert_eq!(before["documents"][0]["dirty"], true);
|
||||
let denied = call(&client, "doc_save", json!({})).await;
|
||||
assert_eq!(denied.is_error, Some(true));
|
||||
assert!(text(&denied).contains("pass `path`"), "{}", text(&denied));
|
||||
assert_eq!(json_of(&call(&client, "session_list", json!({})).await), before);
|
||||
assert_eq!(std::fs::read(library.join("same.pcraft")).unwrap(), original_library);
|
||||
assert_eq!(std::fs::read(work.join("same.pcraft")).unwrap(), original_work);
|
||||
|
||||
json_of(&call(&client, "doc_save", json!({"path": "same.pcraft"})).await);
|
||||
json_of(&call(&client, "command_run", json!({"id": "layer.new.layer", "params": {"name": "Work edit"}})).await);
|
||||
assert_eq!(json_of(&call(&client, "doc_save", json!({})).await)["path"], "same.pcraft");
|
||||
let reopened = json_of(&call(&client, "doc_open", json!({"path": work.join("same.pcraft").to_string_lossy()})).await);
|
||||
assert_eq!(reopened["width"], 11);
|
||||
assert_eq!(json_of(&call(&client, "doc_inspect", json!({})).await)["layers"][0]["name"], "Work edit");
|
||||
assert_eq!(json_of(&call(&client, "session_list", json!({})).await)["documents"][0]["dirty"], false);
|
||||
assert_eq!(std::fs::read(library.join("same.pcraft")).unwrap(), original_library);
|
||||
assert_ne!(std::fs::read(work.join("same.pcraft")).unwrap(), original_work);
|
||||
client.cancel().await.unwrap();
|
||||
cleanup(&base);
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn filesystem_policy_rejects_absolute_and_escaping_paths_before_effects() {
|
||||
let base = tmp("filesystem-policy");
|
||||
@@ -814,7 +857,7 @@ async fn doc_place_is_capability_scoped() {
|
||||
assert_eq!(placed, 3, "the absolute path beneath the root places as well");
|
||||
let refused = call(&client, "doc_place", json!({"path": outside.join("outside.png").to_string_lossy()})).await;
|
||||
assert_eq!(refused.is_error, Some(true));
|
||||
assert!(text(&refused).contains("must be inside the automation root"), "{}", text(&refused));
|
||||
assert!(text(&refused).contains("must be inside an automation read root"), "{}", text(&refused));
|
||||
let after = json_of(&call(&client, "doc_inspect", json!({})).await)["layers"].as_array().unwrap().len();
|
||||
assert_eq!(after, placed, "nothing outside the root was placed");
|
||||
// The ambient command keeps its refusal: the capability-scoped method is the only way in.
|
||||
@@ -847,7 +890,7 @@ async fn doc_replace_smart_object_is_capability_scoped() {
|
||||
assert_ne!(replaced.is_error, Some(true), "{}", text(&replaced));
|
||||
let refused = call(&client, "doc_replace_smart_object", json!({"path": outside.join("outside.png").to_string_lossy(), "layer": layer})).await;
|
||||
assert_eq!(refused.is_error, Some(true));
|
||||
assert!(text(&refused).contains("must be inside the automation root"), "{}", text(&refused));
|
||||
assert!(text(&refused).contains("must be inside an automation read root"), "{}", text(&refused));
|
||||
let ambient = call(&client, "command_run", json!({"id": "layer.smartObjects.replaceContents", "params": {"path": "inside.png", "layer": layer}})).await;
|
||||
assert_eq!(ambient.is_error, Some(true));
|
||||
assert!(text(&ambient).contains("ambient filesystem paths"), "{}", text(&ambient));
|
||||
|
||||
@@ -0,0 +1,297 @@
|
||||
//! Real-document regressions for ordered read roots and independent write authority.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use photocraft_automation::{AuthorizedWorkspace, Headless, files};
|
||||
use photocraft_engine::actions_cmds::Action;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
struct Roots {
|
||||
base: PathBuf,
|
||||
library: PathBuf,
|
||||
work: PathBuf,
|
||||
outside: PathBuf,
|
||||
}
|
||||
|
||||
impl Roots {
|
||||
fn new(name: &str) -> Self {
|
||||
let base = std::env::temp_dir().join(format!("pc-read-roots-{}-{name}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
let roots = Self { library: base.join("library"), work: base.join("work"), outside: base.join("outside"), base };
|
||||
for root in [&roots.library, &roots.work, &roots.outside] {
|
||||
std::fs::create_dir_all(root).unwrap();
|
||||
}
|
||||
roots
|
||||
}
|
||||
|
||||
fn workspace(&self) -> AuthorizedWorkspace {
|
||||
AuthorizedWorkspace::with_read_roots([self.library.as_path(), self.work.as_path()], Some(self.work.as_path())).unwrap()
|
||||
}
|
||||
|
||||
fn headless(&self) -> Headless {
|
||||
Headless::with_workspace(self.workspace())
|
||||
}
|
||||
|
||||
fn seed(&self) -> (Vec<u8>, Vec<u8>) {
|
||||
let library = layered_bytes(11, "white");
|
||||
let work = layered_bytes(7, "black");
|
||||
std::fs::write(self.library.join("same.pcraft"), &library).unwrap();
|
||||
std::fs::write(self.work.join("same.pcraft"), &work).unwrap();
|
||||
(library, work)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Roots {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.base);
|
||||
}
|
||||
}
|
||||
|
||||
fn layered_bytes(width: u32, background: &str) -> Vec<u8> {
|
||||
let mut headless = Headless::new();
|
||||
headless.command_run("file.new", json!({"width": width, "height": 5, "background": background})).unwrap();
|
||||
headless.command_run("layer.new.layer", json!({"name": "Source marker"})).unwrap();
|
||||
let doc = &headless.session.active().unwrap().doc;
|
||||
files::save_bytes(doc, "seed.pcraft", None, &Default::default()).unwrap().0
|
||||
}
|
||||
|
||||
fn snapshot(headless: &mut Headless) -> (Value, Value, Vec<u8>) {
|
||||
(headless.session_list(), headless.inspect(None).unwrap(), headless.render_png(None, 32).unwrap())
|
||||
}
|
||||
|
||||
fn assert_source(headless: &Headless, width: u32, rgba: [u8; 4]) {
|
||||
let state = headless.session.active().unwrap();
|
||||
assert_eq!(state.doc.size.width, width);
|
||||
assert_eq!(state.doc.size.height, 5);
|
||||
let preview = photocraft_compose::thumbnail(&state.doc, 32);
|
||||
assert!(!preview.pixels.is_empty());
|
||||
assert!(preview.pixels.as_chunks::<4>().0.iter().all(|pixel| pixel == &rgba), "opened the wrong source pixels");
|
||||
}
|
||||
|
||||
fn edit(headless: &mut Headless, name: &str) {
|
||||
headless.command_run("layer.new.layer", json!({"name": name})).unwrap();
|
||||
assert!(headless.session.active().unwrap().is_dirty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn library_first_open_cannot_overwrite_same_named_work_until_explicit_save_as() {
|
||||
let roots = Roots::new("save-identity");
|
||||
let (library, work) = roots.seed();
|
||||
let mut headless = roots.headless();
|
||||
headless.open(Path::new("same.pcraft")).unwrap();
|
||||
assert_source(&headless, 11, [255; 4]);
|
||||
assert!(headless.session.active().unwrap().path.is_none());
|
||||
edit(&mut headless, "Library edit");
|
||||
|
||||
let before = snapshot(&mut headless);
|
||||
let error = headless.save(None, None, None, &Default::default()).unwrap_err().to_string();
|
||||
assert!(error.contains("pass `path`"), "{error}");
|
||||
assert_eq!(snapshot(&mut headless), before, "denial must preserve pixels, history, selection, path and dirty revision");
|
||||
assert_eq!(std::fs::read(roots.library.join("same.pcraft")).unwrap(), library);
|
||||
assert_eq!(std::fs::read(roots.work.join("same.pcraft")).unwrap(), work);
|
||||
|
||||
// Naming a target is the explicit transition from a library document to a work file.
|
||||
headless.save(None, Some(Path::new("same.pcraft")), None, &Default::default()).unwrap();
|
||||
assert_eq!(headless.session.active().unwrap().path.as_deref(), Some("same.pcraft"));
|
||||
assert!(!headless.session.active().unwrap().is_dirty());
|
||||
assert_ne!(std::fs::read(roots.work.join("same.pcraft")).unwrap(), work);
|
||||
assert_eq!(std::fs::read(roots.library.join("same.pcraft")).unwrap(), library);
|
||||
|
||||
edit(&mut headless, "Later work edit");
|
||||
assert_eq!(headless.save(None, None, None, &Default::default()).unwrap()["path"], "same.pcraft");
|
||||
assert!(!headless.session.active().unwrap().is_dirty());
|
||||
assert_eq!(std::fs::read(roots.library.join("same.pcraft")).unwrap(), library);
|
||||
|
||||
let mut reopened = roots.headless();
|
||||
reopened.open(&roots.work.join("same.pcraft")).unwrap();
|
||||
assert_source(&reopened, 11, [255; 4]);
|
||||
assert_eq!(reopened.inspect(None).unwrap()["layers"][0]["name"], "Later work edit");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn absolute_path_selects_the_second_read_root_and_allows_its_own_implicit_save() {
|
||||
let roots = Roots::new("absolute-work");
|
||||
let (library, work) = roots.seed();
|
||||
let mut headless = roots.headless();
|
||||
let path = roots.work.join("same.pcraft");
|
||||
headless.open(&path).unwrap();
|
||||
assert_source(&headless, 7, [0, 0, 0, 255]);
|
||||
assert_eq!(headless.session.active().unwrap().path.as_deref(), path.to_str());
|
||||
edit(&mut headless, "Absolute work edit");
|
||||
assert_eq!(headless.save(None, None, None, &Default::default()).unwrap()["path"], path.to_str().unwrap());
|
||||
assert!(!headless.session.active().unwrap().is_dirty());
|
||||
assert_eq!(std::fs::read(roots.library.join("same.pcraft")).unwrap(), library);
|
||||
assert_ne!(std::fs::read(&path).unwrap(), work);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_library_file_falls_through_to_a_writable_work_document() {
|
||||
let roots = Roots::new("relative-work");
|
||||
let work = layered_bytes(7, "black");
|
||||
std::fs::write(roots.work.join("unique.pcraft"), &work).unwrap();
|
||||
let mut headless = roots.headless();
|
||||
headless.open(Path::new("unique.pcraft")).unwrap();
|
||||
assert_source(&headless, 7, [0, 0, 0, 255]);
|
||||
assert_eq!(headless.session.active().unwrap().path.as_deref(), Some("unique.pcraft"));
|
||||
edit(&mut headless, "Relative work edit");
|
||||
headless.save(None, None, None, &Default::default()).unwrap();
|
||||
assert_ne!(std::fs::read(roots.work.join("unique.pcraft")).unwrap(), work);
|
||||
assert!(!roots.library.join("unique.pcraft").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_only_roots_can_reopen_exported_work_without_acquiring_write_authority() {
|
||||
let roots = Roots::new("readonly-reopen");
|
||||
let (library, _) = roots.seed();
|
||||
{
|
||||
let mut writer = roots.headless();
|
||||
writer.open(Path::new("same.pcraft")).unwrap();
|
||||
edit(&mut writer, "Exported for review");
|
||||
writer.save(None, Some(Path::new("review.pcraft")), None, &Default::default()).unwrap();
|
||||
}
|
||||
let exported = std::fs::read(roots.work.join("review.pcraft")).unwrap();
|
||||
let workspace = AuthorizedWorkspace::with_read_roots([roots.library.as_path(), roots.work.as_path()], None).unwrap();
|
||||
let mut reader = Headless::with_workspace(workspace);
|
||||
for path in [PathBuf::from("review.pcraft"), roots.work.join("review.pcraft")] {
|
||||
reader.open(&path).unwrap();
|
||||
assert_source(&reader, 11, [255; 4]);
|
||||
assert_eq!(reader.inspect(None).unwrap()["layers"][0]["name"], "Exported for review");
|
||||
assert!(reader.session.active().unwrap().path.is_none());
|
||||
edit(&mut reader, "Unsaved review edit");
|
||||
let before = snapshot(&mut reader);
|
||||
assert!(reader.save(None, None, None, &Default::default()).is_err());
|
||||
let error = reader.save(None, Some(Path::new("review.pcraft")), None, &Default::default()).unwrap_err().to_string();
|
||||
assert!(error.contains("write authority is absent"), "{error}");
|
||||
assert_eq!(snapshot(&mut reader), before);
|
||||
}
|
||||
assert_eq!(std::fs::read(roots.work.join("review.pcraft")).unwrap(), exported);
|
||||
assert_eq!(std::fs::read(roots.library.join("same.pcraft")).unwrap(), library);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_write_root_does_not_implicitly_grant_read_access_to_saved_work() {
|
||||
let roots = Roots::new("write-is-not-read");
|
||||
let _ = roots.seed();
|
||||
let workspace = AuthorizedWorkspace::with_read_roots([roots.library.as_path()], Some(roots.work.as_path())).unwrap();
|
||||
let mut headless = Headless::with_workspace(workspace);
|
||||
headless.open(Path::new("same.pcraft")).unwrap();
|
||||
headless.save(None, Some(Path::new("written.pcraft")), None, &Default::default()).unwrap();
|
||||
let before = snapshot(&mut headless);
|
||||
for path in [PathBuf::from("written.pcraft"), roots.work.join("written.pcraft")] {
|
||||
assert!(headless.open(&path).is_err());
|
||||
assert_eq!(snapshot(&mut headless), before);
|
||||
}
|
||||
assert!(roots.work.join("written.pcraft").is_file());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flat_export_does_not_arm_implicit_save_for_a_library_document() {
|
||||
let roots = Roots::new("flat-export");
|
||||
let (library, work) = roots.seed();
|
||||
let mut headless = roots.headless();
|
||||
headless.open(Path::new("same.pcraft")).unwrap();
|
||||
edit(&mut headless, "Still unsaved");
|
||||
let before = snapshot(&mut headless);
|
||||
headless.save(None, Some(Path::new("preview.png")), None, &Default::default()).unwrap();
|
||||
assert_eq!(snapshot(&mut headless), before, "a flat export must not clear dirty or attach a save path");
|
||||
let exported = std::fs::read(roots.work.join("preview.png")).unwrap();
|
||||
assert_eq!(photocraft_codecs::decode(&exported).unwrap().dimensions(), (11, 5));
|
||||
assert!(headless.save(None, None, None, &Default::default()).is_err());
|
||||
assert_eq!(snapshot(&mut headless), before);
|
||||
assert_eq!(std::fs::read(roots.work.join("preview.png")).unwrap(), exported);
|
||||
assert_eq!(std::fs::read(roots.library.join("same.pcraft")).unwrap(), library);
|
||||
assert_eq!(std::fs::read(roots.work.join("same.pcraft")).unwrap(), work);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn library_absolute_paths_and_traversal_cannot_be_used_as_save_targets() {
|
||||
let roots = Roots::new("rejected-writes");
|
||||
let (library, work) = roots.seed();
|
||||
let canary = layered_bytes(3, "black");
|
||||
std::fs::write(roots.outside.join("canary.pcraft"), &canary).unwrap();
|
||||
let mut headless = roots.headless();
|
||||
headless.open(&roots.library.join("same.pcraft")).unwrap();
|
||||
assert!(headless.session.active().unwrap().path.is_none());
|
||||
edit(&mut headless, "Must remain unsaved");
|
||||
let before = snapshot(&mut headless);
|
||||
for path in [
|
||||
roots.library.join("same.pcraft"),
|
||||
PathBuf::from("../library/same.pcraft"),
|
||||
PathBuf::from("../outside/canary.pcraft"),
|
||||
roots.work.join("..").join("outside").join("canary.pcraft"),
|
||||
] {
|
||||
let error = headless.save(None, Some(&path), None, &Default::default()).unwrap_err().to_string();
|
||||
assert!(error.contains("automation path rejected"), "{path:?}: {error}");
|
||||
assert_eq!(snapshot(&mut headless), before);
|
||||
}
|
||||
assert_eq!(std::fs::read(roots.library.join("same.pcraft")).unwrap(), library);
|
||||
assert_eq!(std::fs::read(roots.work.join("same.pcraft")).unwrap(), work);
|
||||
assert_eq!(std::fs::read(roots.outside.join("canary.pcraft")).unwrap(), canary);
|
||||
}
|
||||
|
||||
#[cfg(any(unix, windows))]
|
||||
#[test]
|
||||
fn a_work_directory_symlink_cannot_write_into_another_read_root() {
|
||||
let roots = Roots::new("symlink-write");
|
||||
let (library, work) = roots.seed();
|
||||
#[cfg(unix)]
|
||||
std::os::unix::fs::symlink(&roots.library, roots.work.join("library-link")).unwrap();
|
||||
#[cfg(windows)]
|
||||
if let Err(error) = std::os::windows::fs::symlink_dir(&roots.library, roots.work.join("library-link")) {
|
||||
if error.kind() == std::io::ErrorKind::PermissionDenied {
|
||||
eprintln!("symlink regression requires Windows symlink permission: {error}");
|
||||
return;
|
||||
}
|
||||
panic!("create test symlink: {error}");
|
||||
}
|
||||
let mut headless = roots.headless();
|
||||
headless.open(Path::new("same.pcraft")).unwrap();
|
||||
edit(&mut headless, "Cannot follow the write link");
|
||||
let before = snapshot(&mut headless);
|
||||
for path in ["library-link/same.pcraft", "library-link/new.pcraft"] {
|
||||
assert!(headless.save(None, Some(Path::new(path)), None, &Default::default()).is_err());
|
||||
assert_eq!(snapshot(&mut headless), before);
|
||||
}
|
||||
assert_eq!(std::fs::read(roots.library.join("same.pcraft")).unwrap(), library);
|
||||
assert_eq!(std::fs::read(roots.work.join("same.pcraft")).unwrap(), work);
|
||||
assert!(!roots.library.join("new.pcraft").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corrupt_first_match_is_an_error_instead_of_falling_through_to_a_valid_document() {
|
||||
let roots = Roots::new("corrupt-first");
|
||||
let (_, work) = roots.seed();
|
||||
let corrupt = b"this is not a native document";
|
||||
std::fs::write(roots.library.join("same.pcraft"), corrupt).unwrap();
|
||||
let mut headless = roots.headless();
|
||||
// The later file is valid, and a failed open must leave this active document intact.
|
||||
headless.open(&roots.work.join("same.pcraft")).unwrap();
|
||||
assert_source(&headless, 7, [0, 0, 0, 255]);
|
||||
edit(&mut headless, "Existing edit");
|
||||
let before = snapshot(&mut headless);
|
||||
assert!(headless.open(Path::new("same.pcraft")).is_err());
|
||||
assert_eq!(snapshot(&mut headless), before);
|
||||
assert_eq!(std::fs::read(roots.library.join("same.pcraft")).unwrap(), corrupt);
|
||||
assert_eq!(std::fs::read(roots.work.join("same.pcraft")).unwrap(), work);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multiple_roots_do_not_grant_ambient_commands_or_nested_action_file_access() {
|
||||
let roots = Roots::new("ambient-commands");
|
||||
let (library, work) = roots.seed();
|
||||
let mut headless = roots.headless();
|
||||
headless.open(Path::new("same.pcraft")).unwrap();
|
||||
let before = snapshot(&mut headless);
|
||||
let target = roots.work.join("ambient.psd");
|
||||
let error = headless.command_run("file.saveACopy", json!({"path": target})).unwrap_err().to_string();
|
||||
assert!(error.contains("ambient filesystem paths"), "{error}");
|
||||
// A writable destination still cannot be reached through an ambient engine command.
|
||||
headless.session.actions.list.push(Action::new("Write work", vec![("file.saveACopy".into(), json!({"path": target}))]));
|
||||
headless.session.actions.list.push(Action::new("Nested write", vec![("actions.play".into(), json!({"action": "Write work"}))]));
|
||||
let played = headless.command_run("actions.play", json!({"action": "Nested write"})).unwrap();
|
||||
assert!(played["failed"].to_string().contains("ambient filesystem paths"), "{played}");
|
||||
assert_eq!(snapshot(&mut headless), before);
|
||||
assert!(!target.exists());
|
||||
assert_eq!(std::fs::read(roots.library.join("same.pcraft")).unwrap(), library);
|
||||
assert_eq!(std::fs::read(roots.work.join("same.pcraft")).unwrap(), work);
|
||||
}
|
||||
@@ -1577,12 +1577,17 @@ fn app_open(app: &mut PhotocraftApp, path: &str, approved: bool) -> Outcome {
|
||||
Some(read) => read(path),
|
||||
None => Err("automation read authority is not configured".into()),
|
||||
};
|
||||
wrap(opened.and_then(|(name, bytes)| {
|
||||
wrap(opened.and_then(|crate::AutomationReadResult { name, bytes, save_path }| {
|
||||
let name = app.open_name(&name);
|
||||
let warnings = app.open_automation_bytes_with_approval(&name, &bytes, approved)?;
|
||||
// Brushes/gradients go to the preset libraries: no document, no Open Recent entry.
|
||||
if !crate::preset_files_ui::is_preset_file(&name) {
|
||||
app.opened_from(path);
|
||||
if let Some(state) = app.session.active_mut()
|
||||
&& state.path.is_some()
|
||||
{
|
||||
state.path = save_path;
|
||||
}
|
||||
}
|
||||
Ok(json!({"path": path, "name": name, "warnings": warnings}))
|
||||
}))
|
||||
|
||||
@@ -1572,7 +1572,13 @@ fn automation_open_and_save_use_the_roots_and_reply_with_warnings() {
|
||||
Ok((Document::new(name, Size::new(4, 4), ColorMode::Rgb, SampleType::U8), vec!["Adjustment layer flattened".to_string()]))
|
||||
})),
|
||||
export: Some(Box::new(|_d: &Document, _p: &str, _s: &crate::ExportSettings| Ok((b"out".to_vec(), vec!["Layers were flattened".to_string()])))),
|
||||
automation_read: Some(Box::new(|path: &str| Ok((path.rsplit('/').next().unwrap_or(path).to_string(), b"x".to_vec())))),
|
||||
automation_read: Some(Box::new(|path: &str| {
|
||||
Ok(crate::AutomationReadResult {
|
||||
name: path.rsplit('/').next().unwrap_or(path).to_string(),
|
||||
bytes: b"x".to_vec(),
|
||||
save_path: Some(path.to_string()),
|
||||
})
|
||||
})),
|
||||
automation_write: Some(Box::new(move |path: &str, _b: &[u8]| {
|
||||
w.borrow_mut().push(path.to_string());
|
||||
Ok(())
|
||||
@@ -1708,7 +1714,7 @@ fn app_open_opens_a_directory_pcraft_and_falls_back_for_the_zip_form() {
|
||||
})),
|
||||
automation_read: Some(Box::new(|path: &str| {
|
||||
if path == "zipped.pcraft" {
|
||||
Ok((path.rsplit('/').next().unwrap_or(path).to_string(), b"zip-bytes".to_vec()))
|
||||
Ok(crate::AutomationReadResult { name: path.rsplit('/').next().unwrap_or(path).to_string(), bytes: b"zip-bytes".to_vec(), save_path: None })
|
||||
} else {
|
||||
Err(format!("no such path: {path}"))
|
||||
}
|
||||
@@ -2363,6 +2369,71 @@ fn ui_set_mask_target_ends_a_filter_mask_view() {
|
||||
assert_eq!(sm.filter_mask.as_ref().unwrap().value(20, 20), 1.0, "not into the filter mask");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn automation_library_open_requires_explicit_save_as_before_implicit_save() {
|
||||
use photocraft_color::{ColorMode, SampleType};
|
||||
use photocraft_doc::Document;
|
||||
use photocraft_geom::Size;
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
let written: Rc<RefCell<Vec<String>>> = Rc::default();
|
||||
let writes = written.clone();
|
||||
let services = crate::Services {
|
||||
import: Some(Box::new(|name: &str, _: &[u8], _: &photocraft_io::ImportOptions| {
|
||||
Ok((Document::new(name, Size::new(4, 4), ColorMode::Rgb, SampleType::U8), Vec::new()))
|
||||
})),
|
||||
export: Some(Box::new(|_: &Document, _: &str, _: &crate::ExportSettings| Ok((b"saved".to_vec(), Vec::new())))),
|
||||
automation_read: Some(Box::new(|path: &str| {
|
||||
Ok(crate::AutomationReadResult {
|
||||
name: "same.psd".into(),
|
||||
bytes: b"source".to_vec(),
|
||||
save_path: path.starts_with("work/").then(|| path.to_owned()),
|
||||
})
|
||||
})),
|
||||
automation_write: Some(Box::new(move |path: &str, _: &[u8]| {
|
||||
if path == "failed.psd" {
|
||||
return Err("test write failure".into());
|
||||
}
|
||||
writes.borrow_mut().push(path.to_owned());
|
||||
Ok(())
|
||||
})),
|
||||
write: Some(Box::new(|_, _| Err("ambient writer used".into()))),
|
||||
..Default::default()
|
||||
};
|
||||
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services);
|
||||
let ctx = egui::Context::default();
|
||||
let opened = call(&mut app, &ctx, "app.open", json!({"path": "library/same.psd"}));
|
||||
assert_eq!(opened["ok"], true, "{opened}");
|
||||
assert_eq!(app.session.active().unwrap().path, None);
|
||||
assert_eq!(app.ui.recent_files, vec!["library/same.psd"]);
|
||||
app.run("layer.new.layer", json!({"name": "edit"})).unwrap();
|
||||
assert!(app.session.active().unwrap().is_dirty());
|
||||
let refused = call(&mut app, &ctx, "app.save", json!({}));
|
||||
assert!(refused["error"].as_str().unwrap().contains("pass `path`"), "{refused}");
|
||||
assert!(written.borrow().is_empty());
|
||||
assert!(app.session.active().unwrap().is_dirty());
|
||||
let flat = call(&mut app, &ctx, "app.save", json!({"path": "copy.png"}));
|
||||
assert_eq!(flat["ok"], true, "{flat}");
|
||||
assert_eq!(app.session.active().unwrap().path, None);
|
||||
assert!(app.session.active().unwrap().is_dirty());
|
||||
let failed = call(&mut app, &ctx, "app.save", json!({"path": "failed.psd"}));
|
||||
assert_eq!(failed["ok"], false, "{failed}");
|
||||
assert_eq!(app.session.active().unwrap().path, None);
|
||||
assert!(app.session.active().unwrap().is_dirty());
|
||||
let saved = call(&mut app, &ctx, "app.save", json!({"path": "copy.psd"}));
|
||||
assert_eq!(saved["ok"], true, "{saved}");
|
||||
assert_eq!(app.session.active().unwrap().path.as_deref(), Some("copy.psd"));
|
||||
assert!(!app.session.active().unwrap().is_dirty());
|
||||
let again = call(&mut app, &ctx, "app.save", json!({}));
|
||||
assert_eq!(again["ok"], true, "{again}");
|
||||
assert_eq!(*written.borrow(), vec!["copy.png", "copy.psd", "copy.psd"]);
|
||||
let opened = call(&mut app, &ctx, "app.open", json!({"path": "work/same.psd"}));
|
||||
assert_eq!(opened["ok"], true, "{opened}");
|
||||
let saved = call(&mut app, &ctx, "app.save", json!({}));
|
||||
assert_eq!(saved["result"]["path"], "work/same.psd", "{saved}");
|
||||
}
|
||||
|
||||
fn shift_right(app: &mut PhotocraftApp, ctx: &egui::Context, tool: &str) {
|
||||
call(
|
||||
app,
|
||||
|
||||
@@ -256,6 +256,7 @@ pub use prefs::flick_pan;
|
||||
pub use prefs::kys_import;
|
||||
pub use prefs::prefs_ui;
|
||||
use prefs::pressure_curve_ui;
|
||||
pub use services::AutomationReadResult;
|
||||
pub(crate) use services::SAVE_OPTIONS_OPEN;
|
||||
#[cfg(test)]
|
||||
pub(crate) use services::saved_revision_after_write;
|
||||
|
||||
@@ -272,8 +272,15 @@ pub(crate) enum SaveKind {
|
||||
Automation,
|
||||
}
|
||||
|
||||
/// Read bytes through the desktop control session's authorized read root.
|
||||
pub type AutomationReadFn = Box<dyn FnMut(&str) -> Result<(String, Vec<u8>), String>>;
|
||||
/// Bytes and save provenance selected together by the automation read capability.
|
||||
pub struct AutomationReadResult {
|
||||
pub name: String,
|
||||
pub bytes: Vec<u8>,
|
||||
/// None means an explicit Save As is required, even for a layered document.
|
||||
pub save_path: Option<String>,
|
||||
}
|
||||
/// Read bytes through the desktop control session's authorized read roots.
|
||||
pub type AutomationReadFn = Box<dyn FnMut(&str) -> Result<AutomationReadResult, String>>;
|
||||
|
||||
/// Write bytes through the desktop control session's authorized write root.
|
||||
pub type AutomationWriteFn = Box<dyn FnMut(&str, &[u8]) -> Result<(), String>>;
|
||||
|
||||
+43
-13
@@ -410,19 +410,49 @@ lines are visible. The protocol is unencrypted and must remain on loopback; do n
|
||||
it to an untrusted host.
|
||||
|
||||
Filesystem access fails closed unless launch-time read and/or write roots are granted with
|
||||
`--automation-read-root` and `--automation-write-root`. The environment-variable equivalents
|
||||
(`PHOTOCRAFT_AUTOMATION_READ_ROOT` / `PHOTOCRAFT_AUTOMATION_WRITE_ROOT`) are supported by
|
||||
the desktop `photocraft` process, but not by headless `photocraft-cli mcp` or `serve`;
|
||||
for those CLI modes, supply the flags explicitly. In MCP bridge mode, configure roots on the
|
||||
desktop process rather than on the bridging CLI. Request paths must be
|
||||
non-empty, forward-slash relative paths beneath the applicable root, or absolute paths that lie
|
||||
beneath it. An absolute path is compared with the root as text and the rest is checked like a
|
||||
relative path; nothing is resolved on the filesystem. Absolute paths outside the root, parent
|
||||
traversal, alternate separators in relative paths, drive/device/stream prefixes, malformed
|
||||
components, and link escapes are rejected before file effects. Read and write authority are
|
||||
independent; the parent of a new output file must already exist. Engine commands that still use
|
||||
ambient filesystem paths are disabled for automation until they are migrated to the same
|
||||
capability interface. Interactive desktop file pickers retain normal user-selected access.
|
||||
`--automation-read-root` and `--automation-write-root`. Repeat the read flag to grant an ordered
|
||||
list of directories; both `--flag <dir>` and `--flag=<dir>` syntax are supported by desktop,
|
||||
headless MCP and `serve`, and duplicate read roots are allowed. Headless reads try those roots
|
||||
in launch order and select the first existing regular file. Only a missing file (`NotFound`)
|
||||
falls through; directory, permission, path-escape and decoding errors are terminal.
|
||||
Desktop `app.open` also accepts native directory `.pcraft` documents through the selected read
|
||||
capability. It searches in the same order: a ZIP file in an earlier root wins over a directory
|
||||
in a later root. Once a directory is selected, loading errors are terminal. Directory opens
|
||||
never establish an implicit save target, even when the read and write capabilities match;
|
||||
use an explicit layered Save As beneath the write root.
|
||||
Every configured root must be an existing directory. An empty, missing or invalid root fails
|
||||
startup rather than being dropped. There is exactly one optional write root; repeated
|
||||
`--automation-write-root` flags are usage errors (exit 2), even when the values match.
|
||||
|
||||
The desktop `PHOTOCRAFT_AUTOMATION_READ_ROOT` environment variable supplies a single fallback
|
||||
directory, not a path list. Any explicit read-root flags replace it, preserving CLI order.
|
||||
One explicit write-root flag overrides `PHOTOCRAFT_AUTOMATION_WRITE_ROOT`. These environment
|
||||
variables are not supported by headless `photocraft-cli mcp` or `serve`; supply flags explicitly.
|
||||
In MCP bridge mode, configure roots on the desktop process. Supplying root flags to
|
||||
`photocraft-cli mcp --bridge` is a usage error; a bridge client cannot grant filesystem access.
|
||||
|
||||
Request paths must be non-empty, forward-slash relative paths beneath the applicable root, or
|
||||
absolute paths beneath a corresponding granted root. An absolute path is compared with the
|
||||
configured roots as text and the remainder is checked like a relative path. The file is opened
|
||||
through the held directory capability, without ambient filesystem canonicalization of the
|
||||
request. Absolute paths outside all corresponding roots, parent traversal, alternate separators
|
||||
in relative paths, drive/device/stream prefixes, malformed components, and link escapes are
|
||||
rejected before file effects. Read and write authority are independent: a write root never
|
||||
grants reads, and writes do not search read roots. The parent of a new output file must already
|
||||
exist.
|
||||
|
||||
An automation-opened document retains an implicit save target only when its winning read root
|
||||
and configured write root use the same held directory capability. Differently configured aliases
|
||||
and nested roots conservatively require explicit Save As, even if they name the same underlying
|
||||
file. An explicit successful layered save beneath the write root establishes its save target;
|
||||
a flat export does not. Existing PSD/PSB/`.pcraft` restrictions on pathless saves still apply.
|
||||
This automation safeguard leaves interactive file-picker access unchanged. Desktop document
|
||||
identity for Cmd+S and Open Recent is a separate concern.
|
||||
|
||||
Engine commands that still use ambient filesystem paths are disabled for automation until they
|
||||
are migrated to the same capability interface. Extra read roots do not enable ambient asset reads
|
||||
or headless directory-bundle access. Desktop `app.open` supports directory `.pcraft` only through
|
||||
its granted read capabilities. Interactive desktop file pickers retain normal user-selected access.
|
||||
|
||||
## Headless server
|
||||
|
||||
|
||||
+19
-4
@@ -305,11 +305,26 @@ At startup the desktop lists recovery metadata, then decodes one document at a t
|
||||
|
||||
`photocraft-cli mcp` serves MCP on stdio using `crates/automation`, which is built on `rmcp`:
|
||||
|
||||
- **Headless:** `photocraft-cli mcp --automation-read-root <dir> --automation-write-root <dir>`. It drives an in-process engine session and has no file authority when a root is omitted.
|
||||
- **Live app:** start `photocraft --control 7878 --control-token-file <private-path> --automation-read-root <dir> --automation-write-root <dir>`, then run `photocraft-cli mcp --bridge 127.0.0.1:7878 --control-token-file <private-path>`. The desktop process owns the roots. See `docs/control-protocol.md#mcp-bridge`.
|
||||
- **Headless:** `photocraft-cli mcp --automation-read-root <project> --automation-read-root <library> --automation-write-root <project>`. It drives an in-process engine session with ordered read directories and one write directory.
|
||||
- **Live app:** start `photocraft --control 7878 --control-token-file <private-path> --automation-read-root <project> --automation-read-root <library> --automation-write-root <project>`, then run `photocraft-cli mcp --bridge 127.0.0.1:7878 --control-token-file <private-path>`. The desktop process owns the roots; root flags on the bridging CLI are a usage error. See `docs/control-protocol.md#mcp-bridge`.
|
||||
|
||||
For headless MCP clients, pass absolute paths to deliberately chosen trusted workspace directories in the launch arguments. Desktop `PHOTOCRAFT_AUTOMATION_READ_ROOT` and `PHOTOCRAFT_AUTOMATION_WRITE_ROOT` environment variables do **not** grant headless CLI access. Omitting a root flag deliberately denies that direction of access.
|
||||
|
||||
Read flags accumulate in order, including mixed `--automation-read-root <dir>` and
|
||||
`--automation-read-root=<dir>` syntax; duplicate read roots are allowed. A headless relative read
|
||||
uses the first existing regular file. Only a missing file falls through to the next root;
|
||||
directory, permission, path-escape and decoding errors stop the request. Desktop `app.open`
|
||||
(and bridged `doc_open`) also accepts native directory `.pcraft` through the selected read
|
||||
capability. An earlier root's ZIP file wins over a later root's directory, and loading errors
|
||||
in a selected directory are terminal. Directory opens never establish an implicit save target;
|
||||
use explicit layered Save As beneath the write root, even when both capabilities match.
|
||||
Every root must be an existing directory, and empty or missing values fail startup. There is still only one write root;
|
||||
repeating its flag is a usage error even for identical values. Write authority does not imply
|
||||
read authority. A read-only library document needs an explicit Save As into the write root before
|
||||
it has an implicit save target; aliases and nested roots also require explicit Save As.
|
||||
These roots do not enable additional ambient asset reads or headless directory-bundle access;
|
||||
desktop directory `.pcraft` reads use only the granted read capabilities.
|
||||
|
||||
Tools:
|
||||
|
||||
- `session_list`
|
||||
@@ -335,7 +350,7 @@ Claude Code (`.mcp.json` in the repo root, or `claude mcp add`):
|
||||
"mcpServers": {
|
||||
"photocraft": {
|
||||
"command": "/path/to/photocraft/target/release/photocraft-cli",
|
||||
"args": ["mcp", "--automation-read-root", "/absolute/path/to/trusted/workspace", "--automation-write-root", "/absolute/path/to/trusted/workspace"]
|
||||
"args": ["mcp", "--automation-read-root", "/absolute/path/to/trusted/workspace", "--automation-read-root", "/absolute/path/to/reference/library", "--automation-write-root", "/absolute/path/to/trusted/workspace"]
|
||||
},
|
||||
"photocraft-live": {
|
||||
"command": "/path/to/photocraft/target/release/photocraft-cli",
|
||||
@@ -367,7 +382,7 @@ capability-scoped export, resize/crop, CMYK + native save) driven purely over MC
|
||||
Without MCP, `photocraft-cli serve [--port N]` keeps a headless session open and answers JSON lines
|
||||
(see `docs/control-protocol.md#headless-server`).
|
||||
|
||||
A typical agent loop (place inputs under the configured read root and outputs under the write root):
|
||||
A typical agent loop (place inputs under a configured read root and outputs under the write root):
|
||||
|
||||
1. `doc_open {path}`
|
||||
2. `command_list {filter:"blur"}`
|
||||
|
||||
+40
-4
@@ -50,12 +50,48 @@ not put the CLI on `PATH`.
|
||||
PhotoCraft follows the same conventions as FilmCraft #28. Start a headless session:
|
||||
|
||||
```sh
|
||||
photocraft-cli mcp --automation-read-root /work/project --automation-write-root /work/project
|
||||
photocraft-cli mcp \
|
||||
--automation-read-root /work/project \
|
||||
--automation-read-root /library/reference \
|
||||
--automation-write-root /work/project
|
||||
```
|
||||
|
||||
Paths are relative to the corresponding root, or absolute paths beneath it; without a root that
|
||||
filesystem authority is absent. Bridge mode uses `--bridge` and `--control-token-file` as
|
||||
described in [development.md](development.md). UI tools require a running desktop app.
|
||||
Repeat `--automation-read-root` to grant ordered read directories in headless `mcp`, `serve`,
|
||||
or desktop `photocraft --control`. Both `--flag <dir>` and `--flag=<dir>` work and can be mixed;
|
||||
duplicate read roots are allowed. Relative file requests search the roots in launch order.
|
||||
Headless reads select the first existing regular file; only a missing file tries the next root.
|
||||
Directory, permission, path-escape and decoding errors stop headless requests instead of falling back.
|
||||
Desktop `app.open`, including bridged `doc_open`, also supports native directory `.pcraft`
|
||||
documents through the selected read capability. An earlier root's ZIP file wins over a later
|
||||
root's directory; loading errors in a selected directory are terminal. Directory opens have
|
||||
no implicit save target, even through the write root's capability, and need explicit layered
|
||||
Save As beneath the write root.
|
||||
All configured roots must be valid existing directories; an empty, missing or invalid root
|
||||
fails startup rather than being dropped.
|
||||
|
||||
There is still only one `--automation-write-root`. Repeating it is a usage error (exit 2),
|
||||
even with an identical value or mixed flag syntax. Writes are relative to that root, with no
|
||||
fallback to any read root. Read and write authority are independent; a write root does not grant
|
||||
reads, and omitting either kind of root denies that direction of filesystem access.
|
||||
Absolute request paths must be beneath a corresponding granted root and are opened through
|
||||
its directory capability, without ambient filesystem resolution of the requested path.
|
||||
|
||||
A document opened through a read root that does not share the write root's held directory
|
||||
capability has no implicit save target. The same configured root shares that capability;
|
||||
canonical filesystem identity is not inferred. Use an explicit `doc_save {path:"copy.pcraft"}`
|
||||
(or another supported layered format) beneath the write root to establish one. Aliases and nested roots conservatively also
|
||||
require explicit Save As; a flat export does not establish a save target. Existing restrictions
|
||||
on pathless saves still apply. These grants do not enable ambient asset reads or headless
|
||||
directory-bundle access; desktop directory `.pcraft` reads remain scoped to the granted capabilities.
|
||||
|
||||
Bridge mode uses `--bridge` and `--control-token-file` as described in
|
||||
[development.md](development.md). Configure all roots on the desktop process; passing root flags
|
||||
to `photocraft-cli mcp --bridge` is a usage error because the bridge cannot grant them.
|
||||
UI tools require a running desktop app. The desktop environment variable
|
||||
`PHOTOCRAFT_AUTOMATION_READ_ROOT` supplies one fallback directory only when no explicit read-root
|
||||
flags are present; explicit flags replace it, preserving CLI order. Similarly, one explicit
|
||||
write-root flag overrides `PHOTOCRAFT_AUTOMATION_WRITE_ROOT`. These variables do not grant
|
||||
headless CLI file access.
|
||||
|
||||
A client has the full rights of the roots it is given: it can read any file below the read
|
||||
root, and `doc_save`, `doc_export` and the export tools can create files anywhere below the
|
||||
|
||||
Reference in new issue
Block a user