Skip to content

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

Security: harden document exports and automation inputs (#2269)

skylar taylor-barrick61b6276c78f1
diff --git a/Cargo.lock b/Cargo.lock
index 1fbac784a..a197330ab 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4373,6 +4373,7 @@ dependencies = [
"roxmltree",
"serde",
"serde_json",
+ "tempfile",
"thiserror 2.0.21",
"wat",
]
diff --git a/book/src/security/automation-security.md b/book/src/security/automation-security.md
index ee0f989e7..12a767955 100644
--- a/book/src/security/automation-security.md
+++ b/book/src/security/automation-security.md
@@ -7,10 +7,15 @@ Automation is a privilege boundary because requests can cause filesystem access,
- Desktop control binds to `127.0.0.1` and uses one JSON request/reply per line.
- Headless TCP refuses a successfully bound non-loopback address.
- Every desktop-control and headless-TCP connection must authenticate with a 256-bit bearer token before method dispatch.
-- Encoded request lines are limited to 1 MiB on desktop and headless TCP and on the headless
- JSON-lines stdio server (`photocraft-cli serve`). MCP over stdio has no request-byte cap: the
- MCP SDK reads its own lines, and only MCP tool results are size-checked. Active TCP connections
- are limited to 16, and headless/MCP batches to 256 steps.
+- Encoded request lines are limited to 1 MiB on desktop and headless TCP, the headless
+ JSON-lines stdio server (`photocraft-cli serve`), and MCP stdio. The MCP line limit is
+ enforced before rmcp's line buffer; an oversized MCP line closes that stdio session because
+ its request ID cannot safely be parsed. Active TCP connections are limited to 16, and
+ headless/MCP batches to 256 steps.
+- Capability-scoped automation file opens read in chunks without reserving from the file's
+ metadata length. A read rejects data beyond the length observed on the opened file, so growth
+ after the metadata check cannot expand the read. Large PSB files have no fixed automation file
+ size ceiling; their materialized bytes and decoded document still require available memory.
- JSON-lines replies and encoded MCP tool results are limited to 8 MiB; retained batch replies
have an aggregate budget and stop later steps when exhausted. The headless stdio JSON-lines
transport enforces the same request/reply ceilings as TCP.
@@ -49,8 +54,9 @@ Automation is a privilege boundary because requests can cause filesystem access,
- no general per-client or per-tool capability model beyond filesystem read/write authority;
- no automated bulk apply of the Preferences dialog; agents can change individual safe keys with
`prefs.set`;
-- no explicit JSON-depth policy, aggregate document/session-memory accounting, compositor
- scratch-space accounting, or command-duration/cancellation budget;
+- no application-specific JSON-depth policy (serde_json's parser has its default finite recursion
+ limit), aggregate document/session-memory accounting, compositor scratch-space accounting,
+ or command-duration/cancellation budget;
- one thread per accepted TCP connection;
- no structured security audit event stream;
- desktop screenshot capture/encoding and document import/export have no automation-specific
diff --git a/crates/automation/src/server/transport.rs b/crates/automation/src/server/transport.rs
index 7cececd59..44ba4596b 100644
--- a/crates/automation/src/server/transport.rs
+++ b/crates/automation/src/server/transport.rs
@@ -2,6 +2,38 @@
use super::*;
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
+use crate::security::MAX_REQUEST_BYTES;
+
+/// Read a complete request before allowing any of its bytes to reach rmcp. `lines()`
+/// buffers without a limit, while forwarding partial input can make a valid JSON prefix
+/// executable at EOF after an oversized suffix is rejected.
+async fn bounded_line<R: tokio::io::AsyncRead + Unpin>(source: &mut BufReader<R>, maximum: usize) -> std::io::Result<Option<String>> {
+ let mut bytes = Vec::new();
+ loop {
+ let available = source.fill_buf().await?;
+ if available.is_empty() {
+ if bytes.is_empty() {
+ return Ok(None);
+ }
+ return String::from_utf8(bytes).map(Some).map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e));
+ }
+ let newline = available.iter().position(|&byte| byte == b'\n');
+ let length = newline.map_or(available.len(), |at| at + 1);
+ if length > maximum.saturating_sub(bytes.len()) {
+ return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, format!("request exceeds {maximum} bytes")));
+ }
+ bytes.extend_from_slice(&available[..length]);
+ source.consume(length);
+ if newline.is_some() {
+ bytes.pop();
+ if bytes.last() == Some(&b'\r') {
+ bytes.pop();
+ }
+ return String::from_utf8(bytes).map(Some).map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e));
+ }
+ }
+}
+
impl PhotocraftMcp {
/// Serve a JSON-lines stream. A malformed line receives -32700/id:null; the next line
/// is still handled. A single writer serializes parse errors and SDK responses.
@@ -14,8 +46,8 @@ impl PhotocraftMcp {
let (service_out, from_service) = tokio::io::duplex(1 << 20);
let (errors, mut error_rx) = tokio::sync::mpsc::channel::<String>(16);
let reader = tokio::spawn(async move {
- let mut lines = BufReader::new(input).lines();
- while let Some(line) = lines.next_line().await? {
+ let mut lines = BufReader::new(input);
+ while let Some(line) = bounded_line(&mut lines, MAX_REQUEST_BYTES).await? {
if line.trim().is_empty() {
continue;
}
@@ -59,3 +91,56 @@ impl PhotocraftMcp {
result
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[tokio::test]
+ async fn bounded_line_accepts_exact_limit_and_final_line() {
+ let mut input = BufReader::new(std::io::Cursor::new(b"1234\nlast!".to_vec()));
+ assert_eq!(bounded_line(&mut input, 5).await.unwrap().as_deref(), Some("1234"));
+ assert_eq!(bounded_line(&mut input, 5).await.unwrap().as_deref(), Some("last!"));
+ assert!(bounded_line(&mut input, 5).await.unwrap().is_none());
+
+ let mut oversized_eof = BufReader::new(std::io::Cursor::new(b"longer".to_vec()));
+ assert_eq!(bounded_line(&mut oversized_eof, 5).await.unwrap_err().kind(), std::io::ErrorKind::InvalidData);
+ }
+
+ #[tokio::test]
+ async fn oversized_valid_tool_call_never_reaches_dispatch() {
+ let initialize = json!({
+ "jsonrpc": "2.0",
+ "id": 1,
+ "method": "initialize",
+ "params": {
+ "protocolVersion": "2025-06-18",
+ "capabilities": {},
+ "clientInfo": { "name": "admission-test", "version": "1" }
+ }
+ });
+ let mut input = format!("{initialize}\n{}\n", json!({"jsonrpc": "2.0", "method": "notifications/initialized"})).into_bytes();
+ let call = json!({
+ "jsonrpc": "2.0",
+ "id": 2,
+ "method": "tools/call",
+ "params": { "name": "doc_new", "arguments": { "width": 8, "height": 8 } }
+ })
+ .to_string()
+ .into_bytes();
+ assert!(call.len() < MAX_REQUEST_BYTES);
+ input.extend_from_slice(&call);
+ // The valid JSON prefix spans multiple BufReader fills; only its whitespace suffix
+ // crosses the byte limit. No part of this line may be forwarded to rmcp.
+ input.extend(vec![b' '; MAX_REQUEST_BYTES - call.len()]);
+ input.push(b'\n');
+ let server = PhotocraftMcp::headless();
+ let observer = server.clone();
+ let result = tokio::time::timeout(std::time::Duration::from_secs(5), server.serve_io(std::io::Cursor::new(input), tokio::io::sink()))
+ .await
+ .expect("oversized MCP input should end the session");
+ assert!(result.unwrap_err().to_string().contains("request exceeds 1048576 bytes"));
+ let documents = observer.headless_op(|h| Ok(h.session.documents().len())).await.unwrap().unwrap();
+ assert_eq!(documents, 0, "the oversized tool call must not run");
+ }
+}
diff --git a/crates/automation/src/workspace.rs b/crates/automation/src/workspace.rs
index 51a510ca5..76a14c6e3 100644
--- a/crates/automation/src/workspace.rs
+++ b/crates/automation/src/workspace.rs
@@ -1,6 +1,6 @@
//! Capability-based filesystem policy for untrusted automation paths.
-use std::io::Write;
+use std::io::{Read, Write};
use std::path::{Component, Path, PathBuf};
use std::sync::Arc;
@@ -51,8 +51,7 @@ impl AuthorizedWorkspace {
if !metadata.is_file() {
return Err(AutomationError::BadRequest(format!("automation read path is not a regular file: `{path}`")));
}
- // Bounded reads, and a clear error for a file larger than memory (#375).
- photocraft_format::read::read_all(&mut file, metadata.len()).map_err(|e| file_error("read", path, e))
+ read_to_observed_length(&mut file, metadata.len())
}
/// Load one `.pcraft` document in directory form — the native on-disk layout — below the
@@ -108,6 +107,34 @@ impl AuthorizedWorkspace {
}
}
+fn read_to_observed_length(reader: &mut impl Read, observed_length: u64) -> Result<Vec<u8>, AutomationError> {
+ // Do not reserve from a potentially stale or attacker-controlled metadata length. Read in
+ // chunks, and reject growth beyond the length observed on the opened file before appending.
+ let mut bytes = Vec::new();
+ let mut chunk = [0u8; 64 << 10];
+ loop {
+ let remaining = observed_length.saturating_sub(bytes.len() as u64);
+ let ask = chunk.len().min(usize::try_from(remaining.saturating_add(1)).unwrap_or(chunk.len()));
+ let n = match reader.read(&mut chunk[..ask]) {
+ Ok(n) => n,
+ Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
+ Err(e) => return Err(AutomationError::Io(format!("automation read failed: {e}"))),
+ };
+ if n == 0 {
+ return Ok(bytes);
+ }
+ if n as u64 > remaining {
+ return Err(AutomationError::BadRequest(format!("automation file grew beyond its observed length of {observed_length} bytes")));
+ }
+ let needed = bytes.len().checked_add(n).ok_or_else(|| AutomationError::BadRequest("automation file is too large to read".into()))?;
+ if needed > bytes.capacity() {
+ let target = bytes.capacity().saturating_add(bytes.capacity() / 2).max(needed).min(usize::try_from(observed_length).unwrap_or(usize::MAX));
+ bytes.try_reserve_exact(target - bytes.len()).map_err(|e| AutomationError::Io(format!("automation read allocation failed: {e}")))?;
+ }
+ bytes.extend_from_slice(&chunk[..n]);
+ }
+}
+
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() {
@@ -465,6 +492,23 @@ mod tests {
assert_eq!(std::fs::read(inside.join("new-output.txt")).unwrap(), b"created");
}
+ #[test]
+ fn large_observed_length_does_not_trigger_a_fixed_limit_or_upfront_reservation() {
+ let mut shortened = std::io::Cursor::new(b"psb");
+ assert_eq!(read_to_observed_length(&mut shortened, (1 << 30) + 1).unwrap(), b"psb");
+ }
+
+ #[test]
+ fn read_growth_is_rejected_at_the_observed_length() {
+ let mut growing = std::io::repeat(b'x').take(65);
+ let error = read_to_observed_length(&mut growing, 64).unwrap_err().to_string();
+ assert!(error.contains("grew beyond its observed length of 64 bytes"), "{error}");
+ let mut allowed = std::io::repeat(b'x').take(64);
+ assert_eq!(read_to_observed_length(&mut allowed, 64).unwrap().len(), 64);
+ let mut empty = std::io::Cursor::new(b"x");
+ assert!(read_to_observed_length(&mut empty, 0).is_err());
+ }
+
#[test]
fn open_pcraft_loads_a_directory_below_the_read_root() {
let (inside, _, workspace) = roots("pcraft-dir");
diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml
index fa15c3098..d15e0f985 100644
--- a/crates/engine/Cargo.toml
+++ b/crates/engine/Cargo.toml
@@ -38,6 +38,9 @@ flate2 = { workspace = true }
# through photocraft-ui-egui and usvg.
roxmltree = "0.20"
+[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
+tempfile = "3"
+
[dev-dependencies]
photocraft-affinity = { workspace = true, features = ["synth"] }
# Synthetic camera raw files for the open tests.
diff --git a/crates/engine/src/automate_cmds.rs b/crates/engine/src/automate_cmds.rs
index a493cf1e4..b8f827d12 100644
--- a/crates/engine/src/automate_cmds.rs
+++ b/crates/engine/src/automate_cmds.rs
@@ -324,9 +324,11 @@ fn write_shim(droplet: &str) -> Result<String> {
let abs = std::fs::canonicalize(droplet).map(|p| p.to_string_lossy().into_owned()).unwrap_or_else(|_| droplet.to_string());
let base = abs.trim_end_matches(".pcdroplet").trim_end_matches(".json");
let shim = format!("{base}.command");
+ // Single quotes keep shell expansions inert; embedded quotes need to end the
+ // quoted segment, emit a literal quote, then resume it.
+ let quoted_abs = format!("'{}'", abs.replace('\'', "'\\''"));
let body = format!(
- "#!/bin/sh\n# PhotoCraft droplet: runs the action on the files given (or dropped).\nexec \"${{PHOTOCRAFT_CLI:-photocraft-cli}}\" droplet \"{}\" \"$@\"\n",
- abs.replace('"', "\\\"")
+ "#!/bin/sh\n# PhotoCraft droplet: runs the action on the files given (or dropped).\nexec \"${{PHOTOCRAFT_CLI:-photocraft-cli}}\" droplet {quoted_abs} \"$@\"\n"
);
crate::file_cmds::write_file(&shim, body.as_bytes())?;
#[cfg(unix)]
diff --git a/crates/engine/src/automate_cmds/tests.rs b/crates/engine/src/automate_cmds/tests.rs
index 03548d3ac..d4e0a6379 100644
--- a/crates/engine/src/automate_cmds/tests.rs
+++ b/crates/engine/src/automate_cmds/tests.rs
@@ -145,6 +145,43 @@ fn droplets_are_written_and_run() {
assert!(s.execute("file.automate.createDroplet", json!({"path": path, "steps": [["bogus", {}]]})).is_err());
}
+#[cfg(unix)]
+#[test]
+fn droplet_shim_passes_shell_metacharacters_as_a_literal_path() {
+ use std::os::unix::fs::PermissionsExt;
+
+ let dir = tmp("droplet-shell-quote");
+ let path = format!("{dir}/Droplet's \"quote\" $HOME `printf expanded` $(touch shim-injected) \\\nline");
+ let mut session = Session::new();
+ let result = session.execute("file.automate.createDroplet", json!({"path": path, "steps": [["file.new", {}]]})).unwrap();
+ let droplet = result["path"].as_str().unwrap();
+ let shim = result["shim"].as_str().unwrap();
+
+ let cli = format!("{dir}/cli stub");
+ let capture = format!("{dir}/captured path");
+ let marker = format!("{dir}/shim-injected");
+ let input = format!("{dir}/input file");
+ std::fs::write(
+ &cli,
+ "#!/bin/sh\nif [ \"$#\" -ne 3 ] || [ \"$1\" != droplet ] || [ \"$3\" != \"$PHOTOCRAFT_EXPECTED_INPUT\" ]; then exit 90; fi\nprintf '%s' \"$2\" > \"$PHOTOCRAFT_CAPTURE\"\n",
+ )
+ .unwrap();
+ std::fs::set_permissions(&cli, std::fs::Permissions::from_mode(0o755)).unwrap();
+ let output = std::process::Command::new(shim)
+ .arg(&input)
+ .current_dir(&dir)
+ .env("PHOTOCRAFT_CLI", &cli)
+ .env("PHOTOCRAFT_CAPTURE", &capture)
+ .env("PHOTOCRAFT_EXPECTED_INPUT", &input)
+ .output()
+ .unwrap();
+
+ assert!(output.status.success(), "shim exited {:?}: {}", output.status, String::from_utf8_lossy(&output.stderr));
+ assert!(!std::path::Path::new(&marker).exists(), "filename command substitution ran");
+ let expected = std::fs::canonicalize(droplet).unwrap();
+ assert_eq!(std::fs::read(&capture).unwrap(), expected.to_string_lossy().as_bytes());
+}
+
#[test]
fn droplets_carry_the_actions_their_play_steps_call() {
use crate::actions_cmds::Action;
diff --git a/crates/engine/src/fill_cmds.rs b/crates/engine/src/fill_cmds.rs
index 193a1aea8..a7350dafc 100644
--- a/crates/engine/src/fill_cmds.rs
+++ b/crates/engine/src/fill_cmds.rs
@@ -526,7 +526,7 @@ mod tests {
assert!(blacks > 300 && blacks < 900, "{blacks}");
assert!((0..40).all(|x| {
let v = surf.rgba(x, 3)[0];
- !v.is_nan() && !(0.01..=0.99).contains(&v)
+ v.is_finite() && !(0.01..=0.99).contains(&v)
}));
}
diff --git a/crates/engine/src/image_cmds.rs b/crates/engine/src/image_cmds.rs
index 2e926c307..c8055a4d3 100644
--- a/crates/engine/src/image_cmds.rs
+++ b/crates/engine/src/image_cmds.rs
@@ -961,7 +961,7 @@ mod tests {
let surf = st.doc.layers[0].surface().unwrap();
for (x, y) in [(0, 0), (1, 1), (2, 3)] {
let v = surf.rgba(x, y)[0];
- assert!(!v.is_nan() && !(0.01..=0.99).contains(&v), "nearest produced an averaged value {v} at ({x},{y})");
+ assert!(v.is_finite() && !(0.01..=0.99).contains(&v), "nearest produced an averaged value {v} at ({x},{y})");
}
}
diff --git a/crates/engine/src/print_cmds.rs b/crates/engine/src/print_cmds.rs
index 59d6b3e1e..a6acb95a4 100644
--- a/crates/engine/src/print_cmds.rs
+++ b/crates/engine/src/print_cmds.rs
@@ -5,7 +5,8 @@
//! centre crop marks, registration marks, description and label) with a small PDF writer
//! (ISO 32000: one page, a Flate-compressed image XObject, vector marks, Helvetica text), then
//! hands it to the system spooler with `lp` (CUPS, macOS and Linux). `"dryRun": true` stops
-//! before spooling and reports the command line, which is how the tests exercise the path.
+//! before spooling and reports the command line. Without an explicit PDF output, the spool file
+//! is private and removed when `lp` finishes; dry runs do not create one.
//!
//! Paths to Illustrator writes the document's paths as an Adobe Illustrator 3 compatible
//! PostScript file (`m`/`L`/`C` path construction, `n`/`N` unpainted closed/open paths, `*u`/`*U`
@@ -326,8 +327,33 @@ pub fn layout(doc: &Document, p: &Value, cmd: &str) -> Result<PrintLayout> {
Ok(PrintLayout { paper: (pw, ph), rect: (x, y, w, h), scale, marks, emulsion_down })
}
+#[cfg(not(target_arch = "wasm32"))]
+fn private_spool_pdf(pdf: &[u8]) -> Result<tempfile::NamedTempFile> {
+ private_spool_pdf_in(pdf, &std::env::temp_dir())
+}
+
+#[cfg(not(target_arch = "wasm32"))]
+fn private_spool_pdf_in(pdf: &[u8], dir: &std::path::Path) -> Result<tempfile::NamedTempFile> {
+ // tempfile creates a random name with create_new semantics and mode 0600 on Unix.
+ // Keeping this handle alive prevents a symlink at a guessed path from redirecting the write.
+ let mut file = tempfile::Builder::new().prefix("photocraft-print-").suffix(".pdf").tempfile_in(dir).map_err(other)?;
+ file.write_all(pdf).map_err(other)?;
+ file.flush().map_err(other)?;
+ Ok(file)
+}
+
/// Lays out, renders and (unless dry-run) spools a print. Shared by Print and Print One Copy.
fn do_print(s: &mut Session, p: &Value, cmd: &str) -> Result<Value> {
+ do_print_with_spooler(s, p, cmd, spool_pdf)
+}
+
+fn do_print_with_spooler(s: &mut Session, p: &Value, cmd: &str, spooler: impl FnOnce(&[String]) -> Result<String>) -> Result<Value> {
+ let output = p.get("output").and_then(Value::as_str).filter(|v| !v.is_empty()).map(str::to_string);
+ let send = p.get("send").and_then(Value::as_bool).unwrap_or(output.is_none());
+ let dry = p.get("dryRun").and_then(Value::as_bool).unwrap_or(false);
+ if !dry && !send && output.is_none() {
+ return Err(bad(cmd, "send: false needs an output path or dryRun: true"));
+ }
let d = s.active().ok_or(EngineError::NoDocument)?;
let doc = d.doc.clone();
let PrintLayout { paper: (pw, ph), rect: (x, y, w, h), scale, marks, emulsion_down } = layout(&doc, p, cmd)?;
@@ -339,22 +365,23 @@ fn do_print(s: &mut Session, p: &Value, cmd: &str) -> Result<Value> {
.then(|| crate::file_cmds::read_file_info(doc.metadata.xmp.as_deref())["description"].as_str().unwrap_or_default().to_string());
let label = p.get("labels").and_then(Value::as_bool).unwrap_or(false).then(|| doc.name.clone());
let page = PrintPage { paper: (pw, ph), image: img, rect: (x, y, w, h), marks, description, label, emulsion_down };
- let output = p.get("output").and_then(Value::as_str).filter(|v| !v.is_empty()).map(str::to_string);
- let send = p.get("send").and_then(Value::as_bool).unwrap_or(output.is_none());
- let pdf_path = match &output {
- Some(o) => o.clone(),
- None => {
- // Unique per call: concurrent prints of same-named documents must not share a spool file.
- static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
- let n = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
- let tmp = std::env::temp_dir().to_string_lossy().into_owned();
- join(&tmp, &format!("{}-print-{}-{n}.pdf", crate::file_cmds::sanitize(&stem(&doc.name)), std::process::id()))
- }
- };
- let copies = crate::commands::int(p, "copies").unwrap_or(1).clamp(1, 999);
- let dry = p.get("dryRun").and_then(Value::as_bool).unwrap_or(false);
let pdf = print_pdf(&page);
- write_file(&pdf_path, &pdf)?;
+ if let Some(path) = &output {
+ // An explicit output is the caller's requested artifact, including for dry runs.
+ write_file(path, &pdf)?;
+ }
+ #[cfg(not(target_arch = "wasm32"))]
+ let spool_file = if output.is_none() && send && !dry { Some(private_spool_pdf(&pdf)?) } else { None };
+ #[cfg(target_arch = "wasm32")]
+ if output.is_none() && send && !dry {
+ return Err(other("printing needs the desktop app"));
+ }
+ // Dry-run commands use a descriptive placeholder because no spool file exists.
+ let command_path = output.clone();
+ #[cfg(not(target_arch = "wasm32"))]
+ let command_path = command_path.or_else(|| spool_file.as_ref().map(|f| f.path().to_string_lossy().into_owned()));
+ let command_path = command_path.unwrap_or_else(|| "<temporary PDF>".into());
+ let copies = crate::commands::int(p, "copies").unwrap_or(1).clamp(1, 999);
let mut argv: Vec<String> = vec!["lp".into()];
if let Some(pr) = p.get("printer").and_then(Value::as_str).filter(|v| !v.is_empty()) {
argv.extend(["-d".into(), pr.to_string()]);
@@ -362,17 +389,19 @@ fn do_print(s: &mut Session, p: &Value, cmd: &str) -> Result<Value> {
if copies > 1 {
argv.extend(["-n".into(), copies.to_string()]);
}
- argv.extend(["-t".into(), doc.name.clone(), pdf_path.clone()]);
+ argv.extend(["-t".into(), doc.name.clone(), command_path]);
let mut sent = false;
let mut spool = Value::Null;
if send && !dry {
- spool = json!(spool_pdf(&argv)?);
+ spool = json!(spooler(&argv)?);
sent = true;
}
+ #[cfg(not(target_arch = "wasm32"))]
+ drop(spool_file);
remember_print(s, p);
crate::automate_cmds::fire_event(s, "print");
Ok(
- json!({"pdf": pdf_path, "bytes": pdf.len(), "paper": [pw, ph], "imageRect": [x, y, w, h], "emulsionDown": emulsion_down, "scale": scale * 100.0, "copies": copies, "command": if send { json!(argv) } else { Value::Null }, "sent": sent, "spooler": spool, "color": color}),
+ json!({"pdf": output, "bytes": pdf.len(), "paper": [pw, ph], "imageRect": [x, y, w, h], "emulsionDown": emulsion_down, "scale": scale * 100.0, "copies": copies, "command": if send { json!(argv) } else { Value::Null }, "sent": sent, "spooler": spool, "color": color}),
)
}
@@ -382,6 +411,9 @@ fn remember_print(s: &mut Session, p: &Value) {
if let Some(o) = remembered.as_object_mut() {
o.remove("output");
o.remove("dryRun");
+ // A send override can depend on the output or dry-run choice. Neither is remembered,
+ // so replay and the next Print dialog must derive the default from their own output.
+ o.remove("send");
}
s.file_menu.last_print = Some(remembered);
}
@@ -567,7 +599,7 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec { id: $id, label: $label, menu: $menu, shortcut: $sc, params: $params, enabled: $enabled, journal: true, run: $run }
};
}
- const PRINT_PARAMS: &str = r##"{"printer":name? (default printer),"copies":1..999=1,"paper":"letter|legal|tabloid|a3|a4|a5|4x6|5x7"|[w,h] pt="letter","orientation":"portrait|landscape"="portrait","center":bool=true,"top":in?,"left":in?,"scale":%=100,"scaleToFit":bool=false,"colorHandling":"printerManages|photocraftManages|noColorManagement"="printerManages","printerProfile":profile? (photocraftManages),"intent":"perceptual|relative|saturation|absolute"="relative","bpc":bool=true,"cornerCropMarks":bool,"centerCropMarks":bool,"registrationMarks":bool,"description":bool,"labels":bool,"emulsionDown":bool=false (mirror the page left to right, for sublimation and other transfer printing),"output":pdf path? (print to PDF; then "send" defaults to false),"send":bool?,"dryRun":bool=false (render the PDF, report the lp command, don't spool)} → {pdf, imageRect, command, sent}"##;
+ const PRINT_PARAMS: &str = r##"{"printer":name? (default printer),"copies":1..999=1,"paper":"letter|legal|tabloid|a3|a4|a5|4x6|5x7"|[w,h] pt="letter","orientation":"portrait|landscape"="portrait","center":bool=true,"top":in?,"left":in?,"scale":%=100,"scaleToFit":bool=false,"colorHandling":"printerManages|photocraftManages|noColorManagement"="printerManages","printerProfile":profile? (photocraftManages),"intent":"perceptual|relative|saturation|absolute"="relative","bpc":bool=true,"cornerCropMarks":bool,"centerCropMarks":bool,"registrationMarks":bool,"description":bool,"labels":bool,"emulsionDown":bool=false (mirror the page left to right, for sublimation and other transfer printing),"output":pdf path? (print to PDF; then "send" defaults to false),"send":bool?,"dryRun":bool=false (render the PDF, report the lp command, don't spool; no temporary PDF is written)} → {pdf:explicit output path or null, imageRect, command, sent}"##;
vec![
spec!("file.print", "Print…", &["File"], Some("Cmd+P"), PRINT_PARAMS, native_doc, print),
spec!(
diff --git a/crates/engine/src/print_cmds/tests.rs b/crates/engine/src/print_cmds/tests.rs
index 877fb945f..ab2e8c378 100644
--- a/crates/engine/src/print_cmds/tests.rs
+++ b/crates/engine/src/print_cmds/tests.rs
@@ -37,16 +37,19 @@ fn print_dry_run_renders_a_pdf_and_reports_lp() {
let dir = tmp("print");
for depth in [8, 16, 32] {
let mut s = session("rgb", depth);
+ let out = format!("{dir}/rgb-{depth}.pdf");
let r = s
.execute(
"file.print",
- json!({"dryRun": true, "printer": "Office", "copies": 2, "paper": "a4", "cornerCropMarks": true, "registrationMarks": true, "labels": true}),
+ json!({"output": out, "send": true, "dryRun": true, "printer": "Office", "copies": 2, "paper": "a4", "cornerCropMarks": true, "registrationMarks": true, "labels": true}),
)
.unwrap();
let cmd: Vec<String> = serde_json::from_value(r["command"].clone()).unwrap();
assert_eq!(&cmd[..5], &["lp", "-d", "Office", "-n", "2"]);
+ assert_eq!(cmd.last(), Some(&out));
assert_eq!(r["sent"], false);
- let pdf = std::fs::read(r["pdf"].as_str().unwrap()).unwrap();
+ assert_eq!(r["pdf"], out);
+ let pdf = std::fs::read(&out).unwrap();
assert!(pdf.starts_with(b"%PDF-1.4"));
assert!(String::from_utf8_lossy(&pdf).contains("/MediaBox [0 0 595.28 841.89]"));
let (w, h, cs, data) = pdf_image(&pdf);
@@ -56,7 +59,6 @@ fn print_dry_run_renders_a_pdf_and_reports_lp() {
// 300 px at 72 ppi = 300 pt, centred.
let rect: Vec<f64> = serde_json::from_value(r["imageRect"].clone()).unwrap();
assert!((rect[2] - 300.0).abs() < 1e-6 && (rect[0] - (595.28 - 300.0) / 2.0).abs() < 1e-6);
- let _ = std::fs::remove_file(r["pdf"].as_str().unwrap());
}
// Print to PDF: no spooling by default.
let mut s = session("gray", 8);
@@ -75,14 +77,15 @@ fn print_dry_run_renders_a_pdf_and_reports_lp() {
#[test]
fn photocraft_manages_colors_converts_to_the_printer_profile() {
let mut s = session("rgb", 8);
+ let out = format!("{}/managed.pdf", tmp("managed"));
let r = s
.execute(
"file.print",
- json!({"dryRun": true, "colorHandling": "photocraftManages", "printerProfile": "coated-cmyk", "intent": "perceptual", "bpc": false}),
+ json!({"output": out, "dryRun": true, "colorHandling": "photocraftManages", "printerProfile": "coated-cmyk", "intent": "perceptual", "bpc": false}),
)
.unwrap();
assert_eq!(r["color"]["intent"], "perceptual");
- let pdf = std::fs::read(r["pdf"].as_str().unwrap()).unwrap();
+ let pdf = std::fs::read(&out).unwrap();
let (_, _, cs, data) = pdf_image(&pdf);
assert_eq!(cs, "[/ICCBased 7 0 R]");
assert!(String::from_utf8_lossy(&pdf).contains("/N 4 /Alternate /DeviceCMYK"));
@@ -91,7 +94,6 @@ fn photocraft_manages_colors_converts_to_the_printer_profile() {
assert!(data[0] > 150 && data[2] < 60, "{:?}", &data[..4]);
// The document itself is untouched.
assert_eq!(s.active().unwrap().doc.mode, ColorMode::Rgb);
- let _ = std::fs::remove_file(r["pdf"].as_str().unwrap());
}
/// The inflated page content stream (object 4).
@@ -108,9 +110,18 @@ fn pdf_content(pdf: &[u8]) -> String {
#[test]
fn emulsion_down_mirrors_the_whole_page() {
let mut s = session("rgb", 8);
- let plain = s.execute("file.print", json!({"dryRun": true, "paper": "a4", "center": false, "left": 1.0, "top": 1.0, "labels": true})).unwrap();
+ let dir = tmp("emulsion");
+ let plain_path = format!("{dir}/plain.pdf");
+ let mirrored_path = format!("{dir}/mirrored.pdf");
+ let again_path = format!("{dir}/again.pdf");
+ let plain = s
+ .execute("file.print", json!({"output": plain_path, "dryRun": true, "paper": "a4", "center": false, "left": 1.0, "top": 1.0, "labels": true}))
+ .unwrap();
let mirrored = s
- .execute("file.print", json!({"dryRun": true, "paper": "a4", "center": false, "left": 1.0, "top": 1.0, "labels": true, "emulsionDown": true}))
+ .execute(
+ "file.print",
+ json!({"output": mirrored_path, "dryRun": true, "paper": "a4", "center": false, "left": 1.0, "top": 1.0, "labels": true, "emulsionDown": true}),
+ )
.unwrap();
assert_eq!(plain["emulsionDown"], false);
assert_eq!(mirrored["emulsionDown"], true);
@@ -126,20 +137,24 @@ fn emulsion_down_mirrors_the_whole_page() {
// The pixels themselves are not touched (the transform mirrors them).
assert_eq!(pdf_image(&p).3, pdf_image(&m).3);
// Print One Copy keeps it.
- let again = s.execute("file.printOneCopy", json!({"dryRun": true})).unwrap();
+ let again = s.execute("file.printOneCopy", json!({"output": again_path, "dryRun": true})).unwrap();
assert_eq!(again["emulsionDown"], true);
for r in [plain, mirrored, again] {
let _ = std::fs::remove_file(r["pdf"].as_str().unwrap());
}
+ let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn printer_profile_can_be_an_installed_icc_file() {
let dir = tmp("icc");
let icc = format!("{dir}/My Paper.icc");
+ let output = format!("{dir}/managed.pdf");
std::fs::write(&icc, photocraft_cms::Builtin::CoatedCmyk.profile().to_bytes().as_slice()).unwrap();
let mut s = session("rgb", 16);
- let r = s.execute("file.print", json!({"dryRun": true, "colorHandling": "photocraftManages", "printerProfile": icc, "emulsionDown": true})).unwrap();
+ let r = s
+ .execute("file.print", json!({"output": output, "dryRun": true, "colorHandling": "photocraftManages", "printerProfile": icc, "emulsionDown": true}))
+ .unwrap();
assert_eq!(r["color"]["printerProfile"], json!(icc));
let (_, _, cs, data) = pdf_image(&std::fs::read(r["pdf"].as_str().unwrap()).unwrap());
assert_eq!(cs, "[/ICCBased 7 0 R]");
@@ -152,14 +167,112 @@ fn printer_profile_can_be_an_installed_icc_file() {
#[test]
fn print_one_copy_repeats_the_last_settings() {
let mut s = session("rgb", 8);
- s.execute("file.print", json!({"dryRun": true, "copies": 3, "paper": "a5", "scale": 50})).unwrap();
+ let first = s.execute("file.print", json!({"dryRun": true, "copies": 3, "paper": "a5", "scale": 50})).unwrap();
+ assert!(first["pdf"].is_null());
let r = s.execute("file.printOneCopy", json!({"dryRun": true})).unwrap();
assert_eq!(r["copies"], 1);
assert_eq!(r["paper"], json!([419.53, 595.28]));
assert_eq!(r["scale"], 50.0);
let cmd: Vec<String> = serde_json::from_value(r["command"].clone()).unwrap();
assert!(!cmd.contains(&"-n".to_string()));
- let _ = std::fs::remove_file(r["pdf"].as_str().unwrap());
+ assert_eq!(cmd.last().map(String::as_str), Some("<temporary PDF>"));
+ assert!(r["pdf"].is_null());
+}
+
+#[test]
+fn print_without_output_keeps_private_pdf_only_during_spooling() {
+ let mut s = session("rgb", 8);
+ let mut temporary_path = None;
+ let result = do_print_with_spooler(&mut s, &json!({}), "file.print", |argv| {
+ let path = std::path::PathBuf::from(argv.last().unwrap());
+ let data = std::fs::read(&path).unwrap();
+ assert!(data.starts_with(b"%PDF-1.4"));
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o077, 0);
+ }
+ temporary_path = Some(path);
+ Ok("request id 1".into())
+ })
+ .unwrap();
+ assert_eq!(result["sent"], true);
+ assert!(result["pdf"].is_null(), "the temporary path must not be advertised as a retained PDF");
+ assert!(!temporary_path.unwrap().exists(), "spool PDF survives after lp returns");
+}
+
+#[test]
+fn print_spool_error_removes_private_pdf() {
+ let mut s = session("rgb", 8);
+ let mut temporary_path = None;
+ let result = do_print_with_spooler(&mut s, &json!({}), "file.print", |argv| {
+ let path = std::path::PathBuf::from(argv.last().unwrap());
+ assert!(path.is_file());
+ temporary_path = Some(path);
+ Err(other("spooler unavailable"))
+ });
+ assert!(result.is_err());
+ assert!(!temporary_path.unwrap().exists(), "spool PDF survives a failed lp call");
+}
+
+#[cfg(unix)]
+#[test]
+fn private_spool_pdf_does_not_follow_a_guessed_symlink() {
+ let dir = tmp("symlink");
+ let dir = std::path::Path::new(&dir);
+ let victim = dir.join("victim.pdf");
+ let link = dir.join("photocraft-print-AAAAAA.pdf");
+ std::fs::write(&victim, b"keep this").unwrap();
+ std::os::unix::fs::symlink(&victim, &link).unwrap();
+
+ let file = private_spool_pdf_in(b"%PDF-private", dir).unwrap();
+ assert_ne!(file.path(), link);
+ assert_eq!(std::fs::read(&victim).unwrap(), b"keep this");
+ assert_eq!(std::fs::read(file.path()).unwrap(), b"%PDF-private");
+ assert!(std::fs::symlink_metadata(file.path()).unwrap().file_type().is_file());
+ let path = file.path().to_path_buf();
+ drop(file);
+ assert!(!path.exists());
+ assert!(std::fs::symlink_metadata(&link).unwrap().file_type().is_symlink());
+}
+
+#[test]
+fn print_dry_run_without_output_creates_no_spool_pdf() {
+ let mut s = session("rgb", 8);
+ let result = do_print_with_spooler(&mut s, &json!({"dryRun": true}), "file.print", |_| Err(other("dry run invoked spooler"))).unwrap();
+ assert!(result["pdf"].is_null());
+ assert_eq!(result["sent"], false);
+ assert_eq!(result["command"].as_array().unwrap().last().unwrap(), "<temporary PDF>");
+ assert!(result["bytes"].as_u64().unwrap() > 100);
+}
+
+#[test]
+fn print_without_sending_requires_an_output_unless_dry_run() {
+ let mut s = session("rgb", 8);
+ let before = s.file_menu.last_print.clone();
+ let err = do_print_with_spooler(&mut s, &json!({"send": false}), "file.print", |_| Err(other("unexpected spooler call"))).unwrap_err();
+ assert!(err.to_string().contains("needs an output path"), "{err}");
+ assert_eq!(s.file_menu.last_print, before, "a rejected print must not become a remembered successful print");
+ assert!(do_print_with_spooler(&mut s, &json!({"send": false, "dryRun": true}), "file.print", |_| Err(other("dry run invoked spooler"))).is_ok());
+ assert!(s.file_menu.last_print.as_ref().unwrap().get("send").is_none());
+
+ let output = format!("{}/export.pdf", tmp("non-sending-export"));
+ do_print_with_spooler(&mut s, &json!({"output": output, "send": false}), "file.print", |_| Err(other("non-sending export invoked spooler"))).unwrap();
+ assert!(std::path::Path::new(&output).is_file());
+ let mut repeat = s.file_menu.last_print.clone().unwrap();
+ assert!(repeat.get("send").is_none(), "a removed output must not leave send: false in remembered settings");
+ repeat["copies"] = json!(1);
+ let replay = do_print_with_spooler(&mut s, &repeat, "file.printOneCopy", |argv| {
+ assert!(std::path::Path::new(argv.last().unwrap()).is_file());
+ Ok("request id 2".into())
+ })
+ .unwrap();
+ assert_eq!(replay["sent"], true);
+ assert_eq!(replay["copies"], 1);
+
+ let both = format!("{}/print-and-export.pdf", tmp("sending-export"));
+ do_print_with_spooler(&mut s, &json!({"output": both, "send": true, "dryRun": true}), "file.print", |_| Err(other("dry run invoked spooler"))).unwrap();
+ assert!(s.file_menu.last_print.as_ref().unwrap().get("send").is_none(), "a removed output must not leave send: true in remembered settings");
}
#[test]
diff --git a/crates/engine/src/web_cmds.rs b/crates/engine/src/web_cmds.rs
index 7175d452d..a15cb258c 100644
--- a/crates/engine/src/web_cmds.rs
+++ b/crates/engine/src/web_cmds.rs
@@ -626,13 +626,67 @@ fn quantize_rows(px: &mut [[f32; 4]], w: usize, pal: &[[u8; 3]], dither: Dither,
/// A file-name-safe slice name.
fn slice_file(name: &str) -> String {
let s: String = name.chars().map(|c| if c.is_alphanumeric() || matches!(c, '-' | '_') { c } else { '_' }).collect();
- if s.is_empty() { "slice".into() } else { s }
+ let s = if s.is_empty() { "slice".into() } else { s };
+ portable_generated_stem(s)
+}
+
+/// Generated filenames should remain usable on Windows even when a document or slice is named
+/// after a reserved device. Caller-supplied path components are still rejected below.
+fn portable_generated_stem(stem: String) -> String {
+ if is_windows_device_asset_name(&stem) { format!("{stem}_") } else { stem }
}
fn html_escape(s: &str) -> String {
s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;").replace('"', "&quot;")
}
+/// Imported slice URLs are document data. Only ordinary web/contact links and relative links
+/// become anchors; an unsupported scheme leaves the image unlinked.
+fn safe_slice_url(url: &str) -> bool {
+ if url.is_empty() || url.trim() != url || url.chars().any(|c| c.is_control() || c == '\\') {
+ return false;
+ }
+ let delimiter = url.find(['/', '?', '#']).unwrap_or(url.len());
+ let Some(colon) = url.find(':').filter(|pos| *pos < delimiter) else {
+ return true;
+ };
+ let scheme = url.get(..colon).unwrap_or_default().to_ascii_lowercase();
+ let rest = url.get(colon + 1..).unwrap_or_default();
+ match scheme.as_str() {
+ "http" | "https" | "ftp" | "ftps" => rest.strip_prefix("//").is_some_and(|host| !host.is_empty() && !host.starts_with('/')),
+ "mailto" | "tel" => !rest.is_empty(),
+ _ => false,
+ }
+}
+
+/// Keep the image folder relative to the selected export directory on every platform.
+fn web_images_folder(images: &str, cmd: &str) -> Result<String> {
+ if images.is_empty() {
+ return Ok(String::new());
+ }
+ let trimmed = images.trim_end_matches(['/', '\\']);
+ if trimmed.is_empty() {
+ return Err(bad(cmd, "imagesFolder must be a relative folder name"));
+ }
+ let parts = asset_path_components(trimmed).map_err(|e| bad(cmd, format!("imagesFolder: {e}")))?;
+ Ok(parts.join("/"))
+}
+
+fn web_output_path(dir: &str, relative: &str) -> Result<String> {
+ let root = if dir.is_empty() { "." } else { dir };
+ asset_output_path(root, relative).map(|(actual, _)| actual)
+}
+
+fn web_derived_path(dir: &str, relative: &str, native_paths: bool) -> Result<String> {
+ if native_paths {
+ web_output_path(dir, relative)
+ } else {
+ // Browser downloads use logical names, without a host filesystem to inspect.
+ asset_path_components(relative)?;
+ Ok(join(dir, relative))
+ }
+}
+
fn scale_rect(r: Rect, sx: f64, sy: f64) -> Rect {
Rect::new(
(f64::from(r.x0) * sx).round() as i32,
@@ -690,14 +744,14 @@ fn html_table(title: &str, w: u32, h: u32, cells: &[(Rect, String, String)], spa
s.push_str(&td);
}
if let Some(sp) = spacer {
- s.push_str(&format!("\t\t<td>\n\t\t\t<img src=\"{sp}\" width=\"1\" height=\"{}\" alt=\"\"></td>\n", ys[j + 1] - ys[j]));
+ s.push_str(&format!("\t\t<td>\n\t\t\t<img src=\"{}\" width=\"1\" height=\"{}\" alt=\"\"></td>\n", html_escape(sp), ys[j + 1] - ys[j]));
}
s.push_str("\t</tr>\n");
}
if let Some(sp) = spacer {
s.push_str("\t<tr>\n");
for i in 0..nc {
- s.push_str(&format!("\t\t<td>\n\t\t\t<img src=\"{sp}\" width=\"{}\" height=\"1\" alt=\"\"></td>\n", xs[i + 1] - xs[i]));
+ s.push_str(&format!("\t\t<td>\n\t\t\t<img src=\"{}\" width=\"{}\" height=\"1\" alt=\"\"></td>\n", html_escape(sp), xs[i + 1] - xs[i]));
}
s.push_str("\t\t<td></td>\n\t</tr>\n");
}
@@ -707,13 +761,18 @@ fn html_table(title: &str, w: u32, h: u32, cells: &[(Rect, String, String)], spa
/// File › Export › Save for Web (Legacy).
fn save_for_web(s: &mut Session, p: &Value) -> Result<Value> {
- save_for_web_with_writer(s, p, &mut write_file)
+ save_for_web_impl(s, p, &mut write_file, true)
}
/// Save for Web through a platform writer (native files or browser downloads).
/// The writer receives every image, spacer and HTML file. A write error stops the export;
-/// only a complete export remembers its settings and fires the export event.
+/// only a complete export remembers its settings and fires the export event. A custom writer
+/// that targets the local filesystem must enforce its own path confinement.
pub fn save_for_web_with_writer(s: &mut Session, p: &Value, write: &mut dyn FnMut(&str, &[u8]) -> Result<()>) -> Result<Value> {
+ save_for_web_impl(s, p, write, false)
+}
+
+fn save_for_web_impl(s: &mut Session, p: &Value, write: &mut dyn FnMut(&str, &[u8]) -> Result<()>, native_paths: bool) -> Result<Value> {
let cmd = "file.export.saveForWebLegacy";
if let Some(authorize) = s.authorize {
authorize(cmd, p)?;
@@ -743,6 +802,12 @@ pub fn save_for_web_with_writer(s: &mut Session, p: &Value, write: &mut dyn FnMu
.collect();
let single = p.get("path").and_then(Value::as_str).filter(|v| !v.is_empty());
let dir = p.get("dir").and_then(Value::as_str).filter(|v| !v.is_empty());
+ let mut last_web = p.clone();
+ // A trusted-markup decision applies to this export only, never to another document opened
+ // with the dialog's remembered settings.
+ if let Some(last) = last_web.as_object_mut() {
+ last.remove("trustedSliceHtml");
+ }
// Estimate only (the dialog's annotations): the whole image, or each chosen slice.
if single.is_none() && dir.is_none() {
let o = optimize(&buf.px, bw, wdoc.bounds(), &st, icc, xmp.as_deref(), dpi, false)?;
@@ -751,15 +816,16 @@ pub fn save_for_web_with_writer(s: &mut Session, p: &Value, write: &mut dyn FnMu
if let Some(path) = single.filter(|_| dir.is_none() && (all.len() == 1 || p.get("slices").is_none())) {
let o = optimize(&buf.px, bw, wdoc.bounds(), &st, icc, xmp.as_deref(), dpi, false)?;
write(path, &o.bytes)?;
- s.file_menu.last_web = Some(p.clone());
+ s.file_menu.last_web = Some(last_web);
crate::automate_cmds::fire_event(s, "export");
return Ok(json!({"files": [path], "bytes": o.bytes.len(), "width": o.width, "height": o.height, "colors": o.colors}));
}
let dir =
dir.map(str::to_string).or_else(|| single.and_then(|f| std::path::Path::new(f).parent().map(|d| d.to_string_lossy().into_owned()))).unwrap_or_default();
let html = p.get("html").and_then(Value::as_bool).unwrap_or(false);
- let images = p.get("imagesFolder").and_then(Value::as_str).unwrap_or("images").to_string();
- let base = single.map(stem).unwrap_or_else(|| slices::base_name(&doc));
+ let images = web_images_folder(p.get("imagesFolder").and_then(Value::as_str).unwrap_or("images"), cmd)?;
+ let trusted_slice_html = p.get("trustedSliceHtml").and_then(Value::as_bool).unwrap_or(false);
+ let base = portable_generated_stem(single.map(stem).unwrap_or_else(|| slices::base_name(&doc)));
let mut files = Vec::new();
let mut cells: Vec<(Rect, String, String)> = Vec::new();
let mut total = 0usize;
@@ -801,7 +867,7 @@ pub fn save_for_web_with_writer(s: &mut Session, p: &Value, write: &mut dyn FnMu
let text = if k > 0 {
String::new()
} else {
- stored.map(|s| if s.cell_text_is_html { s.cell_text.clone() } else { html_escape(&s.cell_text) }).unwrap_or_default()
+ stored.map(|s| if trusted_slice_html && s.cell_text_is_html { s.cell_text.clone() } else { html_escape(&s.cell_text) }).unwrap_or_default()
};
let bg = stored.and_then(|s| s.background).map(|c| format!(" bgcolor=\"#{:02X}{:02X}{:02X}\"", c[1], c[2], c[3])).unwrap_or_default();
cells.push((piece, bg, text));
@@ -812,12 +878,12 @@ pub fn save_for_web_with_writer(s: &mut Session, p: &Value, write: &mut dyn FnMu
let name = unique(&stem, o.ext);
let rel = if images.is_empty() { name.clone() } else { format!("{images}/{name}") };
let out = join(&dir, &rel);
- write(&out, &o.bytes)?;
+ write(&web_derived_path(&dir, &rel, native_paths)?, &o.bytes)?;
total += o.bytes.len();
files.push(out);
let alt = stored.map_or(String::new(), |s| html_escape(&s.alt));
let img = format!("\n\t\t\t<img src=\"{}\" width=\"{}\" height=\"{}\" alt=\"{alt}\">", html_escape(&rel), piece.width(), piece.height());
- let body = match stored.filter(|s| !s.url.is_empty()) {
+ let body = match stored.filter(|s| safe_slice_url(&s.url)) {
Some(s) => {
let target = if s.target.is_empty() { String::new() } else { format!(" target=\"{}\"", html_escape(&s.target)) };
format!("\n\t\t\t<a href=\"{}\"{target}>{img}</a>", html_escape(&s.url))
@@ -833,14 +899,14 @@ pub fn save_for_web_with_writer(s: &mut Session, p: &Value, write: &mut dyn FnMu
let spacer = grid.then(|| if images.is_empty() { "spacer.gif".to_string() } else { format!("{images}/spacer.gif") });
if let Some(sp) = &spacer {
let gif = photocraft_codecs::web::encode_gif_indexed(1, 1, &[0], &[[0, 0, 0]], Some(0), false).map_err(other)?;
- write(&join(&dir, sp), &gif)?;
+ write(&web_derived_path(&dir, sp, native_paths)?, &gif)?;
}
let page = html_table(&base, wdoc.size.width, wdoc.size.height, &cells, spacer.as_deref());
let hp = join(&dir, &format!("{base}.html"));
- write(&hp, page.as_bytes())?;
+ write(&web_derived_path(&dir, &format!("{base}.html"), native_paths)?, page.as_bytes())?;
html_path = Some(hp);
}
- s.file_menu.last_web = Some(p.clone());
+ s.file_menu.last_web = Some(last_web);
crate::automate_cmds::fire_event(s, "export");
Ok(json!({"files": files, "html": html_path, "bytes": total, "slices": chosen.len(), "width": wdoc.size.width, "height": wdoc.size.height}))
}
@@ -1091,6 +1157,95 @@ fn asset_settings(spec: &AssetSpec) -> WebSettings {
}
}
+fn is_windows_device_asset_name(component: &str) -> bool {
+ let stem = component.split('.').next().unwrap_or(component).trim_end_matches(' ').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"))
+}
+
+/// Layer names and `default` folders are document data, so reject unsafe output components.
+fn asset_path_components(relative: &str) -> Result<Vec<&str>> {
+ // Split both separator styles even on Unix, where a backslash would otherwise be a legal
+ // filename. This also catches Windows drive, rooted, and UNC paths on every platform.
+ let mut parts = Vec::new();
+ for part in relative.split(['/', '\\']) {
+ if part.is_empty()
+ || part == "."
+ || part == ".."
+ || part.ends_with('.')
+ || part.ends_with(' ')
+ || part.contains(':')
+ || part.contains('\0')
+ || is_windows_device_asset_name(part)
+ {
+ return Err(other(format!("asset path {relative:?} has an unsafe component {part:?}")));
+ }
+ parts.push(part);
+ }
+ Ok(parts)
+}
+
+/// Resolve a generated asset below the selected output directory. The atomic writer follows an
+/// existing file symlink, so reject it and directory symlinks before writing.
+fn asset_output_path(dir: &str, relative: &str) -> Result<(String, String)> {
+ if dir.is_empty() {
+ return Err(other("image assets need an output directory"));
+ }
+ let mut parts = asset_path_components(relative)?;
+ // Keep the caller's spelling in the result (for example /var on macOS), while writes use
+ // the canonical directory so a symlink in the selected root cannot move the destination.
+ let mut reported = std::path::PathBuf::from(dir);
+ for part in &parts {
+ reported.push(part);
+ }
+ let file = parts.pop().ok_or_else(|| other(format!("asset path {relative:?} is empty")))?;
+ let chosen_root: std::path::PathBuf = std::path::Path::new(dir).components().collect();
+ std::fs::create_dir_all(&chosen_root).map_err(|e| other(format!("asset output directory {dir:?}: {e}")))?;
+ // The caller chose this root, so a symlink to an existing directory is intentional. All
+ // document-derived components below it are checked against its canonical target.
+ let root = std::fs::canonicalize(&chosen_root).map_err(|e| other(format!("asset output directory {dir:?}: {e}")))?;
+ let mut parent = root.clone();
+ for part in parts {
+ parent.push(part);
+ match std::fs::symlink_metadata(&parent) {
+ Ok(meta) if meta.file_type().is_symlink() => {
+ return Err(other(format!("asset path {relative:?} crosses a symlink at {}", parent.display())));
+ }
+ Ok(meta) if !meta.is_dir() => {
+ return Err(other(format!("asset path {relative:?} has a non-directory at {}", parent.display())));
+ }
+ Ok(_) => {}
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
+ std::fs::create_dir(&parent).map_err(|e| other(format!("asset folder {}: {e}", parent.display())))?;
+ }
+ Err(e) => return Err(other(format!("asset folder {}: {e}", parent.display()))),
+ }
+ let actual = std::fs::canonicalize(&parent).map_err(|e| other(format!("asset folder {}: {e}", parent.display())))?;
+ if !actual.starts_with(&root) {
+ return Err(other(format!("asset path {relative:?} escapes output directory {dir:?}")));
+ }
+ parent = actual;
+ }
+ let parent = std::fs::canonicalize(&parent).map_err(|e| other(format!("asset folder {}: {e}", parent.display())))?;
+ if !parent.starts_with(&root) {
+ return Err(other(format!("asset path {relative:?} escapes output directory {dir:?}")));
+ }
+ let output = parent.join(file);
+ match std::fs::symlink_metadata(&output) {
+ Ok(meta) if meta.file_type().is_symlink() => {
+ return Err(other(format!("asset path {relative:?} points to a symlink")));
+ }
+ Ok(meta) if !meta.is_file() => {
+ return Err(other(format!("asset path {relative:?} is not a file")));
+ }
+ Ok(_) => {}
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
+ Err(e) => return Err(other(format!("asset path {relative:?}: {e}"))),
+ }
+ Ok((output.to_string_lossy().into_owned(), reported.to_string_lossy().into_owned()))
+}
+
/// Exports every asset named by `doc`'s layers into `dir`. Returns (files, errors).
pub fn generate_assets(doc: &Document, dir: &str) -> (Vec<String>, Vec<Value>) {
let dpi = f64::from(doc.resolution_dpi.max(1.0));
@@ -1117,6 +1272,9 @@ pub fn generate_assets(doc: &Document, dir: &str) -> (Vec<String>, Vec<Value>) {
for (id, spec) in &jobs {
for v in &variants {
let r = (|| -> Result<String> {
+ let (name_stem, ext) = spec.file.rsplit_once('.').unwrap_or((spec.file.as_str(), "png"));
+ let rel = format!("{}{}{}.{ext}", v.folder, name_stem, v.suffix);
+ asset_path_components(&rel)?;
let mut one = crate::layer_menu_cmds::layer_document(doc, *id)?;
one.metadata = Default::default();
let (w0, h0) = (f64::from(one.size.width), f64::from(one.size.height));
@@ -1141,17 +1299,16 @@ pub fn generate_assets(doc: &Document, dir: &str) -> (Vec<String>, Vec<Value>) {
let st = asset_settings(spec);
let p = json!({"width": tw.round().max(1.0), "height": th.round().max(1.0)});
let (wdoc, _, _) = web_document(&one, &p, &WebSettings { convert_to_srgb: true, ..st.clone() })?;
- let (name_stem, ext) = spec.file.rsplit_once('.').unwrap_or((spec.file.as_str(), "png"));
- let rel = format!("{}{}{}.{ext}", v.folder, name_stem, v.suffix);
- let out = join(dir, &rel);
if spec.format == "webp" {
+ let (out, reported) = asset_output_path(dir, &rel)?;
crate::file_cmds::save_doc(&wdoc, &out, None)?;
- return Ok(out);
+ return Ok(reported);
}
let buf = photocraft_compose::flatten(&wdoc);
let o = optimize(&buf.px, wdoc.size.width as usize, wdoc.bounds(), &st, None, None, wdoc.resolution_dpi, false)?;
+ let (out, reported) = asset_output_path(dir, &rel)?;
write_file(&out, &o.bytes)?;
- Ok(out)
+ Ok(reported)
})();
match r {
Ok(f) => files.push(f),
@@ -1221,7 +1378,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Save for Web (Legacy)…",
&["File", "Export"],
Some("Cmd+Alt+Shift+S"),
- r##"{"preset":"GIF 128 Dithered|JPEG High|PNG-24|…"?,"format":"gif|png8|png24|jpeg|wbmp"="png24","palette":"perceptual|selective|adaptive|restrictive|exact|systemMac|systemWindows|uniform"="selective","colors":2..256=256,"dither":"none|diffusion|pattern|noise"="diffusion","ditherAmount":0..100=88,"transparency":bool=true,"matte":"#rrggbb|none"="#ffffff","interlaced":bool=false,"webSnap":0..100=0,"quality":0..100=60,"progressive":bool=false,"optimized":bool=true,"embedIcc":bool=false,"metadata":"none|copyright|copyrightAndContact|all"="copyright","convertToSrgb":bool=true,"width"|"height"|"percent"? (image size),"resample":"bicubic|bilinear|nearest"?,"path":file? (whole image),"dir":folder? (one file per slice in images/),"html":bool=false,"slices":"all|user"="all","numbers":[n]?} → no path/dir: {bytes,width,height,colors} estimate; else {files, html, bytes}"##,
+ r##"{"preset":"GIF 128 Dithered|JPEG High|PNG-24|…"?,"format":"gif|png8|png24|jpeg|wbmp"="png24","palette":"perceptual|selective|adaptive|restrictive|exact|systemMac|systemWindows|uniform"="selective","colors":2..256=256,"dither":"none|diffusion|pattern|noise"="diffusion","ditherAmount":0..100=88,"transparency":bool=true,"matte":"#rrggbb|none"="#ffffff","interlaced":bool=false,"webSnap":0..100=0,"quality":0..100=60,"progressive":bool=false,"optimized":bool=true,"embedIcc":bool=false,"metadata":"none|copyright|copyrightAndContact|all"="copyright","convertToSrgb":bool=true,"width"|"height"|"percent"? (image size),"resample":"bicubic|bilinear|nearest"?,"path":file? (whole image),"dir":folder? (one file per slice in images/),"imagesFolder":relative-folder?="images","html":bool=false,"trustedSliceHtml":bool=false (only for trusted documents; emit raw no-image cell HTML),"slices":"all|user"="all","numbers":[n]?} → no path/dir: {bytes,width,height,colors} estimate; else {files, html, bytes}"##,
has_doc,
save_for_web
),
diff --git a/crates/engine/src/web_cmds/tests.rs b/crates/engine/src/web_cmds/tests.rs
index 2e0cacc03..f64e309e9 100644
--- a/crates/engine/src/web_cmds/tests.rs
+++ b/crates/engine/src/web_cmds/tests.rs
@@ -134,6 +134,22 @@ fn platform_writer_receives_slices_spacer_and_html_with_sibling_references() {
assert_eq!(s.file_menu.last_web.as_ref(), Some(&params));
}
+#[test]
+fn reserved_document_and_slice_names_export_with_portable_names() {
+ let dir = tmp("reserved-slice-names");
+ let mut s = session(8);
+ s.edit("rename", |doc, _| {
+ doc.name = "aux.psd".into();
+ Ok(())
+ })
+ .unwrap();
+ s.execute("slice.new", json!({"rect": [0, 0, 16, 16], "name": "con"})).unwrap();
+ let result = s.execute("file.export.saveForWebLegacy", json!({"dir": dir, "format": "png24", "html": true})).unwrap();
+ assert!(result["html"].as_str().unwrap().ends_with("/aux_.html"));
+ assert!(result["files"].as_array().unwrap().iter().any(|f| f.as_str().unwrap().ends_with("/con_.png")));
+ assert!(std::path::Path::new(result["html"].as_str().unwrap()).is_file());
+}
+
#[test]
fn platform_writer_failure_stops_export_and_preserves_saved_settings() {
let mut s = session(8);
@@ -249,6 +265,103 @@ fn slices_export_with_html_table() {
assert_eq!(decode(r["files"][0].as_str().unwrap()).dimensions(), (12, 12));
}
+#[test]
+fn slice_html_escapes_imported_markup_by_default_and_requires_trusted_opt_in() {
+ let dir = tmp("slice-html-safety");
+ let mut s = session(8);
+ let slice = s
+ .execute(
+ "slice.new",
+ json!({"rect": [0, 0, 24, 20], "kind": "noImage", "name": "text", "cellTextIsHtml": true,
+ "cellText": "<script>alert(1)</script><b>Trusted label</b>"}),
+ )
+ .unwrap();
+ let default = s.execute("file.export.saveForWebLegacy", json!({"format": "png24", "dir": dir, "html": true})).unwrap();
+ let page = std::fs::read_to_string(default["html"].as_str().unwrap()).unwrap();
+ assert!(page.contains("&lt;script&gt;alert(1)&lt;/script&gt;"));
+ assert!(!page.contains("<script>"));
+ assert!(page.contains("&lt;b&gt;Trusted label&lt;/b&gt;"));
+
+ let trusted_dir = tmp("slice-html-trusted");
+ let trusted = s.execute("file.export.saveForWebLegacy", json!({"format": "png24", "dir": trusted_dir, "html": true, "trustedSliceHtml": true})).unwrap();
+ let page = std::fs::read_to_string(trusted["html"].as_str().unwrap()).unwrap();
+ assert!(page.contains("<script>alert(1)</script><b>Trusted label</b>"));
+ assert!(s.file_menu.last_web.as_ref().unwrap().get("trustedSliceHtml").is_none());
+
+ let plain_dir = tmp("slice-html-plain");
+ s.execute("slice.set", json!({"slice": slice["slice"], "cellTextIsHtml": false})).unwrap();
+ let plain = s.execute("file.export.saveForWebLegacy", json!({"format": "png24", "dir": plain_dir, "html": true, "trustedSliceHtml": true})).unwrap();
+ let page = std::fs::read_to_string(plain["html"].as_str().unwrap()).unwrap();
+ assert!(page.contains("&lt;script&gt;alert(1)&lt;/script&gt;"));
+}
+
+#[test]
+fn slice_links_allow_normal_urls_and_drop_active_schemes() {
+ let dir = tmp("slice-link-safety");
+ let mut s = session(8);
+ for (x, url) in [
+ (0, "javascript:alert(1)"),
+ (10, "data:text/html,<script>alert(1)</script>"),
+ (20, "https://example.org/page?a=1&b=2"),
+ (30, "../relative/page.html#part"),
+ (40, "mailto:[email protected]"),
+ (50, "JaVa\tscript:alert(1)"),
+ ] {
+ s.execute("slice.new", json!({"rect": [x, 0, 10, 10], "name": format!("link{x}"), "url": url})).unwrap();
+ }
+ let r = s.execute("file.export.saveForWebLegacy", json!({"format": "png24", "dir": dir, "html": true, "slices": "user"})).unwrap();
+ let page = std::fs::read_to_string(r["html"].as_str().unwrap()).unwrap();
+ assert!(!page.contains("href=\"javascript:"));
+ assert!(!page.contains("href=\"data:"));
+ assert!(!page.contains("href=\"JaVa"));
+ assert!(page.contains("href=\"https://example.org/page?a=1&amp;b=2\""));
+ assert!(page.contains("href=\"../relative/page.html#part\""));
+ assert!(page.contains("href=\"mailto:[email protected]\""));
+ assert_eq!(page.matches("<a href=").count(), 3);
+}
+
+#[test]
+fn images_folder_stays_inside_export_directory_and_is_escaped_in_html() {
+ let root = tmp("slice-image-folder");
+ let dir = format!("{root}/output");
+ std::fs::create_dir_all(&dir).unwrap();
+ let mut s = session(8);
+ s.execute(
+ "slice.new",
+ json!({"rect": [0, 0, 20, 20], "name": "logo", "url": "https://example.org", "target": "x\" onclick=\"alert(1)", "alt": "x\" onerror=\"alert(1)"}),
+ )
+ .unwrap();
+ for images in ["../escaped", "..\\escaped", "/absolute", "C:\\absolute", "nested/../../escaped", "/"] {
+ assert!(s.execute("file.export.saveForWebLegacy", json!({"format": "gif", "dir": dir, "html": true, "imagesFolder": images})).is_err(), "{images}");
+ }
+ assert!(!std::path::Path::new(&format!("{root}/escaped")).exists());
+ // Windows forbids quotes in path components; an ampersand still exercises HTML escaping.
+ #[cfg(windows)]
+ let (folder, escaped_folder) = ("nested/im&files", "nested/im&amp;files");
+ #[cfg(not(windows))]
+ let (folder, escaped_folder) = ("nested/im\" onerror=\"alert(1)&", "nested/im&quot; onerror=&quot;alert(1)&amp;");
+ let r = s.execute("file.export.saveForWebLegacy", json!({"format": "gif", "dir": dir, "html": true, "imagesFolder": folder})).unwrap();
+ let page = std::fs::read_to_string(r["html"].as_str().unwrap()).unwrap();
+ assert!(page.contains(&format!("src=\"{escaped_folder}/logo.gif\"")));
+ assert!(page.contains(&format!("src=\"{escaped_folder}/spacer.gif\"")));
+ assert!(page.contains("alt=\"x&quot; onerror=&quot;alert(1)\""));
+ assert!(!page.contains("onerror=\"alert(1)\""));
+ assert!(!page.contains("onclick=\"alert(1)\""));
+ assert!(std::path::Path::new(&dir).join(folder).join("spacer.gif").is_file());
+}
+
+#[cfg(unix)]
+#[test]
+fn images_folder_rejects_existing_symlink_outside_export_directory() {
+ let dir = tmp("slice-image-symlink");
+ let outside = tmp("slice-image-outside");
+ std::os::unix::fs::symlink(&outside, format!("{dir}/linked")).unwrap();
+ let mut s = session(8);
+ s.execute("slice.new", json!({"rect": [0, 0, 20, 20], "name": "logo"})).unwrap();
+ assert!(s.execute("file.export.saveForWebLegacy", json!({"format": "gif", "dir": dir, "html": true, "imagesFolder": "linked"})).is_err());
+ assert!(std::fs::read_dir(&outside).unwrap().next().is_none());
+}
+
#[test]
fn export_preferences_drive_quick_export() {
let dir = tmp("quick");
@@ -374,10 +487,78 @@ fn image_assets_are_generated_now_and_on_save() {
d.layer_mut(lid).unwrap().name = "icon.png".into();
let (files, errors) = generate_assets(&d, &dir);
assert!(errors.is_empty(), "{errors:?}");
- assert_eq!(files, vec![format!("{dir}/[email protected]")]);
+ assert_eq!(files.iter().map(|p| std::path::PathBuf::from(p.as_str())).collect::<Vec<_>>(), vec![std::path::Path::new(&dir).join("[email protected]")]);
assert_eq!(decode(&files[0]).dimensions(), (128, 80));
}
+#[test]
+fn image_assets_reject_traversal_from_names_and_defaults() {
+ let base = tmp("asset-path-guard");
+ let dir = format!("{base}/output");
+ std::fs::create_dir_all(&dir).unwrap();
+ let outside = tmp("asset-path-outside");
+ let mut d = (*session(8).active().unwrap().doc).clone();
+ let id = d.layers[1].id;
+ d.layer_mut(id).unwrap().name =
+ format!("nested/ok.png, ../escaped.png, ..\\backslash.png, {outside}/absolute.png, C:\\drive\\escape.png, CON.png, aux/escape.png, foo./trailing.png");
+ let (files, errors) = generate_assets(&d, &dir);
+ assert_eq!(files.iter().map(|p| std::path::PathBuf::from(p.as_str())).collect::<Vec<_>>(), vec![std::path::Path::new(&dir).join("nested").join("ok.png")]);
+ assert_eq!(errors.len(), 7, "{errors:?}");
+ assert!(errors.iter().all(|e| e["error"].as_str().unwrap().contains("unsafe component")), "{errors:?}");
+ assert!(!std::path::Path::new(&format!("{base}/escaped.png")).exists());
+ assert!(!std::path::Path::new(&format!("{outside}/absolute.png")).exists());
+
+ d.layer_mut(id).unwrap().name = "safe.png".into();
+ d.layers.push(Layer::new(
+ "default ../ + /outside/ + ..\\bad/ + C:\\drive/ + 50% nested/",
+ LayerContent::Group(photocraft_doc::Group { children: vec![], expanded: false, artboard: None }),
+ ));
+ let (files, errors) = generate_assets(&d, &dir);
+ assert_eq!(
+ files.iter().map(|p| std::path::PathBuf::from(p.as_str())).collect::<Vec<_>>(),
+ vec![std::path::Path::new(&dir).join("nested").join("safe.png")]
+ );
+ assert_eq!(errors.len(), 4, "{errors:?}");
+ assert!(errors.iter().all(|e| e["error"].as_str().unwrap().contains("unsafe component")), "{errors:?}");
+}
+
+#[cfg(unix)]
+#[test]
+fn image_assets_reject_existing_symlinks_in_folders_and_files() {
+ let dir = tmp("asset-symlink-guard");
+ let outside = tmp("asset-symlink-outside");
+ let sentinel = format!("{outside}/sentinel.png");
+ std::fs::write(&sentinel, b"unchanged").unwrap();
+ let webp_sentinel = format!("{outside}/sentinel.webp");
+ std::fs::write(&webp_sentinel, b"also unchanged").unwrap();
+ std::os::unix::fs::symlink(&outside, format!("{dir}/linked")).unwrap();
+ std::os::unix::fs::symlink(&sentinel, format!("{dir}/leaf.png")).unwrap();
+ std::os::unix::fs::symlink(&webp_sentinel, format!("{dir}/leaf.webp")).unwrap();
+ let mut d = (*session(8).active().unwrap().doc).clone();
+ let id = d.layers[1].id;
+ d.layer_mut(id).unwrap().name = "linked/new/sub.png, leaf.png, leaf.webp, good/safe.png".into();
+ let (files, errors) = generate_assets(&d, &dir);
+ assert_eq!(files, vec![format!("{dir}/good/safe.png")]);
+ assert_eq!(errors.len(), 3, "{errors:?}");
+ assert!(errors.iter().all(|e| e["error"].as_str().unwrap().contains("symlink")), "{errors:?}");
+ assert!(!std::path::Path::new(&format!("{outside}/new")).exists());
+ assert_eq!(std::fs::read(&sentinel).unwrap(), b"unchanged");
+ assert_eq!(std::fs::read(&webp_sentinel).unwrap(), b"also unchanged");
+
+ let linked_root = format!("{dir}/rootlink");
+ std::os::unix::fs::symlink(&outside, &linked_root).unwrap();
+ d.layer_mut(id).unwrap().name = "root.png".into();
+ let (files, errors) = generate_assets(&d, &format!("{linked_root}/"));
+ assert!(errors.is_empty(), "{errors:?}");
+ assert_eq!(files, vec![format!("{linked_root}/root.png")]);
+ assert!(std::path::Path::new(&format!("{outside}/root.png")).is_file());
+
+ let mut s = session(8);
+ let exported = s.execute("file.export.saveForWebLegacy", json!({"dir": linked_root, "format": "png24", "html": true})).unwrap();
+ assert!(exported["html"].as_str().unwrap().ends_with("/rootlink/web.html"));
+ assert!(std::path::Path::new(&format!("{outside}/web.html")).is_file());
+}
+
#[test]
fn web_settings_from_params() {
let st = WebSettings::from_params(&json!({"preset": "GIF 32 No Dither", "matte": "none", "webSnap": 50}), "x").unwrap();
diff --git a/crates/format/src/store.rs b/crates/format/src/store.rs
index f90e8ebef..674c99f21 100644
--- a/crates/format/src/store.rs
+++ b/crates/format/src/store.rs
@@ -1,7 +1,7 @@
//! Object storage (ZIP or directory), incremental writer and loader.
use std::collections::{BTreeMap, HashMap, HashSet};
-use std::io::Read;
+use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Weak};
use std::time::SystemTime;
@@ -444,14 +444,137 @@ fn file_signature(metadata: &std::fs::Metadata) -> Option<FileSignature> {
}
fn path_signature(path: &Path) -> Result<Option<FileSignature>> {
- match std::fs::metadata(path) {
+ match std::fs::symlink_metadata(path) {
Ok(metadata) if metadata.is_file() => Ok(file_signature(&metadata)),
- Ok(_) => Ok(None),
+ Ok(_) => Err(unsafe_bundle_entry(path)),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(e) => Err(e.into()),
}
}
+fn unsafe_bundle_entry(path: &Path) -> FormatError {
+ FormatError::Io(std::io::Error::new(
+ std::io::ErrorKind::InvalidData,
+ format!("refusing directory bundle save: {} is a symlink or not a regular file", path.display()),
+ ))
+}
+
+/// The generic atomic writer intentionally follows a destination symlink. Directory bundles
+/// must reject one instead: all of their managed entries stay below the bundle root.
+fn plain_file_or_missing(path: &Path) -> Result<()> {
+ match std::fs::symlink_metadata(path) {
+ Ok(metadata) if metadata.is_file() => Ok(()),
+ Ok(_) => Err(unsafe_bundle_entry(path)),
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
+ Err(e) => Err(e.into()),
+ }
+}
+
+fn plain_directory_or_missing(path: &Path) -> Result<()> {
+ match std::fs::symlink_metadata(path) {
+ Ok(metadata) if metadata.is_dir() => Ok(()),
+ Ok(_) => Err(FormatError::Io(std::io::Error::new(
+ std::io::ErrorKind::InvalidData,
+ format!("refusing directory bundle save: {} is a symlink or not a directory", path.display()),
+ ))),
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
+ Err(e) => Err(e.into()),
+ }
+}
+
+/// Use the canonical root after creation so a later replacement of the caller's path cannot
+/// redirect subsequent bundle operations. The caller may choose a symlinked root, but managed
+/// subdirectories and files below its resolved target must not be symlinks.
+fn bundle_root(dir: &Path) -> Result<PathBuf> {
+ let dir: PathBuf = dir.components().collect();
+ std::fs::create_dir_all(&dir)?;
+ let root = std::fs::canonicalize(&dir)?;
+ plain_directory_or_missing(&root)?;
+ for sub in ["tiles", "blobs", "composite"] {
+ let path = root.join(sub);
+ plain_directory_or_missing(&path)?;
+ if !path.exists() {
+ match std::fs::create_dir(&path) {
+ Ok(()) => {}
+ Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {}
+ Err(e) => return Err(e.into()),
+ }
+ }
+ plain_directory_or_missing(&path)?;
+ if std::fs::canonicalize(&path)? != path {
+ return Err(unsafe_bundle_entry(&path));
+ }
+ }
+ Ok(root)
+}
+
+fn validate_bundle_file(root: &Path, path: &Path) -> Result<()> {
+ let parent = path.parent().ok_or_else(|| unsafe_bundle_entry(path))?;
+ if parent != root && parent != root.join("tiles") && parent != root.join("blobs") && parent != root.join("composite") {
+ return Err(unsafe_bundle_entry(path));
+ }
+ plain_directory_or_missing(parent)?;
+ if std::fs::canonicalize(parent)? != parent {
+ return Err(unsafe_bundle_entry(parent));
+ }
+ plain_file_or_missing(path)
+}
+
+fn write_bundle_file(root: &Path, path: &Path, data: &[u8]) -> Result<()> {
+ validate_bundle_file(root, path)?;
+ let parent = path.parent().ok_or_else(|| unsafe_bundle_entry(path))?;
+ let name = path.file_name().ok_or_else(|| unsafe_bundle_entry(path))?;
+ let mut temporary = None;
+ for _ in 0..8 {
+ let candidate = parent.join(crate::atomic::temp_name(&name.to_string_lossy()));
+ match std::fs::OpenOptions::new().write(true).create_new(true).open(&candidate) {
+ Ok(file) => {
+ temporary = Some((candidate, file));
+ break;
+ }
+ Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {}
+ Err(e) => return Err(e.into()),
+ }
+ }
+ let (tmp, mut file) = temporary.ok_or_else(|| {
+ FormatError::Io(std::io::Error::new(std::io::ErrorKind::AlreadyExists, format!("could not create a temporary file beside {}", path.display())))
+ })?;
+ let result = (|| -> Result<()> {
+ // The parent may have changed between validation and create_new. Check the new file's
+ // resolved location before putting document bytes into it.
+ if std::fs::canonicalize(&tmp)? != tmp {
+ return Err(unsafe_bundle_entry(&tmp));
+ }
+ validate_bundle_file(root, path)?;
+ file.write_all(data)?;
+ file.sync_all()?;
+ drop(file);
+ // Preserve the existing mode where possible, as the generic atomic writer does.
+ if let Ok(permissions) = std::fs::metadata(path).map(|m| m.permissions()) {
+ let _ = std::fs::set_permissions(&tmp, permissions);
+ }
+ // Recheck the parent and target just before publishing. rename replaces a symlink
+ // itself, never its referent, even if one appears after this check.
+ validate_bundle_file(root, path)?;
+ crate::atomic::retry_rename(crate::atomic::RenameRetry::platform(), || std::fs::rename(&tmp, path))?;
+ #[cfg(unix)]
+ {
+ let _ = std::fs::File::open(parent).and_then(|d| d.sync_all());
+ }
+ Ok(())
+ })();
+ if result.is_err() && validate_bundle_file(root, &tmp).is_ok() {
+ let _ = std::fs::remove_file(&tmp);
+ }
+ result
+}
+
+fn remove_bundle_file(root: &Path, path: &Path) -> Result<()> {
+ validate_bundle_file(root, path)?;
+ std::fs::remove_file(path)?;
+ Ok(())
+}
+
fn existing_object_is_valid(path: &Path, object: &Object, what: &str) -> Result<(bool, Option<FileSignature>)> {
let mut file = match std::fs::File::open(path) {
Ok(file) => file,
@@ -609,16 +732,19 @@ impl PcraftWriter {
/// rewrites missing or damaged objects, then writes the manifest
/// atomically and removes unreferenced objects.
pub fn save_dir(&mut self, doc: &Document, dir: &Path, opts: &SaveOptions) -> Result<SaveStats> {
+ let canonical_dir = bundle_root(dir)?;
+ let dir = canonical_dir.as_path();
+ let existing = list_objects(dir)?;
+ // Reject a hostile existing entry before writing any object or manifest. This also
+ // covers entries that this save would otherwise leave untouched or garbage-collect.
+ for path in [MANIFEST, THUMB, COMPOSITE] {
+ validate_bundle_file(dir, &dir.join(path))?;
+ }
let p = self.prepare(doc, opts)?;
let mut stats = p.stats;
- for sub in ["tiles", "blobs", "composite"] {
- std::fs::create_dir_all(dir.join(sub))?;
- }
- let canonical_dir = std::fs::canonicalize(dir)?;
if self.verified_directory.as_ref().is_none_or(|cache| cache.directory != canonical_dir) {
- self.verified_directory = Some(DirectoryVerificationCache { directory: canonical_dir, ..Default::default() });
+ self.verified_directory = Some(DirectoryVerificationCache { directory: canonical_dir.clone(), ..Default::default() });
}
- let existing = list_objects(dir)?;
let generation = match &mut self.verified_directory {
Some(cache) => {
cache.generation = cache.generation.saturating_add(1);
@@ -629,6 +755,9 @@ impl PcraftWriter {
let recheck = self.rolling_recheck(&p.objects);
for (path, obj) in &p.objects {
let object_path = dir.join(path);
+ // bundle_root and list_objects validated the fixed parent directories once. Check
+ // each leaf here; write_bundle_file rechecks its parent around every mutation.
+ plain_file_or_missing(&object_path)?;
let signature = path_signature(&object_path)?;
let already_verified = !recheck.contains(path)
&& signature.is_some_and(|signature| {
@@ -658,7 +787,7 @@ impl PcraftWriter {
Object::Tile(..) => stats.tiles_written += 1,
Object::Blob(_) => stats.blobs_written += 1,
}
- write_atomic(&object_path, &obj.compressed())?;
+ write_bundle_file(dir, &object_path, &obj.compressed())?;
let written = path_signature(&object_path)?;
if let Some(cache) = &mut self.verified_directory {
match written {
@@ -672,20 +801,25 @@ impl PcraftWriter {
}
}
for (name, data) in &p.previews {
- write_atomic(&dir.join(name), data)?;
+ write_bundle_file(dir, &dir.join(name), data)?;
}
for stale in [THUMB, COMPOSITE] {
if !p.previews.iter().any(|(n, _)| *n == stale) {
- let _ = std::fs::remove_file(dir.join(stale));
+ let path = dir.join(stale);
+ validate_bundle_file(dir, &path)?;
+ match remove_bundle_file(dir, &path) {
+ Err(FormatError::Io(e)) if e.kind() == std::io::ErrorKind::NotFound => {}
+ other => other?,
+ }
}
}
- write_atomic(&dir.join(MANIFEST), &p.manifest)?;
+ write_bundle_file(dir, &dir.join(MANIFEST), &p.manifest)?;
// The manifest is committed: the save has succeeded. Removing objects it no longer
// references is best-effort housekeeping (a vanished or locked file must not turn a
// complete save into a reported failure); a leftover is retried on the next save.
for path in existing {
if !p.objects.contains_key(&path) {
- if std::fs::remove_file(dir.join(&path)).is_ok() {
+ if remove_bundle_file(dir, &dir.join(&path)).is_ok() {
stats.objects_removed += 1;
}
if let Some(cache) = &mut self.verified_directory {
@@ -736,12 +870,28 @@ impl PcraftWriter {
fn list_objects(dir: &Path) -> Result<HashSet<String>> {
let mut out = HashSet::new();
for sub in ["tiles", "blobs"] {
- let rd = std::fs::read_dir(dir.join(sub))?;
+ let object_dir = dir.join(sub);
+ plain_directory_or_missing(&object_dir)?;
+ if std::fs::canonicalize(&object_dir)? != object_dir {
+ return Err(unsafe_bundle_entry(&object_dir));
+ }
+ let rd = std::fs::read_dir(&object_dir)?;
for e in rd {
let e = e?;
let name = e.file_name().to_string_lossy().into_owned();
if name.ends_with(".zst") {
- out.insert(format!("{sub}/{name}"));
+ let path = e.path();
+ match std::fs::symlink_metadata(&path) {
+ Ok(metadata) if metadata.file_type().is_symlink() => return Err(unsafe_bundle_entry(&path)),
+ Ok(metadata) if metadata.is_file() => {
+ out.insert(format!("{sub}/{name}"));
+ }
+ // Stale directories cannot be removed with remove_file; leave them for later
+ // cleanup without failing a save of otherwise valid content.
+ Ok(_) => {}
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
+ Err(e) => return Err(e.into()),
+ }
}
}
}
diff --git a/crates/format/tests/roundtrip.rs b/crates/format/tests/roundtrip.rs
index d12618366..42dbfae5c 100644
--- a/crates/format/tests/roundtrip.rs
+++ b/crates/format/tests/roundtrip.rs
@@ -257,6 +257,103 @@ fn directory_incremental_and_gc() {
std::fs::remove_dir_all(dir).unwrap();
}
+#[cfg(unix)]
+#[test]
+fn directory_save_rejects_object_directory_symlink_without_deleting_external_objects() {
+ use std::os::unix::fs::symlink;
+
+ let doc = rich_doc(ColorMode::Rgb, SampleType::U8);
+ let dir = temp_dir("symlink-object-dir");
+ let outside = temp_dir("symlink-object-dir-outside");
+ let external_object = outside.join("unrelated.zst");
+ std::fs::write(&external_object, b"keep this object").unwrap();
+ symlink(&outside, dir.join("tiles")).unwrap();
+
+ assert!(PcraftWriter::new().save_dir(&doc, &dir, &SaveOptions::default()).is_err());
+ assert_eq!(std::fs::read(&external_object).unwrap(), b"keep this object");
+ assert!(!dir.join("manifest.json").exists());
+
+ std::fs::remove_file(dir.join("tiles")).unwrap();
+ std::fs::remove_dir_all(dir).unwrap();
+ std::fs::remove_dir_all(outside).unwrap();
+}
+
+#[cfg(unix)]
+#[test]
+fn directory_save_rejects_object_symlink_without_overwriting_target() {
+ use std::os::unix::fs::symlink;
+
+ let doc = rich_doc(ColorMode::Rgb, SampleType::U8);
+ let dir = temp_dir("symlink-object");
+ let outside = temp_dir("symlink-object-outside");
+ let mut writer = PcraftWriter::new();
+ writer.save_dir(&doc, &dir, &SaveOptions::default()).unwrap();
+ let object = std::fs::read_dir(dir.join("tiles")).unwrap().next().unwrap().unwrap().path();
+ std::fs::remove_file(&object).unwrap();
+ let external_object = outside.join("external.zst");
+ std::fs::write(&external_object, b"do not overwrite").unwrap();
+ symlink(&external_object, &object).unwrap();
+
+ assert!(writer.save_dir(&doc, &dir, &SaveOptions::default()).is_err());
+ assert_eq!(std::fs::read(&external_object).unwrap(), b"do not overwrite");
+ assert!(std::fs::symlink_metadata(&object).unwrap().file_type().is_symlink());
+
+ std::fs::remove_dir_all(dir).unwrap();
+ std::fs::remove_dir_all(outside).unwrap();
+}
+
+#[cfg(unix)]
+#[test]
+fn directory_save_accepts_chosen_root_symlink_but_rejects_preview_symlink() {
+ use std::os::unix::fs::symlink;
+
+ let doc = rich_doc(ColorMode::Rgb, SampleType::U8);
+ let outside = temp_dir("symlink-preview-outside");
+ let root_link_parent = temp_dir("symlink-root-parent");
+ let root_link = root_link_parent.join("linked.pcraft");
+ symlink(&outside, &root_link).unwrap();
+ PcraftWriter::new().save_dir(&doc, &root_link, &SaveOptions::default()).unwrap();
+ assert_eq!(load_path(&root_link).unwrap(), doc);
+ let trailing_separator = std::path::PathBuf::from(format!("{}/", root_link.display()));
+ PcraftWriter::new().save_dir(&doc, &trailing_separator, &SaveOptions::default()).unwrap();
+ assert!(outside.join("manifest.json").is_file());
+
+ let dir = temp_dir("symlink-preview");
+ let external_preview = outside.join("preview.png");
+ std::fs::write(&external_preview, b"keep preview").unwrap();
+ std::fs::create_dir(dir.join("composite")).unwrap();
+ symlink(&external_preview, dir.join("composite/preview.png")).unwrap();
+ let opts = SaveOptions { composite: Some(Rgba8Image::new(2, 2)), ..Default::default() };
+ assert!(PcraftWriter::new().save_dir(&doc, &dir, &opts).is_err());
+ assert_eq!(std::fs::read(&external_preview).unwrap(), b"keep preview");
+ assert!(!dir.join("manifest.json").exists());
+
+ std::fs::remove_file(root_link).unwrap();
+ std::fs::remove_dir_all(root_link_parent).unwrap();
+ std::fs::remove_dir_all(dir).unwrap();
+ std::fs::remove_dir_all(outside).unwrap();
+}
+
+#[cfg(unix)]
+#[test]
+fn directory_save_rejects_manifest_symlink_without_overwriting_target() {
+ use std::os::unix::fs::symlink;
+
+ let doc = rich_doc(ColorMode::Rgb, SampleType::U8);
+ let dir = temp_dir("symlink-manifest");
+ let outside = temp_dir("symlink-manifest-outside");
+ let external_manifest = outside.join("external.json");
+ std::fs::write(&external_manifest, b"keep manifest").unwrap();
+ symlink(&external_manifest, dir.join("manifest.json")).unwrap();
+
+ assert!(PcraftWriter::new().save_dir(&doc, &dir, &SaveOptions::default()).is_err());
+ assert_eq!(std::fs::read(&external_manifest).unwrap(), b"keep manifest");
+ assert_eq!(std::fs::read_dir(dir.join("tiles")).unwrap().count(), 0);
+
+ std::fs::remove_dir_all(dir).unwrap();
+ std::fs::remove_dir_all(outside).unwrap();
+}
+
#[test]
fn identical_tiles_are_stored_once() {
let mut doc = Document::new("d", photocraft_doc::Size::new(10, 10), ColorMode::Rgb, SampleType::U8);
diff --git a/crates/ui-egui/src/file_ui.rs b/crates/ui-egui/src/file_ui.rs
index 8b96a51a3..8481ab617 100644
--- a/crates/ui-egui/src/file_ui.rs
+++ b/crates/ui-egui/src/file_ui.rs
@@ -978,4 +978,18 @@ mod tests {
assert!(r["dialog"].is_u64(), "{id}");
}
}
+
+ #[test]
+ fn print_dialog_does_not_inherit_scripted_send_override() {
+ for send in [false, true] {
+ let (mut app, ctx) = app();
+ let out = std::env::temp_dir().join(format!("pc-printui-state-{}-{send}.pdf", std::process::id())).to_string_lossy().into_owned();
+ app.session.execute("file.print", json!({"output": out, "send": send, "dryRun": true})).unwrap();
+ assert!(app.session.file_menu.last_print.as_ref().unwrap().get("send").is_none());
+ let r = crate::menus::invoke(&mut app, &ctx, "file.print", json!({})).unwrap();
+ let id = r["dialog"].as_u64().unwrap();
+ assert!(app.ui.dialog_mut(id).unwrap().fields.get("send").is_none());
+ std::fs::remove_file(out).unwrap();
+ }
+ }
}