diff --git a/.github/workflows/actions.lock b/.github/workflows/actions.lock index 46d7b8d3c..e78310f7f 100644 --- a/.github/workflows/actions.lock +++ b/.github/workflows/actions.lock @@ -46,6 +46,7 @@ workflows: - 'actions/checkout@v7.0.1' - 'dtolnay/rust-toolchain@stable' - 'step-security/harden-runner@v2.22.4' + '.github/workflows/full-validation.yml': [] '.github/workflows/house-rules.yml': [] '.github/workflows/jpeg.yml': - 'actions/checkout@v7.0.1' @@ -144,18 +145,8 @@ dependencies: commit: 'sha1-1d88384fd173af6ecb012dfd0264a306b711241a' owner_id: 88700172 repo_id: 422287306 - 'step-security/rust-cache@v2.9.2': - ref: 'v2.9.2' - commit: 'sha1-8871c8ba063416da7c32246932ea6ae08700453e' - owner_id: 88700172 - repo_id: 822636713 'step-security/taiki-e-install-action@v2.87.32': ref: 'v2.87.32' commit: 'sha1-76747d22a7567cc4438546a84f11bdf18e670ab8' owner_id: 88700172 repo_id: 1382753260 - 'swatinem/rust-cache@v2.9.3': - ref: 'v2.9.3' - commit: 'sha1-d1527c8f67ef9af357290475d4af4b0fab8f12e0' - owner_id: 580492 - repo_id: 298565987 diff --git a/.github/workflows/full-validation.yml b/.github/workflows/full-validation.yml new file mode 100644 index 000000000..85ad96f2f --- /dev/null +++ b/.github/workflows/full-validation.yml @@ -0,0 +1,64 @@ +name: Full validation + +# Add full-validation to a PR for uncapped validation of its merge ref. Keep the label across pushes. +# Fast Workspace checks are not substitutes for these six completed native/PDF gate checks. +on: + pull_request: + types: [opened, synchronize, reopened, labeled] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + # An unrelated label event must not cancel an active full run. + group: full-validation-${{ github.event.action == 'labeled' && github.event.label.name != 'full-validation' && github.run_id || github.event.pull_request.number || github.run_id }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + native: + if: >- + github.event_name == 'workflow_dispatch' || + (contains(github.event.pull_request.labels.*.name, 'full-validation') && + (github.event.action != 'labeled' || github.event.label.name == 'full-validation')) + name: Full native + uses: storytold/craft-common-actions/.github/workflows/gate.yml@main + with: + os: '["ubuntu-latest","windows-latest","macos-latest"]' + select-os: '[]' + timeout-minutes: 120 + tools: "" + packages: mesa-vulkan-drivers libvulkan1 + craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 + linux-env: WGPU_BACKEND=vulkan + windows-env: CRAFT_PRINT_REQUIRE_QUEUE=1 + env: CRAFT_PRINT_REQUIRE_QUEUE=0 + setup-command: bash scripts/ci-test-inputs.sh + command: | + python scripts/test-full-validation.py + bash scripts/ci-full-validation.sh + + pdf-contracts: + if: >- + github.event_name == 'workflow_dispatch' || + (contains(github.event.pull_request.labels.*.name, 'full-validation') && + (github.event.action != 'labeled' || github.event.label.name == 'full-validation')) + name: Full PDF contracts + uses: storytold/craft-common-actions/.github/workflows/gate.yml@main + with: + os: '["ubuntu-latest","windows-latest","macos-latest"]' + select-os: '[]' + timeout-minutes: 120 + tools: "" + craft-fonts-ref: "" + require-craft-fonts: false + env: RUSTFLAGS=--cfg craft_pdf_unicode_fixtures + setup-command: | + python scripts/test-fetch-pdf-test-fonts.py + python scripts/fetch-pdf-test-fonts.py "$RUNNER_TEMP/craft-pdf-test-fonts" + echo "CRAFT_PDF_TEST_FONT_DIR=$RUNNER_TEMP/craft-pdf-test-fonts" >> "$GITHUB_ENV" + command: | + unset CRAFT_HOSTILE_DIVISOR PROPTEST_CASES + cargo clippy -p craft-pdf --all-targets --all-features --locked -- -D warnings + cargo test -p craft-pdf --all-features --locked + cargo test --manifest-path crates/pdf/read-only-contract/Cargo.toml --locked diff --git a/.github/workflows/workspace.yml b/.github/workflows/workspace.yml index af7e04769..5a9e4989d 100644 --- a/.github/workflows/workspace.yml +++ b/.github/workflows/workspace.yml @@ -64,7 +64,12 @@ jobs: python3 scripts/test-workspace-concurrency.py python3 scripts/test-workspace-tests.py fi - cargo fmt --check + # One rustfmt call gets every source root of the workspace, which is longer than + # Windows allows for a command line (os error 206). rustfmt's result is the same on + # every system, so the Linux and macOS legs check it. + if [ "$RUNNER_OS" != Windows ]; then + cargo fmt --check + fi cargo clippy --workspace --all-targets --locked -- -D warnings cargo clippy --workspace --all-targets --all-features --locked -- -D warnings command: | diff --git a/Cargo.lock b/Cargo.lock index 5147fa867..d6e7d3970 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -232,6 +232,17 @@ version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" +[[package]] +name = "apple-native-keyring-store" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b350bfd03649e07aa05c0a81b3e15934374e585c98204a57e20b9d49f49bb9a" +dependencies = [ + "keyring-core", + "log", + "security-framework", +] + [[package]] name = "arbitrary" version = "1.5.0" @@ -1557,6 +1568,16 @@ dependencies = [ "ureq", ] +[[package]] +name = "craft-ai-agents" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-ai-integrations?rev=35e0352666a117407d62230a6c6c2366f3e21a3b#35e0352666a117407d62230a6c6c2366f3e21a3b" +dependencies = [ + "dirs", + "serde", + "serde_json", +] + [[package]] name = "craft-ai-core" version = "0.1.0" @@ -1675,10 +1696,15 @@ dependencies = [ name = "craft-control" version = "0.1.0" dependencies = [ + "craft-ai-agents", + "craft-atomic", + "craft-flags", "getrandom 0.3.4", + "log", "proptest", "serde", "serde_json", + "tempfile", ] [[package]] @@ -1801,6 +1827,7 @@ dependencies = [ "craft-wordmodel", "image", "log", + "md4", "miniz_oxide 0.9.1", "proptest", "serde_json", @@ -1921,6 +1948,16 @@ dependencies = [ "zip 9.1.3", ] +[[package]] +name = "craft-esign" +version = "0.1.0" +dependencies = [ + "craft-cloud", + "serde", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "craft-evm" version = "0.1.0" @@ -3178,6 +3215,21 @@ dependencies = [ "weezl 0.2.1", ] +[[package]] +name = "craft-suite-account" +version = "0.1.0" +dependencies = [ + "dirs", + "keyring", + "keyring-core", + "log", + "serde", + "serde_json", + "sha2 0.10.9", + "tempfile", + "zeroize", +] + [[package]] name = "craft-svg" version = "0.1.0" @@ -3297,6 +3349,7 @@ name = "craft-ui" version = "0.1.0" dependencies = [ "craft-cloud", + "craft-esign", "craft-fonts-build", "craft-i18n", "eframe", @@ -4446,7 +4499,7 @@ dependencies = [ "ff 0.13.1", "generic-array", "group 0.13.0", - "hkdf", + "hkdf 0.12.4", "pem-rfc7468 0.7.0", "pkcs8 0.10.2", "rand_core 0.6.4", @@ -5095,6 +5148,17 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + [[package]] name = "futures-sink" version = "0.3.34" @@ -5115,6 +5179,7 @@ checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" dependencies = [ "futures-core", "futures-io", + "futures-macro", "futures-sink", "futures-task", "memchr", @@ -5724,6 +5789,15 @@ dependencies = [ "hmac 0.12.1", ] +[[package]] +name = "hkdf" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4aaa26c720c68b866f2c96ef5c1264b3e6f473fe5d4ce61cd44bbe913e553018" +dependencies = [ + "hmac 0.13.0", +] + [[package]] name = "hmac" version = "0.12.1" @@ -6705,6 +6779,27 @@ dependencies = [ "serde", ] +[[package]] +name = "keyring" +version = "4.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2270074a3d26bcac93c1dc5d2845eb4c089e8d761ccf6e0ea266a16004640627" +dependencies = [ + "apple-native-keyring-store", + "keyring-core", + "windows-native-keyring-store", + "zbus-secret-service-keyring-store", +] + +[[package]] +name = "keyring-core" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29fbf4b551298c67925f38cf341a1ada797a75f1837bdf8ae1fc8e2ebc6efb59" +dependencies = [ + "log", +] + [[package]] name = "khronos-egl" version = "6.0.0" @@ -7000,6 +7095,15 @@ dependencies = [ "digest 0.11.3", ] +[[package]] +name = "md4" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd76fb0fd6b2e4be62a73f8e0858ca97f81babcb1af322dcaca196f735f17f80" +dependencies = [ + "digest 0.11.3", +] + [[package]] name = "memchr" version = "2.8.3" @@ -8179,7 +8283,7 @@ dependencies = [ "generic-array", "getrandom 0.2.17", "hex", - "hkdf", + "hkdf 0.12.4", "idea", "k256", "log", @@ -9744,6 +9848,25 @@ dependencies = [ "zeroize", ] +[[package]] +name = "secret-service" +version = "5.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5107b24b91445dd2aa449a258a1807b63240942157292354dc5bfdbeb8bc6db8" +dependencies = [ + "aes 0.9.4", + "cbc", + "futures-util", + "getrandom 0.4.3", + "hkdf 0.13.0", + "hybrid-array", + "num", + "once_cell", + "serde", + "sha2 0.11.1", + "zbus", +] + [[package]] name = "security-framework" version = "3.7.0" @@ -12553,6 +12676,19 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" +[[package]] +name = "windows-native-keyring-store" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "063426e76fdec7438d56bb777f67e318a84a25c707b07e575cb8b78e10c028f8" +dependencies = [ + "byteorder", + "keyring-core", + "regex", + "windows-sys 0.61.2", + "zeroize", +] + [[package]] name = "windows-numerics" version = "0.3.1" @@ -13096,6 +13232,17 @@ dependencies = [ "zvariant", ] +[[package]] +name = "zbus-secret-service-keyring-store" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74801d001b9e7729adb4f1825b67b398185fed424749aa3d8bacf70417137d9a" +dependencies = [ + "keyring-core", + "secret-service", + "zbus", +] + [[package]] name = "zbus_macros" version = "5.19.0" diff --git a/Cargo.toml b/Cargo.toml index ddb423c09..25342c02a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -59,6 +59,8 @@ craft-gzip = { path = "crates/gzip" } craft-gridcraft-format = { path = "crates/gridcraft-format" } craft-aaf = { path = "crates/aaf" } craft-atomic = { path = "crates/atomic" } +# The ArtCraft Launcher's app list for AI agents (storytold/craft-ai-integrations, crates/ai-agents). +craft-ai-agents = { git = "https://github.com/storytold/craft-ai-integrations", rev = "35e0352666a117407d62230a6c6c2366f3e21a3b" } craft-dex = { path = "crates/dex" } craft-xtask = { path = "crates/xtask" } craft-captions = { path = "crates/captions" } @@ -96,6 +98,7 @@ craft-dpx = { path = "crates/dpx" } craft-dwg = { path = "crates/dwg" } craft-fcproj-format = { path = "crates/fcproj-format" } craft-ecproj-format = { path = "crates/ecproj-format" } +craft-esign = { path = "crates/esign" } craft-figma-rest = { path = "crates/figma-rest" } craft-exr = { path = "crates/exr" } craft-flags = { path = "crates/flags" } @@ -174,6 +177,7 @@ craft-settings = { path = "crates/settings" } craft-scraft-format = { path = "crates/scraft-format" } craft-time = { path = "crates/time" } craft-silhouette-studio = { path = "crates/silhouette-studio" } +craft-suite-account = { path = "crates/suite-account" } craft-svg = { path = "crates/svg" } craft-stencilcraft-format = { path = "crates/stencilcraft-format" } craft-stencilcraft-document = { path = "crates/stencilcraft-document" } diff --git a/crates/control/Cargo.toml b/crates/control/Cargo.toml index 0a18ccc99..5c4a90242 100644 --- a/crates/control/Cargo.toml +++ b/crates/control/Cargo.toml @@ -10,6 +10,12 @@ repository.workspace = true [lints] workspace = true +[features] +default = [] +# AI agents in the open window (desktop): the ArtCraft Launcher's switch, the connection file and +# the `-cli mcp` side that finds the open window. The agent settings build without it. +agents = ["dep:craft-ai-agents", "dep:craft-atomic", "dep:craft-flags", "dep:log"] + [dependencies] serde = { workspace = true } serde_json = { workspace = true } @@ -18,6 +24,16 @@ serde_json = { workspace = true } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] # The per-launch control token: 32 random bytes from the operating system (MIT OR Apache-2.0). getrandom = "0.3" +# The launcher's app list, read in one place for the launcher, the gateway and every app (MIT OR Apache-2.0, ours). +craft-ai-agents = { workspace = true, optional = true } +craft-atomic = { workspace = true, optional = true } +craft-flags = { workspace = true, optional = true } +log = { workspace = true, optional = true } [dev-dependencies] proptest = { workspace = true } +tempfile = "3" + +[[test]] +name = "agents" +required-features = ["agents"] diff --git a/crates/control/src/agents/connection.rs b/crates/control/src/agents/connection.rs new file mode 100644 index 000000000..0c0bcebc7 --- /dev/null +++ b/crates/control/src/agents/connection.rs @@ -0,0 +1,115 @@ +//! The connection file: where an app's control server listens for agents. + +use std::net::{SocketAddr, TcpStream}; +use std::path::{Path, PathBuf}; +use std::time::Duration; + +use serde::{Deserialize, Serialize}; + +/// The connection file in the app's settings folder, present while the app accepts agents. +pub const CONNECTION_FILE: &str = "agent-connection.json"; +/// The token file the app keeps in its settings folder for agent connections. +pub const TOKEN_FILE: &str = "agent-control.token"; +/// How long [`probe`] waits for a connection to be accepted. +pub const PROBE_TIMEOUT: Duration = Duration::from_millis(500); +/// The version of the [`Connection`] file format. +const CONNECTION_VERSION: u32 = 1; +/// The largest connection file read; anything bigger is not one. +const MAX_CONNECTION_BYTES: u64 = 1 << 20; + +/// What an app publishes in [`CONNECTION_FILE`]: `{"version", "pid", "port", "tokenFile", "app"}`. +/// Holds no secret: the token stays in its own owner-only file. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Connection { + /// The file format's version (1). + pub version: u32, + /// The app's process id: only that process removes the file. + pub pid: u32, + /// The loopback port of the control server. + pub port: u16, + /// The file holding the token. + pub token_file: PathBuf, + /// The app's version, for diagnostics. + pub app: String, +} + +impl Connection { + /// This process's connection on `port`, naming `app` (the app's version string). + pub fn new(port: u16, token_file: PathBuf, app: impl Into) -> Self { + Self { version: CONNECTION_VERSION, pid: std::process::id(), port, token_file, app: app.into() } + } + + /// `127.0.0.1:`. + pub fn addr(&self) -> String { + format!("127.0.0.1:{}", self.port) + } +} + +fn io_error(path: &Path, e: impl std::fmt::Display) -> std::io::Error { + std::io::Error::other(format!("{}: {e}", path.display())) +} + +/// Publishes `c` in `dir` (made if missing), written atomically so a reader never sees half a +/// file. +pub fn write_connection(dir: &Path, c: &Connection) -> std::io::Result<()> { + std::fs::create_dir_all(dir).map_err(|e| io_error(dir, e))?; + let path = dir.join(CONNECTION_FILE); + let text = serde_json::to_string_pretty(c).map_err(|e| io_error(&path, e))?; + craft_atomic::atomic_write(&path, text.as_bytes()).map_err(|e| io_error(&path, e)) +} + +/// The connection published in `dir`, if any. A file of another version, with port 0, or one +/// that does not parse (invalid UTF-8 included) counts as none: the app rewrites it when it next +/// starts listening. Anything but a regular file (a FIFO would block the read) or a file over +/// 1 MiB is an error, and left alone. +pub fn read_connection(dir: &Path) -> std::io::Result> { + let path = dir.join(CONNECTION_FILE); + let meta = match std::fs::metadata(&path) { + Ok(m) => m, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(e) => return Err(io_error(&path, e)), + }; + if !meta.is_file() { + return Err(io_error(&path, "not a regular file")); + } + if meta.len() > MAX_CONNECTION_BYTES { + return Err(io_error(&path, format!("larger than {MAX_CONNECTION_BYTES} bytes"))); + } + let bytes = match std::fs::read(&path) { + Ok(b) => b, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(e) => return Err(io_error(&path, e)), + }; + Ok(serde_json::from_slice::(&bytes).ok().filter(|c| c.version == CONNECTION_VERSION && c.port != 0)) +} + +/// Removes the connection file in `dir` if process `pid` wrote it (another instance may have +/// published its own since). Errors are ignored: a stale file only fails [`probe`]. +pub fn remove_connection(dir: &Path, pid: u32) { + if let Ok(Some(c)) = read_connection(dir) + && c.pid == pid + { + let _ = std::fs::remove_file(dir.join(CONNECTION_FILE)); + } +} + +/// Removes the connection file in `dir` when nothing listens on its port any more (an app that +/// crashed or quit without removing it), or when it does not read as a connection. A live +/// instance's file is kept, and so is anything but a regular file. Errors are ignored. +pub fn remove_stale_connection(dir: &Path) { + let path = dir.join(CONNECTION_FILE); + let stale = match read_connection(dir) { + Ok(Some(c)) => !probe(c.port, PROBE_TIMEOUT), + Ok(None) => path.is_file(), + Err(_) => false, + }; + if stale { + let _ = std::fs::remove_file(path); + } +} + +/// Whether something accepts connections on loopback `port` within `timeout`; port 0 never does. +pub fn probe(port: u16, timeout: Duration) -> bool { + port != 0 && TcpStream::connect_timeout(&SocketAddr::from(([127, 0, 0, 1], port)), timeout).is_ok() +} diff --git a/crates/control/src/agents/live.rs b/crates/control/src/agents/live.rs new file mode 100644 index 000000000..49b242ff5 --- /dev/null +++ b/crates/control/src/agents/live.rs @@ -0,0 +1,601 @@ +//! The other end of the link: where an app's `-cli mcp` sends each tool call. +//! +//! [`Live::resolve`] runs before every tool call. It reads the connection file the app publishes +//! while it accepts agents ([`super::write_connection`]), so the app may start, quit or move to another port +//! while the MCP client stays connected, and the client's configuration holds no port and no +//! token: +//! +//! - An app that accepts agents: the call goes to its open window ([`Route::Window`]). The same +//! port, token and process id keep the window client the app made; any change makes a new one. +//! - No app accepts agents, and the person doesn't let agents use it ([`Consent::allowed`] off, or +//! [`AgentSettings::allow_agent_control`] off, under which the app doesn't listen either): a +//! session without a window with only the folders given to the command +//! ([`LiveConfig::read_roots`], [`LiveConfig::write_root`]), as `mcp` always worked. The app's own +//! folders are for agents the person let in. +//! - No app accepts agents, but agents are allowed: the closed-app choice decides +//! ([`LiveConfig::when_closed`], otherwise [`AgentSettings::when_app_closed`]): start the app and +//! wait until it accepts agents, a headless session with the app's agent folders (the command's +//! folders win), or an error that says what to do. +//! +//! Once headless, the session stays headless: documents don't move under the agent. Only a session +//! made with the app's agent folders ends when the person stops letting agents in; the next call +//! gets one with the command's folders. A window route is dropped as soon as no app accepts agents. +//! Lookups are +//! serialised, so concurrent calls start the app once: calls that queued while a start was under +//! way and found no window get that start's error rather than starting the app again; a call made +//! after it tries again. +//! +//! The crate has no async runtime: `resolve` blocks (file reads, a loopback probe, and while an +//! app starts, polling), so an async MCP server calls it from its blocking pool. What a window +//! client and a headless session are stays the app's ([`LiveConfig::new`]'s `connect` and +//! `headless`), and so do the tools and the transport. Errors are the tool call's result: words +//! for the agent, and through it the person, naming the app. + +use std::ffi::{OsStr, OsString}; +use std::fmt; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Mutex, PoisonError}; +use std::time::{Duration, Instant}; + +use super::{AgentSettings, Connection, PROBE_TIMEOUT, WhenAppClosed, probe, read_connection}; + +/// Starts the desktop app; see [`launcher`]. +pub type LaunchFn = Box Result<(), String> + Send + Sync>; +/// What the person allows now, read from the app's settings folder before every call. +pub type ConsentFn = Box Consent + Send + Sync>; +/// Makes the app's client for its open window. +pub type ConnectFn = Box Result + Send + Sync>; +/// Makes the app's headless session with these folders. +pub type HeadlessFn = Box Result + Send + Sync>; + +/// How long a started app gets to accept agents. A first start can take a while (GPU shader +/// caches, a font scan), but MCP clients give a tool call about a minute. +pub const LAUNCH_TIMEOUT: Duration = Duration::from_secs(45); +/// How often a starting app's connection file is looked for. +pub const LAUNCH_POLL: Duration = Duration::from_millis(250); +/// The longest [`LiveConfig::launch_timeout`] used; a longer one is cut to this. +const MAX_LAUNCH_TIMEOUT: Duration = Duration::from_secs(600); +/// The range [`LiveConfig::poll`] is kept in. +const POLL_RANGE: (Duration, Duration) = (Duration::from_millis(1), Duration::from_secs(1)); + +/// The open window a call goes to: from the connection file, with the token from its token file. +#[derive(Clone, PartialEq, Eq)] +#[non_exhaustive] +pub struct Window { + /// The loopback port of the app's control server. + pub port: u16, + /// The app's process id. + pub pid: u32, + /// The control token, as its token file holds it (trimmed). + pub token: String, +} + +impl Window { + /// `127.0.0.1:`. + pub fn addr(&self) -> String { + format!("127.0.0.1:{}", self.port) + } +} + +impl fmt::Debug for Window { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + // Never the token: Debug output ends up in logs. + f.debug_struct("Window").field("port", &self.port).field("pid", &self.pid).finish_non_exhaustive() + } +} + +/// Whether the person lets agents use the app now, and its agent settings. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +#[non_exhaustive] +pub struct Consent { + /// Agents may use the app: `agents_allowed(mcp_flag(), launcher_allows(""), legacy)` + /// ([`super::agents_allowed`]), with the suite's `AI-MCP` flag the ArtCraft Launcher's switch. + /// [`Live`] also requires [`AgentSettings::allow_agent_control`]. + pub allowed: bool, + /// The app's agent settings (closed-app choice, folders). + pub settings: AgentSettings, +} + +impl Consent { + /// `allowed` with these settings. + pub fn new(allowed: bool, settings: AgentSettings) -> Self { + Self { allowed, settings } + } +} + +/// The folders a headless session may open from and save to. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +#[non_exhaustive] +pub struct HeadlessFolders { + /// Folders files may be opened from. + pub read: Vec, + /// The folder files may be saved to. + pub write: Option, +} + +/// Where a tool call goes: the app's window client or its headless session. +#[derive(Clone, Debug)] +pub enum Route { + /// The open window. + Window(W), + /// A session without a window. + Headless(H), +} + +/// What [`Live`] needs from the app. +#[non_exhaustive] +pub struct LiveConfig { + /// The app's name in messages (`"PhotoCraft"`). + pub app_name: String, + /// The app's settings folder: connection file, token file and settings. + pub config_dir: PathBuf, + /// Overrides the app's closed-app choice (the CLI's `--when-closed`). + pub when_closed: Option, + /// Folders a headless session may open from (the CLI's read roots); while agents are allowed + /// they replace the app's read folder. + pub read_roots: Vec, + /// The folder a headless session may save to (the CLI's write root); while agents are allowed + /// it replaces the app's write folder. + pub write_root: Option, + /// Starts the app; `None` when this install can't ([`launcher`] found nothing to start). + pub launch: Option, + /// How long a started app gets to accept agents ([`LAUNCH_TIMEOUT`]; at most 10 minutes). + pub launch_timeout: Duration, + /// How often a starting app is looked for ([`LAUNCH_POLL`]; kept between 1 ms and 1 s). + pub poll: Duration, + consent: ConsentFn, + connect: ConnectFn, + headless: HeadlessFn, +} + +impl LiveConfig { + /// The app `app_name` with its settings in `config_dir`: `consent` reads whether agents may + /// use it, `connect` makes a client for its open window, `headless` a session without one. + pub fn new( + app_name: impl Into, + config_dir: PathBuf, + consent: impl Fn(&Path) -> Consent + Send + Sync + 'static, + connect: impl Fn(&Window) -> Result + Send + Sync + 'static, + headless: impl Fn(&HeadlessFolders) -> Result + Send + Sync + 'static, + ) -> Self { + Self { + app_name: app_name.into(), + config_dir, + when_closed: None, + read_roots: Vec::new(), + write_root: None, + launch: None, + launch_timeout: LAUNCH_TIMEOUT, + poll: LAUNCH_POLL, + consent: Box::new(consent), + connect: Box::new(connect), + headless: Box::new(headless), + } + } +} + +/// The port, token and process id a window client was made for: a restarted app may keep its +/// port and token, but its old socket is gone. +type WindowKey = (u16, String, u32); +/// The route the last call took. +struct Current { + route: Route, + /// For a window, the key its client was made for. + key: Option, + /// A headless session that holds folders of the app's agent settings: it lasts only while + /// the person lets agents in. + app_folders: bool, +} + +/// Resolves each tool call of one MCP session; see the module docs. +pub struct Live { + cfg: LiveConfig, + /// Serialises lookups, so concurrent calls start the app once; holds the last start's error. + lookup: Mutex>, + /// How many starts have finished, read before a call queues for `lookup`. + finished: AtomicU64, + current: Mutex>>, +} + +impl Live { + /// A session that has not resolved anything yet. + pub fn new(cfg: LiveConfig) -> Self { + Self { cfg, lookup: Mutex::new(None), finished: AtomicU64::new(0), current: Mutex::new(None) } + } + + /// The route the last [`Self::resolve`] chose, if any. + pub fn current(&self) -> Option> { + self.current.lock().unwrap_or_else(PoisonError::into_inner).as_ref().map(|c| c.route.clone()) + } + + fn set(&self, route: Route, key: Option, app_folders: bool) -> Route { + *self.current.lock().unwrap_or_else(PoisonError::into_inner) = Some(Current { route: route.clone(), key, app_folders }); + route + } + + /// The headless session to keep using, if any: one made with the app's folders only while + /// agents are still `allowed`. A route that may not be kept is dropped. + fn sticky_headless(&self, allowed: bool) -> Option> { + let mut current = self.current.lock().unwrap_or_else(PoisonError::into_inner); + match current.as_ref() { + Some(c) if matches!(c.route, Route::Headless(_)) && (allowed || !c.app_folders) => Some(c.route.clone()), + Some(c) if matches!(c.route, Route::Headless(_)) => { + *current = None; + None + } + _ => None, + } + } + + /// Forgets a window route: no app accepts agents any more, so its client is for a socket + /// that is gone. + fn drop_window(&self) { + let mut current = self.current.lock().unwrap_or_else(PoisonError::into_inner); + if current.as_ref().is_some_and(|c| matches!(c.route, Route::Window(_))) { + *current = None; + } + } + + /// Where the next tool call goes. Blocks; see the module docs. The error is the tool call's + /// result. + pub fn resolve(&self) -> Result, String> { + let queued_at = self.finished.load(Ordering::Acquire); + let mut last_failure = self.lookup.lock().unwrap_or_else(PoisonError::into_inner); + let consent = (self.cfg.consent)(&self.cfg.config_dir); + // Allow Agent Control off refuses agents, as the app does: it doesn't listen then. + let allowed = consent.allowed && consent.settings.allow_agent_control; + if let Some(route) = self.sticky_headless(allowed) { + return Ok(route); + } + if let Some(window) = self.find_app()? { + return self.use_window(window); + } + self.drop_window(); + let app = &self.cfg.app_name; + if !allowed { + let folders = HeadlessFolders { read: self.cfg.read_roots.clone(), write: self.cfg.write_root.clone() }; + return self.headless(&folders, false, &format!("{app} can't use the automation roots")); + } + match self.cfg.when_closed.unwrap_or(consent.settings.when_app_closed) { + WhenAppClosed::Error => Err(format!("{app} isn't running: open it, then try again.")), + WhenAppClosed::Headless => { + let app_read = self.cfg.read_roots.is_empty() && consent.settings.read_folder().is_some(); + let app_write = self.cfg.write_root.is_none() && consent.settings.write_folder().is_some(); + let read = + if self.cfg.read_roots.is_empty() { consent.settings.read_folder().into_iter().collect() } else { self.cfg.read_roots.clone() }; + let write = self.cfg.write_root.clone().or_else(|| consent.settings.write_folder()); + let why = format!("{app} isn't running and its agent folders can't be used"); + self.headless(&HeadlessFolders { read, write }, app_read || app_write, &why) + } + WhenAppClosed::Launch => { + // A start finished while this call waited and the app still isn't there: its answer + // is this call's too, rather than a second start of an app that may be opening. + if self.finished.load(Ordering::Acquire) != queued_at + && let Some(failure) = last_failure.as_ref() + { + return Err(failure.clone()); + } + let started = self.launch_and_wait(); + *last_failure = started.as_ref().err().cloned(); + self.finished.fetch_add(1, Ordering::AcqRel); + started + } + } + } + + /// A headless session with `folders` from now on; `app_folders` when some of them are the + /// app's agent folders. `why` leads its error. + fn headless(&self, folders: &HeadlessFolders, app_folders: bool, why: &str) -> Result, String> { + let session = (self.cfg.headless)(folders).map_err(|e| format!("{why}: {e}"))?; + Ok(self.set(Route::Headless(session), None, app_folders)) + } + + /// Starts the app and waits until it accepts agents, at most the launch timeout. + fn launch_and_wait(&self) -> Result, String> { + let app = &self.cfg.app_name; + let Some(launch) = &self.cfg.launch else { + return Err(format!("{app} isn't running, and this install can't start it from here: open {app}, then try again.")); + }; + launch().map_err(|e| format!("couldn't start {app}: {e}"))?; + let timeout = self.cfg.launch_timeout.min(MAX_LAUNCH_TIMEOUT); + let started = Instant::now(); + let deadline = started.checked_add(timeout).unwrap_or(started); + let poll = self.cfg.poll.clamp(POLL_RANGE.0, POLL_RANGE.1); + loop { + std::thread::sleep(poll); + if let Some(window) = self.find_app()? { + return self.use_window(window); + } + if Instant::now() >= deadline { + return Err(format!( + "{app} didn't accept agents within {} s of starting. If it's still opening, try again in a moment; otherwise check that AI agents are on in ArtCraft Launcher › Settings › AI agents.", + timeout.as_secs() + )); + } + } + } + + /// The client for `window`: the one made for the same port, token and process, or a new one. + fn use_window(&self, window: Window) -> Result, String> { + let key: WindowKey = (window.port, window.token.clone(), window.pid); + { + let current = self.current.lock().unwrap_or_else(PoisonError::into_inner); + if let Some(c) = current.as_ref() + && c.key.as_ref() == Some(&key) + { + return Ok(c.route.clone()); + } + } + let client = (self.cfg.connect)(&window).map_err(|e| format!("couldn't reach {}'s window: {e}", self.cfg.app_name))?; + Ok(self.set(Route::Window(client), Some(key), false)) + } + + /// The app accepting agents now: `None` when there is no connection file, or one left by an + /// app that crashed (nothing listens on its port). + fn find_app(&self) -> Result, String> { + find_window(&self.cfg.config_dir, &self.cfg.app_name) + } +} + +/// The window accepting agents with its settings in `dir`, with the token from its token file; +/// `None` when no app accepts agents there. `app_name` names the app in errors. +pub fn find_window(dir: &Path, app_name: &str) -> Result, String> { + let Some(c): Option = read_connection(dir).map_err(|e| e.to_string())? else { return Ok(None) }; + if !probe(c.port, PROBE_TIMEOUT) { + return Ok(None); + } + let token = read_token(&c.token_file).map_err(|e| format!("{app_name}'s agent token: {e}"))?; + Ok(Some(Window { port: c.port, pid: c.pid, token })) +} + +/// The largest token file read; a token is far shorter. +const MAX_TOKEN_FILE: u64 = 4096; + +/// The token in the token file at `path`, trimmed and otherwise as written: the app's server +/// compares it exactly ([`crate::auth::tokens_match`]). The file must be a regular file of at most +/// [`MAX_TOKEN_FILE`] bytes holding one token (no spaces or control characters in it), and on Unix +/// readable by its owner only: a token others could read is refused rather than used. +fn read_token(path: &Path) -> Result { + use std::io::Read; + let shown = |e: &dyn fmt::Display| format!("{}: {e}", path.display()); + // Before opening: opening a FIFO for reading blocks until something writes to it. + if !std::fs::metadata(path).map_err(|e| shown(&e))?.is_file() { + return Err(shown(&"not a regular file")); + } + let file = std::fs::File::open(path).map_err(|e| shown(&e))?; + let meta = file.metadata().map_err(|e| shown(&e))?; + if !meta.is_file() { + return Err(shown(&"not a regular file")); + } + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + if meta.mode() & 0o077 != 0 { + return Err(shown(&format!("readable by group or others (mode {:o}); restrict it to its owner", meta.mode() & 0o777))); + } + } + let mut text = String::new(); + file.take(MAX_TOKEN_FILE + 1).read_to_string(&mut text).map_err(|e| shown(&e))?; + if text.len() as u64 > MAX_TOKEN_FILE { + return Err(shown(&format!("larger than {MAX_TOKEN_FILE} bytes"))); + } + let token = text.trim(); + if token.is_empty() || token.chars().any(|c| c.is_whitespace() || c.is_control()) { + return Err(shown(&"not a control token")); + } + Ok(token.to_owned()) +} + +/// How to start the desktop app `exe` (its file name without `.exe`) that ships beside the CLI at +/// `cli`: detached and with no standard streams, since the CLI's carry the MCP protocol and the +/// app must outlive the MCP client. `None` where this install can't start it: inside a Flatpak, +/// or with no app beside the CLI. +pub fn launcher(cli: &Path, exe: &str) -> Option { + use std::process::{Command, Stdio}; + let env = |name: &str| std::env::var_os(name).filter(|v| !v.is_empty()); + // Both sides resolved, so a mount reached through a symlink (`$TMPDIR`) still matches. + let resolved = |p: &Path| std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf()); + let install = Install { + platform: Platform::current(), + flatpak: env("FLATPAK_ID").is_some(), + appimage: env("APPIMAGE"), + appdir: env("APPDIR").map(|d| resolved(Path::new(&d)).into_os_string()), + system_root: env("SystemRoot"), + }; + let (program, args) = launch_command(&resolved(cli), exe, &install, &|p| p.is_file())?; + let mut command = Command::new(program); + command.args(args); + let command = Mutex::new(command); + Some(Box::new(move || { + let mut c = command.lock().unwrap_or_else(PoisonError::into_inner); + c.stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()); + detach(&mut c); + let child = c.spawn().map_err(|e| e.to_string())?; + reap(child); + Ok(()) + })) +} + +/// Waits for `child` on a thread of its own, so a start helper that exits (`open`, Explorer) or an +/// app that quits before the CLI does is reaped rather than left a zombie until the MCP client +/// ends; the app keeps running on its own either way. Without a thread the child is dropped, as +/// before. +fn reap(mut child: std::process::Child) { + let _ = std::thread::Builder::new().name("app-start-reaper".into()).spawn(move || { + let _ = child.wait(); + }); +} + +/// What [`launch_command`] needs to know about the install, from the environment. +#[derive(Clone, Debug, Default)] +struct Install { + platform: Platform, + /// Inside a Flatpak (`FLATPAK_ID`). + flatpak: bool, + /// The AppImage the running image set (`APPIMAGE`). + appimage: Option, + /// That image's mount point (`APPDIR`). + appdir: Option, + /// `%SystemRoot%` (Windows). + system_root: Option, +} + +/// The platform [`launch_command`] plans for. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +enum Platform { + Windows, + MacOs, + #[default] + Other, +} + +impl Platform { + /// The platform this build runs on. + fn current() -> Self { + if cfg!(windows) { + Self::Windows + } else if cfg!(target_os = "macos") { + Self::MacOs + } else { + Self::Other + } + } +} + +/// The program and arguments that start the app; see [`launcher`]. +fn launch_command(cli: &Path, exe: &str, install: &Install, is_file: &dyn Fn(&Path) -> bool) -> Option<(PathBuf, Vec)> { + let platform = install.platform; + if install.flatpak { + return None; + } + // Only when this CLI runs from that image's mount: a process started from another AppImage + // (an MCP client packaged as one) inherits its `APPIMAGE` too. + if let (Some(image), Some(mount)) = (&install.appimage, &install.appdir) + && cli.starts_with(mount) + { + // The AppImage's mount point goes away with the CLI; the image itself stays. + return Some((PathBuf::from(image), Vec::new())); + } + let dir = cli.parent()?; + if platform == Platform::MacOs + && dir.ends_with("Contents/MacOS") + && let Some(bundle) = dir.parent().and_then(Path::parent) + { + // A macOS app bundle: LaunchServices starts (or brings forward) the app. + return Some((PathBuf::from("/usr/bin/open"), vec![OsString::from("-a"), bundle.as_os_str().to_os_string()])); + } + let app = dir.join(if platform == Platform::Windows { format!("{exe}.exe") } else { exe.to_owned() }); + if !is_file(&app) { + return None; + } + Some(if platform == Platform::Windows { windows_launch(&app, install.system_root.as_deref()) } else { (app, Vec::new()) }) +} + +/// How Windows starts the app at `app`: through Explorer, as a double-click would. The app is then +/// no child of the CLI, so it outlives the MCP client ending the CLI's process tree (Claude Code +/// does on Windows), and it runs outside the container of a Microsoft Store client (Claude +/// Desktop): there, new files under `%APPDATA%` land in the client's package, where the app +/// started from the Start menu would never see them. Explorer reads a comma as a separator, so +/// such a path is started directly. (`%WINDIR%` can be empty under a Store client, hence +/// `%SystemRoot%`.) +fn windows_launch(app: &Path, system_root: Option<&OsStr>) -> (PathBuf, Vec) { + if app.to_string_lossy().contains(',') { + return (app.to_path_buf(), Vec::new()); + } + let root = system_root.filter(|r| !r.is_empty()).map_or_else(|| PathBuf::from(r"C:\Windows"), PathBuf::from); + (root.join("explorer.exe"), vec![app.as_os_str().to_os_string()]) +} + +/// Keeps the app running when the MCP client stops the CLI (and its process group). +fn detach(c: &mut std::process::Command) { + #[cfg(unix)] + { + use std::os::unix::process::CommandExt; + c.process_group(0); + } + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + const DETACHED_PROCESS: u32 = 0x0000_0008; + const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200; + c.creation_flags(DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP); + } + #[cfg(not(any(unix, windows)))] + let _ = c; +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + use super::*; + + fn plan( + cli: &str, + platform: Platform, + flatpak: bool, + appimage: Option<&str>, + root: Option<&str>, + exists: bool, + ) -> Option<(PathBuf, Vec)> { + // An AppImage's mount is where its CLI runs from. + let appdir = appimage.map(|_| OsString::from("/tmp/.mount")); + let install = Install { platform, flatpak, appimage: appimage.map(OsString::from), appdir, system_root: root.map(OsString::from) }; + launch_command(Path::new(cli), "photocraft", &install, &|_| exists) + } + + #[test] + fn windows_starts_the_app_through_explorer() { + let app = Path::new(r"C:\Program Files\PhotoCraft\photocraft.exe"); + let (program, args) = windows_launch(app, Some(OsStr::new(r"D:\Win"))); + assert_eq!(program, Path::new(r"D:\Win").join("explorer.exe")); + assert_eq!(args, [app.as_os_str()]); + // No usable %SystemRoot%: the default Windows folder. + let default = Path::new(r"C:\Windows").join("explorer.exe"); + assert_eq!(windows_launch(app, Some(OsStr::new(""))).0, default); + assert_eq!(windows_launch(app, None).0, default); + // Explorer would split this path at the comma. + let comma = Path::new(r"C:\Apps, tools\photocraft.exe"); + assert_eq!(windows_launch(comma, None), (comma.to_path_buf(), Vec::new())); + } + + #[test] + fn the_launch_command_fits_the_install() { + // Flatpak: the sandbox can't start the app. + assert_eq!(plan("/app/bin/photocraft-cli", Platform::Other, true, Some("/x.AppImage"), None, true), None); + // An AppImage starts its image, not the mount point the CLI runs from. + assert_eq!( + plan("/tmp/.mount/usr/bin/photocraft-cli", Platform::Other, false, Some("/home/a/P.AppImage"), None, false), + Some((PathBuf::from("/home/a/P.AppImage"), Vec::new())) + ); + // Another AppImage's variables (an MCP client packaged as one): the app beside the CLI. + let client = plan("/opt/pc/photocraft-cli", Platform::Other, false, Some("/home/a/Client.AppImage"), None, true); + assert_eq!(client, Some((PathBuf::from("/opt/pc/photocraft"), Vec::new()))); + let no_mount = Install { appimage: Some("/home/a/P.AppImage".into()), ..Install::default() }; + assert_eq!( + launch_command(Path::new("/tmp/.mount/usr/bin/photocraft-cli"), "photocraft", &no_mount, &|_| false), + None, + "APPIMAGE without APPDIR" + ); + // A macOS bundle opens through LaunchServices. + let (program, args) = plan("/Applications/PhotoCraft.app/Contents/MacOS/photocraft-cli", Platform::MacOs, false, None, None, false).unwrap(); + assert_eq!(program, Path::new("/usr/bin/open")); + assert_eq!(args, [OsString::from("-a"), OsString::from("/Applications/PhotoCraft.app")]); + // Beside the CLI, by the app's file name. + assert_eq!(plan("/opt/pc/photocraft-cli", Platform::Other, false, None, None, true), Some((PathBuf::from("/opt/pc/photocraft"), Vec::new()))); + let (program, args) = plan(r"C:\PC\photocraft-cli.exe", Platform::Windows, false, None, Some(r"C:\Win"), true).unwrap(); + assert_eq!(program, Path::new(r"C:\Win").join("explorer.exe")); + // The app beside the CLI (on a non-Windows host the backslashes are no separators). + assert_eq!(args, [Path::new(r"C:\PC\photocraft-cli.exe").parent().unwrap().join("photocraft.exe").into_os_string()]); + // No app beside the CLI: nothing to start. + assert_eq!(plan("/opt/pc/photocraft-cli", Platform::Other, false, None, None, false), None); + assert_eq!(plan("photocraft-cli", Platform::Other, false, None, None, true).map(|p| p.0), Some(PathBuf::from("photocraft"))); + } + + #[test] + fn a_window_never_shows_its_token() { + let w = Window { port: 7, pid: 9, token: "ab".repeat(32) }; + assert!(!format!("{w:?}").contains("abab")); + assert_eq!(w.addr(), "127.0.0.1:7"); + } +} diff --git a/crates/control/src/agents/mod.rs b/crates/control/src/agents/mod.rs new file mode 100644 index 000000000..e1b0b9923 --- /dev/null +++ b/crates/control/src/agents/mod.rs @@ -0,0 +1,78 @@ +//! AI agents in the open window, with no UI toolkit: whether the person lets agents use the app, +//! how the app tells its own `-cli mcp` where it listens, and where that CLI sends each tool +//! call. +//! +//! One switch serves every Craft app: the ArtCraft Launcher's *Settings › AI agents › Let AI agents +//! use Craft apps*, which writes the launcher's app list (`craft_ai_agents`). With the suite's +//! `AI-MCP` flag on, an app lets agents in when that list names it ([`AgentSwitch`]); without the +//! flag, the app's own earlier consent decides ([`agents_allowed`]). Apps have no agents switch of +//! their own. +//! +//! While agents may connect, the app serves its control channel on loopback with a token +//! ([`crate::server`], [`crate::auth`], or its own) and publishes where in its settings folder +//! ([`CONNECTION_FILE`]): the port, its process id and the token file. The app's `-cli mcp` +//! reads that file before every tool call ([`Live`]), so an MCP client's configuration never holds +//! a port or a token. The file holds no secret. A crashed app can leave it behind; nothing then +//! listens on its port ([`probe`]), and the app's next launch removes it +//! ([`remove_stale_connection`]). An app that quits removes its own ([`remove_connection`]). +//! +//! | Part | Names | Builds | +//! |---|---|---| +//! | Settings | [`AgentSettings`], [`WhenAppClosed`], [`agents_allowed`], [`folder`] | every target | +//! | The launcher's switch | [`AgentSwitch`], [`mcp_flag`], [`launcher_allows`], [`POLL`] | desktop, feature `agents` | +//! | The connection file | [`Connection`], [`write_connection`], [`read_connection`], [`remove_connection`], [`remove_stale_connection`], [`probe`] | desktop, feature `agents` | +//! | The CLI's side | [`Live`], [`LiveConfig`], [`Route`], [`Window`], [`Consent`], [`HeadlessFolders`], [`find_window`], [`launcher`] | desktop, feature `agents` | +//! +//! The same formats as `craft_automation::agents` on the shared UI library's branch (`next`), +//! which adds the egui link host and the Agents page of Preferences. +//! +//! # Adding an app +//! +//! The app (its id is the one in the ArtCraft Launcher's catalog, `"gridcraft"`): +//! +//! 1. At start, [`remove_stale_connection`] in its settings folder, then +//! `AgentSwitch::watch("gridcraft", wake)`, where `wake` asks the UI for a frame. +//! 2. Agents may connect while `settings.allow_agent_control && switch.allows(legacy)` +//! ([`AgentSettings::allow_agent_control`], [`AgentSwitch::allows`]); check it again when the +//! launcher's switch wakes the app and when the person changes the setting. When it turns true, +//! listen on loopback with a token, the token in an owner-only file +//! ([`crate::auth::App::write_token_file`]), and [`write_connection`] with [`Connection::new`]; +//! when it turns false, and when the app quits, stop listening and [`remove_connection`] with +//! the app's process id. No restart, no agents switch of its own. There is one connection file +//! per settings folder: an app that runs more than one process on one folder lets only one of +//! them accept agents. +//! +//! Its `gridcraft-cli mcp`: +//! +//! 1. A [`LiveConfig`] with the app's settings folder; `consent` reads its saved +//! [`AgentSettings`] and answers `agents_allowed(mcp_flag(), launcher_allows("gridcraft"), legacy)` +//! ([`agents_allowed`], [`mcp_flag`], [`launcher_allows`]); `connect` makes the app's client for a +//! [`Window`] (its address and token); `headless` makes its session without a window for +//! [`HeadlessFolders`]. [`launcher`] starts the app beside the CLI. +//! 2. Before every tool call, [`Live::resolve`] (from a blocking thread in an async server), then +//! the call goes to the [`Route`] it returns. `--headless` skips [`Live`] altogether. + +// The links above name items of the `agents` feature; without it they have nothing to point at, +// and the docs of the settings alone still build. +#![cfg_attr(not(all(feature = "agents", not(target_arch = "wasm32"))), allow(rustdoc::broken_intra_doc_links))] + +mod settings; +pub use settings::{AgentSettings, WhenAppClosed, agents_allowed, folder}; + +#[cfg(all(feature = "agents", not(target_arch = "wasm32")))] +mod connection; +#[cfg(all(feature = "agents", not(target_arch = "wasm32")))] +mod live; +#[cfg(all(feature = "agents", not(target_arch = "wasm32")))] +mod switch; +#[cfg(all(feature = "agents", not(target_arch = "wasm32")))] +pub use connection::{ + CONNECTION_FILE, Connection, PROBE_TIMEOUT, TOKEN_FILE, probe, read_connection, remove_connection, remove_stale_connection, write_connection, +}; +#[cfg(all(feature = "agents", not(target_arch = "wasm32")))] +pub use live::{ + ConnectFn, Consent, ConsentFn, HeadlessFn, HeadlessFolders, LAUNCH_POLL, LAUNCH_TIMEOUT, LaunchFn, Live, LiveConfig, Route, Window, find_window, + launcher, +}; +#[cfg(all(feature = "agents", not(target_arch = "wasm32")))] +pub use switch::{AgentSwitch, POLL, launcher_allows, mcp_flag}; diff --git a/crates/control/src/agents/settings.rs b/crates/control/src/agents/settings.rs new file mode 100644 index 000000000..04ae933aa --- /dev/null +++ b/crates/control/src/agents/settings.rs @@ -0,0 +1,124 @@ +//! The agent settings an app saves in its preferences, and who decides that agents may connect. + +use std::path::PathBuf; + +use serde::{Deserialize, Serialize}; + +/// The agent settings of an app's Preferences (its `integrations` section in PhotoCraft). Saved in +/// camelCase: `allowAgentControl`, `controlPort`, `readRoot`, `writeRoot`, `whenAppClosed`. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +#[non_exhaustive] +pub struct AgentSettings { + /// Off refuses every control server, `--control` included. + pub allow_agent_control: bool, + /// The loopback port agents connect to; 0 is any free port, published in the connection file. + pub control_port: u32, + /// The folder agents may open from; empty is none. Applied at once while agents are connected. + pub read_root: String, + /// The folder agents may save to; empty is none. Applied at once while agents are connected. + pub write_root: String, + /// What the app's `-cli mcp` does while agents may use the app but it is closed. + pub when_app_closed: WhenAppClosed, +} + +impl Default for AgentSettings { + fn default() -> Self { + Self { + allow_agent_control: true, + control_port: 0, + read_root: String::new(), + write_root: String::new(), + when_app_closed: WhenAppClosed::Launch, + } + } +} + +impl AgentSettings { + /// [`Self::read_root`] as a path ([`folder`]). + pub fn read_folder(&self) -> Option { + folder(&self.read_root) + } + + /// [`Self::write_root`] as a path ([`folder`]). + pub fn write_folder(&self) -> Option { + folder(&self.write_root) + } +} + +/// A folder setting as a path, trimmed; empty or blank is `None`. +pub fn folder(pref: &str) -> Option { + let pref = pref.trim(); + (!pref.is_empty()).then(|| PathBuf::from(pref)) +} + +/// What an app's `-cli mcp` does when an agent calls a tool while the app is closed. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum WhenAppClosed { + /// Open the app and wait for it. + #[default] + Launch, + /// Run the tool without a window. + Headless, + /// Answer with an error that asks to open the app. + Error, +} + +impl WhenAppClosed { + /// The saved names, in [`Self::ALL`] order. + pub const NAMES: &'static [&'static str] = &["launch", "headless", "error"]; + /// Every choice, in the order a menu lists them. + pub const ALL: [Self; 3] = [Self::Launch, Self::Headless, Self::Error]; + + /// The saved name. + pub fn name(self) -> &'static str { + match self { + Self::Launch => "launch", + Self::Headless => "headless", + Self::Error => "error", + } + } + + /// The choice a saved name means; `None` for any other text. + pub fn parse(name: &str) -> Option { + Self::ALL.into_iter().find(|c| c.name() == name) + } +} + +/// Whether agents may use the open window. With the suite's `AI-MCP` flag only the launcher's +/// switch decides: one switch for every Craft app, none in the app. Without the flag the app's own +/// earlier consent decides (`legacy`; PhotoCraft's is a Control Port saved before the switch). +/// Allow Agent Control off still refuses agents either way ([`AgentSettings::allow_agent_control`]). +pub fn agents_allowed(mcp_flag: bool, launcher: bool, legacy: bool) -> bool { + if mcp_flag { launcher } else { legacy } +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used)] + use super::*; + + // The saved names read back as the same choice, and nothing else reads as one. + #[test] + fn when_app_closed_names_round_trip() { + for choice in WhenAppClosed::ALL { + assert_eq!(WhenAppClosed::parse(choice.name()), Some(choice)); + assert_eq!(serde_json::to_value(choice).unwrap(), serde_json::json!(choice.name())); + } + assert_eq!(WhenAppClosed::NAMES, WhenAppClosed::ALL.map(WhenAppClosed::name)); + assert_eq!(WhenAppClosed::parse("Launch"), None); + let settings: AgentSettings = serde_json::from_str(r#"{"whenAppClosed": "headless", "controlPort": 7878}"#).unwrap(); + assert_eq!((settings.when_app_closed, settings.control_port, settings.allow_agent_control), (WhenAppClosed::Headless, 7878, true)); + } + + // A folder setting is trimmed; empty or blank means no folder. + #[test] + fn folder_preferences_are_trimmed() { + assert_eq!(folder(""), None); + assert_eq!(folder(" "), None); + assert_eq!(folder(" /work/project "), Some(PathBuf::from("/work/project"))); + let settings = AgentSettings { read_root: " /in ".into(), ..AgentSettings::default() }; + assert_eq!((settings.read_folder(), settings.write_folder()), (Some(PathBuf::from("/in")), None)); + } +} diff --git a/crates/control/src/agents/switch.rs b/crates/control/src/agents/switch.rs new file mode 100644 index 000000000..9165879dc --- /dev/null +++ b/crates/control/src/agents/switch.rs @@ -0,0 +1,94 @@ +//! The ArtCraft Launcher's switch for one app, behind the suite's `AI-MCP` flag. + +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Weak}; +use std::time::Duration; + +use super::agents_allowed; + +/// How often [`AgentSwitch::watch`] reads the launcher's app list. +pub const POLL: Duration = Duration::from_secs(2); + +/// The suite's `AI-MCP` flag (`ArtCraft/flags.toml` or `CRAFT_FLAGS`). Reads the flags file; +/// what could not be read is logged. +pub fn mcp_flag() -> bool { + let flags = craft_flags::load(); + for problem in &flags.problems { + log::warn!("flags: {problem}"); + } + flags.enabled(&craft_flags::AI_MCP) +} + +/// The launcher's switch (Settings › AI agents › *Let AI agents use Craft apps*) lets agents use +/// the app `app_id`: the `AI-MCP` flag is on and the launcher's app list names the app. Reads two +/// small files; ask from a timer or a command, not every frame ([`AgentSwitch`] does that). +pub fn launcher_allows(app_id: &str) -> bool { + mcp_flag() && craft_ai_agents::allowed(app_id) +} + +/// The launcher's switch for one app, watched on a thread so a frame can ask without touching the +/// disk. The `AI-MCP` flag is read once, at [`Self::watch`]; the launcher's list every [`POLL`]. +/// Clones share one watch; the thread ends after the last clone is dropped. +#[derive(Clone, Debug)] +pub struct AgentSwitch { + mcp_flag: bool, + on: Arc, +} + +impl AgentSwitch { + /// Watches the launcher's list for `app_id`; a change logs `agents on/off` and calls `wake` (the + /// app asks for a frame there). + /// Without the `AI-MCP` flag nothing is watched: the launcher's list means nothing then. + pub fn watch(app_id: &'static str, wake: impl Fn() + Send + 'static) -> Self { + let flag = mcp_flag(); + if !flag { + return Self::fixed(false, false); + } + Self::watch_with(flag, move || craft_ai_agents::allowed(app_id), POLL, wake) + } + + /// A switch that never changes: tests, the web, an app without agents. + pub fn fixed(mcp_flag: bool, launcher: bool) -> Self { + Self { mcp_flag, on: Arc::new(AtomicBool::new(launcher)) } + } + + /// [`Self::watch`] with the flag given, `probe` asked once now and then every `poll`. + #[doc(hidden)] + pub fn watch_with(mcp_flag: bool, probe: impl Fn() -> bool + Send + 'static, poll: Duration, wake: impl Fn() + Send + 'static) -> Self { + let on = Arc::new(AtomicBool::new(probe())); + let seen: Weak = Arc::downgrade(&on); + let started = std::thread::Builder::new().name("launcher-agents".into()).spawn(move || { + loop { + std::thread::sleep(poll); + let now = probe(); + let Some(seen) = seen.upgrade() else { return }; + if seen.swap(now, Ordering::Relaxed) != now { + log::info!("ArtCraft Launcher: agents {}", if now { "on" } else { "off" }); + wake(); + } + } + }); + // Without a thread a later "off" in the launcher would never be seen: agents stay out. + if let Err(e) = started { + log::warn!("couldn't watch the ArtCraft Launcher's agents switch, so agents stay off: {e}"); + on.store(false, Ordering::Relaxed); + } + Self { mcp_flag, on } + } + + /// The `AI-MCP` flag as it was when the watch started. + pub fn mcp_flag(&self) -> bool { + self.mcp_flag + } + + /// Whether the launcher's list named the app at the last poll. + pub fn launcher(&self) -> bool { + self.on.load(Ordering::Relaxed) + } + + /// Whether agents may use the open window ([`agents_allowed`]); `legacy` is the app's own + /// earlier consent, which counts only without the flag. + pub fn allows(&self, legacy: bool) -> bool { + agents_allowed(self.mcp_flag, self.launcher(), legacy) + } +} diff --git a/crates/control/src/lib.rs b/crates/control/src/lib.rs index 26727a97c..56ce2e685 100644 --- a/crates/control/src/lib.rs +++ b/crates/control/src/lib.rs @@ -2,12 +2,15 @@ //! files ([`auth`]), the loopback server that admits a connection by the token and hands each //! request to the window ([`server`]), the client that talks to it ([`client`]), the request the //! window answers ([`ControlRequest`]), the document watch subscribed connections wait on -//! ([`DocumentWatch`]), and what a request still running does when it finishes ([`Effect`]). It +//! ([`DocumentWatch`]), what a request still running does when it finishes ([`Effect`]), and AI +//! agents in the open window behind the ArtCraft Launcher's switch ([`agents`]: its settings on +//! every target, the switch, the connection file and the CLI's side with feature `agents`). It //! needs no UI toolkit; the window's own requests over egui (`ui.screenshot`, `ui.resize`) are //! `craft-control-egui`. #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] #![forbid(unsafe_code)] +pub mod agents; pub mod auth; mod cancel; #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/control/tests/agents.rs b/crates/control/tests/agents.rs new file mode 100644 index 000000000..95a4651eb --- /dev/null +++ b/crates/control/tests/agents.rs @@ -0,0 +1,572 @@ +//! AI agents in the open window: the launcher's switch, the connection file, and where an app's +//! `-cli mcp` sends each tool call. +// Unwrapping, expecting and panicking on failure is fine in tests, unlike in shipped code. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::net::TcpListener; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +use craft_control::agents::{ + AgentSettings, AgentSwitch, CONNECTION_FILE, Connection, Consent, HeadlessFolders, Live, LiveConfig, Route, TOKEN_FILE, WhenAppClosed, Window, + agents_allowed, find_window, read_connection, remove_connection, remove_stale_connection, write_connection, +}; + +fn temp_dir(tag: &str) -> tempfile::TempDir { + tempfile::Builder::new().prefix(&format!("craft-agents-{tag}-")).tempdir().expect("a temp dir") +} + +/// Waits up to five seconds for `done`. +fn wait_for(mut done: impl FnMut() -> bool) -> bool { + let started = Instant::now(); + while !done() { + if started.elapsed() > Duration::from_secs(5) { + return false; + } + std::thread::sleep(Duration::from_millis(5)); + } + true +} + +const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; + +/// Writes `text` as an owner-only token file, as an app's own token writer does. +fn write_token(path: &Path, text: &str) { + std::fs::write(path, text).unwrap(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600)).unwrap(); + } +} + +/// An app accepting agents in `dir`: a listener on a free loopback port, its token file and its +/// connection file. Dropping the listener leaves the file behind, as a crashed app would. +fn publish(dir: &Path) -> (TcpListener, Connection) { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + write_token(&dir.join(TOKEN_FILE), &format!("{}\n", TOKEN.to_ascii_uppercase())); + let c = Connection::new(listener.local_addr().unwrap().port(), dir.join(TOKEN_FILE), "Test 1.0"); + write_connection(dir, &c).unwrap(); + (listener, c) +} + +// ---- The launcher's switch ---------------------------------------------------------------------- + +/// With the `AI-MCP` flag only the launcher's switch decides; without it the app's earlier consent. +#[test] +fn with_the_flag_only_the_launchers_switch_lets_agents_in() { + assert!(agents_allowed(false, false, true), "without the flag, the app's earlier consent"); + assert!(!agents_allowed(false, true, false), "the launcher's list means nothing without the flag"); + assert!(agents_allowed(true, true, false)); + assert!(!agents_allowed(true, false, true), "no second switch in the app"); + assert!(AgentSwitch::fixed(true, true).allows(false)); + assert!(!AgentSwitch::fixed(false, true).allows(false)); +} + +/// The switch follows the launcher's list within a poll, wakes the app once per change rather than +/// once per poll, and its thread ends once the last clone is dropped. +#[test] +fn the_switch_wakes_once_per_change() { + let launcher = Arc::new(AtomicBool::new(false)); + let probes = Arc::new(AtomicUsize::new(0)); + let wakes = Arc::new(AtomicUsize::new(0)); + // Held by the watch thread through its probe: gone once the thread has ended. + let alive = Arc::new(()); + let probe = { + let (launcher, probes, alive) = (launcher.clone(), probes.clone(), alive.clone()); + move || { + let _ = &alive; + probes.fetch_add(1, Ordering::Relaxed); + launcher.load(Ordering::Relaxed) + } + }; + let wake = { + let wakes = wakes.clone(); + move || { + wakes.fetch_add(1, Ordering::Relaxed); + } + }; + let switch = AgentSwitch::watch_with(true, probe, Duration::from_millis(5), wake); + let clone = switch.clone(); + assert!(!switch.launcher()); + + launcher.store(true, Ordering::Relaxed); + assert!(wait_for(|| clone.launcher()), "the switch follows the launcher"); + assert!(switch.allows(false)); + let polled = probes.load(Ordering::Relaxed); + assert!(wait_for(|| probes.load(Ordering::Relaxed) > polled + 10)); + launcher.store(false, Ordering::Relaxed); + assert!(wait_for(|| !switch.launcher())); + assert!(wait_for(|| wakes.load(Ordering::Relaxed) == 2)); + assert_eq!(wakes.load(Ordering::Relaxed), 2, "one wake per change, not per poll"); + + drop(switch); + drop(clone); + assert!(wait_for(|| Arc::strong_count(&alive) == 1), "the watch ended with the last switch"); + let after_end = probes.load(Ordering::Relaxed); + std::thread::sleep(Duration::from_millis(20)); + assert_eq!(probes.load(Ordering::Relaxed), after_end, "nothing probes after the watch ended"); +} + +// ---- The connection file ------------------------------------------------------------------------ + +/// A published connection reads back in its documented shape, and only the process that wrote it +/// removes it. +#[test] +fn a_published_connection_reads_back_and_only_its_writer_removes_it() { + let dir = temp_dir("conn"); + let dir = dir.path(); + assert_eq!(read_connection(dir).unwrap(), None, "no file"); + let c = Connection::new(7878, dir.join(TOKEN_FILE), "MyApp 1.2.3"); + write_connection(dir, &c).unwrap(); + assert_eq!(read_connection(dir).unwrap(), Some(c.clone())); + assert_eq!(c.addr(), "127.0.0.1:7878"); + let v: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(dir.join(CONNECTION_FILE)).unwrap()).unwrap(); + let mut keys: Vec<_> = v.as_object().unwrap().keys().cloned().collect(); + keys.sort(); + assert_eq!(keys, ["app", "pid", "port", "tokenFile", "version"]); + assert_eq!((v["version"].as_u64(), v["port"].as_u64(), v["app"].as_str()), (Some(1), Some(7878), Some("MyApp 1.2.3"))); + + remove_connection(dir, c.pid.wrapping_add(1)); + assert!(dir.join(CONNECTION_FILE).is_file(), "another process's file stays"); + remove_connection(dir, c.pid); + assert!(!dir.join(CONNECTION_FILE).exists()); +} + +/// A damaged, foreign or port-0 file reads as none; a directory in its place is an error and is +/// left alone; a file nobody listens on is removed as stale and a live one kept. +#[test] +fn a_damaged_foreign_or_stale_connection_file_counts_as_none() { + let dir = temp_dir("bad-conn"); + let dir = dir.path(); + for text in [ + &b""[..], + b"{not json", + b"[]", + br#"{"version":2,"pid":1,"port":7878,"tokenFile":"t","app":"x"}"#, + br#"{"version":1,"pid":1,"port":0,"tokenFile":"t","app":"x"}"#, + b"\xff\xfe not utf-8", + ] { + std::fs::write(dir.join(CONNECTION_FILE), text).unwrap(); + assert_eq!(read_connection(dir).unwrap(), None, "{}", String::from_utf8_lossy(text)); + remove_stale_connection(dir); + assert!(!dir.join(CONNECTION_FILE).exists(), "an unreadable file is not a connection"); + } + + std::fs::create_dir(dir.join(CONNECTION_FILE)).unwrap(); + assert!(read_connection(dir).is_err()); + remove_stale_connection(dir); + assert!(dir.join(CONNECTION_FILE).is_dir(), "anything but a regular file is left alone"); + std::fs::remove_dir(dir.join(CONNECTION_FILE)).unwrap(); + + let live = TcpListener::bind("127.0.0.1:0").unwrap(); + let live_port = live.local_addr().unwrap().port(); + write_connection(dir, &Connection { pid: 1, ..Connection::new(live_port, dir.join(TOKEN_FILE), "x") }).unwrap(); + remove_stale_connection(dir); + assert!(dir.join(CONNECTION_FILE).is_file(), "something listens on {live_port}"); + drop(live); + let closed = TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port(); + write_connection(dir, &Connection { pid: 1, ..Connection::new(closed, dir.join(TOKEN_FILE), "x") }).unwrap(); + remove_stale_connection(dir); + assert!(!dir.join(CONNECTION_FILE).exists(), "nothing listens on {closed}"); +} + +// ---- The CLI's side ----------------------------------------------------------------------------- + +/// What the stand-in app made: a window client (its window) or a headless session (its folders), +/// with counts of each. +#[derive(Default)] +struct Made { + connects: AtomicUsize, + sessions: AtomicUsize, +} + +type TestLive = Live; + +fn config(dir: &Path, consent: Consent, made: &Arc) -> LiveConfig { + let (a, b) = (made.clone(), made.clone()); + let mut cfg = LiveConfig::new( + "Test", + dir.to_path_buf(), + move |_: &Path| consent.clone(), + move |w: &Window| { + a.connects.fetch_add(1, Ordering::Relaxed); + Ok(w.clone()) + }, + move |f: &HeadlessFolders| { + b.sessions.fetch_add(1, Ordering::Relaxed); + Ok(f.clone()) + }, + ); + cfg.poll = Duration::from_millis(5); + cfg +} + +fn settings(when: WhenAppClosed, read: &str, write: &str) -> AgentSettings { + let mut s = AgentSettings::default(); + s.when_app_closed = when; + s.read_root = read.into(); + s.write_root = write.into(); + s +} + +fn allowed(when: WhenAppClosed) -> Consent { + Consent::new(true, settings(when, "/app-in", "/app-out")) +} + +fn headless_folders(route: Result, String>) -> HeadlessFolders { + match route { + Ok(Route::Headless(f)) => f, + Ok(Route::Window(w)) => panic!("expected headless, got the window {w:?}"), + Err(e) => panic!("expected headless, got the error {e}"), + } +} + +fn window(route: Result, String>) -> Window { + match route { + Ok(Route::Window(w)) => w, + Ok(Route::Headless(f)) => panic!("expected the window, went headless with {f:?}"), + Err(e) => panic!("expected the window, got the error {e}"), + } +} + +fn paths(p: &[&str]) -> Vec { + p.iter().map(PathBuf::from).collect() +} + +/// An app accepting agents takes the call; the same port, token and process keep the client, a +/// restarted app (another process on the same port and token) gets a new one. +#[test] +fn an_open_app_takes_the_call_and_keeps_its_client_until_it_restarts() { + let dir = temp_dir("window"); + let (_listener, c) = publish(dir.path()); + let made = Arc::new(Made::default()); + // Even without consent: an app publishes its connection only while it accepts agents. + let live = TestLive::new(config(dir.path(), Consent::default(), &made)); + let w = window(live.resolve()); + assert_eq!( + (w.port, w.pid, w.token.as_str(), w.addr()), + (c.port, c.pid, TOKEN.to_ascii_uppercase().as_str(), c.addr()), + "the token is trimmed, otherwise as written" + ); + window(live.resolve()); + assert_eq!(made.connects.load(Ordering::Relaxed), 1, "the same window keeps its client"); + assert!(matches!(live.current(), Some(Route::Window(_)))); + + write_connection(dir.path(), &Connection { pid: c.pid.wrapping_add(1), ..c.clone() }).unwrap(); + assert_eq!(window(live.resolve()).pid, c.pid.wrapping_add(1)); + assert_eq!(made.connects.load(Ordering::Relaxed), 2, "a restarted app gets a new client"); + assert_eq!(made.sessions.load(Ordering::Relaxed), 0); +} + +/// No app accepts agents and the person doesn't let them use it: headless with only the command's +/// folders, never the app's. +#[test] +fn without_consent_a_closed_app_runs_headless_with_the_commands_folders_only() { + let dir = temp_dir("no-consent"); + let made = Arc::new(Made::default()); + let consent = Consent::new(false, settings(WhenAppClosed::Launch, "/app-in", "/app-out")); + let live = TestLive::new(config(dir.path(), consent.clone(), &made)); + assert_eq!(headless_folders(live.resolve()), HeadlessFolders::default(), "no folders given, none used"); + + let mut cfg = config(dir.path(), consent, &made); + cfg.read_roots = paths(&["/cli-in"]); + cfg.write_root = Some(PathBuf::from("/cli-out")); + let f = headless_folders(TestLive::new(cfg).resolve()); + assert_eq!((f.read, f.write), (paths(&["/cli-in"]), Some(PathBuf::from("/cli-out")))); +} + +/// Agents allowed, app closed, "headless": the app's agent folders, each replaced by the command's. +#[test] +fn allowed_and_closed_runs_headless_with_the_apps_folders_unless_the_command_gives_its_own() { + let dir = temp_dir("headless"); + let made = Arc::new(Made::default()); + let f = headless_folders(TestLive::new(config(dir.path(), allowed(WhenAppClosed::Headless), &made)).resolve()); + assert_eq!((f.read, f.write), (paths(&["/app-in"]), Some(PathBuf::from("/app-out")))); + + let mut cfg = config(dir.path(), allowed(WhenAppClosed::Headless), &made); + cfg.read_roots = paths(&["/cli-a", "/cli-b"]); + let f = headless_folders(TestLive::new(cfg).resolve()); + assert_eq!((f.read, f.write), (paths(&["/cli-a", "/cli-b"]), Some(PathBuf::from("/app-out")))); + + let mut cfg = config(dir.path(), allowed(WhenAppClosed::Headless), &made); + cfg.write_root = Some(PathBuf::from("/cli-out")); + let f = headless_folders(TestLive::new(cfg).resolve()); + assert_eq!((f.read, f.write), (paths(&["/app-in"]), Some(PathBuf::from("/cli-out")))); +} + +/// Agents allowed, app closed, "error": the call fails with words that name the app; the command's +/// choice wins over the app's. +#[test] +fn the_closed_app_choice_decides_and_the_command_overrides_it() { + let dir = temp_dir("error"); + let made = Arc::new(Made::default()); + let err = TestLive::new(config(dir.path(), allowed(WhenAppClosed::Error), &made)).resolve().err().unwrap(); + assert_eq!(err, "Test isn't running: open it, then try again."); + + let mut cfg = config(dir.path(), allowed(WhenAppClosed::Error), &made); + cfg.when_closed = Some(WhenAppClosed::Headless); + headless_folders(TestLive::new(cfg).resolve()); + let mut cfg = config(dir.path(), allowed(WhenAppClosed::Headless), &made); + cfg.when_closed = Some(WhenAppClosed::Error); + assert!(TestLive::new(cfg).resolve().is_err()); +} + +/// Once headless, the session stays headless even when the app starts, so documents don't move +/// under the agent. +#[test] +fn a_headless_session_stays_headless() { + let dir = temp_dir("sticky"); + let made = Arc::new(Made::default()); + let live = TestLive::new(config(dir.path(), Consent::default(), &made)); + headless_folders(live.resolve()); + let _app = publish(dir.path()); + headless_folders(live.resolve()); + assert_eq!((made.sessions.load(Ordering::Relaxed), made.connects.load(Ordering::Relaxed)), (1, 0), "one session, no window"); +} + +/// A connection file left by an app that crashed counts as a closed app. +#[test] +fn a_crashed_apps_connection_file_counts_as_closed() { + let dir = temp_dir("crashed"); + drop(publish(dir.path()).0); + let made = Arc::new(Made::default()); + headless_folders(TestLive::new(config(dir.path(), Consent::default(), &made)).resolve()); + assert_eq!(find_window(dir.path(), "Test").unwrap(), None); +} + +/// A token file that isn't a token, is too big, is missing, isn't a regular file or (on Unix) +/// others can read fails the call and names the app; nothing is sent to the window. +#[test] +fn a_bad_token_file_fails_the_call() { + let dir = temp_dir("token"); + let (_listener, _c) = publish(dir.path()); + let made = Arc::new(Made::default()); + for bad in ["", " \n", "not a token", &"a".repeat(5000)] { + write_token(&dir.path().join(TOKEN_FILE), bad); + let err = TestLive::new(config(dir.path(), Consent::default(), &made)).resolve().err().unwrap(); + assert!(err.starts_with("Test's agent token: "), "{err}"); + } + // Any token the app's server accepts is passed on: upper case, dashes. + write_token(&dir.path().join(TOKEN_FILE), "AB12-cd34-EF56-0000-1111-2222-3333-4444"); + assert_eq!(find_window(dir.path(), "Test").unwrap().unwrap().token, "AB12-cd34-EF56-0000-1111-2222-3333-4444"); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let token = dir.path().join(TOKEN_FILE); + write_token(&token, TOKEN); + std::fs::set_permissions(&token, std::fs::Permissions::from_mode(0o644)).unwrap(); + let err = find_window(dir.path(), "Test").err().unwrap(); + assert!(err.contains("readable by group or others"), "{err}"); + // A FIFO would block a plain open until something writes to it. + std::fs::remove_file(&token).unwrap(); + assert!(std::process::Command::new("mkfifo").arg(&token).status().unwrap().success()); + let err = find_window(dir.path(), "Test").err().unwrap(); + assert!(err.contains("not a regular file"), "{err}"); + } + std::fs::remove_file(dir.path().join(TOKEN_FILE)).unwrap(); + assert!(find_window(dir.path(), "Test").is_err()); + assert_eq!(made.connects.load(Ordering::Relaxed), 0); +} + +/// The app's own errors reach the agent with what was being done. +#[test] +fn the_apps_errors_reach_the_agent() { + let dir = temp_dir("app-errors"); + let consent = Consent::default(); + let cfg: LiveConfig = LiveConfig::new( + "Test", + dir.path().to_path_buf(), + move |_: &Path| consent.clone(), + |w: &Window| Ok(w.clone()), + |_: &HeadlessFolders| Err("no such folder".into()), + ); + assert_eq!(TestLive::new(cfg).resolve().err().unwrap(), "Test can't use the automation roots: no such folder"); + + let (_listener, _c) = publish(dir.path()); + let cfg: LiveConfig = LiveConfig::new( + "Test", + dir.path().to_path_buf(), + |_: &Path| Consent::default(), + |_: &Window| Err("refused".into()), + |f: &HeadlessFolders| Ok(f.clone()), + ); + let live = TestLive::new(cfg); + assert_eq!(live.resolve().err().unwrap(), "couldn't reach Test's window: refused"); + assert!(live.current().is_none(), "a failed connect leaves no route"); +} + +/// "Launch" without a way to start the app, a start that fails, and an app that never accepts +/// agents each end with words that say what to do. +#[test] +fn a_launch_that_cannot_happen_or_never_finishes_says_what_to_do() { + let dir = temp_dir("launch-fails"); + let made = Arc::new(Made::default()); + let err = TestLive::new(config(dir.path(), allowed(WhenAppClosed::Launch), &made)).resolve().err().unwrap(); + assert_eq!(err, "Test isn't running, and this install can't start it from here: open Test, then try again."); + + let mut cfg = config(dir.path(), allowed(WhenAppClosed::Launch), &made); + cfg.launch = Some(Box::new(|| Err("boom".into()))); + assert_eq!(TestLive::new(cfg).resolve().err().unwrap(), "couldn't start Test: boom"); + + let mut cfg = config(dir.path(), allowed(WhenAppClosed::Launch), &made); + cfg.launch = Some(Box::new(|| Ok(()))); + cfg.launch_timeout = Duration::from_millis(40); + let err = TestLive::new(cfg).resolve().err().unwrap(); + assert!(err.starts_with("Test didn't accept agents within 0 s of starting."), "{err}"); +} + +/// "Launch" starts the app once, also for calls that arrive together, and the calls go to its +/// window once it accepts agents. +#[test] +fn a_started_app_takes_the_call_and_concurrent_calls_start_it_once() { + let dir = temp_dir("launch"); + let made = Arc::new(Made::default()); + let launches = Arc::new(AtomicUsize::new(0)); + let app: Arc>> = Arc::new(Mutex::new(None)); + let mut cfg = config(dir.path(), allowed(WhenAppClosed::Launch), &made); + let (d, n, slot) = (dir.path().to_path_buf(), launches.clone(), app.clone()); + cfg.launch = Some(Box::new(move || { + n.fetch_add(1, Ordering::Relaxed); + let (d, slot) = (d.clone(), slot.clone()); + // The app takes a moment before it accepts agents. + std::thread::spawn(move || { + std::thread::sleep(Duration::from_millis(60)); + *slot.lock().unwrap() = Some(publish(&d).0); + }); + Ok(()) + })); + let live = Arc::new(TestLive::new(cfg)); + let calls: Vec<_> = (0..4) + .map(|_| { + let live = live.clone(); + std::thread::spawn(move || window(live.resolve())) + }) + .collect(); + let ports: Vec = calls.into_iter().map(|c| c.join().unwrap().port).collect(); + assert_eq!(launches.load(Ordering::Relaxed), 1, "one start for every call"); + assert!(ports.windows(2).all(|p| p[0] == p[1]), "{ports:?}"); + assert_eq!(made.connects.load(Ordering::Relaxed), 1); +} + +/// Calls that queued while a start was under way get its error when the app still isn't there, +/// rather than starting it again; a call made afterwards tries again. +#[test] +fn calls_queued_behind_a_failed_start_share_its_error() { + let dir = temp_dir("launch-shared"); + let made = Arc::new(Made::default()); + let launches = Arc::new(AtomicUsize::new(0)); + let mut cfg = config(dir.path(), allowed(WhenAppClosed::Launch), &made); + let entered = Arc::new(AtomicUsize::new(0)); + let (n, e) = (launches.clone(), entered.clone()); + // The app is started but never accepts agents within the timeout. The start waits until every + // call is under way and then a while longer, so a call that hasn't reached its lookup by the + // time the start ends is very unlikely (there is no hook between the two). + cfg.launch = Some(Box::new(move || { + n.fetch_add(1, Ordering::Relaxed); + assert!(wait_for(|| e.load(Ordering::Relaxed) == 4), "every call starts"); + std::thread::sleep(Duration::from_millis(250)); + Ok(()) + })); + cfg.launch_timeout = Duration::from_millis(150); + let live = Arc::new(TestLive::new(cfg)); + let calls: Vec<_> = (0..4) + .map(|_| { + let (live, entered) = (live.clone(), entered.clone()); + std::thread::spawn(move || { + entered.fetch_add(1, Ordering::Relaxed); + live.resolve() + }) + }) + .collect(); + let answers: Vec<_> = calls.into_iter().map(|c| c.join().unwrap()).collect(); + assert_eq!(launches.load(Ordering::Relaxed), 1, "one start for the calls that came together"); + for answer in &answers { + let err = answer.as_ref().err().unwrap(); + assert!(err.starts_with("Test didn't accept agents within"), "{err}"); + } + assert!(live.resolve().is_err()); + assert_eq!(launches.load(Ordering::Relaxed), 2, "a later call starts the app again"); +} + +/// Allow Agent Control off refuses agents on the CLI's side too, as the app does by not +/// listening: no start, and only the command's folders. +#[test] +fn allow_agent_control_off_counts_as_not_allowed() { + let dir = temp_dir("aac-off"); + let made = Arc::new(Made::default()); + let mut s = settings(WhenAppClosed::Launch, "/app-in", "/app-out"); + s.allow_agent_control = false; + let mut cfg = config(dir.path(), Consent::new(true, s), &made); + cfg.launch = Some(Box::new(|| panic!("nothing may start the app"))); + cfg.read_roots = paths(&["/cli-in"]); + let f = headless_folders(TestLive::new(cfg).resolve()); + assert_eq!((f.read, f.write), (paths(&["/cli-in"]), None)); +} + +/// A window route is dropped once no app accepts agents, so a dead client isn't kept or handed +/// back. +#[test] +fn a_window_that_went_away_is_forgotten() { + let dir = temp_dir("gone"); + let made = Arc::new(Made::default()); + let live = TestLive::new(config(dir.path(), allowed(WhenAppClosed::Error), &made)); + let (listener, c) = publish(dir.path()); + window(live.resolve()); + drop(listener); + remove_connection(dir.path(), c.pid); + assert!(live.resolve().is_err(), "the app is closed and the choice is an error"); + assert!(live.current().is_none(), "the dead window is gone"); +} + +/// A headless session with the app's agent folders ends when the person stops letting agents in; +/// one with only the command's folders stays. +#[test] +fn a_headless_session_with_the_apps_folders_ends_with_consent() { + let dir = temp_dir("revoke"); + let made = Arc::new(Made::default()); + let on = Arc::new(AtomicBool::new(true)); + let gate = on.clone(); + let (b, c) = (made.clone(), made.clone()); + let cfg: LiveConfig = LiveConfig::new( + "Test", + dir.path().to_path_buf(), + move |_: &Path| Consent::new(gate.load(Ordering::Relaxed), settings(WhenAppClosed::Headless, "/app-in", "/app-out")), + move |w: &Window| { + b.connects.fetch_add(1, Ordering::Relaxed); + Ok(w.clone()) + }, + move |f: &HeadlessFolders| { + c.sessions.fetch_add(1, Ordering::Relaxed); + Ok(f.clone()) + }, + ); + let live = TestLive::new(cfg); + assert_eq!(headless_folders(live.resolve()).read, paths(&["/app-in"])); + on.store(false, Ordering::Relaxed); + assert_eq!(headless_folders(live.resolve()), HeadlessFolders::default(), "the app's folders went with the consent"); + on.store(true, Ordering::Relaxed); + assert_eq!(headless_folders(live.resolve()), HeadlessFolders::default(), "a session without the app's folders stays"); + assert_eq!(made.sessions.load(Ordering::Relaxed), 2); +} + +/// A huge launch timeout or poll is cut down rather than overflowing the deadline or blocking. +#[test] +fn a_huge_launch_timeout_or_poll_neither_panics_nor_hangs() { + let dir = temp_dir("huge"); + let made = Arc::new(Made::default()); + let mut cfg = config(dir.path(), allowed(WhenAppClosed::Launch), &made); + let (d, app) = (dir.path().to_path_buf(), Arc::new(Mutex::new(None))); + let slot = app.clone(); + cfg.launch = Some(Box::new(move || { + *slot.lock().unwrap() = Some(publish(&d).0); + Ok(()) + })); + cfg.launch_timeout = Duration::MAX; + cfg.poll = Duration::MAX; + let started = Instant::now(); + window(TestLive::new(cfg).resolve()); + assert!(started.elapsed() < Duration::from_secs(5), "{:?}", started.elapsed()); +} diff --git a/crates/csv/README.md b/crates/csv/README.md index bfd525c8c..8fd264d4c 100644 --- a/crates/csv/README.md +++ b/crates/csv/README.md @@ -11,7 +11,7 @@ mapping a SYLK sheet onto a document are the caller's work. | Function | What it does | |---|---| | `decode_text(bytes)` | UTF-8 and UTF-16 byte order marks; without one, valid UTF-8 is kept; other bytes are Windows-1256 when they read as Arabic, else Windows-1252 | -| `sniff_delimiter(text, quote)` | comma, semicolon or tab: the one with the most consistent field count over the first 20 non-blank records in a 64 KiB sample; when no candidate finds coherent complete records with a delimiter in each, a candidate that finds no complete record counts the delimiters of the first record up to the end of the sample, or up to a quoted field still open there, and a quote inside a field that does not start with one makes that record incoherent; quote boundaries must be coherent, and ties prefer tab, comma, then semicolon | +| `sniff_delimiter(text, quote)` | comma, semicolon or tab: the one with the most consistent field count over the first 20 records with other text in a 64 KiB sample; when none separates those records, the candidates whose records hold only their delimiters and whitespace (rows of empty cells) are compared the same way, leaving out any candidate that found a record with other text; when no candidate finds coherent complete records with a delimiter in each, a candidate that finds no complete record with other text counts the delimiters of the first such record up to the end of the sample, or up to a quoted field still open there (after its rows of empty cells, a record without its delimiter is left out), and a quote inside a field that does not start with one makes that record incoherent; quote boundaries must be coherent, and ties prefer tab, comma, then semicolon | | `parse_records(text, delim, quote, max_fields, on_record)` | records of fields, one callback per record (return `false` to stop); CR, LF and CRLF line ends; quoted fields with doubled quotes and line breaks; a quote in the middle of a field is text | | `records(text, delim, quote, max_records, max_fields)` | the same, collected | | `push_field(out, field, delim)`, `field_len(field, delim)` | one field as written, quoted only when it holds the delimiter, a quote or a line break; its exact length, to enforce a size cap before writing | diff --git a/crates/csv/src/lib.rs b/crates/csv/src/lib.rs index 70f6148a6..395ad2152 100644 --- a/crates/csv/src/lib.rs +++ b/crates/csv/src/lib.rs @@ -33,13 +33,17 @@ pub use decode::{decode_text, decode_utf8}; /// Picks comma, semicolon or tab by consistent field counts in the first non-blank records. /// Quotes start only at a candidate field boundary; candidates with incoherent quoted fields /// are discarded when another coherent candidate separates the records. Ties prefer tab, -/// then comma, then semicolon. Comma is the fallback when no candidate separates the text. +/// then comma, then semicolon. When no candidate separates the records that hold other text, +/// the same rules pick among the candidates whose records hold only their delimiters and +/// whitespace, such as an exported row of empty cells; a candidate that finds a record with +/// other text is left out of that pick. Comma is the fallback when neither pick finds one. /// Only the first 64 KiB are read. A record cut off at the end of that sample is left out, /// except when no candidate finds coherent complete records with a delimiter in each. Then a candidate -/// that finds no complete record counts the delimiters read so far in the first record, and that -/// record is incoherent when it has a quote inside a field that does not start with one. When one -/// of those candidates ends the sample inside a quoted field, each of them counts only up to that -/// field's opening quote. +/// that finds no complete record with other text counts the delimiters read so far in the first +/// such record, unless it found rows of its empty cells and that record has none of its +/// delimiters. That record is incoherent when it has a quote inside a field that does not start +/// with one. When one of those candidates ends the sample inside a quoted field, each of them +/// counts only up to that field's opening quote. pub fn sniff_delimiter(text: &str, quote: char) -> u8 { const SAMPLE_BYTES: usize = 64 * 1024; let mut sample_end = text.len().min(SAMPLE_BYTES); @@ -64,7 +68,15 @@ pub fn sniff_delimiter(text: &str, quote: char) -> u8 { (scan.count, scan.record_has_content, scan.record_coherent, scan.record_bare_quote) = (before_cut.count, before_cut.record_has_content, before_cut.record_coherent, before_cut.record_bare_quote); } - if scan.record_has_content { + if scan.delimiter_only_counts.is_empty() { + if scan.record_has_content { + scan.coherent &= scan.record_coherent && !scan.record_bare_quote; + scan.counts.push(scan.count); + } else { + scan.push_delimiter_only_record(); + } + } else if scan.record_has_content && scan.count > 0 { + // After rows of empty cells, a cut record without this delimiter is left out. scan.coherent &= scan.record_coherent && !scan.record_bare_quote; scan.counts.push(scan.count); } @@ -79,6 +91,8 @@ pub fn sniff_delimiter(text: &str, quote: char) -> u8 { } else if scan.record_has_content { scan.coherent &= scan.record_coherent; scan.counts.push(scan.count); + } else { + scan.push_delimiter_only_record(); } } } @@ -86,23 +100,34 @@ pub fn sniff_delimiter(text: &str, quote: char) -> u8 { } fn pick_delimiter(scans: [DelimiterScan; 3]) -> u8 { - let candidates = - scans.map(|scan| (scan.delimiter, scan.counts.iter().copied().min().unwrap_or(0), scan.counts.iter().sum::(), scan.coherent)); + let with_text = scans.each_ref().map(|scan| (scan.delimiter, scan.counts.as_slice(), scan.coherent)); + // Records of delimiters alone have no quotes, so they are coherent. + let delimiters_only = + scans.each_ref().map(|scan| (scan.delimiter, if scan.counts.is_empty() { scan.delimiter_only_counts.as_slice() } else { &[] }, true)); + best_delimiter(with_text).or_else(|| best_delimiter(delimiters_only)).unwrap_or(b',') +} + +fn best_delimiter(candidates: [(u8, &[usize], bool); 3]) -> Option { + let candidates = candidates + .map(|(delimiter, counts, coherent)| (delimiter, counts.iter().copied().min().unwrap_or(0), counts.iter().sum::(), coherent)); let prefer_coherent = candidates.iter().any(|(_, min, _, coherent)| *min > 0 && *coherent); - let mut best = (b',', 0usize, 0usize); + let mut best: Option<(u8, usize, usize)> = None; for (delimiter, min, total, coherent) in candidates { - if min > 0 && (!prefer_coherent || coherent) && (min, total) > (best.1, best.2) { - best = (delimiter, min, total); + if min > 0 && (!prefer_coherent || coherent) && best.is_none_or(|(_, best_min, best_total)| (min, total) > (best_min, best_total)) { + best = Some((delimiter, min, total)); } } - best.0 + best.map(|(delimiter, _, _)| delimiter) } /// One candidate delimiter's pass over the sample in [`sniff_delimiter`]. struct DelimiterScan { delimiter: u8, - /// Delimiter counts of the complete non-blank records, at most 20. + /// Delimiter counts of the complete records that hold other text, at most 20. counts: Vec, + /// Delimiter counts of the complete records that hold only this candidate's delimiters and + /// whitespace, at most 20. They do not count toward the 20 records above. + delimiter_only_counts: Vec, /// Whether every counted record had coherent quoted fields. coherent: bool, reached_record_limit: bool, @@ -117,10 +142,21 @@ struct DelimiterScan { open_quote: Option, } +impl DelimiterScan { + /// Keeps the open record's delimiter count when the record has no other text and at least + /// one delimiter. + fn push_delimiter_only_record(&mut self) { + if !self.record_has_content && self.count > 0 && self.delimiter_only_counts.len() < 20 { + self.delimiter_only_counts.push(self.count); + } + } +} + fn scan_delimiter(sample: &str, delimiter: u8, quote: char) -> DelimiterScan { let mut scan = DelimiterScan { delimiter, counts: Vec::new(), + delimiter_only_counts: Vec::new(), coherent: true, reached_record_limit: false, count: 0, @@ -158,6 +194,8 @@ fn scan_delimiter(sample: &str, delimiter: u8, quote: char) -> DelimiterScan { scan.reached_record_limit = true; break; } + } else { + scan.push_delimiter_only_record(); } scan.count = 0; after_quote = false; @@ -403,6 +441,64 @@ mod tests { assert_eq!(sniff_delimiter(&format!("a,b,c;\"hello,\";d\n{}", "x;y;z\n".repeat(12_000)), '"'), b';'); } + // A sheet whose only value is far down exports rows of empty cells that fill the whole sample. + #[test] + fn delimiter_sniffing_reads_a_sparse_semicolon_export() { + assert_eq!(sniff_delimiter(&format!("{};7\n", ";\n".repeat(40_000)), '"'), b';'); + } + + #[test] + fn delimiter_sniffing_reads_a_sparse_semicolon_export_with_crlf() { + assert_eq!(sniff_delimiter(&format!("{};7\r\n", ";\r\n".repeat(40_000)), '"'), b';'); + } + + #[test] + fn delimiter_sniffing_reads_a_sparse_tab_export() { + assert_eq!(sniff_delimiter(&format!("{}\t7\r\n", "\t\r\n".repeat(40_000)), '"'), b'\t'); + } + + #[test] + fn delimiter_sniffing_reads_a_short_file_of_empty_semicolon_cells() { + assert_eq!(sniff_delimiter(";;\n;;\n", '"'), b';'); + assert_eq!(sniff_delimiter(";;\r\n;;", '"'), b';'); + } + + #[test] + fn delimiter_sniffing_reads_empty_semicolon_cells_padded_with_whitespace() { + assert_eq!(sniff_delimiter(&"; ; \n".repeat(20_000), '"'), b';'); + } + + #[test] + fn delimiter_sniffing_reads_a_first_record_of_empty_cells_longer_than_the_sample() { + assert_eq!(sniff_delimiter(&format!("{}\n1;2\n", ";".repeat(70_000)), '"'), b';'); + } + + #[test] + fn delimiter_sniffing_leaves_out_a_cut_record_after_a_row_of_empty_cells() { + assert_eq!(sniff_delimiter(&format!(";\n{};7\n", "x".repeat(70_000)), '"'), b';'); + } + + #[test] + fn delimiter_sniffing_counts_a_long_record_after_a_row_of_empty_cells() { + // Delimiters inside the long record's quoted field are text for every candidate. + assert_eq!(sniff_delimiter(&format!("\t\nname\t\"{}\"\n", "x,y".repeat(30_000)), '"'), b'\t'); + assert_eq!(sniff_delimiter(&format!(";\nname;\"{}\"\n", "x,y\t".repeat(20_000)), '"'), b';'); + } + + #[test] + fn delimiter_sniffing_lets_records_with_text_outweigh_records_of_delimiters_alone() { + // Rows of tabs alone are blank to the other candidates and do not outweigh them. + assert_eq!(sniff_delimiter(&format!("{}a;b\nc;d\n", "\t\n".repeat(25)), '"'), b';'); + assert_eq!(sniff_delimiter(&format!("{}a;b\nc;d\n", "\t\t\n".repeat(25)), '"'), b';'); + // The same holds for a record with text cut off at the end of the sample. + assert_eq!(sniff_delimiter(&format!("\t\n{}", "x;".repeat(40_000)), '"'), b';'); + // A candidate with a record of other text is judged on those records alone. + assert_eq!(sniff_delimiter(&format!("title\n{}", ";\n".repeat(25)), '"'), b','); + // Rows of empty cells in a comma file; comma is also the fallback. + assert_eq!(sniff_delimiter("a,b,c,d\n,,,\n,,,\n1,2,3,4\n", '"'), b','); + assert_eq!(sniff_delimiter(&format!("{}x;y\n", ",,,\n".repeat(20_000)), '"'), b','); + } + #[test] fn parser_stops_collecting_fields_at_the_cap() { let (max, extra) = (16_384usize, 50); diff --git a/crates/designcraft-format/src/lib.rs b/crates/designcraft-format/src/lib.rs index eab431eab..9ce481a3b 100644 --- a/crates/designcraft-format/src/lib.rs +++ b/crates/designcraft-format/src/lib.rs @@ -127,9 +127,10 @@ pub fn starts_designcraft(prefix: &[u8]) -> bool { craft_document_bundle::starts_with_mimetype(prefix, BUNDLE) } -/// Read the first-page PNG preview from a ZIP package, with a fixed 4 MiB cap. +/// Read the first-page PNG preview from an unprefixed native ZIP package, with a fixed 4 MiB cap. +/// Nonmatching signatures are rejected after at most four bytes read. pub fn read_preview(reader: R) -> Option> { - craft_document_bundle::read_preview_from(reader, PREVIEW) + craft_document_bundle::read_unprefixed_preview_from(reader, PREVIEW) } fn is_linked(document: &Value, id: &str) -> bool { diff --git a/crates/designcraft-format/src/tests.rs b/crates/designcraft-format/src/tests.rs index 38cf1c34f..736d2e17c 100644 --- a/crates/designcraft-format/src/tests.rs +++ b/crates/designcraft-format/src/tests.rs @@ -167,3 +167,37 @@ fn bytes_supplied_for_a_linked_asset_are_not_written() -> Result<(), Box(&bytes)?.assets, [("8".to_owned(), b"kept".to_vec())]); Ok(()) } + +#[test] +fn preview_uses_the_strict_signature_path_without_losing_cursor_independence() -> Result<(), Box> { + struct Counted { + cursor: std::io::Cursor>, + bytes_read: usize, + } + impl std::io::Read for Counted { + fn read(&mut self, out: &mut [u8]) -> std::io::Result { + let n = self.cursor.read(out)?; + self.bytes_read += n; + Ok(n) + } + } + impl std::io::Seek for Counted { + fn seek(&mut self, position: std::io::SeekFrom) -> std::io::Result { + self.cursor.seek(position) + } + } + let mut non_zip = Counted { cursor: std::io::Cursor::new(vec![0x42; 1 << 20]), bytes_read: 0 }; + non_zip.cursor.set_position(100); + assert_eq!(read_preview(&mut non_zip), None); + assert!(non_zip.bytes_read <= 4); + + let bytes = save(&json!({}), "DesignCraft test", Some(b"png"), &[], &[])?; + let mut cursor = std::io::Cursor::new(&bytes); + cursor.set_position(bytes.len() as u64); + assert_eq!(read_preview(cursor), Some(b"png".to_vec())); + let mut prefixed = b"MZsynthetic-prefix".to_vec(); + prefixed.extend(bytes); + assert_eq!(craft_document_bundle::read_preview_from(std::io::Cursor::new(&prefixed), PREVIEW), Some(b"png".to_vec())); + assert_eq!(read_preview(std::io::Cursor::new(prefixed)), None); + Ok(()) +} diff --git a/crates/doc-binary/Cargo.toml b/crates/doc-binary/Cargo.toml index 6c5a5625e..98b7e2c69 100644 --- a/crates/doc-binary/Cargo.toml +++ b/crates/doc-binary/Cargo.toml @@ -17,6 +17,7 @@ craft-wordmodel = { workspace = true } chrono = { version = "0.4.45", default-features = false, features = ["std"] } image = { version = "0.25", default-features = false, features = ["png", "bmp"] } log = "0.4" +md4 = "0.11" miniz_oxide = "0.9" sha1 = "0.11" thiserror = { workspace = true } diff --git a/crates/doc-binary/src/write/picture.rs b/crates/doc-binary/src/write/picture.rs index 07eb19fa4..6454c320f 100644 --- a/crates/doc-binary/src/write/picture.rs +++ b/crates/doc-binary/src/write/picture.rs @@ -3,7 +3,7 @@ //! picture's place in the BLIP store, crop, alt text) and the `OfficeArtFBSE` with the BLIP //! embedded in it. The character 0x01 in the text points here through `sprmCPicLocation`. -use sha1::Digest; +use md4::Digest; /// `PICF.cbHeader`. const CB_HEADER: u16 = 0x44; @@ -77,14 +77,15 @@ impl Blip { } } - /// The `OfficeArtBlip*` record. - fn record(&self, w_emu: i32, h_emu: i32) -> Vec { + /// The `OfficeArtBlip*` record and its format-defined identifier. + fn record(&self, w_emu: i32, h_emu: i32) -> (Vec, [u8; 16]) { let (raw, (typ, inst)) = match self { Blip::Png(b) => (b, BLIP_PNG), Blip::Jpeg(b) => (b, BLIP_JPEG), Blip::Metafile(b, emf) => (b, if *emf { BLIP_EMF } else { BLIP_WMF }), }; - let mut body = uid(raw).to_vec(); + let id = uid(raw); + let mut body = id.to_vec(); match self { Blip::Png(b) | Blip::Jpeg(b) => { body.push(0xFF); // tag @@ -106,16 +107,14 @@ impl Blip { body.extend_from_slice(&packed); } } - rec(0, inst, typ, &body) + (rec(0, inst, typ, &body), id) } } -/// A 16-byte id for a BLIP (the format wants an MD4; any digest identifies it). +/// MS-ODRAW requires MD4 of the uncompressed BLIP payload, not the original import file. +/// This legacy-format identifier is not authentication or a security integrity check. fn uid(bytes: &[u8]) -> [u8; 16] { - let d = sha1::Sha1::digest(bytes); - let mut u = [0u8; 16]; - u.copy_from_slice(d.get(..16).unwrap_or(&[0; 16])); - u + md4::Md4::digest(bytes).into() } /// An OfficeArt record: header (version, instance, type, length) then the body. @@ -147,9 +146,10 @@ impl Pictures { let gh = (h.max(1.0) / (1.0 - ct - cb).max(0.01)).min(1584.0); let emu = |pt: f32| (pt * 12_700.0).round() as i32; - let blip_rec = blip.record(emu(gw), emu(gh)); + let (blip_rec, id) = blip.record(emu(gw), emu(gh)); let mut fbse = vec![blip.bt(), blip.bt()]; - fbse.extend_from_slice(&uid(bytes)); + // Reuse the embedded BLIP's identifier after PNG conversion/placeable-header removal. + fbse.extend_from_slice(&id); fbse.extend_from_slice(&0x00FFu16.to_le_bytes()); // tag fbse.extend_from_slice(&(blip_rec.len() as u32).to_le_bytes()); fbse.extend_from_slice(&1u32.to_le_bytes()); // cRef @@ -209,3 +209,70 @@ impl Pictures { u32::try_from(at).ok() } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn blip_uid_matches_rfc1320_vectors() { + assert_eq!(uid(b""), [0x31, 0xd6, 0xcf, 0xe0, 0xd1, 0x6a, 0xe9, 0x31, 0xb7, 0x3c, 0x59, 0xd7, 0xe0, 0xc0, 0x89, 0xc0]); + assert_eq!(uid(b"abc"), [0xa4, 0x48, 0x01, 0x7a, 0xaf, 0x21, 0xd8, 0x52, 0x5f, 0xc1, 0x0a, 0xe8, 0x7a, 0xa6, 0x72, 0x9d]); + } + + fn check_record_ids(input: &[u8], payload: &[u8]) { + let mut pictures = Pictures::default(); + assert_eq!(pictures.add(input, 1.0, 1.0, [0.0; 4], ""), Some(0)); + let bytes = &pictures.data; + let shape = usize::from(CB_HEADER); + let shape_len = u32::from_le_bytes(bytes[shape + 4..shape + 8].try_into().unwrap()) as usize; + let fbse = shape + 8 + shape_len; + assert_eq!(&bytes[fbse + 2..fbse + 4], &FBSE.to_le_bytes()); + let embedded = fbse + 8 + 36; + let typ = u16::from_le_bytes(bytes[embedded + 2..embedded + 4].try_into().unwrap()); + let emitted = if typ == BLIP_WMF.0 || typ == BLIP_EMF.0 { + // Controlled tiny fixtures: skip the UID and 34-byte metafile header. + miniz_oxide::inflate::decompress_to_vec_zlib(&bytes[embedded + 58..]).unwrap() + } else { + assert!(typ == BLIP_PNG.0 || typ == BLIP_JPEG.0); + bytes[embedded + 25..].to_vec() + }; + assert_eq!(emitted, payload, "stored image bytes must retain the expected conversion"); + let expected = uid(&emitted); + assert_eq!(&bytes[fbse + 10..fbse + 26], &expected, "FBSE must identify stored data"); + assert_eq!(&bytes[embedded + 8..embedded + 24], &expected, "BLIP must share the same identifier"); + } + + #[test] + fn blip_ids_identify_unmodified_payloads() { + // Tiny format-dispatch fixtures exercise identifier bytes, not image validation. + let png = b"\x89PNGsmall"; + check_record_ids(png, png); + let jpeg = b"\xff\xd8\xffsmall"; + check_record_ids(jpeg, jpeg); + let wmf = [1, 0, 9, 0, 0, 3, 9, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0]; + check_record_ids(&wmf, &wmf); + let mut emf = vec![0; 44]; + emf[..4].copy_from_slice(&1u32.to_le_bytes()); + emf[40..44].copy_from_slice(b" EMF"); + check_record_ids(&emf, &emf); + } + + #[test] + fn blip_ids_exclude_placeable_wmf_header() { + let wmf = [1, 0, 9, 0, 0, 3, 9, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0]; + let mut placeable = vec![0; 22]; + placeable[..4].copy_from_slice(&[0xd7, 0xcd, 0xc6, 0x9a]); + placeable.extend_from_slice(&wmf); + check_record_ids(&placeable, &wmf); + } + + #[test] + fn blip_ids_identify_converted_bmp_payload() { + let mut bmp = std::io::Cursor::new(Vec::new()); + image::DynamicImage::new_rgb8(1, 1).write_to(&mut bmp, image::ImageFormat::Bmp).unwrap(); + let Blip::Png(encoded) = Blip::of(bmp.get_ref()).unwrap() else { panic!("BMP must become PNG") }; + assert_ne!(bmp.get_ref(), &encoded); + check_record_ids(bmp.get_ref(), &encoded); + } +} diff --git a/crates/document-bundle/src/lib.rs b/crates/document-bundle/src/lib.rs index 70a960a1f..b425856ad 100644 --- a/crates/document-bundle/src/lib.rs +++ b/crates/document-bundle/src/lib.rs @@ -315,7 +315,8 @@ pub fn read_preview(bytes: &[u8], preview_entry: &str) -> Option> { archive.read(preview_entry, PREVIEW_LIMIT).ok().flatten() } -/// Read a bounded preview from a seekable file without loading the full bundle into memory. +/// Read a preview from a seekable ZIP, including archives with a leading prefix. +/// The decompressed preview is limited to 4 MiB; archive discovery may perform substantial I/O. pub fn read_preview_from(reader: R, preview_entry: &str) -> Option> { const PREVIEW_LIMIT: u64 = 4 << 20; let mut zip = zip::ZipArchive::new(reader).ok()?; @@ -328,6 +329,22 @@ pub fn read_preview_from(reader: R, preview_entry: &str) -> Opti (u64::try_from(preview.len()).ok()? <= PREVIEW_LIMIT).then_some(preview) } +/// Read a preview only from a ZIP with a local-file header at byte zero. +/// +/// Use for native formats whose contract excludes prefixed/self-extracting archives. +/// Nonmatching inputs require at most four bytes read, regardless of the initial cursor position. +/// Matching ZIPs still require directory I/O; this is not an overall read/time budget. +pub fn read_unprefixed_preview_from(mut reader: R, preview_entry: &str) -> Option> { + reader.seek(std::io::SeekFrom::Start(0)).ok()?; + let mut magic = [0u8; 4]; + reader.read_exact(&mut magic).ok()?; + if &magic != b"PK\x03\x04" { + return None; + } + reader.seek(std::io::SeekFrom::Start(0)).ok()?; + read_preview_from(reader, preview_entry) +} + fn read_legacy(bytes: &[u8], spec: Spec<'_>) -> Result { let mut document: Value = serde_json::from_slice(bytes).map_err(|e| Error::NotBundle(e.to_string()))?; let mut assets = Vec::new(); @@ -409,6 +426,67 @@ mod tests { assert_eq!(read_preview(&bytes, SPEC.preview_entry).as_deref(), Some(&b"png"[..])); } + /// Counts the bytes read through it. + struct Counting { + inner: R, + read: usize, + } + + impl Read for Counting { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + let n = self.inner.read(buf)?; + self.read += n; + Ok(n) + } + } + + impl Seek for Counting { + fn seek(&mut self, pos: std::io::SeekFrom) -> std::io::Result { + self.inner.seek(pos) + } + } + + #[test] + fn preview_from_a_reader_reads_a_bundle() { + let bytes = write(br#"{}"#, 4, "Test 0.1", Some(b"png"), &[], &[], SPEC).unwrap(); + assert_eq!(read_preview_from(Cursor::new(&bytes), SPEC.preview_entry).as_deref(), Some(&b"png"[..])); + } + + #[test] + fn prefixed_bundle_admission_is_explicit() { + let bundle = write(br#"{}"#, 4, "Test 0.1", Some(b"png"), &[], &[], SPEC).unwrap(); + let mut bytes = b"MZsynthetic-prefix".to_vec(); + bytes.extend(bundle); + let mut original = zip::ZipArchive::new(Cursor::new(&bytes)).unwrap(); + let mut preview = Vec::new(); + original.by_name(SPEC.preview_entry).unwrap().read_to_end(&mut preview).unwrap(); + assert_eq!(preview, b"png"); + assert!(has_document(&bytes, SPEC)); + assert!(!starts_with_mimetype(&bytes, SPEC)); + assert_eq!(read_preview_from(Cursor::new(&bytes), SPEC.preview_entry), Some(preview)); + assert_eq!(read_unprefixed_preview_from(Cursor::new(&bytes), SPEC.preview_entry), None); + } + + #[test] + fn preview_from_an_advanced_reader_still_reads_the_bundle() { + let bytes = write(br#"{}"#, 4, "Test 0.1", Some(b"png"), &[], &[], SPEC).unwrap(); + for offset in [1, 4, bytes.len() / 2, bytes.len()] { + let mut reader = Cursor::new(&bytes); + reader.set_position(offset as u64); + assert_eq!(read_preview_from(reader.clone(), SPEC.preview_entry).as_deref(), Some(&b"png"[..]), "offset {offset}"); + assert_eq!(read_unprefixed_preview_from(reader, SPEC.preview_entry).as_deref(), Some(&b"png"[..]), "offset {offset}"); + } + } + + #[test] + fn preview_from_a_non_zip_reads_only_its_signature() { + let mut file = Counting { inner: Cursor::new(vec![0x42u8; 1 << 20]), read: 0 }; + assert_eq!(read_unprefixed_preview_from(&mut file, SPEC.preview_entry), None); + assert!(file.read <= 4, "read {} bytes of a file that is not a zip", file.read); + let mut empty = Counting { inner: Cursor::new(Vec::new()), read: 0 }; + assert_eq!(read_unprefixed_preview_from(&mut empty, SPEC.preview_entry), None); + } + #[test] fn extracts_legacy_inline_assets() { let loaded = read(br#"{"assetData":{"7":"AQID"},"name":"x"}"#, 4, SPEC).unwrap(); diff --git a/crates/docx/src/lib.rs b/crates/docx/src/lib.rs index c3c3e8df3..68d41ab4d 100644 --- a/crates/docx/src/lib.rs +++ b/crates/docx/src/lib.rs @@ -3,8 +3,8 @@ //! [`read`] turns a `.docx` package into a [`craft_wordmodel::Document`]; [`write`] does the //! reverse. Both are written from the public specification. The reader is lenient (unknown //! markup is skipped, bad numbers fall back to defaults) and bounded (zip entry sizes, total -//! decompressed size, XML depth and element counts are capped), so hostile input yields an -//! error or a best-effort document, never a panic. +//! decompressed size, XML depth, element counts per part and a package-wide element budget are +//! capped), so hostile input yields an error or a best-effort document, never a panic. #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] // The code came from an app whose lints allow this. #![allow(clippy::type_complexity)] diff --git a/crates/docx/src/package.rs b/crates/docx/src/package.rs index 3c7f45d94..6f90f56ba 100644 --- a/crates/docx/src/package.rs +++ b/crates/docx/src/package.rs @@ -1,5 +1,6 @@ //! OPC package access: bounded zip reading, relationships, part names. +use std::cell::Cell; use std::collections::{BTreeMap, HashMap}; use std::sync::Arc; @@ -216,6 +217,14 @@ fn opc_error(e: craft_opc::Error) -> DocxError { /// document keeps as it is (a picture, an embedded object) is handed over rather than copied. pub struct Package { opc: craft_opc::Package, + /// Elements this package's XML parts may still be parsed into. Every XML part read through + /// [`Package::xml`] charges it, so a file of many parts each inside the per-part cap builds + /// bounded tree memory in total — a chart part with no series builds a maximal tree for + /// almost no graphic work, and the trees the reader keeps accumulate. + budget: Cell, + /// What [`Package::reset_budget`] restores: the cap the package was opened with (the default, + /// or a smaller one from [`Package::open_limited_within`]). + budget_cap: usize, } impl Package { @@ -227,8 +236,16 @@ impl Package { /// `max_total` (counting entries that fail their checksum), is an error. A damaged entry is /// left out with a logged warning. pub fn open_limited(bytes: &[u8], max_part: u64, max_total: u64) -> Result { + Package::open_limited_within(bytes, max_part, max_total, xml::MAX_ELEMENTS_TOTAL) + } + + /// [`open_limited`] with an XML element budget of its own (nested documents share their + /// container's, tests use a small one). + pub fn open_limited_within(bytes: &[u8], max_part: u64, max_total: u64, max_elements: usize) -> Result { let limits = craft_opc::Limits::new(MAX_ENTRIES, max_part, max_total); - craft_opc::Package::open(bytes, &limits).map(|opc| Package { opc }).map_err(opc_error) + craft_opc::Package::open(bytes, &limits) + .map(|opc| Package { opc, budget: Cell::new(max_elements), budget_cap: max_elements }) + .map_err(opc_error) } /// The bytes of all its parts. @@ -244,7 +261,27 @@ impl Package { /// A package from parts already in memory (a Flat OPC file, a converted document), by part /// name without the leading `/`. pub fn from_parts(files: BTreeMap>) -> Package { - Package { opc: craft_opc::Package::from_parts(files) } + Package { opc: craft_opc::Package::from_parts(files), budget: Cell::new(xml::MAX_ELEMENTS_TOTAL), budget_cap: xml::MAX_ELEMENTS_TOTAL } + } + + /// Start a read's element budget over: the budget is per read, not per package's lifetime. + pub(crate) fn reset_budget(&self) { + self.budget.set(self.budget_cap); + } + + /// The XML elements left of the package's budget: nested documents open within it. + pub(crate) fn elements_left(&self) -> usize { + self.budget.get() + } + + /// Charge `count` elements a parsed part built against the budget. + pub(crate) fn charge(&self, count: usize) -> Result<(), DocxError> { + let left = self.budget.get(); + if count > left { + return Err(DocxError::Limit(format!("{count} XML elements, {left} left of the package's {} budget", self.budget_cap))); + } + self.budget.set(left - count); + Ok(()) } /// Part bytes by name (leading `/` ignored; case-insensitive). @@ -261,14 +298,28 @@ impl Package { /// [`Package::xml`] for the main document part: malformed XML is an error, not a truncated read. pub fn xml_strict(&self, name: &str) -> Result, DocxError> { match self.get(name) { - Some(b) => xml::parse_strict(b).map(Some), + Some(b) => { + // The parser stops at the remaining budget or the per-part cap, whichever is less: + // a part over what is left of the package's budget is refused before the whole + // per-part tree is built. + let (el, count) = xml::parse_strict_counted(b, self.budget.get().min(xml::MAX_ELEMENTS))?; + self.charge(count)?; + Ok(Some(el)) + } None => Ok(None), } } + /// A package part as a parsed XML tree, charged against the element budget: the parser + /// stops at what is left of the budget or the per-part cap, whichever is less, and the + /// count it built is charged after. A lenient read: malformed XML is a truncated one. pub fn xml(&self, name: &str) -> Result, DocxError> { match self.get(name) { - Some(b) => xml::parse(b).map(Some), + Some(b) => { + let (el, count) = xml::parse_counted(b, self.budget.get().min(xml::MAX_ELEMENTS))?; + self.charge(count)?; + Ok(Some(el)) + } None => Ok(None), } } @@ -448,6 +499,82 @@ mod tests { let junk = EmbeddedManifest::parse(b"R\tnope\trId1\tk\tt\tI\nP\tonly-two\n\t\t\n\xff\xfe"); assert!(junk.parts.is_empty()); } + + /// A file of many parts each inside the per-part cap is bounded in total: every XML part + /// read through the package charges a package-wide budget, and a part over it is skipped + /// (warned), never built. A chart part with no series builds a maximal tree for almost no + /// graphic work, so the trees a reader keeps would otherwise accumulate one per part. + #[test] + fn the_xml_element_budget_is_package_wide() { + let ns = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main""#; + let rels = r#""#; + let document = format!(r#""#); + let dense = |root: &str| format!(r#"<{root} {ns}>{}"#, "".repeat(900)); + let z = zip_of(&[ + ("word/document.xml", document.into_bytes()), + ("word/_rels/document.xml.rels", rels.as_bytes().to_vec()), + ("word/styles.xml", dense("w:styles").into_bytes()), + ("word/numbering.xml", dense("w:numbering").into_bytes()), + ]); + let pkg = Package::open_limited_within(&z, MAX_PART, MAX_TOTAL, 1_000).unwrap(); + // styles (900 elements) reads; numbering (900 more) is over what is left and is skipped + // with a warning, not built. + let read = || crate::read::read_opened(&pkg, None); + let (first, warned) = crate::test_log::warnings(read); + assert!(first.is_ok(), "{:?}", first.err()); + let refused: Vec<_> = warned.iter().filter(|w| w.contains("numbering") && w.contains("XML element")).collect(); + assert_eq!(refused.len(), 1, "{warned:?}"); + // The budget is per read: a second read starts it over and behaves the same. + let (second, warned) = crate::test_log::warnings(read); + assert!(second.is_ok(), "{:?}", second.err()); + assert_eq!(warned.iter().filter(|w| w.contains("numbering") && w.contains("XML element")).count(), 1, "{warned:?}"); + } + + /// The main document part itself is strict: over the budget it is an error, not a + /// best-effort read of a tree the file then paid for. + #[test] + fn a_main_part_over_the_element_budget_is_refused() { + let ns = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main""#; + let document = format!(r#"{}"#, "".repeat(20)); + let z = zip_of(&[("word/document.xml", document.into_bytes())]); + let pkg = Package::open_limited_within(&z, MAX_PART, MAX_TOTAL, 10).unwrap(); + assert!(matches!(crate::read::read_opened(&pkg, None), Err(DocxError::Limit(_)))); + } + + /// A part over what is left of the package's budget is refused while parsing, not after the + /// whole per-part tree is built: the parser stops at the remaining budget or the per-part + /// cap, whichever is less, so the file pays for at most what is left of the budget. + #[test] + fn a_part_over_the_remaining_budget_is_refused_while_parsing() { + let ns = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main""#; + let document = format!(r#"{}"#, "".repeat(200)); + let z = zip_of(&[("word/document.xml", document.into_bytes())]); + // 200 elements: inside the per-part cap, over the package's 100 budget. The parse + // refuses at the budget, so the error is the parse's, not the charge's, and names + // the effective limit for this parse (the remaining budget), not the whole budget. + let pkg = Package::open_limited_within(&z, MAX_PART, MAX_TOTAL, 100).unwrap(); + let e = crate::read::read_opened(&pkg, None).expect_err("refused"); + assert_eq!(e, DocxError::Limit("over the XML element budget for this parse: at most 100 elements".into())); + } + + /// A part parsed earlier shrinks what is left of the budget: the next part is refused while + /// parsing at the remaining, not at the whole budget, and the error names the effective limit + /// for this parse (the remaining), not the package's budget. + #[test] + fn an_earlier_part_reduces_the_remaining_budget_the_next_part_names_it() { + let ns = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main""#; + let styles = format!(r#"{}"#, "".repeat(60)); + let settings = format!(r#"{}"#, "".repeat(60)); + let z = zip_of(&[("word/styles.xml", styles.into_bytes()), ("word/settings.xml", settings.into_bytes())]); + // 100 elements of budget. The styles part parses (the main-part path: `xml_strict`) and + // charges its 61 elements, leaving 39. + let pkg = Package::open_limited_within(&z, MAX_PART, MAX_TOTAL, 100).unwrap(); + pkg.xml_strict("word/styles.xml").unwrap(); + // The settings part needs 61 elements, over the 39 left and under the per-part cap: the + // parse refuses at the remaining, so the error names 39, not the package's 100 budget. + let e = pkg.xml("word/settings.xml").expect_err("refused"); + assert_eq!(e, DocxError::Limit("over the XML element budget for this parse: at most 39 elements".into())); + } } #[cfg(test)] diff --git a/crates/docx/src/read.rs b/crates/docx/src/read.rs index 746225e97..18c9ea47a 100644 --- a/crates/docx/src/read.rs +++ b/crates/docx/src/read.rs @@ -154,9 +154,11 @@ pub(crate) fn read_opened(pkg: &Package, chunks: Option) -> Resul read_opened_in(pkg, ChunkState::new(chunks)).map(|(doc, ..)| doc) } -/// [`read_opened`] with what chunks may still bring in; also gives the chunks, chunk bytes and -/// graphic work left of that. -fn read_opened_in(pkg: &Package, chunks: ChunkState) -> Result<(Document, usize, u64, usize), DocxError> { +/// [`read_opened`] with what chunks may still bring in; also gives the chunks, chunk bytes, +/// graphic work and XML elements left of that. +fn read_opened_in(pkg: &Package, chunks: ChunkState) -> Result<(Document, usize, u64, usize, usize), DocxError> { + // The budget is per read, so a package read twice (tests, a Flat OPC conversion) starts over. + pkg.reset_budget(); let root_rels = pkg.rels(""); let main = root_rels.by_type(rt::OFFICE_DOC).filter(|r| !r.external).map(|r| r.target.clone()).unwrap_or_else(|| "word/document.xml".to_string()); let Some(root) = pkg.xml_strict(&main)? else { @@ -371,11 +373,11 @@ fn read_opened_in(pkg: &Package, chunks: ChunkState) -> Result<(Document, usize, if r.shape_ids { keep_glued_ids(&mut r.doc, &r.glued); } - let (left, bytes, graphic) = (r.chunks.left, r.chunks.bytes, r.chunks.graphic); + let (left, bytes, graphic, elements) = (r.chunks.left, r.chunks.bytes, r.chunks.graphic, pkg.elements_left()); let mut doc = r.doc; doc.skipped_parts.extend(pkg.skipped().iter().cloned()); doc.ensure_nonempty(); - Ok((doc, left, bytes, graphic)) + Ok((doc, left, bytes, graphic, elements)) } /// Most move ranges open at once, and most move names tracked, per file. diff --git a/crates/docx/src/read/chunk.rs b/crates/docx/src/read/chunk.rs index 2dc1674a7..113c701ff 100644 --- a/crates/docx/src/read/chunk.rs +++ b/crates/docx/src/read/chunk.rs @@ -110,11 +110,27 @@ impl Reader<'_> { log::warn!("docx: alternative format chunks nest deeper than {MAX_CHUNK_NESTING}; the inner ones are left out"); return None; } - let pkg = - Package::open_limited(bytes, MAX_PART, self.chunks.bytes).map_err(|e| log::warn!("docx: unreadable nested document chunk: {e}")).ok()?; + // The nested document shares the file's element budget: open_limited_within, not a + // fresh cap — nesting goes deep, so 5 packages each getting 16M is the OOM class the + // budget exists for. The container's own parse spent part of the chain, so the cap is + // the lesser of the chain and what the container has left. + let cap = self.chunks.elements.min(self.pkg.elements_left()); + let pkg = Package::open_limited_within(bytes, MAX_PART, self.chunks.bytes, cap) + .map_err(|e| log::warn!("docx: unreadable nested document chunk: {e}")) + .ok()?; self.chunks.bytes = self.chunks.bytes.saturating_sub(pkg.size()); let state = ChunkState { nesting: self.chunks.nesting + 1, depth: depth + 1, ..self.chunks }; - let (doc, left, bytes, graphic) = match super::read_opened_in(&pkg, state) { + let read = super::read_opened_in(&pkg, state); + // A parsed main part can still fail semantic validation (for example, a non-Word + // root). Charge its elements before returning that error, so later siblings cannot + // reuse the reservation. On success this is the same single charge as before. + let elements = pkg.elements_left(); + self.chunks.elements = elements; + let spent = cap.saturating_sub(elements); + if let Err(e) = self.pkg.charge(spent) { + log::warn!("docx: nested document chunk outspent the container's element budget: {e}"); + } + let (doc, left, bytes, graphic, _) = match read { Ok(read) => read, Err(e) => { log::warn!("docx: unreadable nested document chunk: {e}"); @@ -139,6 +155,9 @@ pub(crate) struct ChunkState<'a> { /// Graphic work left in the file's budget ([`super::MAX_GRAPHIC_WORK`]): nested documents' /// charts and diagrams count against it too. pub graphic: usize, + /// XML elements left in the file's budget: nested packages share their container's + /// ([`crate::xml::MAX_ELEMENTS_TOTAL`]), not one of their own. + pub elements: usize, /// How deep in nested WordprocessingML chunks this reader is. pub nesting: u8, /// The XML depth its stories start at (a nested document's: that of the chunk naming it). @@ -148,7 +167,15 @@ pub(crate) struct ChunkState<'a> { impl<'a> ChunkState<'a> { pub fn new(import: Option>) -> Self { - ChunkState { left: MAX_CHUNKS, bytes: MAX_TOTAL, graphic: super::MAX_GRAPHIC_WORK, nesting: 0, depth: 0, import } + ChunkState { + left: MAX_CHUNKS, + bytes: MAX_TOTAL, + graphic: super::MAX_GRAPHIC_WORK, + elements: crate::xml::MAX_ELEMENTS_TOTAL, + nesting: 0, + depth: 0, + import, + } } } @@ -159,7 +186,7 @@ mod tests { use craft_wordmodel::{Block, Document, InlineObject}; use super::ChunkState; - use crate::package::Package; + use crate::package::{MAX_PART, MAX_TOTAL, Package}; /// A package whose body is `body`, with the document relationship `rel` (id, type, target) to /// the part `(name, bytes)`. @@ -198,8 +225,8 @@ mod tests { let outer = package(r#""#, ("rIdC", "aFChunk", "afchunk.docx"), ("word/afchunk.docx", &inner)); let pkg = Package::open(&outer).unwrap(); let read = |graphic| { - let (d, .., left) = super::super::read_opened_in(&pkg, ChunkState { graphic, ..ChunkState::new(None) }).unwrap(); - (drawn(&d), left) + let (d, .., work, _) = super::super::read_opened_in(&pkg, ChunkState { graphic, ..ChunkState::new(None) }).unwrap(); + (drawn(&d), work) }; let (shown, left) = read(super::super::MAX_GRAPHIC_WORK); assert!(shown); @@ -207,4 +234,152 @@ mod tests { // With the file's budget spent, the nested document doesn't get one of its own. assert_eq!(read(0), (false, 0)); } + + /// A package whose body is `body`, with the document relationships `rels` (id, type, target) + /// and the parts `(name, bytes)` they name. + fn package_parts(body: &str, rels: &[(&str, &str, &str)], parts: &[(&str, &[u8])]) -> Vec { + let ns = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main""#; + let rels_xml = + |inner: &str| format!(r#"{inner}"#); + let rel = |(id, ty, target): &(&str, &str, &str)| { + format!(r#""#) + }; + let names: String = rels.iter().map(rel).collect::>().join(""); + let mut files: Vec<(&str, Vec)> = vec![ + ("_rels/.rels", rels_xml(&rel(&("rId1", "officeDocument", "word/document.xml"))).into_bytes()), + ("word/document.xml", format!(r#"{body}"#).into_bytes()), + ("word/_rels/document.xml.rels", rels_xml(&names).into_bytes()), + ]; + files.extend(parts.iter().map(|(name, bytes)| (*name, bytes.to_vec()))); + let mut zw = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + for (name, bytes) in files { + zw.start_file(name, zip::write::SimpleFileOptions::default()).unwrap(); + zw.write_all(&bytes).unwrap(); + } + zw.finish().unwrap().into_inner() + } + + /// Whether the body holds a paragraph with `s`. + fn has(d: &Document, s: &str) -> bool { + d.body.iter().any(|b| b.as_para().map(|p| p.text.contains(s)).unwrap_or(false)) + } + + #[test] + fn a_nested_documents_elements_come_out_of_the_files_budget() { + // Three levels: the outer's altChunk names the inner, whose altChunk names the + // innermost. The chain spends down: the inner's own parse charges the file's budget, + // so the innermost opens with what the inner has left, not a fresh cap. + let innermost = package(r#"innermost"#, ("rIdZ", "chart", "charts/z.xml"), ("word/charts/z.xml", b"")); + let inner = package( + r#"inner"#, + ("rIdD", "aFChunk", "afchunk.docx"), + ("word/afchunk.docx", &innermost), + ); + let outer = package(r#""#, ("rIdC", "aFChunk", "afchunk.docx"), ("word/afchunk.docx", &inner)); + let pkg = Package::open(&outer).unwrap(); + let read = |elements| { + let (d, ..) = super::super::read_opened_in(&pkg, ChunkState { elements, ..ChunkState::new(None) }).unwrap(); + (has(&d, "inner"), has(&d, "innermost")) + }; + // With room, both levels flow in. + assert_eq!(read(crate::xml::MAX_ELEMENTS_TOTAL), (true, true)); + // The inner's own parse (its rels, then its main part) charged the file's budget: the + // innermost is left out instead of getting one of its own (before this, each nested + // package started with the full 16M). + assert_eq!(read(10), (true, false)); + } + + #[test] + fn a_nested_documents_elements_charge_the_container() { + // The nested document's XML usage comes out of the container's budget too: the cap + // the nested package was given, minus its returned remainder, is charged, so the + // container's remaining parts parse against what is left of the shared cap — not a + // budget that ignores the chunk. + let nested = package(r#"inner"#, ("rIdZ", "chart", "charts/z.xml"), ("word/charts/z.xml", b"")); + let body = r#"after"#; + let with = package(&format!(r#"{body}"#), ("rIdC", "aFChunk", "afchunk.docx"), ("word/afchunk.docx", &nested)); + let without = package(body, ("rIdZ", "chart", "charts/z.xml"), ("word/charts/z.xml", b"")); + let read = |outer: &[u8]| { + let pkg = Package::open(outer).unwrap(); + let (d, ..) = super::super::read_opened_in(&pkg, ChunkState { elements: 10, ..ChunkState::new(None) }).unwrap(); + (has(&d, "inner"), pkg.elements_left()) + }; + let (inner_in, charged) = read(&with); + assert!(inner_in); + let (_, base) = read(&without); + assert!(charged < base, "the nested document's usage is the container's: {charged} of {base}"); + } + + #[test] + fn a_grandchilds_reservation_charges_every_level() { + // Three levels: the innermost's reservation comes out of the inner's budget, and the + // inner's out of the outer's — the chain charges every container, so the outer's + // remainder is smaller with the deeper chain than with a shallow one. + let innermost = package(r#"leaf"#, ("rIdZ", "chart", "charts/z.xml"), ("word/charts/z.xml", b"")); + let inner = package( + r#"mid"#, + ("rIdD", "aFChunk", "afchunk.docx"), + ("word/afchunk.docx", &innermost), + ); + let outer = package(r#""#, ("rIdC", "aFChunk", "afchunk.docx"), ("word/afchunk.docx", &inner)); + let pkg = Package::open(&outer).unwrap(); + let (d, .., elements) = super::super::read_opened_in(&pkg, ChunkState::new(None)).unwrap(); + assert!(has(&d, "mid"), "the inner document didn't flow in"); + assert!(has(&d, "leaf"), "the innermost document didn't flow in"); + // The same container with a shallow chain: one reservation instead of two. + let shallow = package(r#""#, ("rIdC", "aFChunk", "afchunk.docx"), ("word/afchunk.docx", &innermost)); + let pkg = Package::open(&shallow).unwrap(); + let (.., shallow_elements) = super::super::read_opened_in(&pkg, ChunkState::new(None)).unwrap(); + assert!(elements < shallow_elements, "every level's reservation is charged: {elements} of {shallow_elements}"); + } + + #[test] + fn a_charged_budget_bounds_the_containers_part_and_the_sibling_after_it() { + // The container's budget pays for the parts it parses (the section's header, read + // during the chunk's own walk) and for the chunks after the first one: with a budget + // that fits the grandchild chunk and the header but not the sibling document's XML, + // the sibling is left out; skip the header's charge and it would flow in. + let hdr = r#"headheadhead"#; + let gc = package(r#"gc"#, ("rIdZ", "chart", "charts/z.xml"), ("word/charts/z.xml", b"")); + let sibling = + package(&r#"sibling"#.repeat(8), ("rIdZ", "chart", "charts/z.xml"), ("word/charts/z.xml", b"")); + let inner = package_parts( + r#"mid"#, + &[("rIdD", "aFChunk", "afchunk.docx"), ("rIdH", "header", "header1.xml"), ("rIdS", "aFChunk", "afchunk2.docx")], + &[("word/afchunk.docx", &gc), ("word/header1.xml", hdr.as_bytes()), ("word/afchunk2.docx", &sibling)], + ); + let outer = package(r#""#, ("rIdC", "aFChunk", "afchunk.docx"), ("word/afchunk.docx", &inner)); + let pkg = Package::open(&outer).unwrap(); + let read = |elements| { + let (d, ..) = super::super::read_opened_in(&pkg, ChunkState { elements, ..ChunkState::new(None) }).unwrap(); + (has(&d, "mid"), has(&d, "gc"), has(&d, "sibling")) + }; + // With room, everything flows in. + assert_eq!(read(crate::xml::MAX_ELEMENTS_TOTAL), (true, true, true)); + // The grandchild chunk and the header fit the file's budget; the sibling document's + // XML (8 paragraphs) doesn't, so it's left out instead of getting a fresh cap. + assert_eq!(read(40), (true, true, false)); + } + + #[test] + fn a_rejected_nested_root_still_charges_the_siblings_budget() { + // Four outer elements, sixty rejected elements, five sibling elements: 69 in total. + let bad_xml = format!("{}", "".repeat(59)); + let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + zip.start_file("word/document.xml", zip::write::SimpleFileOptions::default()).unwrap(); + zip.write_all(bad_xml.as_bytes()).unwrap(); + let bad = zip.finish().unwrap().into_inner(); + let sibling = package_parts(r#"sibling"#, &[], &[]); + let outer = package_parts( + r#""#, + &[("bad", "aFChunk", "bad.docx"), ("good", "aFChunk", "good.docx")], + &[("word/bad.docx", &bad), ("word/good.docx", &sibling)], + ); + for (cap, included, remaining) in [(69, true, 0), (68, false, 4)] { + let pkg = Package::open_limited_within(&outer, MAX_PART, MAX_TOTAL, cap).unwrap(); + let doc = super::super::read_opened(&pkg, None).unwrap(); + assert_eq!(has(&doc, "sibling"), included, "budget {cap}"); + assert_eq!(pkg.elements_left(), remaining, "budget {cap}"); + } + } } diff --git a/crates/docx/src/xml.rs b/crates/docx/src/xml.rs index fa50d217a..46da6911d 100644 --- a/crates/docx/src/xml.rs +++ b/crates/docx/src/xml.rs @@ -10,6 +10,10 @@ use crate::DocxError; pub const MAX_DEPTH: usize = 256; /// Maximum number of elements in one part. pub const MAX_ELEMENTS: usize = 8_000_000; +/// Maximum number of elements summed over every part a read parses: a file of many parts each +/// inside [`MAX_ELEMENTS`] would otherwise cost a tree per part, and the trees a reader keeps +/// (the main part's, charts' and diagrams') accumulate. +pub const MAX_ELEMENTS_TOTAL: usize = MAX_ELEMENTS * 2; /// Maximum number of attributes on one element (#3702). pub const MAX_ATTRS: usize = 1024; @@ -329,19 +333,31 @@ pub fn parse(bytes: &[u8]) -> Result { parse_ns(bytes, &[]) } +/// [`parse`], with the number of elements it built, stopping early at `max` elements: the caller +/// charges the count against a package-wide budget (see [`MAX_ELEMENTS_TOTAL`]), and a part over +/// what is left of it is refused before the whole per-part tree is built. +pub fn parse_counted(bytes: &[u8], max: usize) -> Result<(El, usize), DocxError> { + parse_with(bytes, &[], false, max) +} + +/// [`parse_counted`], strict, for a part whose loss would be silent data loss (the main +/// document): a mismatched end tag or an element left open at the end of the data is an error, +/// not a cue to stop reading. +pub fn parse_strict_counted(bytes: &[u8], max: usize) -> Result<(El, usize), DocxError> { + parse_with(bytes, &[], true, max) +} + /// [`parse`] with `extra` namespaces (prefix, URI) mapped to canonical prefixes first, so a /// related vocabulary (WordprocessingML 2003) reads with the prefixes the reader knows. pub fn parse_ns(bytes: &[u8], extra: &[(&'static str, &str)]) -> Result { - parse_with(bytes, extra, false) + parse_with(bytes, extra, false, MAX_ELEMENTS).map(|(e, _)| e) } -/// [`parse`] for a part whose loss would be silent data loss (the main document): a mismatched end -/// tag or an element left open at the end of the data is an error, not a cue to stop reading. -pub fn parse_strict(bytes: &[u8]) -> Result { - parse_with(bytes, &[], true) -} - -fn parse_with(bytes: &[u8], extra: &[(&'static str, &str)], strict: bool) -> Result { +/// The XML parser everything else goes through: transcodes UTF-16, walks the events and builds +/// the tree depth-first, stopping at `max` elements and counting the ones it built. A mismatched +/// end tag or an element left open at the end of the data is an error when `strict`, a cue to +/// stop reading when not. +fn parse_with(bytes: &[u8], extra: &[(&'static str, &str)], strict: bool, max: usize) -> Result<(El, usize), DocxError> { let namespaces: Vec<(&str, &str)> = extra.iter().copied().chain(NAMESPACES.iter().copied()).chain(OTHER_NAMESPACES.iter().copied()).chain(STRICT.iter().copied()).collect(); // The prefix of an element: its namespace's, with two exceptions for Strict documents @@ -375,7 +391,9 @@ fn parse_with(bytes: &[u8], extra: &[(&'static str, &str)], strict: bool) -> Res max_depth: MAX_DEPTH + 1, // Text stretches count as nodes too: two for each element. max_nodes: 2 * MAX_ELEMENTS, - max_elements: MAX_ELEMENTS, + // The parse stops here before the whole tree is built: a part over what is left of the + // package's element budget pays for at most that, not for the per-part cap. + max_elements: max, max_attrs: MAX_ATTRS, max_attrs_total: 2 * MAX_ELEMENTS, }; @@ -383,17 +401,27 @@ fn parse_with(bytes: &[u8], extra: &[(&'static str, &str)], strict: bool) -> Res if strict { options = options.strict(); } - let root = options.parse(bytes).map_err(|e| if e.is_limit() { DocxError::Limit(e.to_string()) } else { DocxError::Xml(e.to_string()) })?; - Ok(from_tree(root)) + let root = options.parse(bytes).map_err(|e| match &e { + craft_xml::Error::TooManyElements(_) => DocxError::Limit(format!("over the XML element budget for this parse: at most {max} elements")), + e if e.is_limit() => DocxError::Limit(e.to_string()), + e => DocxError::Xml(e.to_string()), + })?; + Ok(from_tree_counted(root)) } -/// The `craft-xml` tree as this module's (whose shape the reader was written against). +/// The `craft-xml` tree as this module's (whose shape the reader was written against), with the +/// number of elements the subtree holds (the caller charges it against a package-wide budget). // shortcut: one copy of each parsed part; read craft_xml::El directly when the reader is ported to it. -fn from_tree(e: craft_xml::El) -> El { +fn from_tree_counted(e: craft_xml::El) -> (El, usize) { let mut kids = Vec::with_capacity(e.children.len()); + let mut count = 1usize; for n in e.children { match n { - craft_xml::Node::El(c) => kids.push(Node::El(from_tree(c))), + craft_xml::Node::El(c) => { + let (kid, built) = from_tree_counted(c); + count += built; + kids.push(Node::El(kid)); + } craft_xml::Node::Text(t) | craft_xml::Node::CData(t) => match kids.last_mut() { Some(Node::Text(prev)) => prev.push_str(&t), _ => kids.push(Node::Text(t)), @@ -401,7 +429,7 @@ fn from_tree(e: craft_xml::El) -> El { craft_xml::Node::Pi { .. } | craft_xml::Node::Comment(_) => {} } } - El { name: e.name, attrs: e.attrs, kids } + (El { name: e.name, attrs: e.attrs, kids }, count) } /// This module's tree as `craft-xml`'s, for the shared readers (`craft-drawingml`, `craft-math`) @@ -515,12 +543,13 @@ mod tests { fn strict_parsing_rejects_a_dropped_entity_and_trailing_markup() { let bad = [&b"before &unknown; after"[..], b"", b""]; for xml in bad { - assert!(parse_strict(xml).is_err(), "{}", String::from_utf8_lossy(xml)); + assert!(parse_strict_counted(xml, MAX_ELEMENTS).is_err(), "{}", String::from_utf8_lossy(xml)); } assert!( - parse_strict( + parse_strict_counted( b"x & y -" +", + MAX_ELEMENTS ) .is_ok() ); diff --git a/crates/docx/tests/it/element_budget.rs b/crates/docx/tests/it/element_budget.rs new file mode 100644 index 000000000..6b220ae7c --- /dev/null +++ b/crates/docx/tests/it/element_budget.rs @@ -0,0 +1,44 @@ +//! The package-wide XML element budget: a file of many parts each inside the per-part +//! cap reads bounded, where every part used to build its own tree and the trees the +//! reader keeps accumulated. + +use crate::fixtures; +use craft_docx::read; + +const W_NS: &str = r#"xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships""#; + +#[test] +fn a_file_of_element_budget_parts_still_reads() { + // Nine chart parts of 2M elements each: 18M over the package's 16M budget. The later + // parts are skipped with a warning instead of built, and the file still reads. Before + // the budget, every part's whole tree was parsed and the chart trees stayed cached for + // the whole read (~230 MB per 2M-element part, measured), so a file like this cost one + // tree per part and scales linearly with the part count. + let parts = 9usize; + let chunk = "".repeat(2_000_000); + let chart_xml = format!(r#"{chunk}"#); + let mut document = format!( + r#""# + ); + for i in 0..parts { + document.push_str(&format!( + r#""# + )); + } + document.push_str(""); + let mut rels = String::from(r#""#); + for i in 0..parts { + rels.push_str(&format!( + r#""# + )); + } + rels.push_str(""); + let mut entries: Vec<(&str, Vec)> = vec![("word/document.xml", document.into_bytes()), ("word/_rels/document.xml.rels", rels.into_bytes())]; + for i in 0..parts { + entries.push((Box::leak(format!("word/charts/chart{i}.xml").into_boxed_str()), chart_xml.clone().into_bytes())); + } + let refs: Vec<(&str, &[u8])> = entries.iter().map(|(n, b)| (*n, b.as_slice())).collect(); + let z = fixtures::zip(&refs); + let doc = read(&z).expect("a file over the element budget still reads, the extra parts skipped"); + assert_eq!(doc.body.len(), parts, "the document's own paragraphs read"); +} diff --git a/crates/docx/tests/it/main.rs b/crates/docx/tests/it/main.rs index 926cb5154..942d946ae 100644 --- a/crates/docx/tests/it/main.rs +++ b/crates/docx/tests/it/main.rs @@ -16,6 +16,7 @@ mod default_size; mod drawing_payload; mod east_asian_lang; mod east_asian_layout; +mod element_budget; mod emphasis_marks; mod fixtures; mod font_table; diff --git a/crates/esign/Cargo.toml b/crates/esign/Cargo.toml new file mode 100644 index 000000000..7a2efc324 --- /dev/null +++ b/crates/esign/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "craft-esign" +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true +rust-version.workspace = true +description = "What an e-sign service offers the Craft apps: envelopes, recipients and events as contracts, with no vendor and no IO" + +[lints] +workspace = true + +[dependencies] +craft-cloud = { workspace = true } +serde = { workspace = true } +thiserror = { workspace = true } + +[dev-dependencies] +serde_json = { workspace = true } diff --git a/crates/esign/src/error.rs b/crates/esign/src/error.rs new file mode 100644 index 000000000..fca354b45 --- /dev/null +++ b/crates/esign/src/error.rs @@ -0,0 +1,63 @@ +//! One error type for every e-sign contract. +//! +//! Cloud failures are wrapped so a host can surface sign-in and reachability +//! the same way it already does for files. The e-sign-only cases are the ones +//! a UI acts on differently: declined, voided, expired, identity check. + +use thiserror::Error; + +#[derive(Debug, Error)] +pub enum Error { + /// Something the cloud contracts already classify. + #[error(transparent)] + Cloud(#[from] craft_cloud::Error), + + /// A recipient refused to sign. + #[error("declined: {0}")] + Declined(String), + + /// The sender voided the envelope. + #[error("voided: {0}")] + Voided(String), + + /// The envelope passed its deadline without completing. + #[error("expired: {0}")] + Expired(String), + + /// The provider rejected the signer's identity check. + #[error("identity check failed: {0}")] + IdentityCheck(String), + + /// The chosen provider refuses this request under its policy. + #[error("provider policy: {0}")] + ProviderPolicy(String), + + /// The service does not offer this at all. + #[error("this signing service does not support {0}")] + Unsupported(&'static str), + + /// The answer did not match the protocol. + #[error("malformed {what}: {detail}")] + Malformed { what: &'static str, detail: String }, + + /// A field the caller supplied could not be used safely. + #[error("invalid {what}: {detail}")] + Invalid { what: &'static str, detail: String }, +} + +impl Error { + pub fn malformed(what: &'static str, detail: impl Into) -> Error { + Error::Malformed { what, detail: detail.into() } + } + + pub fn invalid(what: &'static str, detail: impl Into) -> Error { + Error::Invalid { what, detail: detail.into() } + } + + /// Whether trying again could succeed without the user doing anything. + pub fn is_transient(&self) -> bool { + matches!(self, Error::Cloud(e) if e.is_transient()) + } +} + +pub type Result = std::result::Result; diff --git a/crates/esign/src/lib.rs b/crates/esign/src/lib.rs new file mode 100644 index 000000000..e9e6fa04b --- /dev/null +++ b/crates/esign/src/lib.rs @@ -0,0 +1,318 @@ +//! What an e-sign service has to offer the Craft apps, and nothing about who +//! provides it. +//! +//! An envelope is a ceremony: a document snapshot, a set of recipients, field +//! placements, and a status. The legal audit trail, identity checks and +//! invitation mail belong to the signing service. This crate only names the +//! contracts an app needs to create, send, watch and finish that ceremony. +//! +//! Nothing in this crate opens a socket. Each trait is implemented by a host +//! (CollabCraft, a desktop adapter, a test double) that brings its own +//! transport. No type here names a vendor. No type here knows about PDF +//! structure: a document is opaque bytes plus a content hash. +//! +//! This crate sits beside `craft-cloud`. It reuses [`craft_cloud::Identity`] +//! and the idea of a contact for autocomplete, but it does not extend +//! [`craft_cloud::Provider`] or [`craft_cloud::Capability`]. Signing is not +//! file access, and a signer role is not a share permission. + +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +mod error; +mod types; + +pub use error::{Error, Result}; +pub use types::{ + CompletedDocument, Envelope, EnvelopeDraft, EnvelopeEvent, EnvelopeStatus, EsignCapability, FieldPlacement, Recipient, RecipientStatus, +}; + +/// Creating and driving envelopes. +/// +/// Methods that a minimal service may omit are defaulted to +/// [`Error::Unsupported`], the same pattern [`craft_cloud::Conversations`] +/// uses for optional cloud features. +pub trait Envelopes { + /// Create a draft from a document snapshot. + /// + /// `document` is the exact byte sequence the ceremony seals. The + /// implementation hashes it and stores `content_sha256` on the envelope. + /// `idempotency_key` makes a retried create return the same envelope. + fn create(&self, draft: &EnvelopeDraft, document: &[u8], idempotency_key: &str) -> Result; + + /// Send invitations and move the envelope to [`EnvelopeStatus::Sent`]. + fn send(&self, envelope: &str) -> Result; + + /// Current status, including per-recipient progress. + fn status(&self, envelope: &str) -> Result; + + /// The finished document and provider evidence. + /// + /// Fails unless status is [`EnvelopeStatus::Completed`]. The returned + /// [`CompletedDocument`] carries both the original document's content + /// digest and the signed artifact's digest, computed honestly rather + /// than copied from one another: the implementation must not assume the + /// provider's sealing left the bytes unchanged. + fn completed(&self, envelope: &str) -> Result; + + /// Cancel an in-flight envelope. + fn void(&self, _envelope: &str, _reason: &str) -> Result<()> { + Err(Error::Unsupported("void")) + } + + /// Nudge one recipient who has not signed yet. + fn remind(&self, _envelope: &str, _recipient: &str) -> Result<()> { + Err(Error::Unsupported("reminders")) + } + + /// A URL the recipient opens to sign inside the provider's UI. + fn signing_url(&self, _envelope: &str, _recipient: &str, _return_to: &str) -> Result { + Err(Error::Unsupported("embedded signing")) + } +} + +/// Turning provider webhooks into [`EnvelopeEvent`]s. +/// +/// Server-side only. A desktop host that implements [`Envelopes`] never needs +/// a webhook secret and need not implement this beyond refusing. +pub trait EventIntake { + /// Verify authenticity and parse zero or more events from one HTTP body. + fn verify_event(&self, headers: &[(String, String)], body: &[u8]) -> Result>; +} + +/// Everything one signing service can do. +/// +/// A service implements the capabilities it has and reports the rest as +/// absent, so a caller can hide void on a stub that only supports the happy +/// path rather than offering a control that fails on use. +pub trait SigningService: Envelopes + EventIntake { + /// A stable identifier, such as `stub` or `documenso`. Used in + /// configuration and logs, never shown to a user. + fn id(&self) -> &str; + + /// What this service actually supports. + fn capabilities(&self) -> Vec; + + fn supports(&self, capability: EsignCapability) -> bool { + self.capabilities().contains(&capability) + } + + /// The party that holds legal and compliance responsibility for the + /// ceremony. Shown to senders before they send (upstream #2315). + fn responsible_party(&self) -> String; +} + +#[cfg(test)] +mod tests { + use std::sync::Mutex; + + use super::*; + use craft_cloud::Identity; + + struct RefuseAll; + + impl Envelopes for RefuseAll { + fn create(&self, _: &EnvelopeDraft, _: &[u8], _: &str) -> Result { + Err(Error::Unsupported("create")) + } + + fn send(&self, _: &str) -> Result { + Err(Error::Unsupported("send")) + } + + fn status(&self, _: &str) -> Result { + Err(Error::Unsupported("status")) + } + + fn completed(&self, _: &str) -> Result { + Err(Error::Unsupported("completed")) + } + } + + impl EventIntake for RefuseAll { + fn verify_event(&self, _: &[(String, String)], _: &[u8]) -> Result> { + Err(Error::Unsupported("webhooks")) + } + } + + impl SigningService for RefuseAll { + fn id(&self) -> &str { + "refuse" + } + + fn capabilities(&self) -> Vec { + Vec::new() + } + + fn responsible_party(&self) -> String { + "nobody".into() + } + } + + #[test] + fn defaulted_methods_are_unsupported() { + let s = RefuseAll; + assert!(matches!(s.void("e", "x"), Err(Error::Unsupported("void")))); + assert!(matches!(s.remind("e", "r"), Err(Error::Unsupported("reminders")))); + assert!(matches!(s.signing_url("e", "r", "https://example"), Err(Error::Unsupported("embedded signing")))); + assert!(!s.supports(EsignCapability::Envelopes)); + assert_eq!(s.responsible_party(), "nobody"); + } + + #[test] + fn draft_round_trips_json() { + let draft = EnvelopeDraft { + title: "NDA".into(), + message: Some("please sign".into()), + sender: Identity { id: "u1".into(), display: "Ada".into(), email: Some("ada@example.com".into()), avatar: None }, + document_id: Some("doc-1".into()), + document_etag: Some("\"abc\"".into()), + recipients: vec![Recipient { + id: "r1".into(), + name: "Bob".into(), + email: "bob@example.com".into(), + role: "Signer".into(), + required: true, + status: RecipientStatus::Pending, + }], + placements: vec![FieldPlacement { + role: "Signer".into(), + page: 0, + x: 0.1, + y: 0.2, + w: 0.3, + h: 0.05, + kind: "signature".into(), + required: true, + }], + expires: Some("2026-12-31".into()), + }; + let json = serde_json::to_string(&draft).expect("serialize"); + let back: EnvelopeDraft = serde_json::from_str(&json).expect("deserialize"); + assert_eq!(back, draft); + } + + #[test] + fn cloud_errors_wrap_and_report_transient() { + let err = Error::from(craft_cloud::Error::Unreachable("down".into())); + assert!(err.is_transient()); + let err = Error::Declined("no".into()); + assert!(!err.is_transient()); + } + + /// A non-cryptographic stand-in for a content digest. Good enough to + /// prove two byte strings differ; this crate takes no hashing + /// dependency, since hashing the document is an adapter's job. + fn fake_digest(bytes: &[u8]) -> String { + use std::hash::{Hash, Hasher}; + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + bytes.hash(&mut hasher); + format!("{:016x}", hasher.finish()) + } + + /// An honest in-process double for [`Envelopes`]. It keeps the exact + /// bytes `create` was given, and on `completed` returns a "signed" + /// artifact built by appending a stub provider seal to those bytes, so + /// `original_content_sha256` and `signed_content_sha256` are computed + /// from genuinely different byte strings, the way a real provider's + /// sealing would produce them, rather than one copied from the other. + struct Double { + document: Mutex>>, + } + + impl Double { + fn new() -> Double { + Double { document: Mutex::new(None) } + } + } + + impl Envelopes for Double { + fn create(&self, draft: &EnvelopeDraft, document: &[u8], _idempotency_key: &str) -> Result { + *self.document.lock().expect("lock") = Some(document.to_vec()); + Ok(Envelope { + id: "env-double".into(), + title: draft.title.clone(), + message: draft.message.clone(), + sender: draft.sender.clone(), + document_id: draft.document_id.clone(), + document_etag: draft.document_etag.clone(), + content_sha256: fake_digest(document), + recipients: draft.recipients.clone(), + placements: draft.placements.clone(), + status: EnvelopeStatus::Draft, + expires: draft.expires.clone(), + created: None, + completed_at: None, + }) + } + + fn send(&self, envelope: &str) -> Result { + self.status(envelope) + } + + fn status(&self, envelope: &str) -> Result { + let document = self.document.lock().expect("lock").clone().unwrap_or_default(); + Ok(Envelope { + id: envelope.into(), + title: "Double".into(), + message: None, + sender: Identity { id: "u1".into(), display: "Ada".into(), email: None, avatar: None }, + document_id: None, + document_etag: None, + content_sha256: fake_digest(&document), + recipients: Vec::new(), + placements: Vec::new(), + status: EnvelopeStatus::Completed, + expires: None, + created: None, + completed_at: None, + }) + } + + fn completed(&self, envelope: &str) -> Result { + let original = self.document.lock().expect("lock").clone().unwrap_or_default(); + let mut signed = original.clone(); + signed.extend_from_slice(b"\0provider-seal"); + Ok(CompletedDocument { + envelope_id: envelope.into(), + bytes: signed.clone(), + original_content_sha256: fake_digest(&original), + signed_content_sha256: fake_digest(&signed), + evidence: b"certificate-of-completion".to_vec(), + }) + } + } + + /// RFC-0021's evidence guarantee: `CompletedDocument` carries the + /// original document's digest and the signed artifact's digest as two + /// distinct, honestly computed fields, and they differ when the + /// provider's sealing changes the bytes. + #[test] + fn completed_document_keeps_original_and_signed_digests_distinct() { + let double = Double::new(); + let draft = EnvelopeDraft { + title: "Contract".into(), + message: None, + sender: Identity { id: "u1".into(), display: "Ada".into(), email: None, avatar: None }, + document_id: Some("doc-1".into()), + document_etag: None, + recipients: Vec::new(), + placements: Vec::new(), + expires: None, + }; + let original_bytes = b"the original document bytes"; + let envelope = double.create(&draft, original_bytes, "idem-1").expect("create"); + let completed = double.completed(&envelope.id).expect("completed"); + + assert_eq!(completed.original_content_sha256, fake_digest(original_bytes)); + assert_ne!(completed.bytes, original_bytes, "the signed artifact's bytes differ from the original"); + assert_eq!(completed.signed_content_sha256, fake_digest(&completed.bytes)); + assert_ne!( + completed.original_content_sha256, completed.signed_content_sha256, + "sealing changed the bytes, so the two digests must not be conflated" + ); + + let json = serde_json::to_string(&completed).expect("serialize"); + let back: CompletedDocument = serde_json::from_str(&json).expect("deserialize"); + assert_eq!(back, completed); + } +} diff --git a/crates/esign/src/types.rs b/crates/esign/src/types.rs new file mode 100644 index 000000000..08d42456e --- /dev/null +++ b/crates/esign/src/types.rs @@ -0,0 +1,186 @@ +//! The data the e-sign contracts pass around. +//! +//! Every type here is plain and vendor-neutral. A field that only means +//! something to one product belongs in that provider's crate. Nothing here +//! knows about PDF structure; a document is opaque bytes plus a content hash. + +use craft_cloud::Identity; +use serde::{Deserialize, Serialize}; + +/// What a signing service can do. +/// +/// Reported rather than assumed, so a caller hides void or remind on a service +/// that only supports create/send/status/completed. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum EsignCapability { + /// Create, send, poll status, and fetch the completed document. + Envelopes, + /// Cancel an in-flight envelope. + Void, + /// Nudge a recipient who has not signed yet. + Reminders, + /// Return a URL the recipient opens to sign in the provider's UI. + EmbeddedSigning, + /// Accept provider webhooks and turn them into [`EnvelopeEvent`]s. + Webhooks, +} + +/// Where an envelope is in its life. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum EnvelopeStatus { + /// Created but not yet sent to recipients. + Draft, + /// At least one recipient still owes a signature. + Sent, + /// Every required recipient has signed. + Completed, + /// The sender cancelled it. + Voided, + /// A recipient declined. + Declined, + /// The deadline passed without completion. + Expired, +} + +/// What one recipient still owes, or has done. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum RecipientStatus { + Pending, + Viewed, + Signed, + Declined, +} + +/// Who must sign, as the dialog and the service agree. +/// +/// Built from a [`craft_cloud::Contact`] by an explicit conversion at the host +/// boundary. Never a [`craft_cloud::ShareTarget`]: signing is not access. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Recipient { + /// Opaque handle the service wants back. + pub id: String, + /// What to show. A display name where there is one. + pub name: String, + /// Delivery address. Required for invitation mail. + pub email: String, + /// Signer role label, such as "Client" or "Countersign". Colours and + /// field placement key off this string within one envelope. + pub role: String, + /// Whether the envelope cannot complete without this person. + pub required: bool, + pub status: RecipientStatus, +} + +/// One signature (or initials / date) placement on the document. +/// +/// Coordinates are normalised page space: origin top-left, `x`/`y`/`w`/`h` in +/// `[0.0, 1.0]` of the page. The document implementation maps these onto its +/// own field model; this crate never sees PDF objects. +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct FieldPlacement { + /// Recipient role this field belongs to. + pub role: String, + /// Zero-based page index. + pub page: u32, + pub x: f32, + pub y: f32, + pub w: f32, + pub h: f32, + /// Machine-readable kind: `signature`, `initials`, `date`, `text`. + pub kind: String, + pub required: bool, +} + +impl PartialEq for FieldPlacement { + fn eq(&self, other: &Self) -> bool { + self.role == other.role + && self.page == other.page + && self.kind == other.kind + && self.required == other.required + && self.x.to_bits() == other.x.to_bits() + && self.y.to_bits() == other.y.to_bits() + && self.w.to_bits() == other.w.to_bits() + && self.h.to_bits() == other.h.to_bits() + } +} + +impl Eq for FieldPlacement {} + +/// What the caller wants to send, before the service assigns an id. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct EnvelopeDraft { + /// Human title for the ceremony. + pub title: String, + /// Optional note shown to recipients. + pub message: Option, + /// Who is asking for signatures. Bound to the active account at send time. + pub sender: Identity, + /// Cloud document identity at the moment of the snapshot, when known. + pub document_id: Option, + pub document_etag: Option, + pub recipients: Vec, + pub placements: Vec, + /// `YYYY-MM-DD`. After this the envelope expires if still open. + pub expires: Option, +} + +/// An envelope the service knows about. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Envelope { + pub id: String, + pub title: String, + pub message: Option, + pub sender: Identity, + pub document_id: Option, + pub document_etag: Option, + /// SHA-256 of the document bytes at create time, lowercase hex. + pub content_sha256: String, + pub recipients: Vec, + pub placements: Vec, + pub status: EnvelopeStatus, + pub expires: Option, + /// RFC 3339. + pub created: Option, + /// RFC 3339 when status became [`EnvelopeStatus::Completed`]. + pub completed_at: Option, +} + +/// The finished document plus whatever evidence the provider returns. +/// +/// Carries two digests as distinct fields, never conflated: the original +/// document's content digest and the returned signed artifact's digest. The +/// two are the same hash family as [`Envelope::content_sha256`] and can +/// differ in value. A provider's sealing (a certificate page, flattening, a +/// visible audit stamp) can change the signed bytes relative to the document +/// the envelope was created from, so a caller must not assume `bytes` hashes +/// back to `original_content_sha256`. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct CompletedDocument { + pub envelope_id: String, + /// Signed document bytes. Opaque to this crate. + pub bytes: Vec, + /// SHA-256 of the original document bytes the envelope was created from, + /// lowercase hex. Matches the envelope's own `content_sha256`. + pub original_content_sha256: String, + /// SHA-256 of `bytes`, the returned signed artifact, lowercase hex. May + /// differ from `original_content_sha256`; see the struct's docs. + pub signed_content_sha256: String, + /// Provider evidence (certificate of completion, audit export, …). + pub evidence: Vec, +} + +/// Something that happened to an envelope. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct EnvelopeEvent { + pub envelope_id: String, + /// Machine-readable kind: `sent`, `viewed`, `signed`, `declined`, `voided`, `completed`. + pub kind: String, + /// Recipient id when the event is about one person. + pub recipient_id: Option, + /// RFC 3339. + pub at: Option, + pub detail: Option, +} diff --git a/crates/flow/src/from_doc.rs b/crates/flow/src/from_doc.rs index e3e915201..b167779e7 100644 --- a/crates/flow/src/from_doc.rs +++ b/crates/flow/src/from_doc.rs @@ -1114,6 +1114,9 @@ fn flow_table(doc: &Document, t: &Table, depth: usize, tracked: FlowOpts) -> FTa // Word. Only Repeat as header row makes it one then. let header = r.props.header || (ri == 0 && style.is_some() && t.props.look.header_row && t.rows.len() > 1); let mut cells = Vec::new(); + for _ in 0..r.first_grid() { + cells.push(Cell::default()); + } for (ci, c) in r.cells.iter().enumerate() { let styled = if bake { styled_cell(t, style.as_ref(), (ri, ci), ncols) } else { None }; let mut rowspan = 1; @@ -1159,6 +1162,8 @@ fn flow_table(doc: &Document, t: &Table, depth: usize, tracked: FlowOpts) -> FTa Some(Box::new(crate::CellPic { img, repeat: p.repeat, align: p.align })) }), width: None, + vmerge_restart: c.props.vmerge == VMerge::Restart, + synthetic_covered: false, }); } rows.push(cells); diff --git a/crates/flow/src/to_doc.rs b/crates/flow/src/to_doc.rs index 0375c448c..3d27d521f 100644 --- a/crates/flow/src/to_doc.rs +++ b/crates/flow/src/to_doc.rs @@ -284,6 +284,18 @@ impl<'a> Builder<'a> { /// `cp` as a run may keep it: without its link and font once the runs' copies of them are /// over budget. + /// A run's properties with its tracked insertion, deletion and formatting change. + fn tracked_props(&mut self, f: &Fmt) -> CharProps { + let mut cp = self.budget(char_props(f)); + cp.ins = f.ins.as_ref().map(|m| self.revision(RevisionKind::Insert, m)); + cp.del = f.del.as_ref().map(|m| self.revision(RevisionKind::Delete, m)); + if let Some(c) = &f.fmt_change { + let old = self.budget(char_props(&c.old)); + cp.fmt_change = PropChange::boxed(self.revision(RevisionKind::Format, &c.mark), old); + } + cp + } + fn budget(&mut self, mut cp: CharProps) -> CharProps { let n = cp.link.as_ref().map_or(0, String::len).saturating_add(cp.font.as_ref().map_or(0, String::len)); match self.run_strings.checked_add(n).filter(|&t| t <= MAX_RUN_STRINGS) { @@ -553,13 +565,7 @@ impl<'a> Builder<'a> { match i { Inline::Text(t, f) => { let t = clean_text(t); - let mut cp = self.budget(char_props(f)); - cp.ins = f.ins.as_ref().map(|m| self.revision(RevisionKind::Insert, m)); - cp.del = f.del.as_ref().map(|m| self.revision(RevisionKind::Delete, m)); - if let Some(c) = &f.fmt_change { - let old = self.budget(char_props(&c.old)); - cp.fmt_change = PropChange::boxed(self.revision(RevisionKind::Format, &c.mark), old); - } + let mut cp = self.tracked_props(f); if p.kind == Kind::Code { // Code's font comes from its style, before a change as after it. if cp.font.as_deref() == Some(MONO_FONT) { @@ -633,7 +639,8 @@ impl<'a> Builder<'a> { } } Inline::Field { instr, result, fmt, locked } => { - let cp = self.budget(char_props(fmt)); + // A field inserted or deleted with tracked changes keeps them (RTF `\chpgn`). + let cp = self.tracked_props(fmt); let (instr, result) = (clean_text(instr), clean_text(result)); if instr.trim().is_empty() { append(&mut out, &result, &cp, None); @@ -907,6 +914,41 @@ impl<'a> Builder<'a> { } tb.rows.push(row); } + let starts: Vec<(usize, usize)> = (0..tb.rows.first().map_or(0, |row| row.cells.len())) + .filter(|&ci| tb.rows.first().and_then(|row| row.cells.get(ci)).is_some_and(|c| c.props.vmerge == VMerge::Continue)) + .map(|ci| (ci, tb.grid_col(0, ci))) + .collect(); + for (ci, g) in starts { + let span = tb.rows.first().map_or(1, |r| r.cells[ci].props.span); + let more = tb + .cell_at_grid(1, g) + .filter(|&i| tb.grid_col(1, i) == g) + .and_then(|i| tb.rows.get(1)?.cells.get(i)) + .is_some_and(|c| c.props.vmerge == VMerge::Continue && c.props.span == span); + if let Some(cell) = tb.rows.first_mut().and_then(|r| r.cells.get_mut(ci)) { + cell.props.vmerge = if more { VMerge::Restart } else { VMerge::None }; + } + } + for r in 1..tb.rows.len() { + for ci in 0..tb.rows[r].cells.len() { + if tb.rows[r].cells[ci].props.vmerge == VMerge::Continue { + let g = tb.grid_col(r, ci); + let span = tb.rows[r].cells[ci].props.span; + let prev_r = r - 1; + if let Some(up_ci) = tb.cell_at_grid(prev_r, g) + && tb.grid_col(prev_r, up_ci) == g + && tb.rows[prev_r].cells[up_ci].props.span == span + { + let up_cell = &mut tb.rows[prev_r].cells[up_ci]; + if up_cell.props.vmerge == VMerge::None { + up_cell.props.vmerge = VMerge::Restart; + } + } else { + tb.rows[r].cells[ci].props.vmerge = VMerge::None; + } + } + } + } // Its markup kept for the writer, by its place among the top's tables. if depth == 0 { if t.kept.is_some() || t.wrap.is_some() { diff --git a/crates/flow/src/types.rs b/crates/flow/src/types.rs index d5abb7537..fcd955a30 100644 --- a/crates/flow/src/types.rs +++ b/crates/flow/src/types.rs @@ -881,6 +881,10 @@ pub struct Cell { /// The width, points, the source gives a cell spanning one column (HTML): see /// [`FTable::widths_from_cells`]. pub width: Option, + /// Whether the source explicitly started a vertical merge (`mso-yfti-vmerge:restart`). + pub vmerge_restart: bool, + /// Whether this covered placeholder was synthesized by [`FTable::insert_covered`]. + pub synthetic_covered: bool, } /// A cell's background picture: the picture at its own size, how it fills the cell, and where an @@ -907,6 +911,8 @@ impl Default for Cell { direction: Default::default(), picture: None, width: None, + vmerge_restart: false, + synthetic_covered: false, } } } @@ -999,8 +1005,8 @@ impl FTable { let mut g = 0usize; let mut ci = 0usize; while let Some(c) = self.rows.get(r).and_then(|row| row.get(ci)) { - let (span, rs, covered) = (c.colspan.clamp(1, 63) as usize, c.rowspan.clamp(1, 1000) as usize, c.covered); - if rs > 1 && !covered { + let (span, rs, vmerge_restart) = (c.colspan.clamp(1, 63) as usize, c.rowspan.clamp(1, 1000) as usize, c.vmerge_restart); + if rs > 1 { for k in 1..rs { work += 1; if work > MAX_COVERED_WORK { @@ -1017,8 +1023,14 @@ impl FTable { } x += cc.colspan.clamp(1, 63) as usize; } + if at < row.len() && x == g && row[at].covered && (vmerge_restart || row[at].synthetic_covered) { + // Row already has a matching explicit continuation (when this cell had + // `mso-yfti-vmerge:restart`) or a synthetic placeholder from an earlier + // row. Avoid adding a duplicate covered cell which would make the row ragged. + continue; + } if row.len() < 64 { - row.insert(at, Cell { colspan: span as u32, covered: true, ..Default::default() }); + row.insert(at, Cell { colspan: span as u32, covered: true, synthetic_covered: true, ..Default::default() }); } } } diff --git a/crates/html/src/doc/builder.rs b/crates/html/src/doc/builder.rs index 68bb7d8db..b6859523f 100644 --- a/crates/html/src/doc/builder.rs +++ b/crates/html/src/doc/builder.rs @@ -55,6 +55,27 @@ struct TableB { row: Option>, /// The table or one of its cells asks for borders. bordered: bool, + /// Explicit column widths from `` and childless ``. + col_widths: Vec>, + /// Pending ``: `(span, width, has_child_cols)`. + pending_colgroup: Option<(usize, Option, bool)>, +} + +impl TableB { + /// Commit pending colgroup widths: if childless, push span columns with group width. + /// When child `` elements are present, they have already received the group width + /// during `` handling; columns from earlier groups are never backfilled. + fn commit_pending_colgroup(&mut self) { + if let Some((span, group_w, has_child_cols)) = self.pending_colgroup.take() + && !has_child_cols + { + for _ in 0..span { + if self.col_widths.len() < MAX_TABLE_COLS { + self.col_widths.push(group_w); + } + } + } + } } struct ElementStyle { @@ -863,6 +884,15 @@ impl<'r> Builder<'r> { } } + /// Finalize an open HTML element popped from the stack. + /// + /// Side effects: + /// - Flushes any buffered inline text into the current block container. + /// - Sets `pending_page_break` if the element requests page break before or after. + /// - For `Cell`: pops the cell container, attaches generated blocks to the cell, and pushes into the active row. + /// - For `Tr`: commits any pending `` definitions and pushes the completed row into the active table. + /// - For `Table`: commits pending colgroup widths, finalizes table rows with `insert_covered` (bounded to `MAX_ROWS`), + /// resolves explicit column widths from colgroups/cells, and appends the resulting table to the enclosing container. fn close(&mut self, e: &El) { if e.page_break_after || e.page_break { self.pending_page_break = true; @@ -881,26 +911,53 @@ impl<'r> Builder<'r> { } } ElKind::Tr => { - if let Some(t) = self.tables.last_mut() - && let Some(r) = t.row.take() - { - t.rows.push(r); + if let Some(t) = self.tables.last_mut() { + t.commit_pending_colgroup(); + if let Some(r) = t.row.take() { + t.rows.push(r); + } } } ElKind::Table => { if let Some(mut t) = self.tables.pop() { + t.commit_pending_colgroup(); if let Some(r) = t.row.take() { t.rows.push(r); } let borderless = !t.bordered; // Keep at most MAX_ROWS rows (the model drops the rest anyway): bounds the // O(rows × rowspan) work of `insert_covered` on a table of millions of ``. - let rows: Vec<_> = t.rows.into_iter().filter(|r| !r.is_empty()).take(craft_wordmodel::table::MAX_ROWS).collect(); + let rows: Vec<_> = t.rows.into_iter().take(craft_wordmodel::table::MAX_ROWS).collect(); let mut ft = FTable { rows, widths: Vec::new(), borderless, extra: None, kept: None, wrap: None }; + let col_widths = &t.col_widths; if !ft.rows.is_empty() { ft.insert_covered(); - // Columns keep the widths their cells give when every column has one. - if ft.cols() <= MAX_TABLE_COLS { + ft.rows.retain(|r| !r.is_empty()); + } + if !ft.rows.is_empty() { + if !col_widths.is_empty() && ft.cols() <= MAX_TABLE_COLS { + let mut widths = vec![None; ft.cols()]; + for (i, &cw) in col_widths.iter().take(ft.cols()).enumerate() { + if let Some(w) = cw { + widths[i] = Some(w); + } + } + for row in &ft.rows { + let mut g = 0; + for c in row { + if let (Some(w), Some(slot)) = (c.width, widths.get_mut(g)) { + slot.get_or_insert(w); + } + g += c.colspan.clamp(1, 63) as usize; + } + } + if widths.iter().any(Option::is_some) { + let known_sum: f32 = widths.iter().filter_map(|w| *w).sum(); + let known_count = widths.iter().filter(|w| w.is_some()).count(); + let avg = if known_count > 0 { known_sum / known_count as f32 } else { 72.0 }; + ft.widths = widths.into_iter().map(|w| w.unwrap_or(avg)).collect(); + } + } else if ft.cols() <= MAX_TABLE_COLS { ft.widths_from_cells(); } self.container().push(FBlock::Table(ft)); @@ -1001,6 +1058,14 @@ impl<'r> Builder<'r> { } } + /// Process void or special HTML elements (`br`, `hr`, `wbr`, `col`, `colgroup`, `img`). + /// + /// Side effects: + /// - `br` / `wbr`: inserts line break or zero-width break into the active paragraph. + /// - `hr`: inserts a thematic horizontal rule block with borders and spacing into the container. + /// - `col`: extracts span and explicit CSS width, resolves against active ``, and appends up to `MAX_TABLE_COLS` column widths to the table. + /// - `colgroup`: commits any previous pending colgroup and buffers new span and width styles until child cols or closing tag arrive. + /// - `img`: parses dimensions, styles, and data/remote sources, creating an image block or inline image run. fn start_special(&mut self, name: &str, attrs: &[(String, String)]) -> bool { match name { "br" => { @@ -1020,6 +1085,34 @@ impl<'r> Builder<'r> { let fmt = self.fmt(); self.start_para().push_text("\u{200B}", &fmt); } + "col" => { + let css = self.css_of(name, attrs); + let span = attr(attrs, "span").and_then(|v| v.trim().parse::().ok()).unwrap_or(1).clamp(1, MAX_TABLE_COLS); + let w = cell_width(&css, attrs); + if let Some(t) = self.tables.last_mut() { + let group_w = if let Some((_, group_w, has_child_cols)) = &mut t.pending_colgroup { + *has_child_cols = true; + *group_w + } else { + None + }; + let effective_w = w.or(group_w); + for _ in 0..span { + if t.col_widths.len() < MAX_TABLE_COLS { + t.col_widths.push(effective_w); + } + } + } + } + "colgroup" => { + let css = self.css_of(name, attrs); + let span = attr(attrs, "span").and_then(|v| v.trim().parse::().ok()).unwrap_or(1).clamp(1, MAX_TABLE_COLS); + let w = cell_width(&css, attrs); + if let Some(t) = self.tables.last_mut() { + t.commit_pending_colgroup(); + t.pending_colgroup = Some((span, w, false)); + } + } "img" => { let alt = attr(attrs, "alt").unwrap_or("").to_string(); let dim = |key: &str| attr(attrs, key).and_then(|v| v.trim().trim_end_matches("px").trim().parse::().ok()).map(|p| p * 0.75); @@ -1164,12 +1257,20 @@ impl<'r> Builder<'r> { let css = self.css_of(name, attrs); let ElementStyle { mut fmt, block_background, align, preserve, page_break, page_break_after } = self.element_style(name, attrs, kind, &css); match kind { - ElKind::Table => self.tables.push(TableB { rows: Vec::new(), row: None, bordered: declares_border(attrs, &css, true) }), + ElKind::Table => self.tables.push(TableB { + rows: Vec::new(), + row: None, + bordered: declares_border(attrs, &css, true), + col_widths: Vec::new(), + pending_colgroup: None, + }), ElKind::Tr => { - if let Some(t) = self.tables.last_mut() - && let Some(r) = t.row.take() - { - t.rows.push(r); + if let Some(t) = self.tables.last_mut() { + t.commit_pending_colgroup(); + if let Some(r) = t.row.take() { + t.rows.push(r); + } + t.row = Some(Vec::new()); } } ElKind::Cell => { @@ -1216,11 +1317,16 @@ impl<'r> Builder<'r> { _ => {} } } + // The last declaration wins, as in the cascade. + let mso_vmerge = decls(&css).filter(|(k, _)| k == "mso-yfti-vmerge").last().map(|(_, v)| v.trim().to_ascii_lowercase()); + let is_mso_vmerge_continue = mso_vmerge.as_deref() == Some("continue"); + let is_mso_vmerge_restart = mso_vmerge.as_deref() == Some("restart"); + let rowspan = attr(attrs, "rowspan").and_then(|v| v.trim().parse::().ok()).map(|v| v.clamp(1, 1000)).unwrap_or(1); self.cells.push(Cell { blocks: Vec::new(), colspan, - rowspan: attr(attrs, "rowspan").and_then(|v| v.trim().parse::().ok()).map(|v| v.clamp(1, 1000)).unwrap_or(1), - covered: false, + rowspan, + covered: is_mso_vmerge_continue, header: name == "th", shading, borders: cell_borders(&css), @@ -1229,6 +1335,8 @@ impl<'r> Builder<'r> { direction: Default::default(), picture: None, width: if colspan == 1 { cell_width(&css, attrs) } else { None }, + vmerge_restart: is_mso_vmerge_restart, + synthetic_covered: false, }); fmt.background = None; self.containers.push(Vec::new()); @@ -1261,6 +1369,12 @@ impl<'r> Builder<'r> { } return; } + if name == "colgroup" { + if let Some(t) = self.tables.last_mut() { + t.commit_pending_colgroup(); + } + return; + } let crosses = matches!(name, "table"); let target = if matches!(name, "td" | "th") { self.find_open(|e| e.kind == ElKind::Cell, |e| e.kind == ElKind::Table) diff --git a/crates/html/src/doc/export.rs b/crates/html/src/doc/export.rs index 9fb861d85..52f7f50f0 100644 --- a/crates/html/src/doc/export.rs +++ b/crates/html/src/doc/export.rs @@ -263,21 +263,87 @@ fn para_html(p: &Para) -> String { } } +/// Render an HTML table element, emitting `` column widths and cell attributes. fn table_html(t: &FTable, out: &mut String, depth: usize) { out.push_str("\n"); - for row in &t.rows { - out.push_str(""); - for c in row { - if c.covered { + if !t.widths.is_empty() { + out.push_str("\n"); + for w in &t.widths { + out.push_str(&format!("\n")); + } + out.push_str("\n"); + } + let nrows = t.rows.len(); + let grid_cols: Vec> = t + .rows + .iter() + .map(|row| { + let mut x = 0usize; + row.iter() + .map(|c| { + let start = x; + x = x.saturating_add(c.colspan.clamp(1, 63) as usize); + start + }) + .collect() + }) + .collect(); + let cell_at_grid = |r: usize, target_g: usize| -> Option { grid_cols.get(r)?.binary_search(&target_g).ok() }; + let grid_col = |r: usize, ci: usize| -> usize { grid_cols.get(r).and_then(|row| row.get(ci)).copied().unwrap_or(0) }; + + let mut is_covered: Vec> = t.rows.iter().map(|r| vec![false; r.len()]).collect(); + let mut rowspans: Vec> = t.rows.iter().map(|r| r.iter().map(|c| c.rowspan.clamp(1, 1000)).collect()).collect(); + + for r in 0..nrows { + let row_len = t.rows.get(r).map_or(0, |row| row.len()); + for ci in 0..row_len { + if is_covered.get(r).and_then(|row| row.get(ci)).copied().unwrap_or(false) { continue; } + let Some(c) = t.rows.get(r).and_then(|row| row.get(ci)) else { continue }; + let g = grid_col(r, ci); + let span = c.colspan.clamp(1, 63) as usize; + let mut extent = 1u32; + for down_r in (r + 1)..nrows { + let Some(down_ci) = cell_at_grid(down_r, g) else { break }; + let Some(down_c) = t.rows.get(down_r).and_then(|row| row.get(down_ci)) else { break }; + let down_covered = is_covered.get(down_r).and_then(|row| row.get(down_ci)).copied().unwrap_or(false); + if grid_col(down_r, down_ci) == g + && down_c.colspan.clamp(1, 63) as usize == span + && down_c.covered + && !down_c.vmerge_restart + && !down_covered + { + if let Some(down_row) = is_covered.get_mut(down_r) + && let Some(slot) = down_row.get_mut(down_ci) + { + *slot = true; + } + extent = extent.saturating_add(1); + } else { + break; + } + } + if let Some(slot) = rowspans.get_mut(r).and_then(|row| row.get_mut(ci)) { + *slot = (*slot).max(extent); + } + } + } + + for (ri, row) in t.rows.iter().enumerate() { + out.push_str(""); + for (ci, c) in row.iter().enumerate() { + if is_covered.get(ri).and_then(|r| r.get(ci)).copied().unwrap_or(false) { + continue; + } + let rowspan = rowspans.get(ri).and_then(|r| r.get(ci)).copied().unwrap_or(c.rowspan.clamp(1, 1000)); let tag = if c.header { "th" } else { "td" }; let mut attrs = String::new(); if c.colspan > 1 { attrs.push_str(&format!(" colspan=\"{}\"", c.colspan)); } - if c.rowspan > 1 { - attrs.push_str(&format!(" rowspan=\"{}\"", c.rowspan)); + if rowspan > 1 { + attrs.push_str(&format!(" rowspan=\"{}\"", rowspan)); } let v_css = match c.valign { Some(VAlign::Center) => "vertical-align:middle", @@ -288,6 +354,9 @@ fn table_html(t: &FTable, out: &mut String, depth: usize) { if !t.borderless { css.insert(0, "border:1px solid #999".to_string()); } + if let Some(w) = c.width { + css.push(format!("width:{w:.2}pt")); + } if let Some(s) = c.shading { css.push(format!("background-color:#{}", s.hex())); } diff --git a/crates/html/src/doc/tests.rs b/crates/html/src/doc/tests.rs index c0b00084b..6c4e5fe8e 100644 --- a/crates/html/src/doc/tests.rs +++ b/crates/html/src/doc/tests.rs @@ -717,6 +717,195 @@ fn cells_give_their_columns_widths() { assert_eq!(t.widths, [75.0, 150.0]); } +#[test] +fn col_elements_give_table_column_widths() { + let f = parse("
AB
"); + let FBlock::Table(t) = &f.blocks[0] else { panic!() }; + assert_eq!(t.widths, [75.0, 150.0]); + + // col with span + let f2 = parse( + "
123
", + ); + let FBlock::Table(t2) = &f2.blocks[0] else { panic!() }; + assert_eq!(t2.widths, [72.0, 72.0, 144.0]); + + // Childless colgroup defines widths across declared span + let f3 = parse("
12
"); + let FBlock::Table(t3) = &f3.blocks[0] else { panic!() }; + assert_eq!(t3.widths, [75.0, 75.0]); + + // Child col elements override colgroup widths + let f4 = parse("
1
"); + let FBlock::Table(t4) = &f4.blocks[0] else { panic!() }; + assert_eq!(t4.widths, [150.0]); + + // Mixed childless colgroup and colgroup with child col elements + let f5 = parse( + "
123
", + ); + let FBlock::Table(t5) = &f5.blocks[0] else { panic!() }; + assert_eq!(t5.widths, [75.0, 200.0, 300.0]); + + // Child col elements inherit parent colgroup width when unset + let f6 = parse("
12
"); + let FBlock::Table(t6) = &f6.blocks[0] else { panic!() }; + assert_eq!(t6.widths, [90.0, 90.0]); + + // Child col elements without width inherit group width while explicit child width takes precedence + let f7 = parse("
12
"); + let FBlock::Table(t7) = &f7.blocks[0] else { panic!() }; + assert_eq!(t7.widths, [150.0, 90.0]); + + // Partial explicit col widths fall back to average for unset columns + let f8 = parse("
12
"); + let FBlock::Table(t8) = &f8.blocks[0] else { panic!() }; + assert_eq!(t8.widths, [100.0, 100.0]); + + // Export includes colgroup + let doc = model::to_doc(&f); + let html = export(&doc); + assert!(html.contains(""), "html export includes colgroup: {html}"); + assert!(html.contains(""), "{html}"); + assert!(html.contains(""), "{html}"); +} + +#[test] +fn word_html_vertical_merge_is_preserved() { + use craft_wordmodel::props::VMerge; + let html = "\ + \ + \ +
TopB1
ContB2
"; + let f = parse(html); + let FBlock::Table(t) = &f.blocks[0] else { panic!() }; + assert_eq!(t.rows.len(), 2); + assert_eq!(t.rows[0].len(), 2); + assert_eq!(t.rows[1].len(), 2, "second row must have exactly 2 cells, no duplicate synthetic cell"); + assert!(!t.rows[0][0].covered); + assert!(t.rows[1][0].covered); + + let doc = model::to_doc(&f); + let craft_wordmodel::Block::Table(tb) = &*doc.body[0] else { panic!() }; + assert_eq!(tb.rows[0].cells[0].props.vmerge, VMerge::Restart); + assert_eq!(tb.rows[1].cells[0].props.vmerge, VMerge::Continue); + assert_eq!(tb.rows[1].cells.len(), 2, "table model second row has exactly 2 cells"); + assert_eq!(tb.vertical_extent(0, 0), Some((0, 2))); +} + +#[test] +fn html_multiple_colgroups_do_not_backfill_earlier_groups() { + // Earlier colgroup with unset column must not be backfilled by later colgroup width. + let html = "\ + \ + \ + \ +
12
"; + let f = parse(html); + let FBlock::Table(t) = &f.blocks[0] else { panic!() }; + assert_eq!(t.widths, [50.0, 50.0], "column 0 was not backfilled by group 2 width of 200pt"); +} + +#[test] +fn word_html_rowspan_with_explicit_vmerge_continue_no_duplicate_cell() { + use craft_wordmodel::props::VMerge; + let html = "\ + \ + \ +
AB1
A_contB2
"; + let f = parse(html); + let FBlock::Table(t) = &f.blocks[0] else { panic!() }; + assert_eq!(t.rows.len(), 2); + assert_eq!(t.rows[0].len(), 2); + assert_eq!(t.rows[1].len(), 2, "second row must have exactly 2 cells, not ragged"); + assert!(!t.rows[0][0].covered); + assert!(t.rows[1][0].covered); + + let doc = model::to_doc(&f); + let craft_wordmodel::Block::Table(tb) = &*doc.body[0] else { panic!() }; + assert_eq!(tb.rows[0].cells[0].props.vmerge, VMerge::Restart); + assert_eq!(tb.rows[1].cells[0].props.vmerge, VMerge::Continue); + assert_eq!(tb.rows[1].cells.len(), 2); + assert_eq!(tb.vertical_extent(0, 0), Some((0, 2))); +} + +#[test] +fn to_doc_normalises_row_0_continue_cell() { + use craft_wordmodel::props::VMerge; + // Case 1: Row 0 has continue and Row 1 has continue -> Row 0 normalised to Restart. + let html_multi = "\ + \ + \ +
TopContB1
BottomContB2
"; + let f_multi = parse(html_multi); + let doc_multi = model::to_doc(&f_multi); + let craft_wordmodel::Block::Table(tb_multi) = &*doc_multi.body[0] else { panic!() }; + assert_eq!(tb_multi.rows[0].cells[0].props.vmerge, VMerge::Restart, "row 0 continue normalised to restart"); + assert_eq!(tb_multi.rows[1].cells[0].props.vmerge, VMerge::Continue); + + // Case 2: Row 0 has continue but table has only 1 row (or no continuation) -> normalised to None. + let html_single = "\ + \ +
SoloContB1
"; + let f_single = parse(html_single); + let doc_single = model::to_doc(&f_single); + let craft_wordmodel::Block::Table(tb_single) = &*doc_single.body[0] else { panic!() }; + assert_eq!(tb_single.rows[0].cells[0].props.vmerge, VMerge::None, "orphaned row 0 continue normalised to none"); + + // Case 3: Row 0 col 1 has continue, Row 1 has a spanning continue starting at col 0 -> col 1 normalised to None. + let html_span = "\ + \ + \ +
A0B0
SpanCont
"; + let f_span = parse(html_span); + let doc_span = model::to_doc(&f_span); + let craft_wordmodel::Block::Table(tb_span) = &*doc_span.body[0] else { panic!() }; + assert_eq!(tb_span.rows[0].cells[1].props.vmerge, VMerge::None, "unaligned spanning continuation in row 1 must not mark row 0 cell as restart"); +} + +/// #1785: A covered continuation cell with `rowspan > 1` expands into the following row when +/// no restart cell above spans it. +#[test] +fn covered_continuation_with_rowspan_expands_into_next_row() { + use craft_wordmodel::props::VMerge; + let html = "\ + \ + \ + \ +
TopB0
MidB1
B2
"; + let f = parse(html); + let doc = model::to_doc(&f); + let craft_wordmodel::Block::Table(tb) = &*doc.body[0] else { panic!() }; + assert_eq!(tb.rows.len(), 3); + assert_eq!(tb.rows[2].cells.len(), 2, "row 2 should have placeholder + B2"); + assert_eq!(tb.rows[2].cells[0].props.vmerge, VMerge::Continue); +} + +/// #1785: A plain `rowspan=2` cell `A` in col 0 followed by `B` (`vmerge:restart`) and `D` +/// must still insert a placeholder for `A` in row 1 even when `B`'s explicit `vmerge:continue` +/// is the first `` in row 1. +#[test] +fn rowspan_before_explicit_vmerge_continue_keeps_grid_columns() { + use craft_wordmodel::props::VMerge; + let html = "\ + \ + \ +
ABD
B_contD1
"; + let f = parse(html); + let doc = model::to_doc(&f); + let craft_wordmodel::Block::Table(tb) = &*doc.body[0] else { panic!() }; + assert_eq!(tb.rows.len(), 2); + assert_eq!(tb.rows[0].cells.len(), 3); + assert_eq!(tb.rows[1].cells.len(), 3, "row 1 should have placeholder for A, B_cont, and D1"); + assert_eq!(tb.rows[1].cells[0].props.vmerge, VMerge::Continue); + assert_eq!(tb.rows[1].cells[1].props.vmerge, VMerge::Continue); + let craft_wordmodel::Block::Para(p1) = &*tb.rows[1].cells[1].blocks[0] else { panic!() }; + assert_eq!(p1.text, "B_cont"); + assert_eq!(tb.rows[1].cells[2].props.vmerge, VMerge::None); + let craft_wordmodel::Block::Para(p2) = &*tb.rows[1].cells[2].blocks[0] else { panic!() }; + assert_eq!(p2.text, "D1"); +} + #[test] fn cells_take_their_css_borders() { use craft_wordmodel::props::{Border, BorderStyle}; @@ -768,6 +957,240 @@ fn hostile_style_sheets_never_panic() { } } +#[test] +fn conflicting_mso_vmerge_declarations_last_wins() { + let html_restart_wins = "
A
"; + let f1 = parse(html_restart_wins); + let FBlock::Table(t1) = &f1.blocks[0] else { panic!() }; + assert!(t1.rows[0][0].vmerge_restart); + assert!(!t1.rows[0][0].covered); + + let html_continue_wins = "
B
"; + let f2 = parse(html_continue_wins); + let FBlock::Table(t2) = &f2.blocks[0] else { panic!() }; + assert!(!t2.rows[0][0].vmerge_restart); + assert!(t2.rows[0][0].covered); +} + +#[test] +fn export_flow_derives_rowspan_for_vmerge_continuations() { + let html = "\ + \ + \ +
TopB1
ContB2
"; + let f = parse(html); + let exported = export_flow(&f, "en"); + assert!(exported.contains(""), "covered continuation cell should not be emitted: {exported}"); + assert!(exported.contains(">B1"), "{exported}"); + assert!(exported.contains(">B2"), "{exported}"); +} + +#[test] +fn export_flow_preserves_orphan_covered_continuation_content() { + let html = "\ + \ + \ +
Orphan0B0
A1B1
"; + let f = parse(html); + let exported = export_flow(&f, "en"); + assert!(exported.contains("Orphan0"), "orphan continuation content in row 0 must be preserved: {exported}"); +} + +#[test] +fn html_roundtrip_preserves_colgroups_widths_and_vmerge() { + use craft_wordmodel::props::VMerge; + + let html = "\ + \ + \ + \ + \ +
MergeAB1
MergeA_contB2
"; + + let f1 = parse(html); + let FBlock::Table(t1) = &f1.blocks[0] else { panic!() }; + assert_eq!(t1.widths, [80.0, 120.0]); + assert_eq!(t1.rows.len(), 2); + assert_eq!(t1.rows[0].len(), 2); + assert_eq!(t1.rows[1].len(), 2); + assert!(!t1.rows[0][0].covered); + assert!(t1.rows[0][0].vmerge_restart); + assert!(t1.rows[1][0].covered); + + let doc1 = model::to_doc(&f1); + let craft_wordmodel::Block::Table(tb1) = &*doc1.body[0] else { panic!() }; + assert_eq!(tb1.rows[0].cells[0].props.vmerge, VMerge::Restart); + assert_eq!(tb1.rows[1].cells[0].props.vmerge, VMerge::Continue); + assert_eq!(tb1.vertical_extent(0, 0), Some((0, 2))); + + // Export to HTML via export() + let exported = export(&doc1); + assert!(exported.contains(""), "exported HTML must contain colgroup: {exported}"); + assert!(exported.contains("width:80.00pt"), "{exported}"); + assert!(exported.contains("width:120.00pt"), "{exported}"); + assert!(exported.contains("rowspan=\"2\""), "exported HTML must emit rowspan=\"2\": {exported}"); + + // Parse the exported HTML again + let f2 = parse(&exported); + let FBlock::Table(t2) = &f2.blocks[0] else { panic!() }; + assert_eq!(t2.widths, t1.widths, "column widths must match"); + assert_eq!(t2.rows.len(), t1.rows.len(), "row counts must match"); + assert_eq!(t2.rows[0].len(), t1.rows[0].len(), "row 0 cell count must match"); + assert_eq!(t2.rows[1].len(), t1.rows[1].len(), "row 1 cell count must match"); + assert_eq!(t2.rows[0][0].covered, t1.rows[0][0].covered, "row 0 cell 0 covered flag must match"); + assert_eq!(t2.rows[1][0].covered, t1.rows[1][0].covered, "row 1 cell 0 covered flag must match"); + + let doc2 = model::to_doc(&f2); + let craft_wordmodel::Block::Table(tb2) = &*doc2.body[0] else { panic!() }; + assert_eq!(tb2.rows[0].cells[0].props.vmerge, tb1.rows[0].cells[0].props.vmerge, "vmerge restart matches"); + assert_eq!(tb2.rows[1].cells[0].props.vmerge, tb1.rows[1].cells[0].props.vmerge, "vmerge continue matches"); + assert_eq!(tb2.vertical_extent(0, 0), tb1.vertical_extent(0, 0), "vertical merge extent matches"); +} + +fn assert_single_col_vmerge_table(tb: &craft_wordmodel::Table) { + use craft_wordmodel::props::VMerge; + assert_eq!(tb.rows.len(), 3, "table must have 3 rows"); + assert_eq!(tb.grid.len(), 1, "table must have 1 column"); + assert_eq!(tb.rows[0].cells.len(), 1); + assert_eq!(tb.rows[1].cells.len(), 1); + assert_eq!(tb.rows[2].cells.len(), 1); + assert_eq!(tb.rows[0].cells[0].props.vmerge, VMerge::Restart); + assert_eq!(tb.rows[1].cells[0].props.vmerge, VMerge::Continue); + assert_eq!(tb.rows[2].cells[0].props.vmerge, VMerge::None); + assert_eq!(tb.vertical_extent(0, 0), Some((0, 2))); + assert_eq!(tb.grid_col(2, 0), 0, "Bottom cell must be at grid column 0"); + let bottom_text = match &*tb.rows[2].cells[0].blocks[0] { + craft_wordmodel::Block::Para(p) => &p.text, + _ => panic!("expected paragraph in Bottom cell"), + }; + assert_eq!(bottom_text, "Bottom", "Bottom must be at row 2, cell 0"); +} + +#[test] +fn html_roundtrip_preserves_fully_covered_row_and_single_column_table() { + // A one-column table with a Word vertical merge across the first two rows, + // followed by an ordinary "Bottom" cell in row three. + let html = "\ + \ + \ + \ +
Top
Cont
Bottom
"; + + let f1 = parse(html); + let FBlock::Table(t1) = &f1.blocks[0] else { panic!() }; + assert_eq!(t1.rows.len(), 3, "initial import must have 3 rows"); + assert_eq!(t1.cols(), 1, "initial import must have 1 column"); + assert_eq!(t1.rows[0].len(), 1); + assert_eq!(t1.rows[1].len(), 1); + assert_eq!(t1.rows[2].len(), 1); + assert!(!t1.rows[0][0].covered); + assert!(t1.rows[0][0].vmerge_restart); + assert!(t1.rows[1][0].covered); + assert!(!t1.rows[2][0].covered); + + let doc1 = model::to_doc(&f1); + let craft_wordmodel::Block::Table(tb1) = &*doc1.body[0] else { panic!() }; + assert_single_col_vmerge_table(tb1); + + // Export to HTML via export() + let exported = export(&doc1); + assert!(exported.contains("rowspan=\"2\""), "exported HTML must emit rowspan=\"2\": {exported}"); + assert!(exported.contains(""), "covered row with no visible cells must emit empty tr: {exported}"); + assert!(exported.contains("Bottom"), "exported HTML must contain Bottom: {exported}"); + + // Parse the exported HTML again + let f2 = parse(&exported); + let FBlock::Table(t2) = &f2.blocks[0] else { panic!() }; + assert_eq!(t2.rows.len(), 3, "round-trip Flow must keep 3 rows"); + assert_eq!(t2.cols(), 1, "round-trip Flow must keep 1 column"); + assert_eq!(t2.rows[0].len(), 1, "row 0 has 1 cell"); + assert_eq!(t2.rows[1].len(), 1, "row 1 (fully covered row) has 1 cell"); + assert_eq!(t2.rows[2].len(), 1, "row 2 has 1 cell"); + assert!(!t2.rows[0][0].covered); + assert!(t2.rows[1][0].covered, "row 1 cell must be covered placeholder"); + assert!(!t2.rows[2][0].covered, "row 2 cell (Bottom) must not be covered"); + + // Convert round-tripped flow to document model + let doc2 = model::to_doc(&f2); + let craft_wordmodel::Block::Table(tb2) = &*doc2.body[0] else { panic!() }; + assert_single_col_vmerge_table(tb2); +} + +#[test] +fn vmerge_validation_requires_matching_spans() { + use craft_wordmodel::props::VMerge; + + // 1. Later-row check: row 0 has colspan=2, row 1 has continuation with colspan=1. + // Mismatched spans must clear continuation to None and NOT promote row 0 cell to Restart. + let ft_mismatched = FTable { + rows: vec![ + vec![Cell { colspan: 2, ..Cell::default() }], + vec![Cell { colspan: 1, covered: true, ..Cell::default() }, Cell { colspan: 1, ..Cell::default() }], + ], + widths: vec![50.0, 50.0], + ..Default::default() + }; + let doc = model::to_doc(&Flow { blocks: vec![FBlock::Table(ft_mismatched)], ..Default::default() }); + let craft_wordmodel::Block::Table(tb) = &*doc.body[0] else { panic!() }; + assert_eq!(tb.rows[0].cells[0].props.vmerge, VMerge::None, "mismatched span must not promote to Restart"); + assert_eq!(tb.rows[1].cells[0].props.vmerge, VMerge::None, "mismatched span must clear Continue to None"); + + // 2. First-row check: row 0 has continuation with colspan=2, row 1 has continuation with colspan=1. + // Mismatched spans must clear row 0 continuation to None, not promote to Restart. + let ft_row0_mismatched = FTable { + rows: vec![ + vec![Cell { colspan: 2, covered: true, ..Cell::default() }], + vec![Cell { colspan: 1, covered: true, ..Cell::default() }, Cell { colspan: 1, ..Cell::default() }], + ], + widths: vec![50.0, 50.0], + ..Default::default() + }; + let doc0 = model::to_doc(&Flow { blocks: vec![FBlock::Table(ft_row0_mismatched)], ..Default::default() }); + let craft_wordmodel::Block::Table(tb0) = &*doc0.body[0] else { panic!() }; + assert_eq!(tb0.rows[0].cells[0].props.vmerge, VMerge::None, "mismatched span in row 0 must clear to None"); + assert_eq!(tb0.rows[1].cells[0].props.vmerge, VMerge::None, "mismatched span in row 1 must clear to None"); + + // 3. Matching spans: row 0 has colspan=2, row 1 has continuation with colspan=2. + // Matching spans must promote row 0 to Restart and keep row 1 as Continue. + let ft_matching = FTable { + rows: vec![vec![Cell { colspan: 2, ..Cell::default() }], vec![Cell { colspan: 2, covered: true, ..Cell::default() }]], + widths: vec![50.0, 50.0], + ..Default::default() + }; + let doc_m = model::to_doc(&Flow { blocks: vec![FBlock::Table(ft_matching)], ..Default::default() }); + let craft_wordmodel::Block::Table(tb_m) = &*doc_m.body[0] else { panic!() }; + assert_eq!(tb_m.rows[0].cells[0].props.vmerge, VMerge::Restart); + assert_eq!(tb_m.rows[1].cells[0].props.vmerge, VMerge::Continue); +} + +#[test] +fn export_table_preserves_first_grid_column_alignment() { + let mut doc = craft_wordmodel::Document::default(); + let mut table = craft_wordmodel::Table::new(2, 3, 240.0); + table.grid = vec![40.0, 80.0, 120.0]; + table.rows[0].cells = vec![craft_wordmodel::Cell::with_text("A"), craft_wordmodel::Cell::with_text("B"), craft_wordmodel::Cell::with_text("C")]; + table.rows[1].props.grid_before = 1; + table.rows[1].cells = vec![craft_wordmodel::Cell::with_text("D"), craft_wordmodel::Cell::with_text("E")]; + doc.body = vec![std::sync::Arc::new(craft_wordmodel::Block::Table(table))]; + + // Flow representation should preserve the leading grid position + let flow = model::from_doc(&doc); + let FBlock::Table(ft) = &flow.blocks[0] else { panic!() }; + assert_eq!(ft.rows.len(), 2); + assert_eq!(ft.rows[0].len(), 3); + assert_eq!(ft.rows[1].len(), 3, "row 1 must have 3 cells (1 leading placeholder + 2 data cells)"); + assert_eq!(ft.widths, vec![40.0, 80.0, 120.0]); + + // HTML export should emit 3 colgroup cols and preserve cell alignment + let html = export(&doc); + assert!(html.contains(""), "must contain col 0 width: {html}"); + assert!(html.contains(""), "must contain col 1 width: {html}"); + assert!(html.contains(""), "must contain col 2 width: {html}"); + assert!(html.contains(">D"), "must contain cell D: {html}"); + assert!(html.contains(">E"), "must contain cell E: {html}"); +} + /// Ensure container elements (such as `div` and `p`) with background colors do not leak /// character shading onto their child text runs (#1786). #[test] diff --git a/crates/mcmat/README.md b/crates/mcmat/README.md index 074a0ac44..2f69e68c9 100644 --- a/crates/mcmat/README.md +++ b/crates/mcmat/README.md @@ -1,17 +1,10 @@ # craft-mcmat -A bounded reader and writer for portable MaterialCraft `.mcmat` ZIP packages. A package -contains `material.json`, named texture maps and a source package. Applications interpret -parameter values and cook or render maps themselves; this crate does not depend on an app's -model. It supports callers that read either version 1 or version 2 of the manifest, or both. +The MCMAT v3 portable material is a ZIP containing a version-only `material.json`, one +`source.sbs`, and the required source assets under `resources/`. The sole root-level +material graph in the SBS is the entry. Applications inspect its exposed controls and +cook its outputs through MaterialCraft. Texture maps and MaterialX documents are generated +by exporters. Earlier archives must be republished from their original projects. -`is_material` checks for a manifest with a bounded ZIP index; `Material::open` takes caller-provided version, entry-count, map-count, per-entry and total -expanded-byte limits. Each subsequent `read` and `read_source` shares that budget, including -repeated references to the same ZIP member. Duplicate member names are refused. The manifest -preserves unknown fields at the top level and on maps; parameter, input and preset objects are -kept as JSON values so their unknown fields survive too. `write` preserves the caller's source -entry name and map names, and rejects duplicate archive member names through `craft-zip`. - -The source package is opaque. Version 1 commonly names `source.mcraft`; MaterialCraft's version 2 -writer names `source.sbs`. Callers that invoke another application must preserve the source's -format and extension rather than infer it from `.mcmat` alone. +`Material::open` checks archive entries and expansion budgets before returning source +files. `write` compresses the XML and version marker and preserves source asset bytes. diff --git a/crates/mcmat/src/lib.rs b/crates/mcmat/src/lib.rs index 75b8709ef..ca3fa7641 100644 --- a/crates/mcmat/src/lib.rs +++ b/crates/mcmat/src/lib.rs @@ -1,133 +1,150 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] #![forbid(unsafe_code)] -//! Bounded interchange for MaterialCraft portable materials (`.mcmat`). -//! -//! The manifest and its version belong to the format, while interpreting parameter values, -//! cooking maps and opening the source package belong to the caller. Unknown fields survive -//! deserialization and serialization, including fields added by later versions. - -use std::collections::BTreeMap; +//! The clean-room MCMAT v3 source archive. Applications interpret the SBS entry graph. use craft_zip::{Archive, Compression, Writer}; -use serde::{Deserialize, Serialize}; -use serde_json::Value; +use serde::Deserializer; +use serde::de::{IgnoredAny, MapAccess, Visitor}; +use std::collections::{BTreeMap, BTreeSet}; -pub const FORMAT: &str = "craft-material"; +pub const VERSION: u32 = 3; pub const MANIFEST_ENTRY: &str = "material.json"; +pub const SOURCE_ENTRY: &str = "source.sbs"; +const MARKER: &[u8] = br#"{"version":3}"#; -/// A portable manifest; typed parameter values remain JSON so applications can adapt their own model. -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct Manifest { - pub format: String, - pub version: u32, - pub name: String, - pub graph: String, - pub size: [u32; 2], - pub maps: Vec, - #[serde(default)] - pub parameters: Vec, - #[serde(default)] - pub inputs: Vec, - #[serde(default)] - pub presets: Vec, - pub source: String, - #[serde(flatten)] - pub extra: BTreeMap, -} - -#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct MapEntry { - pub usage: String, - pub file: String, - #[serde(flatten)] - pub extra: BTreeMap, -} - -/// All limits are supplied by the consumer, including the versions it understands. #[derive(Clone, Copy, Debug)] pub struct Limits { - pub min_version: u32, - pub max_version: u32, pub max_entries: u64, - pub max_maps: usize, pub max_manifest_bytes: u64, pub max_entry_bytes: u64, pub max_total_bytes: u64, } +impl Default for Limits { + fn default() -> Self { + Self { max_entries: 100_000, max_manifest_bytes: 64 << 20, max_entry_bytes: 256 << 20, max_total_bytes: 1 << 30 } + } +} + #[derive(Debug, thiserror::Error)] pub enum Error { #[error("invalid portable material: {0}")] Invalid(String), - #[error("unsupported portable material version {0}")] + #[error("unsupported .mcmat version {0} (expected 3). Republish from the original authoring project")] Version(u32), - #[error("portable material limit: {0}")] - Limit(String), #[error("portable material archive: {0}")] Archive(#[from] craft_zip::Error), } -/// Whether a bounded ZIP index contains a material manifest. This does not validate the manifest. +/// File sniffing also recognizes old manifests so the reader can give republishing guidance. pub fn is_material(bytes: &[u8], max_entries: u64) -> bool { - Archive::open(bytes, craft_zip::Limits { max_entries, max_total_bytes: 0 }) - .is_ok_and(|archive| !archive.has_duplicate_names() && archive.contains(MANIFEST_ENTRY)) + Archive::open(bytes, craft_zip::Limits { max_entries, max_total_bytes: 0 }).is_ok_and(|archive| archive.contains(MANIFEST_ENTRY)) } -/// Manifest and original archive, retaining one shared expanded-byte budget across reads. -pub struct Material<'a> { - pub manifest: Manifest, - archive: Archive<'a>, - max_entry_bytes: u64, +fn valid_resource(name: &str) -> bool { + name.len() <= 4096 + && name.starts_with("resources/") + && !name.contains(['\\', ':']) + && !name.chars().any(char::is_control) + && name.split('/').all(|part| !matches!(part, "" | "." | "..")) } -impl<'a> Material<'a> { - pub fn open(bytes: &'a [u8], limits: Limits) -> Result { +#[derive(Debug)] +pub struct Material { + pub source: Vec, + /// Keys are paths relative to source.sbs, including the resources/ prefix. + pub resources: BTreeMap>, +} + +impl Material { + pub fn open(bytes: &[u8], limits: Limits) -> Result { let mut archive = Archive::open(bytes, craft_zip::Limits { max_entries: limits.max_entries, max_total_bytes: limits.max_total_bytes })?; - if archive.has_duplicate_names() { - return Err(Error::Invalid("duplicate archive entries".into())); + if archive.has_duplicate_names() || archive.has_overlapping_files()? { + return Err(Error::Invalid("duplicate or overlapping archive entries".into())); } - let json = archive.read(MANIFEST_ENTRY, limits.max_manifest_bytes)?.ok_or_else(|| Error::Invalid("material.json is missing".into()))?; - let manifest: Manifest = serde_json::from_slice(&json).map_err(|e| Error::Invalid(format!("material.json: {e}")))?; - if manifest.format != FORMAT { - return Err(Error::Invalid(format!("format `{}`", manifest.format))); + let json = archive.read(MANIFEST_ENTRY, limits.max_manifest_bytes)?.ok_or_else(|| Error::Invalid("missing material.json".into()))?; + struct Marker; + impl<'de> Visitor<'de> for Marker { + type Value = (u32, bool); + fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("a version object") + } + fn visit_map>(self, mut map: A) -> Result { + let mut version = None; + let mut extra = false; + while let Some(key) = map.next_key::()? { + if key == "version" { + if version.is_some() { + return Err(serde::de::Error::duplicate_field("version")); + } + version = Some(map.next_value::()?); + } else { + map.next_value::()?; + extra = true; + } + } + Ok((version.ok_or_else(|| serde::de::Error::missing_field("version"))?, extra)) + } } - if !(limits.min_version..=limits.max_version).contains(&manifest.version) { - return Err(Error::Version(manifest.version)); + let mut deserializer = serde_json::Deserializer::from_slice(&json); + let (version, extra) = deserializer.deserialize_map(Marker).map_err(|err| Error::Invalid(format!("material.json: {err}")))?; + deserializer.end().map_err(|err| Error::Invalid(format!("material.json: {err}")))?; + if version != VERSION { + return Err(Error::Version(version)); } - if manifest.maps.len() > limits.max_maps { - return Err(Error::Limit(format!("{} maps exceeds {}", manifest.maps.len(), limits.max_maps))); + if extra { + return Err(Error::Invalid("material.json must contain only the version".into())); } - Ok(Self { manifest, archive, max_entry_bytes: limits.max_entry_bytes }) - } - - /// Read one named member, charging it to the same budget as previous reads. - pub fn read(&mut self, name: &str) -> Result, Error> { - self.archive.read(name, self.max_entry_bytes)?.ok_or_else(|| Error::Invalid(format!("{name} is missing"))) - } - - pub fn read_source(&mut self) -> Result, Error> { - self.read(&self.manifest.source.clone()) + let source = archive.read(SOURCE_ENTRY, limits.max_entry_bytes)?.ok_or_else(|| Error::Invalid("missing source.sbs".into()))?; + let mut resources = BTreeMap::new(); + let mut seen = BTreeSet::new(); + for index in 0..archive.len() { + let name = archive.entry_name(index)?.ok_or_else(|| Error::Invalid("invalid entry name".into()))?; + if name == SOURCE_ENTRY || name == MANIFEST_ENTRY { + continue; + } + if name.strip_suffix('/').is_some_and(|dir| dir == "resources" || valid_resource(dir)) { + if archive.entry_sizes(index)? != Some((0, 0)) { + return Err(Error::Invalid("directory entries must have no payload".into())); + } + continue; + } + if !valid_resource(&name) || !seen.insert(name.to_ascii_lowercase()) { + return Err(Error::Invalid(format!("invalid or ambiguous resource path `{name}`"))); + } + let data = archive.read_index(index, limits.max_entry_bytes)?.ok_or_else(|| Error::Invalid(format!("missing `{name}`")))?; + resources.insert(name, data); + } + Ok(Self { source, resources }) } } -/// Write a manifest, its named maps, and the source. Duplicate member names are rejected. -pub fn write(manifest: &Manifest, maps: &[(String, Vec)], source: &[u8]) -> Result, Error> { - // Flattened fields must not serialize a second copy of a known key. - const KNOWN: &[&str] = &["format", "version", "name", "graph", "size", "maps", "parameters", "inputs", "presets", "source"]; - if manifest.extra.keys().any(|key| KNOWN.contains(&key.as_str())) - || manifest.maps.iter().any(|map| map.extra.contains_key("usage") || map.extra.contains_key("file")) - { - return Err(Error::Invalid("an extra field duplicates a known field".into())); - } - let json = serde_json::to_vec_pretty(manifest).map_err(|e| Error::Invalid(format!("material.json: {e}")))?; +/// Write one SBS document with its referenced source assets. +pub fn write<'a>(source: &[u8], resources: impl IntoIterator) -> Result, Error> { + let limits = Limits::default(); let mut writer = Writer::new(); - writer.add(MANIFEST_ENTRY, &json, Compression::Deflated)?; - for (name, bytes) in maps { - writer.add(name, bytes, Compression::Stored)?; + let mut seen = BTreeSet::new(); + let mut total = (source.len() as u64).saturating_add(MARKER.len() as u64); + if source.len() as u64 > limits.max_entry_bytes { + return Err(Error::Invalid("source.sbs exceeds the entry limit".into())); + } + writer.add(MANIFEST_ENTRY, MARKER, Compression::Deflated)?; + writer.add(SOURCE_ENTRY, source, Compression::Deflated)?; + for (name, bytes) in resources { + if !valid_resource(name) || !seen.insert(name.to_ascii_lowercase()) { + return Err(Error::Invalid(format!("invalid or ambiguous resource path `{name}`"))); + } + total = total.saturating_add(bytes.len() as u64); + if bytes.len() as u64 > limits.max_entry_bytes || total > limits.max_total_bytes || seen.len() as u64 + 2 > limits.max_entries { + return Err(Error::Invalid(format!("archive limits exceeded at `{name}`"))); + } + let extension = name.rsplit_once('.').map(|(_, ext)| ext.to_ascii_lowercase()); + let compression = match extension.as_deref() { + Some("png" | "jpg" | "jpeg" | "webp" | "gif" | "exr" | "woff" | "woff2") => Compression::Stored, + _ => Compression::Deflated, + }; + writer.add(name, bytes, compression)?; } - writer.add(&manifest.source, source, Compression::Stored)?; Ok(writer.finish()?) } @@ -135,82 +152,108 @@ pub fn write(manifest: &Manifest, maps: &[(String, Vec)], source: &[u8]) -> mod tests { use super::*; - fn limits() -> Limits { - Limits { - min_version: 1, - max_version: 2, - max_entries: 100, - max_maps: 4, - max_manifest_bytes: 4096, - max_entry_bytes: 100, - max_total_bytes: 8192, - } - } - - fn sample(version: u32) -> Manifest { - serde_json::from_value(serde_json::json!({ - "format": "craft-material", "version": version, "name": "Stone", "graph": "Stone", "size": [64, 64], - "maps": [{"usage": "baseColor", "file": "maps/base.png", "colorSpace": "srgb", "futureMap": true}], - "parameters": [{"id": "rough", "value": {"t": "float", "v": 0.25}, "futureParam": 42}], - "inputs": [{"identifier": "curvature", "kind": "gray"}], "presets": [], - "source": if version == 1 { "source.mcraft" } else { "source.sbs" }, "futureField": {"keep": true} - })) - .unwrap() - } - #[test] - fn both_protocol_versions_keep_unknown_fields_and_payloads() { - for version in [1, 2] { - let manifest = sample(version); - let bytes = write(&manifest, &[("maps/base.png".into(), vec![1, 2, 3])], b"source").unwrap(); - assert!(is_material(&bytes, 100)); - assert!(!is_material(&bytes, 1)); - let mut material = Material::open(&bytes, limits()).unwrap(); - assert_eq!(material.manifest, manifest); - assert_eq!(material.read("maps/base.png").unwrap(), [1, 2, 3]); - assert_eq!(material.read_source().unwrap(), b"source"); - let json = serde_json::to_value(&material.manifest).unwrap(); - assert_eq!(json["futureField"]["keep"], true); - assert_eq!(json["maps"][0]["futureMap"], true); - assert_eq!(json["parameters"][0]["futureParam"], 42); + fn procedural_source_and_assets_round_trip_under_one_budget() { + let bytes = write(b"", [("resources/oak.png", b"image".as_slice())]).unwrap(); + let pkg = Material::open(&bytes, Limits::default()).unwrap(); + assert_eq!(pkg.source, b""); + assert_eq!(pkg.resources["resources/oak.png"], b"image"); + let mut archive = Archive::open(&bytes, craft_zip::Limits { max_entries: 3, max_total_bytes: 128 }).unwrap(); + assert_eq!(archive.read(MANIFEST_ENTRY, 32).unwrap().unwrap(), MARKER); + assert_eq!(archive.is_stored(SOURCE_ENTRY), Some(false)); + assert_eq!(archive.is_stored("resources/oak.png"), Some(true)); + for limits in [ + Limits { max_entries: 2, ..Default::default() }, + Limits { max_entry_bytes: 2, ..Default::default() }, + Limits { max_total_bytes: 24, ..Default::default() }, + ] { + assert!(Material::open(&bytes, limits).is_err()); } } #[test] - fn limits_apply_to_the_manifest_maps_and_aggregate_reads() { - let manifest = sample(2); - let bytes = write(&manifest, &[("maps/base.png".into(), vec![1; 8])], &[2; 8]).unwrap(); - let mut unsupported = limits(); - unsupported.max_version = 1; - assert!(matches!(Material::open(&bytes, unsupported), Err(Error::Version(2)))); - let mut no_maps = limits(); - no_maps.max_maps = 0; - assert!(matches!(Material::open(&bytes, no_maps), Err(Error::Limit(_)))); - let mut tiny_entry = limits(); - tiny_entry.max_entry_bytes = 7; - assert!(Material::open(&bytes, tiny_entry).unwrap().read("maps/base.png").is_err()); - let json_len = serde_json::to_vec_pretty(&manifest).unwrap().len() as u64; - let mut aggregate = limits(); - aggregate.max_total_bytes = json_len + 15; - let mut material = Material::open(&bytes, aggregate).unwrap(); - assert_eq!(material.read("maps/base.png").unwrap().len(), 8); - assert!(material.read_source().is_err()); + fn marker_requires_an_object_and_complete_input() { + for marker in [b"[3]".as_slice(), b"[2]", b"null", b"3", br#"{"version":3} {}"#, br#"{"version":3,"version":3}"#] { + let mut zip = Writer::new(); + zip.add(MANIFEST_ENTRY, marker, Compression::Stored).unwrap(); + zip.add(SOURCE_ENTRY, b"source", Compression::Stored).unwrap(); + assert!(matches!(Material::open(&zip.finish().unwrap(), Limits::default()), Err(Error::Invalid(_)))); + } } #[test] - fn refuses_extra_fields_that_duplicate_known_keys() { - let mut manifest = sample(2); - manifest.extra.insert("version".into(), 3.into()); - assert!(write(&manifest, &[], b"source").is_err()); - manifest.extra.remove("version"); - manifest.maps[0].extra.insert("file".into(), "other".into()); - assert!(write(&manifest, &[], b"source").is_err()); + fn directory_members_must_be_empty() { + for payload in [b"".as_slice(), b"hidden"] { + let mut zip = Writer::new(); + zip.add(MANIFEST_ENTRY, MARKER, Compression::Stored).unwrap(); + zip.add(SOURCE_ENTRY, b"source", Compression::Stored).unwrap(); + zip.add("resources/", payload, Compression::Stored).unwrap(); + assert_eq!(Material::open(&zip.finish().unwrap(), Limits::default()).is_ok(), payload.is_empty()); + } } #[test] - fn refuses_duplicate_names_on_write() { - let manifest = sample(2); - let duplicate = [("maps/base.png".to_string(), vec![1]), ("maps/base.png".to_string(), vec![2])]; - assert!(write(&manifest, &duplicate, b"source").is_err()); + fn legacy_encoded_resource_names_read_by_index_under_one_budget() { + let mut zip = Writer::new(); + zip.add(MANIFEST_ENTRY, MARKER, Compression::Stored).unwrap(); + zip.add(SOURCE_ENTRY, b"s", Compression::Stored).unwrap(); + zip.add("resources/a.bin", b"data", Compression::Stored).unwrap(); + let mut bytes = zip.finish().unwrap(); + // Same-length CP437 name in both headers: no UTF-8 flag, 0x82 decodes to é. + let offsets: Vec<_> = + bytes.windows(b"resources/a.bin".len()).enumerate().filter_map(|(i, n)| (n == b"resources/a.bin").then_some(i + 10)).collect(); + assert_eq!(offsets.len(), 2); + for offset in offsets { + bytes[offset] = 0x82; + } + let total = MARKER.len() as u64 + 1 + 4; + let limits = Limits { max_total_bytes: total, ..Default::default() }; + let material = Material::open(&bytes, limits).unwrap(); + assert_eq!(material.resources["resources/é.bin"], b"data"); + assert!(Material::open(&bytes, Limits { max_total_bytes: total - 1, ..limits }).is_err()); + } + + #[test] + fn compresses_unencoded_source_assets() { + let bytes = write(b"", [("resources/shape.svg", b"".as_slice()), ("resources/font.ttf", b"font".as_slice())]).unwrap(); + let mut archive = Archive::open(&bytes, craft_zip::Limits { max_entries: 4, max_total_bytes: 128 }).unwrap(); + assert_eq!(archive.is_stored("resources/shape.svg"), Some(false)); + assert_eq!(archive.is_stored("resources/font.ttf"), Some(false)); + } + + #[test] + fn rejects_previous_versions_before_requiring_the_v3_layout() { + for version in [0, 1, 2, 4] { + let mut zip = Writer::new(); + zip.add(MANIFEST_ENTRY, format!(r#"{{"format":"craft-material","version":{version}}}"#).as_bytes(), Compression::Deflated).unwrap(); + let bytes = zip.finish().unwrap(); + assert!(is_material(&bytes, 2)); + assert!(matches!(Material::open(&bytes, Limits::default()), Err(Error::Version(v)) if v == version)); + } + } + + #[test] + fn v3_requires_source_and_a_version_only_marker() { + for (marker, source) in [(MARKER, None), (br#"{"version":3,"graph":"Other"}"#.as_slice(), Some(b"".as_slice()))] { + let mut zip = Writer::new(); + zip.add(MANIFEST_ENTRY, marker, Compression::Deflated).unwrap(); + if let Some(source) = source { + zip.add(SOURCE_ENTRY, source, Compression::Deflated).unwrap(); + } + assert!(Material::open(&zip.finish().unwrap(), Limits::default()).is_err()); + } + } + + #[test] + fn rejects_ambiguous_or_nonlocal_resource_members() { + for name in ["resources/../../x", "resources/a\\x", "/x", "maps/color.png", "resources/C:/x", "preview.png"] { + assert!(write(b"x", [(name, &b"x"[..])]).is_err()); + let mut zip = Writer::new(); + zip.add(MANIFEST_ENTRY, MARKER, Compression::Stored).unwrap(); + zip.add(SOURCE_ENTRY, b"x", Compression::Deflated).unwrap(); + zip.add(name, b"x", Compression::Stored).unwrap(); + assert!(Material::open(&zip.finish().unwrap(), Limits::default()).is_err()); + } + assert!(write(b"x", [("resources/A", &b"a"[..]), ("resources/a", &b"b"[..])]).is_err()); } } diff --git a/crates/mesh/src/gltf.rs b/crates/mesh/src/gltf.rs index c92051b84..d074f1ed1 100644 --- a/crates/mesh/src/gltf.rs +++ b/crates/mesh/src/gltf.rs @@ -120,6 +120,16 @@ pub fn uri_decode(s: &str) -> String { String::from_utf8_lossy(&percent_decode(s)).into_owned() } +/// Percent-decode a URI, rejecting decoded bytes that are not UTF-8. +/// +/// As with [`uri_decode`], incomplete or non-hex escapes stay literal and `+` stays +/// `+`. This does not validate or confine a filesystem path; callers must retain +/// their own reference policy. Decoding is linear and output is no larger than input. +/// Use this instead of the lossy decoder when a resolver requires exact UTF-8 names. +pub fn uri_decode_strict(s: &str) -> Option { + String::from_utf8(percent_decode(s)).ok() +} + /// [`uri_decode`] as bytes, so escaped bytes that are not UTF-8 survive. fn percent_decode(s: &str) -> Vec { let b = s.as_bytes(); diff --git a/crates/mesh/src/tests/gltf.rs b/crates/mesh/src/tests/gltf.rs index 8892fe241..c47b911df 100644 --- a/crates/mesh/src/tests/gltf.rs +++ b/crates/mesh/src/tests/gltf.rs @@ -950,3 +950,32 @@ fn morph_targets_and_other_scenes_are_named_in_warnings() { let s = parse(&one_mesh(&b, plain.clone())).unwrap(); assert!(s.warnings.is_empty(), "{:?}", s.warnings); } + +#[test] +fn strict_uri_decoding_preserves_exact_names_and_rejects_invalid_utf8() { + use crate::gltf::uri_decode_strict; + for (input, expected) in [ + ("", Some("")), + ("a+b", Some("a+b")), + ("a%20b", Some("a b")), + ("é/%E2%82%AC", Some("é/€")), + ("%", Some("%")), + ("%2", Some("%2")), + ("%GG", Some("%GG")), + ("%252e%252e", Some("%2e%2e")), + ("%2e%2e%2fmesh.bin", Some("../mesh.bin")), + ("%00", Some("\0")), + ("%FF", None), + ("%C0%AF", None), + ("%ED%A0%80", None), + ("%E2%82", None), + ] { + assert_eq!(uri_decode_strict(input).as_deref(), expected, "{input}"); + } + // Keep the existing API's replacement-character behavior unchanged. + assert_eq!(uri_decode("%FF"), "�"); + let input = "%41%GG+é".repeat(100_000); + let decoded = uri_decode_strict(&input).unwrap(); + assert_eq!(decoded, "A%GG+é".repeat(100_000)); + assert!(decoded.len() <= input.len()); +} diff --git a/crates/pkcs7/src/revocation.rs b/crates/pkcs7/src/revocation.rs index 0aa9be9c6..dfb398cae 100644 --- a/crates/pkcs7/src/revocation.rs +++ b/crates/pkcs7/src/revocation.rs @@ -63,6 +63,27 @@ pub struct CertificateList { pub revoked: Vec<(Vec, Time)>, } +/// Owned parsed components for adapters. This is not a signature or trust verdict. +/// Consuming conversion moves buffers without reparsing or cloning signed material. +pub struct CertificateListParts { + pub tbs: Vec, + pub sig_alg: Vec, + pub signature: Vec, + pub issuer_raw: Vec, + pub this_update: Time, + pub next_update: Option