Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

security: constrain automation filesystem access (#72)

Gh0stly5716c2f6f1e3
diff --git a/Cargo.lock b/Cargo.lock
index 0b83026cd..7badb851b 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -167,6 +167,12 @@ version = "0.2.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"
+[[package]]
+name = "ambient-authority"
+version = "0.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e9d4ee0d472d1cd2e28c97dfa124b3d8d992e10eb0a035f33f5d12e3a177ba3b"
+
[[package]]
name = "android-activity"
version = "0.6.1"
@@ -717,6 +723,36 @@ dependencies = [
"wayland-client",
]
+[[package]]
+name = "cap-primitives"
+version = "4.0.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8b5f74729fd2f44701d1a8eb47e906cdb3ccd9ec0f02baad85a744b791940b18"
+dependencies = [
+ "ambient-authority",
+ "fs-set-times",
+ "io-extras",
+ "io-lifetimes 3.0.1",
+ "ipnet",
+ "maybe-owned",
+ "rustix 1.1.5",
+ "rustix-linux-procfs",
+ "windows-sys 0.61.2",
+ "winx",
+]
+
+[[package]]
+name = "cap-std"
+version = "4.0.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c1ec78e242cfa2cfe276807ac2ecc00315a6c97786977414bcd1c3963b6c91b8"
+dependencies = [
+ "cap-primitives",
+ "io-extras",
+ "io-lifetimes 3.0.1",
+ "rustix 1.1.5",
+]
+
[[package]]
name = "cast"
version = "0.3.0"
@@ -1616,6 +1652,17 @@ version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b"
+[[package]]
+name = "fs-set-times"
+version = "0.20.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "94e7099f6313ecacbe1256e8ff9d617b75d1bcb16a6fddef94866d225a01a14a"
+dependencies = [
+ "io-lifetimes 2.0.4",
+ "rustix 1.1.5",
+ "windows-sys 0.59.0",
+]
+
[[package]]
name = "futures"
version = "0.3.34"
@@ -2186,6 +2233,34 @@ dependencies = [
"syn 2.0.119",
]
+[[package]]
+name = "io-extras"
+version = "0.19.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "20fd6de4ccfcc187e38bc21cfa543cb5a302cb86a8b114eb7f0bf0dc9f8ac00f"
+dependencies = [
+ "io-lifetimes 3.0.1",
+ "windows-sys 0.60.2",
+]
+
+[[package]]
+name = "io-lifetimes"
+version = "2.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "06432fb54d3be7964ecd3649233cddf80db2832f47fec34c01f65b3d9d774983"
+
+[[package]]
+name = "io-lifetimes"
+version = "3.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2f0fb0570afe1fed943c5c3d4102d5358592d8625fda6a0007fdbe65a92fba96"
+
+[[package]]
+name = "ipnet"
+version = "2.12.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0"
+
[[package]]
name = "is-docker"
version = "0.2.0"
@@ -2500,6 +2575,12 @@ dependencies = [
"imgref",
]
+[[package]]
+name = "maybe-owned"
+version = "0.3.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4facc753ae494aeb6e3c22f839b158aebd4f9270f55cd3c79906c45476c47ab4"
+
[[package]]
name = "maybe-rayon"
version = "0.1.1"
@@ -3308,6 +3389,7 @@ name = "photocraft-automation"
version = "0.1.1"
dependencies = [
"base64",
+ "cap-std",
"getrandom 0.3.4",
"photocraft-codecs",
"photocraft-compose",
@@ -3415,6 +3497,7 @@ dependencies = [
"photocraft-ops",
"photocraft-paint",
"photocraft-plugins",
+ "photocraft-psd",
"photocraft-raster",
"photocraft-raw",
"photocraft-text",
@@ -3579,6 +3662,7 @@ dependencies = [
name = "photocraft-ui-egui"
version = "0.1.1"
dependencies = [
+ "base64",
"eframe",
"egui",
"egui_extras",
@@ -4303,6 +4387,16 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "rustix-linux-procfs"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2fc84bf7e9aa16c4f2c758f27412dc9841341e16aa682d9c7ac308fe3ee12056"
+dependencies = [
+ "once_cell",
+ "rustix 1.1.5",
+]
+
[[package]]
name = "rustversion"
version = "1.0.23"
@@ -6011,6 +6105,16 @@ dependencies = [
"version_check",
]
+[[package]]
+name = "winx"
+version = "0.36.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3f3fd376f71958b862e7afb20cfe5a22830e1963462f3a17f49d82a6c1d1f42d"
+dependencies = [
+ "bitflags 2.13.2",
+ "windows-sys 0.59.0",
+]
+
[[package]]
name = "wit-bindgen"
version = "0.57.1"
diff --git a/apps/photocraft-cli/src/lib.rs b/apps/photocraft-cli/src/lib.rs
index f2bba008b..7def236d5 100644
--- a/apps/photocraft-cli/src/lib.rs
+++ b/apps/photocraft-cli/src/lib.rs
@@ -6,7 +6,7 @@
use std::io::Write;
use std::path::{Path, PathBuf};
-use photocraft_automation::{Headless, PhotocraftMcp, files, security};
+use photocraft_automation::{AuthorizedWorkspace, Headless, PhotocraftMcp, files, security};
use photocraft_io::ExportOptions;
use serde_json::{Value, json};
@@ -28,8 +28,10 @@ USAGE:
photocraft-cli commands [--json] [--filter <text>]
List the engine command registry.
photocraft-cli mcp [--bridge <127.0.0.1:port>] [--control-token <64-hex> | --control-token-file <path>]
+ [--automation-read-root <dir>] [--automation-write-root <dir>]
Run the MCP server on stdio (headless engine, or bridge to a running `photocraft --control <port>`).
photocraft-cli serve [--port <port>] [--control-token <64-hex> | --control-token-file <path>]
+ [--automation-read-root <dir>] [--automation-write-root <dir>]
Keep one headless session open and answer JSON lines ({\"id\",\"method\",\"params\"}) on stdio,
or on 127.0.0.1:<port>. Methods: engine.execute, engine.commands, doc.open/new/save/inspect/render/
select/close, session.list, batch, methods (docs/control-protocol.md#headless-server).
@@ -54,6 +56,8 @@ const VALUE_FLAGS: &[&str] = &[
"--port",
"--control-token",
"--control-token-file",
+ "--automation-read-root",
+ "--automation-write-root",
];
fn parse(args: &[String]) -> Result<Args, String> {
@@ -147,6 +151,11 @@ fn warn_all(err: &mut dyn Write, ws: &[String]) {
}
}
+fn automation_workspace(args: &Args) -> Result<AuthorizedWorkspace, String> {
+ AuthorizedWorkspace::new(args.get("--automation-read-root").map(Path::new), args.get("--automation-write-root").map(Path::new))
+ .map_err(|error| error.to_string())
+}
+
fn convert(a: &Args, _out: &mut dyn Write, err: &mut dyn Write) -> R {
let [input, output] = a.positional.as_slice() else {
return Err("convert needs <in> <out>".into());
@@ -167,7 +176,7 @@ fn info(a: &Args, out: &mut dyn Write) -> R {
let [file] = a.positional.as_slice() else {
return Err("info needs <file>".into());
};
- let mut h = Headless::new();
+ let mut h = Headless::trusted_local();
let opened = h.open(Path::new(file)).map_err(|e| e.to_string())?;
let mut doc = h.inspect(None).map_err(|e| e.to_string())?;
doc["warnings"] = opened["warnings"].clone();
@@ -198,7 +207,7 @@ fn command_list(a: &Args) -> Result<Vec<(String, Value)>, String> {
}
fn run_cmds(a: &Args, out: &mut dyn Write, err: &mut dyn Write) -> R {
- let mut h = Headless::new();
+ let mut h = Headless::trusted_local();
match (a.positional.as_slice(), a.get("--new")) {
([file], None) => {
let o = h.open(Path::new(file)).map_err(|e| e.to_string())?;
@@ -267,7 +276,7 @@ fn batch(a: &Args, out: &mut dyn Write, err: &mut dyn Write) -> R {
let stem = input.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default();
let target = out_dir.join(format!("{stem}.{ext}"));
let r = (|| -> Result<Vec<String>, String> {
- let mut h = Headless::new();
+ let mut h = Headless::trusted_local();
h.open(input).map_err(|e| e.to_string())?;
for (id, p) in &actions {
h.command_run(id, p.clone()).map_err(|e| format!("`{id}`: {e}"))?;
@@ -337,7 +346,7 @@ fn commands(a: &Args, out: &mut dyn Write) -> R {
fn serve(a: &Args, err: &mut dyn Write) -> R {
use std::sync::{Arc, Mutex};
- let h = Arc::new(Mutex::new(Headless::new()));
+ let h = Arc::new(Mutex::new(Headless::with_workspace(automation_workspace(a)?)));
match a.get("--port") {
Some(port) => {
let port: u16 = port.parse().map_err(|_| format!("bad --port `{port}`"))?;
@@ -368,7 +377,7 @@ fn mcp(a: &Args) -> R {
let token = security::client_token(supplied.as_deref(), token_file.as_deref()).map_err(|e| e.to_string())?;
PhotocraftMcp::bridge(addr, &token).map_err(|e| e.to_string())?
}
- None => PhotocraftMcp::headless(),
+ None => PhotocraftMcp::headless_with_workspace(automation_workspace(a)?),
};
let rt = tokio::runtime::Builder::new_multi_thread().enable_all().build().map_err(|e| e.to_string())?;
rt.block_on(server.serve_stdio()).map_err(|e| e.to_string())
diff --git a/apps/photocraft/src/main.rs b/apps/photocraft/src/main.rs
index ad9761ebe..56460ab84 100644
--- a/apps/photocraft/src/main.rs
+++ b/apps/photocraft/src/main.rs
@@ -1,7 +1,8 @@
//! Photocraft desktop app.
//!
//! Usage: `photocraft [--control <port>] [--control-token <64-hex> |
-//! --control-token-file <path>] [files…]`
+//! --control-token-file <path>] [--automation-read-root <dir>]
+//! [--automation-write-root <dir>] [files…]`
//!
//! `--control <port>` (or `PHOTOCRAFT_CONTROL_PORT`) starts a localhost JSON-lines control server.
//! The first line must authenticate; subsequent request lines get reply lines.
@@ -40,6 +41,8 @@ fn main() -> eframe::Result {
let mut control_port: Option<u16> = std::env::var("PHOTOCRAFT_CONTROL_PORT").ok().and_then(|p| p.parse().ok());
let mut control_token = None;
let mut control_token_file = None;
+ let mut automation_read_root = std::env::var_os("PHOTOCRAFT_AUTOMATION_READ_ROOT").map(std::path::PathBuf::from);
+ let mut automation_write_root = std::env::var_os("PHOTOCRAFT_AUTOMATION_WRITE_ROOT").map(std::path::PathBuf::from);
let mut files = Vec::new();
let mut args = std::env::args().skip(1);
while let Some(a) = args.next() {
@@ -47,6 +50,8 @@ fn main() -> eframe::Result {
"--control" => control_port = args.next().and_then(|p| p.parse().ok()),
"--control-token" => control_token = args.next(),
"--control-token-file" => control_token_file = args.next().map(std::path::PathBuf::from),
+ "--automation-read-root" => automation_read_root = args.next().map(std::path::PathBuf::from),
+ "--automation-write-root" => automation_write_root = args.next().map(std::path::PathBuf::from),
"--version" => {
println!("photocraft {}", photocraft_engine::build_info::long_version());
return Ok(());
@@ -73,7 +78,14 @@ fn main() -> eframe::Result {
} else {
eprintln!("photocraft: using supplied control token");
}
- Some((port, token))
+ let workspace = match photocraft_automation::AuthorizedWorkspace::new(automation_read_root.as_deref(), automation_write_root.as_deref()) {
+ Ok(workspace) => workspace,
+ Err(error) => {
+ eprintln!("photocraft: cannot configure automation workspace: {error}");
+ return Ok(());
+ }
+ };
+ Some((port, token, workspace))
} else {
None
};
@@ -103,7 +115,8 @@ fn main() -> eframe::Result {
"Photocraft",
options,
Box::new(move |cc| {
- let mut app = PhotocraftApp::new(Session::new(), services::native());
+ let automation = control.as_ref().map(|(_, _, workspace)| workspace.clone());
+ let mut app = PhotocraftApp::new(Session::new(), services::native(automation));
app.integrated_titlebar = cfg!(target_os = "macos");
if let Ok(Some(icc)) = monitor.recv_timeout(std::time::Duration::from_secs(2)) {
app.session.color.monitor_profile = Some(std::sync::Arc::new(icc));
@@ -115,7 +128,7 @@ fn main() -> eframe::Result {
{
app.set_wgpu(rs);
}
- if let Some((port, token)) = control {
+ if let Some((port, token, _)) = control {
let rx = control_server::start(port, token, cc.egui_ctx.clone());
app = app.with_control(rx);
}
diff --git a/apps/photocraft/src/services.rs b/apps/photocraft/src/services.rs
index 9722a2c58..9157f1ddb 100644
--- a/apps/photocraft/src/services.rs
+++ b/apps/photocraft/src/services.rs
@@ -71,9 +71,24 @@ fn write_atomic(path: &Path, bytes: &[u8]) -> Result<(), String> {
std::fs::rename(&tmp, path).map_err(|e| e.to_string())
}
-pub fn native() -> Services {
+pub fn native(automation: Option<photocraft_automation::AuthorizedWorkspace>) -> Services {
let savers: Rc<RefCell<HashMap<u64, Autosaver>>> = Rc::default();
let savers2 = savers.clone();
+ let automation_read = automation.clone().map(|workspace| {
+ Box::new(move |path: &str| {
+ let bytes = workspace.read(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))
+ }) as photocraft_ui_egui::AutomationReadFn
+ });
+ let automation_write = automation.clone().map(|workspace| {
+ Box::new(move |path: &str, bytes: &[u8]| workspace.write(path, bytes).map_err(|error| error.to_string())) as photocraft_ui_egui::AutomationWriteFn
+ });
+ let automation_command = automation.map(|_| {
+ Box::new(|id: &str, params: &serde_json::Value| {
+ photocraft_automation::workspace::authorize_desktop_engine_command(id, params).map_err(|error| error.to_string())
+ }) as photocraft_ui_egui::AutomationCommandFn
+ });
Services {
import: Some(Box::new(|name: &str, bytes: &[u8]| {
crate::crash_guard::guard("Open", || photocraft_io::import(name, bytes).map(|r| (r.document, r.warnings)).map_err(|e| e.to_string()))
@@ -102,6 +117,9 @@ pub fn native() -> Services {
Some(d.save_file()?.to_string_lossy().to_string())
})),
write: Some(Box::new(|path: &str, bytes: &[u8]| std::fs::write(path, bytes).map_err(|e| e.to_string()))),
+ automation_read,
+ automation_write,
+ automation_command,
encode_png: Some(Box::new(|w, h, rgba| {
let img = Image::from_u8(w, h, ChannelLayout::Rgba, rgba.to_vec()).map_err(|e| e.to_string())?;
photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &EncodeOptions::default()).map_err(|e| e.to_string())
diff --git a/book/src/architecture/automation.md b/book/src/architecture/automation.md
index 2122a79a4..cbdd207ac 100644
--- a/book/src/architecture/automation.md
+++ b/book/src/architecture/automation.md
@@ -16,4 +16,11 @@ Headless file operations are implemented in `crates/automation/src/files.rs`; RP
The control and headless TCP listeners are restricted to loopback addresses. Stdio MCP avoids a listening network socket, but the MCP process still acts with the filesystem permissions of the user who launched it.
-Loopback is not authentication. TCP transports now require a bearer token and enforce request-byte, batch-step, and active-connection limits, but they do not implement capability scopes, allowed filesystem roots, client identity, encryption, or operation budgets. See the [Automation security model](../automation/security-model.md) and [Automation security](../security/automation-security.md) before exposing or extending these surfaces.
+Loopback is not authentication. TCP transports require a bearer token and enforce request-byte,
+batch-step, and active-connection limits. Remote file methods use an `AuthorizedWorkspace` with
+independent read and write directory capabilities; paths are relative to a configured root and
+fail closed when the applicable root is absent. General per-method scopes, client identity,
+encryption, and operation budgets are not implemented. See the
+[Automation security model](../automation/security-model.md) and
+[Automation security](../security/automation-security.md) before exposing or extending these
+surfaces.
diff --git a/book/src/automation/control-protocol.md b/book/src/automation/control-protocol.md
index c74c124d8..84baef48e 100644
--- a/book/src/automation/control-protocol.md
+++ b/book/src/automation/control-protocol.md
@@ -17,8 +17,18 @@ Implementation is split across:
## Current security posture
-**Implemented:** the desktop server binds to IPv4 loopback; every TCP connection authenticates before dispatch; the bridge accepts only loopback-style addresses and authenticates on connection; encoded request lines are limited to 1 MiB; active connections are limited to 16; socket I/O and handler waits use timeouts; MCP and headless batches are limited to 256 steps.
-
-**Known limitations:** the token is a bearer credential and grants the complete exposed control surface. There is no encryption, client identity, per-method capability check, allowed filesystem root, JSON-depth limit, or operation/resource budget. The listener creates one thread per authenticated active connection, within the connection cap.
+**Implemented:** the desktop server binds to IPv4 loopback; every TCP connection authenticates
+before dispatch; the bridge accepts only loopback-style addresses and authenticates on
+connection; encoded request lines are limited to 1 MiB; active connections are limited to 16;
+socket I/O and handler waits use timeouts; MCP and headless batches are limited to 256 steps.
+Automation file methods require separately configured read and write roots. Request paths are
+relative, and absolute, traversal, alternate-separator, device-name, and link-escape paths are
+rejected before file effects.
+
+**Known limitations:** the token is a bearer credential and grants the complete non-filesystem
+control surface. There is no encryption, client identity, general per-method capability check,
+JSON-depth limit, or operation/resource budget. The listener creates one thread per authenticated
+active connection, within the connection cap. Trusted one-shot CLI operations and interactive
+desktop file pickers retain the launching user's normal filesystem authority.
Use a private token file, enable `--control` only for a trusted local automation session, and never proxy the unencrypted protocol beyond loopback. See [Automation security](../security/automation-security.md) for the remaining gateway work.
diff --git a/book/src/automation/mcp.md b/book/src/automation/mcp.md
index 580254c6b..830208fc3 100644
--- a/book/src/automation/mcp.md
+++ b/book/src/automation/mcp.md
@@ -8,7 +8,7 @@
Start the headless server with:
```sh
-photocraft-cli mcp
+photocraft-cli mcp --automation-read-root /work/project --automation-write-root /work/project
```
Bridge to a running desktop application with the same private token file used by the app:
@@ -21,8 +21,12 @@ Tools cover session/document operations, command discovery and execution, batchi
## Security notes
-Stdio MCP does not open a network listener. Its client can still invoke file operations and engine commands using the MCP process's operating-system permissions. Bridge mode authenticates its loopback control connection with a bearer token before invoking any control method.
+Stdio MCP does not open a network listener. Its client receives only the read and write roots
+explicitly granted at launch; omitting a root omits that authority. Bridge mode authenticates its
+loopback control connection with a bearer token before invoking any control method and uses the
+roots configured on the desktop process.
The current server does not issue scoped sessions or distinguish trusted tools from high-impact tools. Authentication proves possession of the token; it does not restrict an authenticated client to document-only access. Do not expose either transport through an untrusted broker, shell, proxy, or remote service without adding an external policy boundary.
-Capability-scoped MCP access is [proposed](../security/automation-security.md), not implemented.
+Filesystem capabilities are implemented. General tool and method capabilities remain
+[proposed](../security/automation-security.md).
diff --git a/book/src/automation/security-model.md b/book/src/automation/security-model.md
index 6e8b94dcf..2d0f181c0 100644
--- a/book/src/automation/security-model.md
+++ b/book/src/automation/security-model.md
@@ -8,15 +8,15 @@ Automation requests are untrusted input with potential effects beyond the active
| Stdio transport | **Implemented** for MCP and headless JSON lines |
| Command-level error handling | **Implemented**, with command-specific tests and `panic_hunt` coverage |
| Control-channel authentication | **Implemented:** 256-bit bearer token required before TCP method dispatch |
-| MCP capability scopes | **Known limitation:** absent |
-| Allowed read/write roots | **Known limitation:** absent |
-| Symlink-safe capability filesystem | **Known limitation:** absent |
+| MCP capability scopes | **Partial:** filesystem read/write capabilities only; general tool scopes are absent |
+| Allowed read/write roots | **Implemented:** separate launch-time roots, with absent authority failing closed |
+| Symlink-safe capability filesystem | **Implemented:** relative operations use held directory capabilities and reject link escapes |
| Request-byte and JSON-depth limits | **Partial:** 1 MiB request-line limit; no explicit JSON-depth policy |
| Batch-step limit | **Implemented:** 256 steps for headless and MCP batches |
| Connection/worker limit | **Implemented:** 16 active TCP connections; one worker thread per accepted active connection |
| Security audit events | **Proposed** |
-## Proposed gateway
+## Gateway status and remaining work
```text
MCP or control client
@@ -24,8 +24,8 @@ MCP or control client
authenticated session
v
security gateway
- - capabilities
- - path handles/roots
+ - general method capabilities (proposed)
+ - path handles/read-write roots (implemented)
- request budgets
- command policy
- audit events
@@ -34,4 +34,7 @@ MCP or control client
command engine / UI shell
```
-The current token proves possession of a secret but does not limit what that client can do. The remaining design combines the authenticated transport with explicit capabilities, filesystem handles, resource budgets, and command policy. Until those controls land, private token handling, process isolation, and least-privileged execution are practical containment mechanisms.
+The current token proves possession of a secret but does not provide general method authorization.
+Filesystem handles and a defensive command-path policy are implemented; explicit non-filesystem
+capabilities, broader resource budgets, and audit events remain. Private token handling, process
+isolation, and least-privileged execution are still practical containment measures.
diff --git a/book/src/security/automation-security.md b/book/src/security/automation-security.md
index b3a8d2947..3fbfb9598 100644
--- a/book/src/security/automation-security.md
+++ b/book/src/security/automation-security.md
@@ -11,11 +11,18 @@ Automation is a privilege boundary because requests can cause filesystem access,
- MCP normally uses stdio and can optionally bridge to loopback control TCP.
- The bridge and UI request paths use timeouts.
- Engine commands are expected to reject invalid parameters without panicking.
+- Remote filesystem methods use separately granted read and write directory capabilities.
+- Automation paths must be relative beneath the applicable root. Absolute paths, parent
+ traversal, alternate separators, Windows device names, malformed components, and link escapes
+ are rejected before file effects.
+- Engine commands that still use ambient paths fail closed at the automation boundary. Synthetic
+ UI input reaches the same command policy, and automation-triggered file hooks do not run
+ user-configured script-event paths.
## Known limitations
- no per-client or per-tool capabilities;
-- no filesystem read/write root restriction;
+- no general per-client or per-tool capability model beyond filesystem read/write authority;
- no explicit JSON-depth, response-size, render, document-memory, or command-duration budget;
- one thread per accepted TCP connection;
- no structured security audit event stream;
@@ -25,15 +32,15 @@ Automation is a privilege boundary because requests can cause filesystem access,
The transport now establishes an authenticated connection from a cryptographically random credential before method discovery. A future security gateway should turn that authenticated connection into a short-lived, capability-scoped session.
-Capabilities should be explicit and composable, for example:
+Remaining capabilities should be explicit and composable, for example:
```text
DocumentRead
DocumentWrite
UiInspect
UiControl
-FilesystemRead
-FilesystemWrite
+FilesystemRead (implemented as a root capability)
+FilesystemWrite (implemented as a separate root capability)
PreferencesWrite
ApplicationControl
```
@@ -55,4 +62,7 @@ Limits should fail with stable errors, be applied before expensive work, and be
## Deployment guidance today
-Prefer stdio, start control TCP only when needed, use a private token file, keep the listener on loopback, use a least-privileged OS account, and isolate untrusted agents from sensitive files. Do not commit or log bearer tokens. Do not tunnel or proxy the unencrypted loopback protocol to another host.
+Prefer stdio, start control TCP only when needed, grant the narrowest read and write roots, use a
+private token file, keep the listener on loopback, use a least-privileged OS account, and isolate
+untrusted agents from sensitive files. Do not commit or log bearer tokens. Do not tunnel or proxy
+the unencrypted loopback protocol to another host.
diff --git a/book/src/security/secure-file-handling.md b/book/src/security/secure-file-handling.md
index b3f6b4ed1..36d81497c 100644
--- a/book/src/security/secure-file-handling.md
+++ b/book/src/security/secure-file-handling.md
@@ -1,6 +1,7 @@
# Secure file handling
-PhotoCraft reads and writes documents in the desktop app, CLI, headless RPC server, and MCP server. Current automation accepts caller-supplied strings and converts them directly to `PathBuf`; render-to-file uses `std::fs::write`, and shared save code may create parent directories.
+PhotoCraft reads and writes documents in the desktop app, CLI, headless RPC server, and MCP server.
+Remote automation paths are untrusted relative names resolved beneath explicitly granted roots.
## Implemented
@@ -8,18 +9,26 @@ PhotoCraft reads and writes documents in the desktop app, CLI, headless RPC serv
- `.pcraft` ZIP loading validates archive offsets, entry sizes, CRCs, content hashes, and configured decompressed-size budgets.
- Raster and PSD loaders apply parser/decode limits before major pixel allocation.
- Native `.pcraft` saves use temporary-file/rename patterns in relevant store paths.
-
-These are file-content protections, not path authorization.
+- `AuthorizedWorkspace` holds independent read and write directory capabilities for remote
+ automation.
+- Absolute paths, parent traversal, alternate separators, drive/device/stream prefixes, reserved
+ Windows device names, empty or dot components, and link escapes are rejected before file
+ effects.
+- Non-existent output files are supported when their parent already exists beneath the write
+ root. Automation does not create caller-selected directory trees.
+- Filesystem-bearing engine commands that have not migrated to capability I/O fail closed for
+ automation. Trusted local CLI subcommands and user-driven desktop file pickers keep their
+ intended ambient authority.
## Known limitations
-- Automation has no configured read or write root.
-- Absolute paths and parent traversal are not rejected by a central policy.
-- Canonicalization and symlink/junction handling are not enforced as an authorization boundary.
- Directory `.pcraft` bundles have not been documented as resistant to link replacement or time-of-check/time-of-use races.
-- The same automation session can combine document access and general filesystem effects.
+- Root grants are process launch configuration, not per-document grants.
+- General method capabilities and structured filesystem audit events are not implemented.
+- Existing hard links inside a granted root are trusted root contents; the path policy cannot
+ infer how they were created.
-## Proposed capability-based design
+## Capability-based design
Prefer an opened directory capability or workspace handle over repeated string sanitization:
@@ -30,7 +39,10 @@ AuthorizedWorkspace
- export_render(relative_path)
```
-The handle should be created from an explicit user grant, preserve separate read/write permissions, reject absolute and escaping paths, define link behavior, and perform operations relative to the held directory capability. New files require a parent-directory handle because a non-existent target cannot be canonicalized safely.
+The handle is created from an explicit launch-time grant, preserves separate read/write
+permissions, rejects absolute and escaping paths, and performs operations relative to the held
+directory capability. New files require an existing in-root parent because a non-existent target
+cannot be canonicalized safely.
## Design requirements
@@ -41,4 +53,5 @@ The handle should be created from an explicit user grant, preserve separate read
- Logs should avoid file contents and should minimize disclosure of full private paths.
- Tests should cover `..`, absolute paths, mixed separators, case behavior, symlinks/junctions, non-existent targets, and replacement races on supported platforms.
-Until this design is implemented, run untrusted automation inside an OS account, VM, container, or sandbox whose filesystem access already matches the intended workspace.
+OS-account, VM, container, or sandbox isolation remains appropriate defense in depth for
+untrusted automation and for controls not yet covered by general method capabilities.
diff --git a/book/src/security/trust-boundaries.md b/book/src/security/trust-boundaries.md
index 1139aea1a..0d6d5cdfe 100644
--- a/book/src/security/trust-boundaries.md
+++ b/book/src/security/trust-boundaries.md
@@ -40,7 +40,8 @@ TRUSTED INTERNAL STATE
| Path to filesystem effect | `crates/automation/src/files.rs`, app services | authorized root/handle, link policy, create/replace semantics |
| Document to GPU work | `crates/gpu`, UI planner | texture limits, buffer sizes, supported-plan validation |
-The filesystem and automation rows describe where policy belongs; the workspace-root, symlink, authentication, and capability controls are not yet implemented.
+Authentication and filesystem read/write capabilities are implemented at these boundaries.
+General method capabilities, structured audit events, and broader operation budgets remain open.
## Agent guidance
diff --git a/crates/automation/Cargo.toml b/crates/automation/Cargo.toml
index d6b9c0ed7..0738140a4 100644
--- a/crates/automation/Cargo.toml
+++ b/crates/automation/Cargo.toml
@@ -25,6 +25,7 @@ tokio = { version = "1", features = ["rt-multi-thread", "macros", "io-std", "syn
base64 = "0.22"
schemars = "1"
getrandom = { workspace = true }
+cap-std = "4"
[dev-dependencies]
rmcp = { version = "3.5", default-features = false, features = ["client", "server", "macros", "transport-io"] }
diff --git a/crates/automation/src/files.rs b/crates/automation/src/files.rs
index 979c616cd..424da5ccd 100644
--- a/crates/automation/src/files.rs
+++ b/crates/automation/src/files.rs
@@ -15,6 +15,15 @@ pub struct Opened {
pub warnings: Vec<String>,
}
+/// Decode a document that was read through a filesystem capability.
+pub fn open_bytes(name: &str, bytes: &[u8]) -> Result<Opened, AutomationError> {
+ if Path::new(name).extension().is_some_and(|extension| extension.eq_ignore_ascii_case(photocraft_format::EXTENSION)) {
+ return Ok(Opened { document: photocraft_format::load_from_bytes(bytes)?, warnings: Vec::new() });
+ }
+ let r = photocraft_io::import(name, bytes)?;
+ Ok(Opened { document: r.document, warnings: r.warnings })
+}
+
/// Open a document from disk. Directory bundles and `.pcraft` ZIPs load
/// natively; everything else goes through `photocraft-io` (PSD, PNG, …).
pub fn open(path: &Path) -> Result<Opened, AutomationError> {
@@ -23,8 +32,7 @@ pub fn open(path: &Path) -> Result<Opened, AutomationError> {
}
let bytes = std::fs::read(path).map_err(|e| AutomationError::Io(format!("{}: {e}", path.display())))?;
let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
- let r = photocraft_io::import(&name, &bytes)?;
- Ok(Opened { document: r.document, warnings: r.warnings })
+ open_bytes(&name, &bytes)
}
/// Previews for a `.pcraft` bundle.
@@ -60,6 +68,20 @@ pub fn save(
Ok(r.warnings)
}
+/// Encode a document for a capability-scoped write. Unlike [`save`], this
+/// never obtains ambient filesystem authority and emits `.pcraft` as a ZIP.
+pub fn save_bytes(doc: &Document, name: &str, format_override: Option<&str>, opts: &ExportOptions) -> Result<(Vec<u8>, Vec<String>), AutomationError> {
+ let ext = format_override
+ .map(|format| format.trim_start_matches('.').to_ascii_lowercase())
+ .or_else(|| Path::new(name).extension().map(|extension| extension.to_string_lossy().to_ascii_lowercase()))
+ .ok_or_else(|| AutomationError::BadRequest(format!("cannot tell the format of `{name}`; pass a format")))?;
+ if ext == photocraft_format::EXTENSION {
+ return Ok((photocraft_format::save_to_bytes(doc, &previews(doc))?, Vec::new()));
+ }
+ let result = photocraft_io::export(doc, &ext, opts)?;
+ Ok((result.bytes, result.warnings))
+}
+
/// Flattened document as PNG, scaled to fit `max_side` (0 = full size).
pub fn render_png(doc: &Document, max_side: u32) -> Result<Vec<u8>, AutomationError> {
let side = if max_side == 0 { doc.size.width.max(doc.size.height) } else { max_side };
diff --git a/crates/automation/src/headless.rs b/crates/automation/src/headless.rs
index 4f3b01125..d73cac6cc 100644
--- a/crates/automation/src/headless.rs
+++ b/crates/automation/src/headless.rs
@@ -9,21 +9,46 @@ use photocraft_format::PcraftWriter;
use photocraft_io::ExportOptions;
use serde_json::{Value, json};
-use crate::{AutomationError, files};
+use crate::workspace::authorize_engine_command;
+use crate::{AuthorizedWorkspace, AutomationError, files};
+
+enum Filesystem {
+ Denied,
+ TrustedLocal,
+ Workspace(AuthorizedWorkspace),
+}
/// A headless editing session.
-#[derive(Default)]
pub struct Headless {
pub session: Session,
/// Incremental `.pcraft` writers per document id.
writers: HashMap<u64, PcraftWriter>,
+ filesystem: Filesystem,
+}
+
+impl Default for Headless {
+ fn default() -> Self {
+ Self { session: Session::new(), writers: HashMap::new(), filesystem: Filesystem::Denied }
+ }
}
impl Headless {
+ /// Create an automation session with no filesystem authority.
pub fn new() -> Self {
Self::default()
}
+ /// Create a session for an explicit local CLI invocation. The CLI caller,
+ /// not a remote automation client, supplies these host paths.
+ pub fn trusted_local() -> Self {
+ Self { session: Session::new(), writers: HashMap::new(), filesystem: Filesystem::TrustedLocal }
+ }
+
+ /// Create an automation session with capability-scoped file access.
+ pub fn with_workspace(workspace: AuthorizedWorkspace) -> Self {
+ Self { session: Session::new(), writers: HashMap::new(), filesystem: Filesystem::Workspace(workspace) }
+ }
+
fn doc_index(&self, index: Option<usize>) -> Result<usize, AutomationError> {
match index {
Some(i) if i < self.session.documents().len() => Ok(i),
@@ -34,8 +59,17 @@ impl Headless {
/// Open a file and make it the active document.
pub fn open(&mut self, path: &Path) -> Result<Value, AutomationError> {
- let o = files::open(path)?;
- let index = self.session.add_document(o.document, Some(path.to_string_lossy().into_owned()));
+ let requested = path.to_str().ok_or_else(|| AutomationError::BadRequest("automation paths must be valid UTF-8".into()))?;
+ let o = match &self.filesystem {
+ Filesystem::Denied => return Err(AutomationError::BadRequest("automation filesystem access is not granted: read authority is absent".into())),
+ Filesystem::TrustedLocal => files::open(path)?,
+ Filesystem::Workspace(workspace) => {
+ let bytes = workspace.read(requested)?;
+ let name = path.file_name().and_then(|name| name.to_str()).unwrap_or(requested);
+ files::open_bytes(name, &bytes)?
+ }
+ };
+ let index = self.session.add_document(o.document, Some(requested.to_string()));
let d = &self.session.documents()[index];
Ok(json!({
"index": index,
@@ -51,17 +85,30 @@ impl Headless {
/// saves to the document's own path.
pub fn save(&mut self, index: Option<usize>, path: Option<&Path>, format: Option<&str>, opts: &ExportOptions) -> Result<Value, AutomationError> {
let i = self.doc_index(index)?;
- let st = &self.session.documents()[i];
- let target: PathBuf = match (path, &st.path) {
+ let (stored_path, doc) = {
+ let state = &self.session.documents()[i];
+ (state.path.clone(), state.doc.clone())
+ };
+ let target: PathBuf = match (path, stored_path.as_deref()) {
(Some(p), _) => p.to_path_buf(),
(None, Some(p)) => PathBuf::from(p),
(None, None) => {
return Err(AutomationError::BadRequest("document has no path; pass `path`".into()));
}
};
- let doc = st.doc.clone();
- let writer = self.writers.entry(doc.id.0).or_default();
- let warnings = files::save(&doc, &target, format, opts, Some(writer))?;
+ let target_text = target.to_str().ok_or_else(|| AutomationError::BadRequest("automation paths must be valid UTF-8".into()))?;
+ let warnings = match &self.filesystem {
+ Filesystem::Denied => return Err(AutomationError::BadRequest("automation filesystem access is not granted: write authority is absent".into())),
+ Filesystem::TrustedLocal => {
+ let writer = self.writers.entry(doc.id.0).or_default();
+ files::save(&doc, &target, format, opts, Some(writer))?
+ }
+ Filesystem::Workspace(workspace) => {
+ let (bytes, warnings) = files::save_bytes(&doc, target_text, format, opts)?;
+ workspace.write(target_text, &bytes)?;
+ warnings
+ }
+ };
let is_native = format
.map(|f| f.trim_start_matches('.').eq_ignore_ascii_case("pcraft"))
.unwrap_or_else(|| target.extension().is_some_and(|e| e.eq_ignore_ascii_case("pcraft")));
@@ -75,6 +122,16 @@ impl Headless {
Ok(json!({ "path": target.to_string_lossy(), "warnings": warnings }))
}
+ /// Write rendered bytes through the configured write authority.
+ pub fn write_render(&self, path: &Path, bytes: &[u8]) -> Result<(), AutomationError> {
+ let requested = path.to_str().ok_or_else(|| AutomationError::BadRequest("automation paths must be valid UTF-8".into()))?;
+ match &self.filesystem {
+ Filesystem::Denied => Err(AutomationError::BadRequest("automation filesystem access is not granted: write authority is absent".into())),
+ Filesystem::TrustedLocal => std::fs::write(path, bytes).map_err(|error| AutomationError::Io(format!("{}: {error}", path.display()))),
+ Filesystem::Workspace(workspace) => workspace.write(requested, bytes),
+ }
+ }
+
pub fn inspect(&self, index: Option<usize>) -> Result<Value, AutomationError> {
let i = self.doc_index(index)?;
Ok(photocraft_engine::inspect::document(&self.session.documents()[i]))
@@ -121,6 +178,9 @@ impl Headless {
pub fn command_run(&mut self, id: &str, params: Value) -> Result<Value, AutomationError> {
let params = if params.is_null() { json!({}) } else { params };
+ if !matches!(&self.filesystem, Filesystem::TrustedLocal) {
+ authorize_engine_command(id, &params)?;
+ }
Ok(self.session.execute(id, params)?)
}
}
diff --git a/crates/automation/src/lib.rs b/crates/automation/src/lib.rs
index 7405c41bf..644b736d1 100644
--- a/crates/automation/src/lib.rs
+++ b/crates/automation/src/lib.rs
@@ -22,10 +22,12 @@ pub mod headless;
pub mod rpc;
pub mod security;
pub mod server;
+pub mod workspace;
pub use bridge::BridgeClient;
pub use headless::Headless;
pub use server::{Backend, PhotocraftMcp};
+pub use workspace::AuthorizedWorkspace;
#[derive(Debug, thiserror::Error)]
pub enum AutomationError {
diff --git a/crates/automation/src/rpc.rs b/crates/automation/src/rpc.rs
index e98dbd881..e1ff4924f 100644
--- a/crates/automation/src/rpc.rs
+++ b/crates/automation/src/rpc.rs
@@ -100,7 +100,7 @@ impl Headless {
let png = self.render_png(index_of(&p), max)?;
match str_of(&p, "path") {
Some(path) => {
- std::fs::write(path, &png).map_err(|e| AutomationError::Io(e.to_string()))?;
+ self.write_render(&PathBuf::from(path), &png)?;
Ok(json!({"path": path, "bytes": png.len()}))
}
None => Ok(json!({
@@ -263,7 +263,7 @@ mod tests {
use super::*;
fn session() -> Mutex<Headless> {
- Mutex::new(Headless::new())
+ Mutex::new(Headless::trusted_local())
}
#[test]
diff --git a/crates/automation/src/server.rs b/crates/automation/src/server.rs
index ea9efca1a..b10ce7883 100644
--- a/crates/automation/src/server.rs
+++ b/crates/automation/src/server.rs
@@ -16,7 +16,7 @@ use serde_json::{Value, json};
use crate::bridge::BridgeClient;
use crate::headless::Headless;
use crate::security::MAX_BATCH_STEPS;
-use crate::{AutomationError, files};
+use crate::{AuthorizedWorkspace, AutomationError, files};
/// Where tools are executed.
pub enum Backend {
@@ -45,7 +45,7 @@ pub struct DocIndex {
#[derive(Debug, Deserialize, JsonSchema)]
pub struct OpenParams {
- /// Absolute path of the file to open (.pcraft, .psd, .png, .jpg, .tif, .exr, …).
+ /// Forward-slash relative path beneath the configured automation read root.
pub path: String,
}
@@ -70,7 +70,8 @@ pub struct NewParams {
#[derive(Debug, Default, Deserialize, JsonSchema)]
pub struct SaveParams {
- /// Target path; the extension selects the format. Omit to save to the document's own path.
+ /// Forward-slash relative target beneath the configured automation write root.
+ /// The extension selects the format. Omit to save to the document's own relative path.
#[serde(default)]
pub path: Option<String>,
/// Format override as an extension (pcraft, psd, png, jpg, tif, webp, exr, …).
@@ -197,6 +198,10 @@ impl PhotocraftMcp {
Self::with_backend(Backend::Headless(Arc::new(Mutex::new(Headless::new()))))
}
+ pub fn headless_with_workspace(workspace: AuthorizedWorkspace) -> Self {
+ Self::with_backend(Backend::Headless(Arc::new(Mutex::new(Headless::with_workspace(workspace)))))
+ }
+
pub fn bridge(addr: &str, token: &str) -> Result<Self, AutomationError> {
Ok(Self::with_backend(Backend::Bridge(Arc::new(BridgeClient::new(addr, token)?))))
}
@@ -242,15 +247,17 @@ impl PhotocraftMcp {
}
async fn screenshot(&self, b: &BridgeClient, max_side: Option<u32>) -> Result<CallToolResult, McpError> {
- let path = std::env::temp_dir().join(format!("photocraft-mcp-shot-{}.png", std::process::id()));
- if let Err(e) = b.call("ui.screenshot", json!({"path": path.to_string_lossy()})).await {
- return Ok(fail(e));
- }
- let bytes = match std::fs::read(&path) {
- Ok(b) => b,
- Err(e) => return Ok(fail(format!("screenshot file: {e}"))),
+ let response = match b.call("ui.screenshot", json!({})).await {
+ Ok(response) => response,
+ Err(error) => return Ok(fail(error)),
+ };
+ let Some(encoded) = response.get("base64").and_then(Value::as_str) else {
+ return Ok(fail("app screenshot response did not contain PNG data"));
+ };
+ let bytes = match base64::engine::general_purpose::STANDARD.decode(encoded) {
+ Ok(bytes) => bytes,
+ Err(error) => return Ok(fail(format!("app screenshot data: {error}"))),
};
- let _ = std::fs::remove_file(&path);
let bytes = match max_side {
Some(m) if m > 0 => downscale_png(&bytes, m).unwrap_or(bytes),
_ => bytes,
diff --git a/crates/automation/src/workspace.rs b/crates/automation/src/workspace.rs
new file mode 100644
index 000000000..7ca2b38f2
--- /dev/null
+++ b/crates/automation/src/workspace.rs
@@ -0,0 +1,369 @@
+//! Capability-based filesystem policy for untrusted automation paths.
+
+use std::io::{Read, Write};
+use std::path::{Path, PathBuf};
+use std::sync::Arc;
+
+use cap_std::ambient_authority;
+use cap_std::fs::{Dir, OpenOptions};
+use serde_json::Value;
+
+use crate::AutomationError;
+
+const DENIED: &str = "automation filesystem access is not granted";
+
+#[derive(Clone)]
+struct RootCapability {
+ dir: Arc<Dir>,
+}
+
+/// Separate directory capabilities for automation reads and writes.
+///
+/// Root paths are trusted launch-time configuration. Request paths are always
+/// untrusted, forward-slash relative paths resolved by `cap-std` beneath the
+/// held directory handle. Absolute paths, parent traversal, alternate
+/// separators, Windows prefixes and empty components are rejected before I/O.
+#[derive(Clone, Default)]
+pub struct AuthorizedWorkspace {
+ read: Option<RootCapability>,
+ write: Option<RootCapability>,
+}
+
+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")? })
+ }
+
+ /// Read one regular file below the configured read root.
+ pub fn read(&self, path: &str) -> Result<Vec<u8>, AutomationError> {
+ let relative = relative_path(path)?;
+ 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))?;
+ 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}`")));
+ }
+ let mut bytes = Vec::new();
+ file.read_to_end(&mut bytes).map_err(|e| file_error("read", path, e))?;
+ Ok(bytes)
+ }
+
+ /// Create or replace one file below the configured write root.
+ ///
+ /// The parent directory must already exist. `cap-std` performs path
+ /// resolution and file creation relative to the held directory handle, so
+ /// a non-existent final target is supported without ambient path access.
+ pub fn write(&self, path: &str, bytes: &[u8]) -> Result<(), AutomationError> {
+ let relative = relative_path(path)?;
+ let root = self.write.as_ref().ok_or_else(|| AutomationError::BadRequest(format!("{DENIED}: write authority is absent")))?;
+ let mut options = OpenOptions::new();
+ options.write(true).create(true).truncate(true);
+ let mut file = root.dir.open_with(&relative, &options).map_err(|e| file_error("write", path, e))?;
+ file.write_all(bytes).map_err(|e| file_error("write", path, e))?;
+ file.flush().map_err(|e| file_error("write", path, e))
+ }
+}
+
+fn open_root(path: Option<&Path>, authority: &str) -> Result<Option<RootCapability>, AutomationError> {
+ let Some(path) = path else { return Ok(None) };
+ if path.as_os_str().is_empty() {
+ return Err(AutomationError::BadRequest(format!("automation {authority} root is empty")));
+ }
+ let dir = Dir::open_ambient_dir(path, ambient_authority())
+ .map_err(|e| AutomationError::Io(format!("cannot open automation {authority} root `{}`: {e}", path.display())))?;
+ Ok(Some(RootCapability { dir: Arc::new(dir) }))
+}
+
+fn relative_path(raw: &str) -> Result<PathBuf, AutomationError> {
+ if raw.is_empty() {
+ return Err(path_error(raw, "path is empty"));
+ }
+ if raw.contains('\\') {
+ return Err(path_error(raw, "alternate separators are not allowed; use `/`"));
+ }
+ if raw.starts_with('/') {
+ return Err(path_error(raw, "absolute paths are not allowed"));
+ }
+ if raw.contains(':') {
+ return Err(path_error(raw, "drive, device and stream prefixes are not allowed"));
+ }
+ for component in raw.split('/') {
+ if component.is_empty() {
+ return Err(path_error(raw, "empty path components are not allowed"));
+ }
+ if component == "." {
+ return Err(path_error(raw, "`.` path components are not allowed"));
+ }
+ if component == ".." {
+ return Err(path_error(raw, "parent traversal is not allowed"));
+ }
+ if component.ends_with(['.', ' ']) {
+ return Err(path_error(raw, "path components ending in a dot or space are not allowed"));
+ }
+ if is_windows_device_name(component) {
+ return Err(path_error(raw, "reserved device names are not allowed"));
+ }
+ }
+ Ok(PathBuf::from(raw))
+}
+
+fn is_windows_device_name(component: &str) -> bool {
+ let stem = component.split('.').next().unwrap_or(component).to_ascii_uppercase();
+ matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL" | "CLOCK$" | "CONIN$" | "CONOUT$")
+ || stem.strip_prefix("COM").is_some_and(|n| matches!(n, "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"))
+ || stem.strip_prefix("LPT").is_some_and(|n| matches!(n, "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"))
+}
+
+fn path_error(path: &str, reason: &str) -> AutomationError {
+ AutomationError::BadRequest(format!("automation path rejected: {reason}: `{path}`"))
+}
+
+fn file_error(operation: &str, path: &str, error: std::io::Error) -> AutomationError {
+ let kind = error.kind();
+ AutomationError::Io(format!("automation {operation} `{path}` failed ({kind:?}): {error}"))
+}
+
+/// Filesystem-bearing engine commands have not yet been converted to consume
+/// directory capabilities. Automation must use `doc.open`, `doc.save` and
+/// `doc.render` for file effects until those commands are migrated.
+pub fn authorize_engine_command(id: &str, params: &Value) -> Result<(), AutomationError> {
+ let safe_file_command = matches!(
+ id,
+ "file.new"
+ | "file.close"
+ | "file.closeAll"
+ | "file.closeOthers"
+ | "file.fileInfo"
+ | "file.automate.fitImage"
+ | "file.automate.conditionalModeChange"
+ | "file.scripts.flattenAllLayerEffects"
+ | "file.scripts.flattenAllMasks"
+ | "file.scripts.deleteAllEmptyLayers"
+ | "file.export.exportPreferences"
+ );
+ if id.starts_with("file.") && !safe_file_command {
+ return Err(command_error(id));
+ }
+ if (id.starts_with("layer.smartObjects.") && id != "layer.smartObjects.convertToSmartObject")
+ || matches!(
+ id,
+ "pattern.import"
+ | "pattern.export"
+ | "edit.presets.migratePresets"
+ | "measurementLog.export"
+ | "layer.videoLayers.newVideoLayerFromFile"
+ | "layer.videoLayers.replaceFootage"
+ | "layer.videoLayers.reloadFrame"
+ | "image.applyDataSet"
+ )
+ || profile_command_may_read_ambient(id, params)
+ || preferences_may_grant_ambient_paths(id, params)
+ || params_contain_ambient_path(id, params)
+ {
+ return Err(command_error(id));
+ }
+ Ok(())
+}
+
+/// Desktop sessions may already contain user-configured ambient colour-profile
+/// paths. Commands which implicitly resolve those settings are denied even
+/// when their request parameters contain no path. Fresh headless sessions
+/// cannot acquire such settings through the automation interface.
+pub fn authorize_desktop_engine_command(id: &str, params: &Value) -> Result<(), AutomationError> {
+ authorize_engine_command(id, params)?;
+ if id.starts_with("image.mode.") {
+ return Err(command_error(id));
+ }
+ Ok(())
+}
+
+fn params_contain_ambient_path(id: &str, params: &Value) -> bool {
+ let keys: &[&str] = match id {
+ "image.adjustments.colorLookup" | "layer.newAdjustmentLayer.colorLookup" | "layer.setAdjustment" => &["file"],
+ "filter.distort.displace" => &["mapPath"],
+ "layer.quickExportAsPng" | "layer.exportAs" => &["path"],
+ "edit.assignProfile" | "edit.convertToProfile" | "edit.profileInfo" | "view.proofSetup" | "view.gamutWarning" => &["profile"],
+ "edit.colorSettings" => &["workingRgb", "workingCmyk", "workingGray"],
+ _ => &[],
+ };
+ keys.iter().any(|key| {
+ params
+ .get(*key)
+ .and_then(Value::as_str)
+ .is_some_and(|value| if matches!(*key, "file" | "mapPath" | "path") { !value.is_empty() } else { looks_like_path(value) })
+ })
+}
+
+fn profile_command_may_read_ambient(id: &str, params: &Value) -> bool {
+ if matches!(id, "color.profileMismatch" | "edit.colorSettings" | "view.proofSetup") {
+ return true;
+ }
+ matches!(id, "edit.assignProfile" | "edit.convertToProfile" | "edit.profileInfo")
+ && params.get("profile").and_then(Value::as_str).is_some_and(|profile| {
+ matches!(profile, "working" | "default" | "working-cmyk" | "workingCmyk" | "working-rgb" | "workingRgb" | "working-gray" | "workingGray")
+ })
+}
+
+fn preferences_may_grant_ambient_paths(id: &str, params: &Value) -> bool {
+ if id != "prefs.set" {
+ return false;
+ }
+ let direct = params
+ .get("path")
+ .and_then(Value::as_str)
+ .is_some_and(|path| path == "colorSettings" || path.starts_with("colorSettings.") || path == "scriptEvents" || path.starts_with("scriptEvents."));
+ let batch = params.get("values").and_then(Value::as_object).is_some_and(|values| {
+ values.keys().any(|path| path == "colorSettings" || path.starts_with("colorSettings.") || path == "scriptEvents" || path.starts_with("scriptEvents."))
+ });
+ direct || batch
+}
+
+fn looks_like_path(value: &str) -> bool {
+ value.contains('/')
+ || value.contains('\\')
+ || value.contains(':')
+ || value.to_ascii_lowercase().ends_with(".icc")
+ || value.to_ascii_lowercase().ends_with(".icm")
+}
+
+fn command_error(id: &str) -> AutomationError {
+ AutomationError::BadRequest(format!("automation command `{id}` uses ambient filesystem paths and is disabled; use capability-scoped document methods"))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn roots(name: &str) -> (PathBuf, PathBuf, AuthorizedWorkspace) {
+ let base = std::env::temp_dir().join(format!("photocraft-workspace-{}-{name}", std::process::id()));
+ let inside = base.join("inside");
+ let outside = base.join("outside");
+ let _ = std::fs::remove_dir_all(&base);
+ std::fs::create_dir_all(&inside).unwrap();
+ std::fs::create_dir_all(&outside).unwrap();
+ let workspace = AuthorizedWorkspace::new(Some(&inside), Some(&inside)).unwrap();
+ (inside, outside, workspace)
+ }
+
+ #[test]
+ fn valid_read_and_nonexistent_output_write_stay_in_root() {
+ let (inside, _, workspace) = roots("valid");
+ std::fs::write(inside.join("read.txt"), b"canary").unwrap();
+ assert_eq!(workspace.read("read.txt").unwrap(), b"canary");
+ workspace.write("new-output.txt", b"created").unwrap();
+ assert_eq!(std::fs::read(inside.join("new-output.txt")).unwrap(), b"created");
+ }
+
+ #[test]
+ fn rejects_absolute_traversal_mixed_prefix_and_malformed_paths_without_panicking() {
+ let (_, _, workspace) = roots("reject");
+ for path in [
+ "",
+ "/absolute",
+ "../escape",
+ "a/../escape",
+ "a\\..\\escape",
+ "a\\b",
+ "C:/escape",
+ "a//b",
+ "./a",
+ "name:stream",
+ "NUL",
+ "con.txt",
+ "folder/COM1.log",
+ ] {
+ assert!(workspace.read(path).is_err(), "read accepted {path:?}");
+ assert!(workspace.write(path, b"x").is_err(), "write accepted {path:?}");
+ }
+ }
+
+ #[test]
+ fn read_and_write_authority_are_separate() {
+ let (inside, _, _) = roots("separate");
+ std::fs::write(inside.join("read.txt"), b"canary").unwrap();
+ let read_only = AuthorizedWorkspace::new(Some(&inside), None).unwrap();
+ assert_eq!(read_only.read("read.txt").unwrap(), b"canary");
+ assert!(read_only.write("blocked.txt", b"x").is_err());
+ let write_only = AuthorizedWorkspace::new(None, Some(&inside)).unwrap();
+ assert!(write_only.read("read.txt").is_err());
+ write_only.write("written.txt", b"ok").unwrap();
+ }
+
+ #[test]
+ fn missing_parent_is_a_stable_error_before_any_file_is_created() {
+ let (inside, _, workspace) = roots("missing-parent");
+ let error = workspace.write("missing/output.txt", b"x").unwrap_err().to_string();
+ assert!(error.contains("automation write"), "{error}");
+ assert!(!inside.join("missing").exists());
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn symlink_escape_is_rejected() {
+ use std::os::unix::fs::symlink;
+
+ let (inside, outside, workspace) = roots("symlink");
+ std::fs::write(outside.join("secret.txt"), b"outside").unwrap();
+ symlink(&outside, inside.join("link")).unwrap();
+ assert!(workspace.read("link/secret.txt").is_err());
+ assert!(workspace.write("link/new.txt", b"blocked").is_err());
+ assert!(!outside.join("new.txt").exists());
+ }
+
+ #[cfg(windows)]
+ #[test]
+ fn windows_symlink_escape_is_rejected_when_supported() {
+ use std::os::windows::fs::symlink_dir;
+
+ let (inside, outside, workspace) = roots("windows-link");
+ std::fs::write(outside.join("secret.txt"), b"outside").unwrap();
+ if symlink_dir(&outside, inside.join("link")).is_err() {
+ return;
+ }
+ assert!(workspace.read("link/secret.txt").is_err());
+ assert!(workspace.write("link/new.txt", b"blocked").is_err());
+ assert!(!outside.join("new.txt").exists());
+ }
+
+ #[cfg(windows)]
+ #[test]
+ fn windows_junction_escape_is_rejected_when_supported() {
+ use std::process::Command;
+
+ let (inside, outside, workspace) = roots("windows-junction");
+ std::fs::write(outside.join("secret.txt"), b"outside").unwrap();
+ let link = inside.join("junction");
+ let status = Command::new("cmd.exe").args(["/D", "/C", "mklink", "/J"]).arg(&link).arg(&outside).status();
+ if !status.is_ok_and(|status| status.success()) {
+ return;
+ }
+ assert!(workspace.read("junction/secret.txt").is_err());
+ assert!(workspace.write("junction/new.txt", b"blocked").is_err());
+ assert!(!outside.join("new.txt").exists());
+ let _ = std::fs::remove_dir(link);
+ }
+
+ #[test]
+ fn filesystem_commands_fail_closed() {
+ for id in [
+ "file.openAs",
+ "file.export.saveForWebLegacy",
+ "pattern.import",
+ "layer.smartObjects.exportContents",
+ "measurementLog.export",
+ "layer.videoLayers.reloadFrame",
+ "image.applyDataSet",
+ "edit.colorSettings",
+ ] {
+ assert!(authorize_engine_command(id, &serde_json::json!({})).is_err());
+ }
+ assert!(authorize_engine_command("file.new", &serde_json::json!({})).is_ok());
+ assert!(authorize_engine_command("image.mode.cmyk", &serde_json::json!({})).is_ok());
+ assert!(authorize_desktop_engine_command("image.mode.cmyk", &serde_json::json!({})).is_err());
+ assert!(authorize_engine_command("filter.distort.displace", &serde_json::json!({"mapPath": "outside.png"})).is_err());
+ assert!(authorize_engine_command("layer.setAdjustment", &serde_json::json!({"file": "outside.cube"})).is_err());
+ assert!(authorize_engine_command("prefs.set", &serde_json::json!({"path": "colorSettings.workingRgb", "value": "outside.icc"})).is_err());
+ }
+}
diff --git a/crates/automation/tests/agent_tasks.rs b/crates/automation/tests/agent_tasks.rs
index 65f2847b7..64d3b17ca 100644
--- a/crates/automation/tests/agent_tasks.rs
+++ b/crates/automation/tests/agent_tasks.rs
@@ -5,7 +5,7 @@
use std::io::Write;
-use photocraft_automation::PhotocraftMcp;
+use photocraft_automation::{AuthorizedWorkspace, PhotocraftMcp};
use rmcp::model::{CallToolRequestParams, CallToolResult, ClientConfig};
use rmcp::service::RunningService;
use rmcp::{ClientHandler, RoleClient, ServiceExt};
@@ -21,10 +21,11 @@ impl ClientHandler for Client {
type Conn = RunningService<RoleClient, Client>;
-async fn connect() -> Conn {
+async fn connect(root: &std::path::Path) -> Conn {
let (s, c) = tokio::io::duplex(1 << 20);
+ let workspace = AuthorizedWorkspace::new(Some(root), Some(root)).expect("test workspace");
tokio::spawn(async move {
- if let Ok(running) = PhotocraftMcp::headless().serve(s).await {
+ if let Ok(running) = PhotocraftMcp::headless_with_workspace(workspace).serve(s).await {
let _ = running.waiting().await;
}
});
@@ -73,7 +74,7 @@ fn tmp(name: &str) -> std::path::PathBuf {
}
/// A 64×48 RGB gradient PNG (red ramps across, green down).
-fn gradient_png(dir: &std::path::Path) -> String {
+fn gradient_png(dir: &std::path::Path) -> &'static str {
let (w, h) = (64u32, 48u32);
let mut px = Vec::with_capacity((w * h * 3) as usize);
for y in 0..h {
@@ -84,7 +85,7 @@ fn gradient_png(dir: &std::path::Path) -> String {
let img = photocraft_codecs::Image::from_u8(w, h, photocraft_codecs::ChannelLayout::Rgb, px).unwrap();
let path = dir.join("gradient.png");
std::fs::File::create(&path).unwrap().write_all(&photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &Default::default()).unwrap()).unwrap();
- path.to_string_lossy().into_owned()
+ "gradient.png"
}
fn close(a: &[f64], b: &[f64], tol: f64) -> bool {
@@ -95,7 +96,7 @@ fn close(a: &[f64], b: &[f64], tol: f64) -> bool {
async fn agent_completes_ten_scripted_tasks() {
let dir = tmp("tasks");
let png = gradient_png(&dir);
- let c = connect().await;
+ let c = connect(&dir).await;
// 1. Make a title card: type layer with a drop shadow, exported as PNG.
tool(&c, "doc_new", json!({"width": 200, "height": 120, "background": "white"})).await;
@@ -107,7 +108,7 @@ async fn agent_completes_ten_scripted_tasks() {
assert_eq!(t["text"]["text"], "Hello", "task 1: {t}");
assert_eq!(t["effects"]["items"][0]["kind"], "Drop Shadow", "task 1: {t}");
let out = dir.join("card.png");
- tool(&c, "doc_export", json!({"path": out.to_string_lossy()})).await;
+ tool(&c, "doc_export", json!({"path": "card.png"})).await;
let card = photocraft_codecs::decode(&std::fs::read(&out).unwrap()).unwrap();
assert_eq!(card.dimensions(), (200, 120), "task 1");
tool(&c, "doc_close", json!({})).await;
@@ -187,12 +188,12 @@ async fn agent_completes_ten_scripted_tasks() {
.collect();
assert_eq!(xs, [10, 10, 10], "task 7: {}", doc["layers"]);
- // 8. Export every layer to its own file.
+ // 8. Export through the capability-scoped document API.
let layers_dir = dir.join("layers");
std::fs::create_dir_all(&layers_dir).unwrap();
- run(&c, "file.export.layersToFiles", json!({"dir": layers_dir.to_string_lossy(), "format": "png", "prefix": "swatch"})).await;
+ tool(&c, "doc_export", json!({"path": "layers/swatch.png"})).await;
let n = std::fs::read_dir(&layers_dir).unwrap().filter(|e| e.as_ref().is_ok_and(|e| e.path().extension().is_some_and(|x| x == "png"))).count();
- assert_eq!(n, 4, "task 8: three swatches plus the background");
+ assert_eq!(n, 1, "task 8: capability-scoped export");
// 9. Resize, then crop to a square.
run(&c, "image.imageSize", json!({"width": 60, "height": 45})).await;
@@ -203,10 +204,9 @@ async fn agent_completes_ten_scripted_tasks() {
// 10. Prepare for print: convert to CMYK and save natively, then reopen.
run(&c, "image.mode.cmyk", json!({"intent": "perceptual"})).await;
assert_eq!(inspect(&c).await["mode"], "Cmyk", "task 10");
- let saved = dir.join("print.pcraft");
- tool(&c, "doc_save", json!({"path": saved.to_string_lossy()})).await;
+ tool(&c, "doc_save", json!({"path": "print.pcraft"})).await;
tool(&c, "doc_close", json!({})).await;
- tool(&c, "doc_open", json!({"path": saved.to_string_lossy()})).await;
+ tool(&c, "doc_open", json!({"path": "print.pcraft"})).await;
let doc = inspect(&c).await;
assert_eq!((doc["mode"].as_str(), doc["width"].as_u64()), (Some("Cmyk"), Some(45)), "task 10");
assert_eq!(doc["layers"].as_array().unwrap().len(), 4, "task 10");
diff --git a/crates/automation/tests/mcp.rs b/crates/automation/tests/mcp.rs
index d28021892..f4179badc 100644
--- a/crates/automation/tests/mcp.rs
+++ b/crates/automation/tests/mcp.rs
@@ -3,7 +3,7 @@
use std::io::Write;
use base64::Engine as _;
-use photocraft_automation::PhotocraftMcp;
+use photocraft_automation::{AuthorizedWorkspace, PhotocraftMcp};
use rmcp::model::{CallToolRequestParams, CallToolResult, ClientConfig};
use rmcp::service::RunningService;
use rmcp::{ClientHandler, RoleClient, ServiceExt};
@@ -54,6 +54,22 @@ fn tmp(name: &str) -> std::path::PathBuf {
d
}
+fn cleanup(path: &std::path::Path) {
+ for _ in 0..20 {
+ match std::fs::remove_dir_all(path) {
+ Ok(()) => return,
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return,
+ Err(_) => std::thread::sleep(std::time::Duration::from_millis(10)),
+ }
+ }
+ std::fs::remove_dir_all(path).expect("remove test workspace after server shutdown");
+}
+
+fn headless_in(root: &std::path::Path) -> PhotocraftMcp {
+ let workspace = AuthorizedWorkspace::new(Some(root), Some(root)).expect("test workspace");
+ PhotocraftMcp::headless_with_workspace(workspace)
+}
+
#[tokio::test(flavor = "multi_thread")]
async fn lists_expected_tools() {
let client = connect(PhotocraftMcp::headless()).await;
@@ -94,7 +110,7 @@ async fn lists_expected_tools() {
#[tokio::test(flavor = "multi_thread")]
async fn headless_edit_render_save_roundtrip() {
let dir = tmp("edit");
- let client = connect(PhotocraftMcp::headless()).await;
+ let client = connect(headless_in(&dir)).await;
let r = call(&client, "doc_new", json!({"width": 64, "height": 48, "background": "white", "name": "Agent"})).await;
assert_ne!(r.is_error, Some(true), "{}", text(&r));
@@ -116,18 +132,17 @@ async fn headless_edit_render_save_roundtrip() {
let decoded = photocraft_codecs::decode(&png).unwrap();
assert_eq!(decoded.dimensions(), (32, 24));
- let pc = dir.join("agent.pcraft");
- let r = json_of(&call(&client, "doc_save", json!({"path": pc.to_string_lossy()})).await);
- assert_eq!(r["path"], pc.to_string_lossy().as_ref());
+ let r = json_of(&call(&client, "doc_save", json!({"path": "agent.pcraft"})).await);
+ assert_eq!(r["path"], "agent.pcraft");
let png_path = dir.join("agent.png");
- json_of(&call(&client, "doc_export", json!({"path": png_path.to_string_lossy()})).await);
+ json_of(&call(&client, "doc_export", json!({"path": "agent.png"})).await);
let jpg_path = dir.join("agent.jpg");
- json_of(&call(&client, "doc_export", json!({"path": jpg_path.to_string_lossy(), "quality": 70})).await);
+ json_of(&call(&client, "doc_export", json!({"path": "agent.jpg", "quality": 70})).await);
assert!(photocraft_codecs::decode(&std::fs::read(&png_path).unwrap()).is_ok());
assert!(std::fs::metadata(&jpg_path).unwrap().len() > 100);
// Re-open the native file: identical layer tree.
- let o = json_of(&call(&client, "doc_open", json!({"path": pc.to_string_lossy()})).await);
+ let o = json_of(&call(&client, "doc_open", json!({"path": "agent.pcraft"})).await);
assert_eq!(o["index"], 1);
let doc2 = json_of(&call(&client, "doc_inspect", json!({"index": 1})).await);
assert_eq!(doc2["layers"].as_array().unwrap().len(), 2);
@@ -136,7 +151,7 @@ async fn headless_edit_render_save_roundtrip() {
json_of(&call(&client, "doc_close", json!({"index": 1})).await);
json_of(&call(&client, "doc_select", json!({"index": 0})).await);
client.cancel().await.unwrap();
- std::fs::remove_dir_all(dir).unwrap();
+ cleanup(&dir);
}
#[tokio::test(flavor = "multi_thread")]
@@ -180,13 +195,47 @@ async fn open_png_and_inspect() {
let img = photocraft_codecs::Image::from_u8(8, 4, photocraft_codecs::ChannelLayout::Rgb, vec![200; 96]).unwrap();
let path = dir.join("in.png");
std::fs::File::create(&path).unwrap().write_all(&photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &Default::default()).unwrap()).unwrap();
- let client = connect(PhotocraftMcp::headless()).await;
- let o = json_of(&call(&client, "doc_open", json!({"path": path.to_string_lossy()})).await);
+ let client = connect(headless_in(&dir)).await;
+ let o = json_of(&call(&client, "doc_open", json!({"path": "in.png"})).await);
assert_eq!((o["width"].as_u64(), o["height"].as_u64()), (Some(8), Some(4)));
let px = json_of(&call(&client, "command_run", json!({"id": "document.pixel", "params": {"x": 1, "y": 1}})).await);
assert!(px.to_string().contains("0.78"), "{px}");
client.cancel().await.unwrap();
- std::fs::remove_dir_all(dir).unwrap();
+ cleanup(&dir);
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn filesystem_policy_rejects_absolute_and_escaping_paths_before_effects() {
+ let base = tmp("filesystem-policy");
+ let root = base.join("workspace");
+ let outside = base.join("outside");
+ std::fs::create_dir_all(&root).unwrap();
+ std::fs::create_dir_all(&outside).unwrap();
+
+ let img = photocraft_codecs::Image::from_u8(4, 3, photocraft_codecs::ChannelLayout::Rgb, vec![42; 36]).unwrap();
+ let bytes = photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &Default::default()).unwrap();
+ std::fs::write(root.join("inside.png"), bytes).unwrap();
+ let client = connect(headless_in(&root)).await;
+
+ assert_ne!(call(&client, "doc_open", json!({"path": "inside.png"})).await.is_error, Some(true));
+ let absolute = outside.join("absolute.png");
+ let response = call(&client, "doc_save", json!({"path": absolute.to_string_lossy()})).await;
+ assert_eq!(response.is_error, Some(true));
+ assert!(text(&response).contains("automation path rejected"), "{}", text(&response));
+ assert!(!absolute.exists());
+
+ for path in ["../outside/traversal.png", "..\\outside\\mixed.png", "C:/outside/prefix.png", ""] {
+ let response = call(&client, "doc_save", json!({"path": path})).await;
+ assert_eq!(response.is_error, Some(true), "path {path:?}: {}", text(&response));
+ }
+ assert!(!outside.join("traversal.png").exists());
+ assert!(!outside.join("mixed.png").exists());
+
+ let response = call(&client, "command_run", json!({"id": "layer.smartObjects.exportContents", "params": {"path": "outside.bin"}})).await;
+ assert_eq!(response.is_error, Some(true));
+ assert!(text(&response).contains("ambient filesystem paths"), "{}", text(&response));
+ client.cancel().await.unwrap();
+ cleanup(&base);
}
// ---------------------------------------------------------------------------
@@ -224,10 +273,10 @@ async fn fake_app() -> (String, tokio::task::JoinHandle<Vec<Value>>) {
json!({"id": id, "ok": true, "result": [{"id": "file.new", "label": "New…", "enabled": true}]})
}
"ui.screenshot" => {
- let path = req["params"]["path"].as_str().unwrap().to_owned();
let img = photocraft_codecs::Image::from_u8(40, 20, photocraft_codecs::ChannelLayout::Rgba, vec![9; 3200]).unwrap();
- std::fs::write(&path, photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &Default::default()).unwrap()).unwrap();
- json!({"id": id, "ok": true, "result": {"path": path}})
+ let bytes = photocraft_codecs::encode(&img, photocraft_codecs::Format::Png, &Default::default()).unwrap();
+ let png = base64::engine::general_purpose::STANDARD.encode(bytes);
+ json!({"id": id, "ok": true, "result": {"mimeType": "image/png", "base64": png}})
}
_ => json!({"id": id, "ok": false, "error": format!("unknown tool `{method}`")}),
};
diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml
index d6b6f22ae..8a5b4f745 100644
--- a/crates/ui-egui/Cargo.toml
+++ b/crates/ui-egui/Cargo.toml
@@ -24,6 +24,7 @@ eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] }
serde = { workspace = true }
serde_json = { workspace = true }
log = { workspace = true }
+base64 = "0.22"
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
rayon = { workspace = true }
diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs
index 8ce749bbb..8c612df52 100644
--- a/crates/ui-egui/src/control.rs
+++ b/crates/ui-egui/src/control.rs
@@ -18,11 +18,12 @@
//! - `ui.screenshot {path?, focus?}`: capture the main window (PNG). Raises the window first (default)
//! because occluded macOS windows stop rendering
//! - `ui.focus`: bring the main window to the front
-//! - `app.open {path}` / `app.save {path}`: file I/O through the configured services
+//! - `app.open {path}` / `app.save {path}`: relative file I/O under the automation roots; reply with `warnings`
//! - `app.quit`
use std::sync::mpsc::Sender;
+use base64::Engine as _;
use serde_json::{Value, json};
use crate::PhotocraftApp;
@@ -76,13 +77,26 @@ pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest
"engine.execute" | "ui.menu.invoke" => {
let Some(id) = s("command").or(s("id")) else { return err("missing `command`") };
let params = p.get("params").cloned().unwrap_or(json!({}));
+ if let Some(authorize) = app.services.automation_command.as_ref()
+ && let Err(error) = authorize(id, &params)
+ {
+ return err(error);
+ }
// `engine.execute` is programmatic: engine commands run directly with their default
// params and never open a dialog (an agent would otherwise get a modal instead of a
// result). `ui.menu.invoke` behaves like a menu click, so it may open the dialog.
if req.method == "engine.execute" && photocraft_engine::commands::find(id).is_some() {
- return wrap(app.run(id, params));
+ return wrap(app.run_automation(id, params));
+ }
+ let events_enabled = app.session.prefs().script_events.enabled;
+ if events_enabled {
+ app.session.edit_prefs(|prefs| prefs.script_events.enabled = false);
}
- wrap(crate::menus::invoke(app, ctx, id, params))
+ let result = crate::menus::invoke(app, ctx, id, params);
+ if events_enabled {
+ app.session.edit_prefs(|prefs| prefs.script_events.enabled = true);
+ }
+ wrap(result)
}
"engine.commands" => wrap(app.run("command.list", json!({}))),
"ui.menu.list" => ok(serde_json::to_value(crate::menus::menu_items(app)).unwrap_or_default()),
@@ -192,7 +206,26 @@ pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest
}
}
"ui.dialog.confirm" => match u("dialog") {
- Some(id) => wrap(crate::dialogs::confirm(app, id)),
+ Some(id) => {
+ let command = app.ui.dialogs.iter().find(|dialog| dialog.id == id).and_then(|dialog| {
+ dialog.fields.get("__command").and_then(Value::as_str).map(|command| (command.to_string(), Value::Object(dialog.fields.clone())))
+ });
+ if let Some((command, params)) = command
+ && let Some(authorize) = app.services.automation_command.as_ref()
+ && let Err(error) = authorize(&command, &params)
+ {
+ return err(error);
+ }
+ let events_enabled = app.session.prefs().script_events.enabled;
+ if events_enabled {
+ app.session.edit_prefs(|prefs| prefs.script_events.enabled = false);
+ }
+ let result = crate::dialogs::confirm(app, id);
+ if events_enabled {
+ app.session.edit_prefs(|prefs| prefs.script_events.enabled = true);
+ }
+ wrap(result)
+ }
None => err("missing `dialog`"),
},
"ui.dialog.cancel" => match u("dialog").and_then(|id| app.ui.close_dialog(id)) {
@@ -316,10 +349,26 @@ pub fn handle(app: &mut PhotocraftApp, ctx: &egui::Context, req: &ControlRequest
Outcome::Screenshot { token, path: s("path").map(str::to_string) }
}
"app.open" => match s("path") {
- Some(path) => wrap(crate::menus::invoke(app, ctx, "file.open", json!({"path": path}))),
+ Some(path) => {
+ let opened = match app.services.automation_read.as_mut() {
+ Some(read) => read(path),
+ None => Err("automation read authority is not configured".into()),
+ };
+ wrap(opened.and_then(|(name, bytes)| {
+ let warnings = app.open_automation_bytes(&name, &bytes)?;
+ // Brushes/gradients go to the preset libraries: no document, no Open Recent entry.
+ if !crate::preset_files_ui::is_preset_file(&name) {
+ if let Some(state) = app.session.active_mut() {
+ state.path = Some(path.to_string());
+ }
+ app.push_recent(path);
+ }
+ Ok(json!({"path": path, "name": name, "warnings": warnings}))
+ }))
+ }
None => err("missing `path`"),
},
- "app.save" => wrap(app.save_as(s("path").map(str::to_string)).map(|(p, w)| json!({"path": p, "warnings": w}))),
+ "app.save" => wrap(app.save_automation(s("path").map(str::to_string)).map(|(p, w)| json!({"path": p, "warnings": w}))),
"app.quit" => {
app.allow_close = true;
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
@@ -358,18 +407,29 @@ pub fn inspect(app: &PhotocraftApp, ctx: &egui::Context) -> Value {
pub fn save_screenshot(app: &mut PhotocraftApp, image: &egui::ColorImage, path: Option<&str>) -> Value {
let [w, h] = image.size;
let rgba: Vec<u8> = image.pixels.iter().flat_map(|c| c.to_array()).collect();
- let Some(path) = path else {
- return json!({"ok": true, "result": {"width": w, "height": h}});
- };
let png = match app.services.encode_png.as_ref() {
Some(enc) => enc(w as u32, h as u32, &rgba),
None => Err("no PNG encoder configured".into()),
};
- let r = png.and_then(|bytes| match app.services.write.as_mut() {
- Some(wr) => wr(path, &bytes),
- None => Err("no writer configured".into()),
+ let Some(path) = path else {
+ return match png {
+ Ok(bytes) => json!({
+ "ok": true,
+ "result": {
+ "base64": base64::engine::general_purpose::STANDARD.encode(bytes),
+ "mime": "image/png",
+ "width": w,
+ "height": h,
+ }
+ }),
+ Err(error) => json!({"ok": false, "error": error}),
+ };
+ };
+ let result = png.and_then(|bytes| match app.services.automation_write.as_mut() {
+ Some(write) => write(path, &bytes),
+ None => Err("automation write authority is not configured".into()),
});
- match r {
+ match result {
Ok(()) => json!({"ok": true, "result": {"path": path, "width": w, "height": h}}),
Err(e) => json!({"ok": false, "error": e}),
}
@@ -402,4 +462,64 @@ mod tests {
assert!(r.to_string().contains("dialog"), "ui.menu.invoke should open the dialog: {r}");
assert_eq!(app.session.active().unwrap().revision, rev, "opening a dialog must not edit the document");
}
+
+ #[test]
+ fn synthetic_shortcuts_use_the_automation_command_policy() {
+ let services = crate::Services {
+ automation_command: Some(Box::new(|id, _| if id.starts_with("file.") { Err("filesystem command denied".into()) } else { Ok(()) })),
+ ..Default::default()
+ };
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services);
+ let ctx = egui::Context::default();
+ app.automation_input = true;
+ let error = crate::menus::invoke(&mut app, &ctx, "file.open", json!({})).unwrap_err();
+ assert_eq!(error, "filesystem command denied");
+ }
+
+ #[test]
+ fn automation_open_and_save_use_the_roots_and_reply_with_warnings() {
+ use photocraft_color::{ColorMode, SampleType};
+ use photocraft_doc::Document;
+ use photocraft_geom::Size;
+ use std::cell::RefCell;
+ use std::rc::Rc;
+
+ // Without granted roots both fail closed, even with an exporter and an ambient writer.
+ let services = crate::Services {
+ export: Some(Box::new(|_d: &Document, _p: &str, _s: &crate::ExportSettings| Ok((b"out".to_vec(), Vec::new())))),
+ write: Some(Box::new(|_p: &str, _b: &[u8]| Err("ambient writer used".into()))),
+ ..Default::default()
+ };
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services);
+ let ctx = egui::Context::default();
+ let r = call(&mut app, &ctx, "app.open", json!({"path": "in/warn.psd"}));
+ assert!(r.to_string().contains("automation read authority is not configured"), "{r}");
+ app.run("file.new", json!({"width": 8, "height": 8})).unwrap();
+ let r = call(&mut app, &ctx, "app.save", json!({"path": "out.png"}));
+ assert!(r.to_string().contains("automation write authority is not configured"), "{r}");
+
+ let written: Rc<RefCell<Vec<String>>> = Rc::default();
+ let w = written.clone();
+ let services = crate::Services {
+ import: Some(Box::new(|name: &str, _b: &[u8]| {
+ 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_write: Some(Box::new(move |path: &str, _b: &[u8]| {
+ w.borrow_mut().push(path.to_string());
+ Ok(())
+ })),
+ ..Default::default()
+ };
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), services);
+ let r = call(&mut app, &ctx, "app.open", json!({"path": "in/warn.psd"}));
+ assert_eq!(r["result"]["warnings"], json!(["Adjustment layer flattened"]), "{r}");
+ assert_eq!(r["result"]["name"], "warn.psd");
+ assert_eq!(app.session.active().unwrap().path.as_deref(), Some("in/warn.psd"));
+ assert_eq!(app.ui.recent_files, vec!["in/warn.psd".to_string()]);
+ let r = call(&mut app, &ctx, "app.save", json!({"path": "out.png"}));
+ assert_eq!(r["result"], json!({"path": "out.png", "warnings": ["Layers were flattened"]}), "{r}");
+ assert_eq!(*written.borrow(), vec!["out.png".to_string()]);
+ }
}
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 95adc7d11..3b7e21670 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -103,6 +103,12 @@ pub type ExportFn = Box<dyn Fn(&Document, &str, &ExportSettings) -> Result<(Vec<
pub type PickOpenFn = Box<dyn FnMut() -> Option<(String, Vec<u8>)>>;
pub type PickSaveFn = Box<dyn FnMut(&str) -> Option<String>>;
pub type WriteFn = Box<dyn FnMut(&str, &[u8]) -> Result<(), String>>;
+/// Read bytes through the desktop control session's authorized read root.
+pub type AutomationReadFn = Box<dyn FnMut(&str) -> Result<(String, Vec<u8>), String>>;
+/// Write bytes through the desktop control session's authorized write root.
+pub type AutomationWriteFn = Box<dyn FnMut(&str, &[u8]) -> Result<(), String>>;
+/// Reject engine commands which still perform ambient filesystem I/O.
+pub type AutomationCommandFn = Box<dyn Fn(&str, &Value) -> Result<(), String>>;
/// Open a URL in the system browser (native) — reliable cross-platform, unlike `ctx.open_url`.
pub type OpenUrlFn = Box<dyn Fn(&str) -> Result<(), String>>;
pub type EncodePngFn = Box<dyn Fn(u32, u32, &[u8]) -> Result<Vec<u8>, String>>;
@@ -141,6 +147,11 @@ pub struct Services {
pub pick_save: Option<PickSaveFn>,
/// Write bytes to a path (native) or trigger a download (web).
pub write: Option<WriteFn>,
+ /// File access used only by control/MCP requests. Interactive dialogs keep
+ /// using `pick_open`, `pick_save` and `write` with the user's authority.
+ pub automation_read: Option<AutomationReadFn>,
+ pub automation_write: Option<AutomationWriteFn>,
+ pub automation_command: Option<AutomationCommandFn>,
/// Encode an RGBA8 image as PNG (used for screenshots and `ui.render`).
pub encode_png: Option<EncodePngFn>,
/// Open a URL in the system browser (native). Falls back to `ctx.open_url` (web) when unset.
@@ -202,6 +213,10 @@ pub struct PhotocraftApp {
pub(crate) filter_preview: Option<filter_dialog::FilterPreview>,
/// Synthetic input events queued by automation (`ui.click`, `ui.key`, …), injected next frame.
pub(crate) synthetic: Vec<egui::Event>,
+ /// True only while a frame is processing synthetic automation input. It
+ /// makes shortcut- and dialog-triggered commands pass the same policy as
+ /// direct control calls.
+ pub(crate) automation_input: bool,
/// Levels/Curves histogram cache: (document, adjustment layer, revision it is valid for).
pub(crate) tone_hist: Option<(DocId, photocraft_doc::LayerId, u64, std::sync::Arc<tone::Histograms>)>,
/// Histogram panel cache: (document, revision, computed at ms, histograms).
@@ -276,6 +291,7 @@ impl PhotocraftApp {
outline_cache: None,
filter_preview: None,
synthetic: Vec::new(),
+ automation_input: false,
channel_thumbs: None,
channel_views: HashMap::new(),
type_layout: None,
@@ -323,6 +339,15 @@ impl PhotocraftApp {
/// Run an engine command, reporting errors in the status bar.
pub fn run(&mut self, id: &str, params: Value) -> Result<Value, String> {
+ if self.automation_input
+ && let Some(authorize) = self.services.automation_command.as_ref()
+ {
+ authorize(id, &params)?;
+ }
+ let suppress_events = self.automation_input && self.session.prefs().script_events.enabled;
+ if suppress_events {
+ self.session.edit_prefs(|prefs| prefs.script_events.enabled = false);
+ }
let t0 = gpu_canvas::now_ms();
if matches!(id, "edit.paste" | "edit.pasteSpecial.pasteInPlace") {
self.import_os_clipboard();
@@ -346,6 +371,9 @@ impl PhotocraftApp {
self.ui.status_error = true;
}
}
+ if suppress_events {
+ self.session.edit_prefs(|prefs| prefs.script_events.enabled = true);
+ }
r
}
@@ -391,6 +419,53 @@ impl PhotocraftApp {
Ok(warnings)
}
+ /// Open bytes supplied by an authenticated automation client without
+ /// invoking user-configured script-event paths outside the granted root.
+ /// Returns the import warnings (also shown to the user). Brush and gradient
+ /// files go to the preset libraries, as for interactive opens.
+ pub fn open_automation_bytes(&mut self, name: &str, bytes: &[u8]) -> Result<Vec<String>, String> {
+ let events_enabled = self.session.prefs().script_events.enabled;
+ if events_enabled {
+ self.session.edit_prefs(|prefs| prefs.script_events.enabled = false);
+ }
+ let result = match preset_files_ui::open(self, name, bytes) {
+ Some(r) => r.map(|()| Vec::new()),
+ None => self.import_automation_document(name, bytes),
+ };
+ if events_enabled {
+ self.session.edit_prefs(|prefs| prefs.script_events.enabled = true);
+ }
+ result
+ }
+
+ /// The document half of [`open_automation_bytes`](Self::open_automation_bytes): no script
+ /// events and no Color Settings policy (which may read user-configured profile paths).
+ fn import_automation_document(&mut self, name: &str, bytes: &[u8]) -> Result<Vec<String>, String> {
+ let import = self.services.import.as_ref().ok_or("no importer configured")?;
+ let (doc, warnings) = import(name, bytes)?;
+ self.session.add_document(doc, Some(name.to_string()));
+ self.sync_views();
+ self.ui.status = format!("Opened {name}");
+ self.ui.status_error = false;
+ notices::io_warnings(self, &format!("Opened {name}"), &warnings);
+ Ok(warnings)
+ }
+
+ /// Run one engine command on behalf of automation while suppressing
+ /// user-configured script-event file reads. Interactive commands retain
+ /// their normal event behavior.
+ pub fn run_automation(&mut self, id: &str, params: Value) -> Result<Value, String> {
+ let events_enabled = self.session.prefs().script_events.enabled;
+ if events_enabled {
+ self.session.edit_prefs(|prefs| prefs.script_events.enabled = false);
+ }
+ let result = self.run(id, params);
+ if events_enabled {
+ self.session.edit_prefs(|prefs| prefs.script_events.enabled = true);
+ }
+ result
+ }
+
/// File › Open: the platform dialog returns the chosen file's path (native; the web delivers
/// picks through the inbox instead).
pub fn open_dialog_file(&mut self) {
@@ -438,6 +513,27 @@ impl PhotocraftApp {
Ok((path, warnings))
}
+ /// Save through the control session's capability-scoped writer. No file
+ /// picker or ambient writer is reachable from this path. Returns the path
+ /// written and the export warnings (also shown to the user).
+ pub fn save_automation(&mut self, path: Option<String>) -> Result<(String, Vec<String>), String> {
+ let state = self.session.active().ok_or("no document")?;
+ let target = path.or_else(|| state.path.clone()).ok_or("document has no relative path; pass `path`")?;
+ let export = self.services.export.as_ref().ok_or("no exporter configured")?;
+ let (bytes, warnings) = export(&state.doc, &target, &ExportSettings::default())?;
+ let write = self.services.automation_write.as_mut().ok_or("automation write authority is not configured")?;
+ write(&target, &bytes)?;
+ if let Some(state) = self.session.active_mut() {
+ state.path = Some(target.clone());
+ state.saved_revision = state.revision;
+ }
+ self.ui.status = format!("Saved {target}");
+ self.ui.status_error = false;
+ notices::io_warnings(self, &format!("Saved {}", file_open::display_name(&target)), &warnings);
+ self.sync_views();
+ Ok((target, warnings))
+ }
+
fn drain_control(&mut self, ctx: &egui::Context) {
let Some(rx) = self.control_rx.take() else { return };
while let Ok(req) = rx.try_recv() {
@@ -564,6 +660,7 @@ impl eframe::App for PhotocraftApp {
// Fonts registered via set_fonts only take effect next frame; named families would panic now.
if !self.fonts_ready {
ctx.request_repaint();
+ self.automation_input = false;
return;
}
let t0 = gpu_canvas::now_ms();
@@ -607,6 +704,7 @@ impl eframe::App for PhotocraftApp {
wide_angle_ui::show(self, &ctx);
canvas::extra_windows(self, &ctx);
notices::show(self, &ctx);
+ self.automation_input = false;
self.perf.frame(gpu_canvas::now_ms() - t0);
// Synthetic input is injected one press/release step per frame: keep frames coming until
// the queue is empty, then release control replies waiting on it.
@@ -733,7 +831,11 @@ impl PhotocraftApp {
.iter()
.position(|e| matches!(e, egui::Event::PointerButton { pressed: false, .. } | egui::Event::Key { pressed: false, .. }))
.map_or(self.synthetic.len(), |i| i + 1);
- self.synthetic.drain(..n).collect()
+ let events: Vec<_> = self.synthetic.drain(..n).collect();
+ if !events.is_empty() {
+ self.automation_input = true;
+ }
+ events
}
/// Install fonts, image loaders and the theme. Call from the app creator when possible so the
diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs
index e16944cc2..db20638b1 100644
--- a/crates/ui-egui/src/menus.rs
+++ b/crates/ui-egui/src/menus.rs
@@ -98,6 +98,11 @@ fn workspace_name(id: &str) -> Option<&'static str> {
/// Run a command id from any source (menu, shortcut, palette, automation).
pub fn invoke(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: Value) -> Result<Value, String> {
+ if app.automation_input
+ && let Some(authorize) = app.services.automation_command.as_ref()
+ {
+ authorize(id, &params)?;
+ }
if crate::discard_ui::intercept(app, id, &params) {
return Ok(Value::Null);
}
diff --git a/docs/architecture.md b/docs/architecture.md
index 1bb88dbf1..5201b546b 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -429,6 +429,9 @@ psd/src/
- `session.list`, `doc.open`, `doc.save`, `doc.export`, `doc.inspect` (layer tree as JSON), `doc.render_preview` (PNG).
- `command.list` and `command.run(id, params)`, both generated from the registry.
- Stdio for agent CLIs, and optionally loopback TCP with a token so it can attach to a running GUI.
+ - `AuthorizedWorkspace`, which holds independent read and write directory capabilities. Remote
+ paths are validated relative names; engine commands that still require ambient filesystem
+ access fail closed at the automation boundary.
- **Actions:** recorded `Vec<CommandInvocation>`, replayable in batch (File → Automate → Batch).
- **Scripting (later):** embed a scripting language over the same registry. Options are Rhai, or Lua via mlua (C). JS via QuickJS is possible if we want Photoshop-script familiarity.
- **Plugins:** sandboxed WebAssembly filter plug-ins (`photocraft-plugins`, L4) run by `wasmi`, a pure-Rust interpreter, with fuel, memory, stack and wall-time limits and no host imports. They are driven by the `plugin.*` commands and listed under Filter › Plug-ins; the ABI is in [`plugins.md`](plugins.md). Native Photoshop `.8BF`/CEP/UXP hosting is out of scope (it needs unsafe FFI and can't run on the web). Panel plug-ins are later.
diff --git a/docs/control-protocol.md b/docs/control-protocol.md
index 8496fd605..2463fcba3 100644
--- a/docs/control-protocol.md
+++ b/docs/control-protocol.md
@@ -3,7 +3,8 @@
The desktop app listens on `127.0.0.1:<port>` (loopback only). Start it with a token file so the credential is not exposed in the process command line:
```sh
-photocraft --control 7878 --control-token-file /private/path/photocraft-control.token
+photocraft --control 7878 --control-token-file /private/path/photocraft-control.token \
+ --automation-read-root /work/project --automation-write-root /work/project
```
If the file does not exist, PhotoCraft creates it with a fresh 256-bit token. On Unix the new file is mode `0600`; on Windows, protect it with an appropriate user-only ACL. An existing file is reused. If neither a token nor token file is configured, PhotoCraft generates a token for that launch and writes it to standard error. `PHOTOCRAFT_CONTROL_TOKEN` and `PHOTOCRAFT_CONTROL_TOKEN_FILE` are the environment-variable equivalents.
@@ -42,10 +43,11 @@ The transport is `apps/photocraft/src/control_server.rs`, and the handlers are i
- `ui.key {key, command?, shift?, alt?, ctrl?}` (flags may also be grouped under `modifiers`): press and release a key, e.g. `{"key": "ArrowLeft", "shift": true}`
- `ui.type {text}`: type text (goes to the focused widget, or to the canvas while the Type tool is editing)
- `ui.resize {width, height}`: resize the main window
-- `ui.screenshot {path?, focus?}`: capture the main window (PNG). Raises the window first (default)
- because occluded macOS windows stop rendering
+- `ui.screenshot {path?, focus?}`: capture the main window (PNG). With no path the reply contains
+ base64 PNG data; a path is relative to the automation write root. Raises the window first
+ (default) because occluded macOS windows stop rendering
- `ui.focus`: bring the main window to the front
-- `app.open {path}` / `app.save {path}`: file I/O through the configured services. Both reply with `warnings` (import/export notes such as "adjustment layer flattened"; `[]` when none), also shown to the user in the status bar and as a notice (`notices` in `ui.inspect`); `app.save` also returns the `path` written. `file.open`, `file.save`, `file.saveAs` and `file.saveACopy` reply the same way
+- `app.open {path}` / `app.save {path}`: relative file I/O through the configured automation roots (`app.open` reads under the read root, `app.save` writes under the write root; absolute paths, `..` and paths escaping the root are refused, and both fail closed when no root was granted). Both reply with `warnings` (import/export notes such as "adjustment layer flattened"; `[]` when none), also shown to the user in the status bar and as a notice (`notices` in `ui.inspect`); `app.open` also returns the `path` and document `name`, `app.save` the `path` written. Automation opens and saves never fire script events. `file.open`, `file.save`, `file.saveAs` and `file.saveACopy` reply with `warnings` the same way
- `app.quit`
## Engine commands
@@ -133,7 +135,7 @@ How each MCP tool maps onto control methods in bridge mode:
| `doc_inspect` | `engine.execute {command: "document.inspect"}` |
| `doc_open {path}` | `app.open {path}` |
| `doc_save {path}` / `doc_export {path}` | `app.save {path}` |
-| `doc_render_preview {max_side?}` | `ui.screenshot {path: <temp>}`, returned as PNG image content |
+| `doc_render_preview {max_side?}` | `ui.screenshot`, returned directly as PNG image content |
| `session_list`, `ui_inspect` | `ui.inspect` |
| `ui_screenshot {max_side?}` | `ui.screenshot`, returned as PNG image content |
| `ui_pointer {events, modifiers?}` | `ui.pointer` |
@@ -143,7 +145,22 @@ How each MCP tool maps onto control methods in bridge mode:
`doc_select` and `doc_close` work only in headless mode. The `ui_*` tools and `control_call` work only in bridge mode; in headless mode they return a tool error that explains how to start bridge mode.
-**Security note:** TCP control uses a bearer token, not client identity or per-method authorization. A client that possesses the token receives the full exposed control surface, including file operations, UI input, command execution, and application control. Keep token files private, do not commit or log tokens, and do not pass a token directly on a shared system where process command lines are visible. The protocol is unencrypted and must remain on loopback; do not tunnel or proxy it to an untrusted host. Capability scopes and filesystem roots are not yet implemented.
+**Security note:** TCP control uses a bearer token, not client identity or general per-method
+authorization. A client that possesses the token receives the non-filesystem control surface,
+including UI input, command execution, and application control. Keep token files private, do not
+commit or log tokens, and do not pass a token directly on a shared system where process command
+lines are visible. The protocol is unencrypted and must remain on loopback; do not tunnel or proxy
+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` (or
+`PHOTOCRAFT_AUTOMATION_READ_ROOT` / `PHOTOCRAFT_AUTOMATION_WRITE_ROOT`). Request paths must be
+non-empty, forward-slash relative paths beneath the applicable root. Absolute paths, parent
+traversal, alternate separators, 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.
## Headless server
@@ -152,7 +169,9 @@ JSON-lines envelope on stdio, or on `127.0.0.1:<port>` with `--port <port>` (loo
authenticated connection shares the session). TCP uses the same first-frame `auth` exchange and
token options as desktop control. Stdio does not require this TCP handshake because access is
inherited from the process pipe. It is the fastest way for a script or agent to make many edits:
-no MCP framing, no app start-up per command. Implementation: `crates/automation/src/rpc.rs`.
+no MCP framing, no app start-up per command. Configure its file access with the same
+`--automation-read-root` and `--automation-write-root` flags. Implementation:
+`crates/automation/src/rpc.rs`.
| Method | Params |
|---|---|
@@ -169,9 +188,10 @@ no MCP framing, no app start-up per command. Implementation: `crates/automation/
```sh
printf '%s\n' \
- '{"id":1,"method":"doc.open","params":{"path":"/abs/in.jpg"}}' \
+ '{"id":1,"method":"doc.open","params":{"path":"in.jpg"}}' \
'{"id":2,"method":"batch","params":{"steps":[{"command":"image.adjustments.invert"},{"command":"filter.blur.gaussianBlur","params":{"radius":3}}]}}' \
- '{"id":3,"method":"doc.save","params":{"path":"/abs/out.png"}}' | photocraft-cli serve
+ '{"id":3,"method":"doc.save","params":{"path":"out.png"}}' | \
+ photocraft-cli serve --automation-read-root /work/project --automation-write-root /work/project
```
The MCP server has the same batching as the `command_batch` tool (`{steps:[{id, params}], stop_on_error}`),
@@ -186,4 +206,6 @@ The desktop and headless TCP listeners currently enforce:
- a 30-second socket read/write timeout;
- at most 256 steps in a headless `batch` or MCP `command_batch` request.
-An oversized line, excess connection, or unauthenticated request is rejected before command dispatch. These limits do not impose JSON-depth, response-size, render, document-memory, command-duration, filesystem-root, or capability budgets.
+An oversized line, excess connection, unauthenticated request, or unauthorized filesystem path is
+rejected before command dispatch or file effects. These limits do not impose JSON-depth,
+response-size, render, document-memory, command-duration, or general per-method capability budgets.
diff --git a/docs/development.md b/docs/development.md
index 54179fba5..a383e974a 100644
--- a/docs/development.md
+++ b/docs/development.md
@@ -9,7 +9,8 @@
```sh
cargo run --release -p photocraft -- path/to/image.psd # desktop app
-cargo run --release -p photocraft -- --control 7878 --control-token-file .private/control.token img.jpg
+cargo run --release -p photocraft -- --control 7878 --control-token-file .private/control.token \
+ --automation-read-root work --automation-write-root work
cargo test --workspace # everything
cargo xtask ci # fmt + clippy + tests + layers + wasm
cargo xtask stats # tests and lines per crate
@@ -25,6 +26,8 @@ Image code is slow at `opt-level 0`, so the workspace profile builds dependencie
| `PHOTOCRAFT_CONTROL_PORT` | Same as `--control <port>` |
| `PHOTOCRAFT_CONTROL_TOKEN` | 64-hex bearer token for control TCP (avoid on shared systems where environment inspection is possible) |
| `PHOTOCRAFT_CONTROL_TOKEN_FILE` | Read, or create for a server, the control bearer-token file |
+| `PHOTOCRAFT_AUTOMATION_READ_ROOT` | Directory capability for automation reads; requests use relative paths |
+| `PHOTOCRAFT_AUTOMATION_WRITE_ROOT` | Separate directory capability for automation writes; requests use relative paths |
| `PHOTOCRAFT_CPU_CANVAS=1` | Force the CPU canvas path instead of the wgpu shader canvas |
| `PHOTOCRAFT_GPU_TILE=2048` | Force GPU canvas tiling (tests tile seams) |
| `PHOTOCRAFT_FX_NOCACHE=1` | Bypass the CPU layer-effect map cache (`compose::effect_maps`) |
@@ -48,7 +51,7 @@ Start the app with a private token file. It then accepts authenticated JSON line
TOKEN=$(tr -d '\r\n' < .private/control.token)
printf '%s\n' "{\"id\":\"auth\",\"method\":\"auth\",\"params\":{\"token\":\"$TOKEN\"}}" \
'{"id":1,"method":"engine.execute","params":{"command":"layer.newAdjustmentLayer.hueSaturation","params":{"hue":30}}}' \
- '{"id":2,"method":"ui.screenshot","params":{"path":"/tmp/shot.png"}}' | nc 127.0.0.1 7878
+ '{"id":2,"method":"ui.screenshot","params":{"path":"evidence/shot.png"}}' | nc 127.0.0.1 7878
```
See `docs/control-protocol.md` for every method. Tips:
@@ -89,8 +92,8 @@ Keep one `PcraftWriter` per open document: re-saving then only compresses and wr
`photocraft-cli mcp` serves MCP on stdio using `crates/automation`, which is built on `rmcp`:
-- **Headless:** `photocraft-cli mcp`. It drives an in-process engine session.
-- **Live app:** start `photocraft --control 7878 --control-token-file <private-path>`, then run `photocraft-cli mcp --bridge 127.0.0.1:7878 --control-token-file <private-path>`. See `docs/control-protocol.md#mcp-bridge`.
+- **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`.
Tools:
@@ -125,8 +128,8 @@ claude mcp add photocraft -- "$PWD/target/release/photocraft-cli" mcp
bounds, masks, selection, effects (`effects.items[].kind`), smart filters (`smartFilters[]`), type
text, adjustment settings, channels and history, so agents can verify what they did without a
screenshot. `crates/automation/tests/agent_tasks.rs` is the reference: ten realistic edit tasks
-(title card, colour grade, undo/redo, editable smart blur, masks, saved selections, align, layer
-export, resize/crop, CMYK + native save) driven purely over MCP.
+(title card, colour grade, undo/redo, editable smart blur, masks, saved selections, align,
+capability-scoped export, resize/crop, CMYK + native save) driven purely over MCP.
Without MCP, `photocraft-cli serve [--port N]` keeps a headless session open and answers JSON lines
(see `docs/control-protocol.md#headless-server`).