mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-25 12:03:42 +01:00
Merge remote-tracking branch 'storytold/main' into feat/dex-reader
This commit is contained in:
97 files changed
+12423
-368
No files matched your search
@@ -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
|
||||
@@ -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
|
||||
@@ -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: |
|
||||
|
||||
Generated
+149
-2
@@ -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"
|
||||
|
||||
@@ -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" }
|
||||
|
||||
@@ -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 `<id>-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"]
|
||||
@@ -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<String>) -> Self {
|
||||
Self { version: CONNECTION_VERSION, pid: std::process::id(), port, token_file, app: app.into() }
|
||||
}
|
||||
|
||||
/// `127.0.0.1:<port>`.
|
||||
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<Option<Connection>> {
|
||||
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::<Connection>(&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()
|
||||
}
|
||||
@@ -0,0 +1,601 @@
|
||||
//! The other end of the link: where an app's `<id>-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<dyn Fn() -> Result<(), String> + Send + Sync>;
|
||||
/// What the person allows now, read from the app's settings folder before every call.
|
||||
pub type ConsentFn = Box<dyn Fn(&Path) -> Consent + Send + Sync>;
|
||||
/// Makes the app's client for its open window.
|
||||
pub type ConnectFn<W> = Box<dyn Fn(&Window) -> Result<W, String> + Send + Sync>;
|
||||
/// Makes the app's headless session with these folders.
|
||||
pub type HeadlessFn<H> = Box<dyn Fn(&HeadlessFolders) -> Result<H, String> + 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:<port>`.
|
||||
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("<id>"), 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<PathBuf>,
|
||||
/// The folder files may be saved to.
|
||||
pub write: Option<PathBuf>,
|
||||
}
|
||||
|
||||
/// Where a tool call goes: the app's window client or its headless session.
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum Route<W, H> {
|
||||
/// The open window.
|
||||
Window(W),
|
||||
/// A session without a window.
|
||||
Headless(H),
|
||||
}
|
||||
|
||||
/// What [`Live`] needs from the app.
|
||||
#[non_exhaustive]
|
||||
pub struct LiveConfig<W, H> {
|
||||
/// 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<WhenAppClosed>,
|
||||
/// 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<PathBuf>,
|
||||
/// 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<PathBuf>,
|
||||
/// Starts the app; `None` when this install can't ([`launcher`] found nothing to start).
|
||||
pub launch: Option<LaunchFn>,
|
||||
/// 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<W>,
|
||||
headless: HeadlessFn<H>,
|
||||
}
|
||||
|
||||
impl<W, H> LiveConfig<W, H> {
|
||||
/// 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<String>,
|
||||
config_dir: PathBuf,
|
||||
consent: impl Fn(&Path) -> Consent + Send + Sync + 'static,
|
||||
connect: impl Fn(&Window) -> Result<W, String> + Send + Sync + 'static,
|
||||
headless: impl Fn(&HeadlessFolders) -> Result<H, String> + 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<W, H> {
|
||||
route: Route<W, H>,
|
||||
/// For a window, the key its client was made for.
|
||||
key: Option<WindowKey>,
|
||||
/// 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<W, H> {
|
||||
cfg: LiveConfig<W, H>,
|
||||
/// Serialises lookups, so concurrent calls start the app once; holds the last start's error.
|
||||
lookup: Mutex<Option<String>>,
|
||||
/// How many starts have finished, read before a call queues for `lookup`.
|
||||
finished: AtomicU64,
|
||||
current: Mutex<Option<Current<W, H>>>,
|
||||
}
|
||||
|
||||
impl<W: Clone, H: Clone> Live<W, H> {
|
||||
/// A session that has not resolved anything yet.
|
||||
pub fn new(cfg: LiveConfig<W, H>) -> 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<Route<W, H>> {
|
||||
self.current.lock().unwrap_or_else(PoisonError::into_inner).as_ref().map(|c| c.route.clone())
|
||||
}
|
||||
|
||||
fn set(&self, route: Route<W, H>, key: Option<WindowKey>, app_folders: bool) -> Route<W, H> {
|
||||
*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<Route<W, H>> {
|
||||
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<Route<W, H>, 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<Route<W, H>, 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<Route<W, H>, 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<Route<W, H>, 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<Option<Window>, 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<Option<Window>, String> {
|
||||
let Some(c): Option<Connection> = 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<String, String> {
|
||||
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<LaunchFn> {
|
||||
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<OsString>,
|
||||
/// That image's mount point (`APPDIR`).
|
||||
appdir: Option<OsString>,
|
||||
/// `%SystemRoot%` (Windows).
|
||||
system_root: Option<OsString>,
|
||||
}
|
||||
|
||||
/// 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<OsString>)> {
|
||||
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<OsString>) {
|
||||
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<OsString>)> {
|
||||
// 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");
|
||||
}
|
||||
}
|
||||
@@ -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 `<id>-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 `<id>-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};
|
||||
@@ -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 `<id>-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<PathBuf> {
|
||||
folder(&self.read_root)
|
||||
}
|
||||
|
||||
/// [`Self::write_root`] as a path ([`folder`]).
|
||||
pub fn write_folder(&self) -> Option<PathBuf> {
|
||||
folder(&self.write_root)
|
||||
}
|
||||
}
|
||||
|
||||
/// A folder setting as a path, trimmed; empty or blank is `None`.
|
||||
pub fn folder(pref: &str) -> Option<PathBuf> {
|
||||
let pref = pref.trim();
|
||||
(!pref.is_empty()).then(|| PathBuf::from(pref))
|
||||
}
|
||||
|
||||
/// What an app's `<id>-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> {
|
||||
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));
|
||||
}
|
||||
}
|
||||
@@ -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<AtomicBool>,
|
||||
}
|
||||
|
||||
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<AtomicBool> = 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)
|
||||
}
|
||||
}
|
||||
@@ -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"))]
|
||||
|
||||
@@ -0,0 +1,572 @@
|
||||
//! AI agents in the open window: the launcher's switch, the connection file, and where an app's
|
||||
//! `<id>-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<Window, HeadlessFolders>;
|
||||
|
||||
fn config(dir: &Path, consent: Consent, made: &Arc<Made>) -> LiveConfig<Window, HeadlessFolders> {
|
||||
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<Route<Window, HeadlessFolders>, 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<Route<Window, HeadlessFolders>, 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<PathBuf> {
|
||||
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<Window, HeadlessFolders> = 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<Window, HeadlessFolders> = 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<Mutex<Option<TcpListener>>> = 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<u16> = 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<Window, HeadlessFolders> = 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());
|
||||
}
|
||||
@@ -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 |
|
||||
|
||||
+109
-13
@@ -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::<usize>(), 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<u8> {
|
||||
let candidates = candidates
|
||||
.map(|(delimiter, counts, coherent)| (delimiter, counts.iter().copied().min().unwrap_or(0), counts.iter().sum::<usize>(), 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<usize>,
|
||||
/// 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<usize>,
|
||||
/// Whether every counted record had coherent quoted fields.
|
||||
coherent: bool,
|
||||
reached_record_limit: bool,
|
||||
@@ -117,10 +142,21 @@ struct DelimiterScan {
|
||||
open_quote: Option<usize>,
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
@@ -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<R: Read + Seek>(reader: R) -> Option<Vec<u8>> {
|
||||
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 {
|
||||
|
||||
@@ -167,3 +167,37 @@ fn bytes_supplied_for_a_linked_asset_are_not_written() -> Result<(), Box<dyn std
|
||||
assert_eq!(load::<Value>(&bytes)?.assets, [("8".to_owned(), b"kept".to_vec())]);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preview_uses_the_strict_signature_path_without_losing_cursor_independence() -> Result<(), Box<dyn std::error::Error>> {
|
||||
struct Counted {
|
||||
cursor: std::io::Cursor<Vec<u8>>,
|
||||
bytes_read: usize,
|
||||
}
|
||||
impl std::io::Read for Counted {
|
||||
fn read(&mut self, out: &mut [u8]) -> std::io::Result<usize> {
|
||||
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<u64> {
|
||||
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(())
|
||||
}
|
||||
@@ -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 }
|
||||
|
||||
@@ -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<u8> {
|
||||
/// The `OfficeArtBlip*` record and its format-defined identifier.
|
||||
fn record(&self, w_emu: i32, h_emu: i32) -> (Vec<u8>, [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);
|
||||
}
|
||||
}
|
||||
@@ -315,7 +315,8 @@ pub fn read_preview(bytes: &[u8], preview_entry: &str) -> Option<Vec<u8>> {
|
||||
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<R: Read + Seek>(reader: R, preview_entry: &str) -> Option<Vec<u8>> {
|
||||
const PREVIEW_LIMIT: u64 = 4 << 20;
|
||||
let mut zip = zip::ZipArchive::new(reader).ok()?;
|
||||
@@ -328,6 +329,22 @@ pub fn read_preview_from<R: Read + Seek>(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<R: Read + Seek>(mut reader: R, preview_entry: &str) -> Option<Vec<u8>> {
|
||||
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<Package, Error> {
|
||||
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<R> {
|
||||
inner: R,
|
||||
read: usize,
|
||||
}
|
||||
|
||||
impl<R: Read> Read for Counting<R> {
|
||||
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
|
||||
let n = self.inner.read(buf)?;
|
||||
self.read += n;
|
||||
Ok(n)
|
||||
}
|
||||
}
|
||||
|
||||
impl<R: Seek> Seek for Counting<R> {
|
||||
fn seek(&mut self, pos: std::io::SeekFrom) -> std::io::Result<u64> {
|
||||
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();
|
||||
|
||||
@@ -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)]
|
||||
|
||||
+131
-4
@@ -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<usize>,
|
||||
/// 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, DocxError> {
|
||||
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<Package, DocxError> {
|
||||
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<String, Vec<u8>>) -> 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<Option<El>, 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<Option<El>, 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#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/><Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering" Target="numbering.xml"/></Relationships>"#;
|
||||
let document = format!(r#"<w:document {ns}><w:body/></w:document>"#);
|
||||
let dense = |root: &str| format!(r#"<{root} {ns}>{}</{root}>"#, "<a/>".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#"<w:document {ns}>{}</w:document>"#, "<a/>".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#"<w:document {ns}>{}</w:document>"#, "<a/>".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#"<w:styles {ns}>{}</w:styles>"#, "<a/>".repeat(60));
|
||||
let settings = format!(r#"<w:settings {ns}>{}</w:settings>"#, "<a/>".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)]
|
||||
|
||||
@@ -154,9 +154,11 @@ pub(crate) fn read_opened(pkg: &Package, chunks: Option<ChunkImporter>) -> 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.
|
||||
|
||||
@@ -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<ChunkImporter<'a>>) -> 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#"<w:altChunk r:id="rIdC"/>"#, ("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<u8> {
|
||||
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#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">{inner}</Relationships>"#);
|
||||
let rel = |(id, ty, target): &(&str, &str, &str)| {
|
||||
format!(r#"<Relationship Id="{id}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/{ty}" Target="{target}"/>"#)
|
||||
};
|
||||
let names: String = rels.iter().map(rel).collect::<Vec<_>>().join("");
|
||||
let mut files: Vec<(&str, Vec<u8>)> = vec![
|
||||
("_rels/.rels", rels_xml(&rel(&("rId1", "officeDocument", "word/document.xml"))).into_bytes()),
|
||||
("word/document.xml", format!(r#"<w:document {ns}><w:body>{body}</w:body></w:document>"#).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#"<w:p><w:r><w:t>innermost</w:t></w:r></w:p>"#, ("rIdZ", "chart", "charts/z.xml"), ("word/charts/z.xml", b"<a/>"));
|
||||
let inner = package(
|
||||
r#"<w:p><w:r><w:t>inner</w:t></w:r></w:p><w:altChunk r:id="rIdD"/>"#,
|
||||
("rIdD", "aFChunk", "afchunk.docx"),
|
||||
("word/afchunk.docx", &innermost),
|
||||
);
|
||||
let outer = package(r#"<w:altChunk r:id="rIdC"/>"#, ("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#"<w:p><w:r><w:t>inner</w:t></w:r></w:p>"#, ("rIdZ", "chart", "charts/z.xml"), ("word/charts/z.xml", b"<a/>"));
|
||||
let body = r#"<w:p><w:r><w:t>after</w:t></w:r></w:p>"#;
|
||||
let with = package(&format!(r#"<w:altChunk r:id="rIdC"/>{body}"#), ("rIdC", "aFChunk", "afchunk.docx"), ("word/afchunk.docx", &nested));
|
||||
let without = package(body, ("rIdZ", "chart", "charts/z.xml"), ("word/charts/z.xml", b"<a/>"));
|
||||
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#"<w:p><w:r><w:t>leaf</w:t></w:r></w:p>"#, ("rIdZ", "chart", "charts/z.xml"), ("word/charts/z.xml", b"<a/>"));
|
||||
let inner = package(
|
||||
r#"<w:p><w:r><w:t>mid</w:t></w:r></w:p><w:altChunk r:id="rIdD"/>"#,
|
||||
("rIdD", "aFChunk", "afchunk.docx"),
|
||||
("word/afchunk.docx", &innermost),
|
||||
);
|
||||
let outer = package(r#"<w:altChunk r:id="rIdC"/>"#, ("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#"<w:altChunk r:id="rIdC"/>"#, ("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#"<w:hdr xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:p><w:r><w:t>head</w:t></w:r></w:p><w:p><w:r><w:t>head</w:t></w:r></w:p><w:p><w:r><w:t>head</w:t></w:r></w:p></w:hdr>"#;
|
||||
let gc = package(r#"<w:p><w:r><w:t>gc</w:t></w:r></w:p>"#, ("rIdZ", "chart", "charts/z.xml"), ("word/charts/z.xml", b"<a/>"));
|
||||
let sibling =
|
||||
package(&r#"<w:p><w:r><w:t>sibling</w:t></w:r></w:p>"#.repeat(8), ("rIdZ", "chart", "charts/z.xml"), ("word/charts/z.xml", b"<a/>"));
|
||||
let inner = package_parts(
|
||||
r#"<w:p><w:r><w:t>mid</w:t></w:r></w:p><w:altChunk r:id="rIdD"/><w:p><w:pPr><w:sectPr><w:headerReference r:id="rIdH"/></w:sectPr></w:pPr></w:p><w:altChunk r:id="rIdS"/>"#,
|
||||
&[("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#"<w:altChunk r:id="rIdC"/>"#, ("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!("<notword>{}</notword>", "<a/>".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#"<w:p><w:r><w:t>sibling</w:t></w:r></w:p>"#, &[], &[]);
|
||||
let outer = package_parts(
|
||||
r#"<w:altChunk r:id="bad"/><w:altChunk r:id="good"/>"#,
|
||||
&[("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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
+47
-18
@@ -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<El, DocxError> {
|
||||
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<El, DocxError> {
|
||||
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<El, DocxError> {
|
||||
parse_with(bytes, &[], true)
|
||||
}
|
||||
|
||||
fn parse_with(bytes: &[u8], extra: &[(&'static str, &str)], strict: bool) -> Result<El, DocxError> {
|
||||
/// 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"<w:t>before &unknown; after</w:t>"[..], b"<a></a><b></b>", b"<a></a><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"<a>x & y</a>
|
||||
"
|
||||
",
|
||||
MAX_ELEMENTS
|
||||
)
|
||||
.is_ok()
|
||||
);
|
||||
|
||||
@@ -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 = "<a/>".repeat(2_000_000);
|
||||
let chart_xml = format!(r#"<c:chart {W_NS}>{chunk}</c:chart>"#);
|
||||
let mut document = format!(
|
||||
r#"<w:document {W_NS} xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:c="http://schemas.openxmlformats.org/drawingml/2006/chart"><w:body>"#
|
||||
);
|
||||
for i in 0..parts {
|
||||
document.push_str(&format!(
|
||||
r#"<w:p><w:r><w:drawing><wp:inline><wp:extent cx="635000" cy="635000"/><a:graphic><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/chart"><c:chart r:id="rId{i}"/></a:graphicData></a:graphic></wp:inline></w:drawing></w:r></w:p>"#
|
||||
));
|
||||
}
|
||||
document.push_str("</w:body></w:document>");
|
||||
let mut rels = String::from(r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">"#);
|
||||
for i in 0..parts {
|
||||
rels.push_str(&format!(
|
||||
r#"<Relationship Id="rId{i}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart" Target="charts/chart{i}.xml"/>"#
|
||||
));
|
||||
}
|
||||
rels.push_str("</Relationships>");
|
||||
let mut entries: Vec<(&str, Vec<u8>)> = 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");
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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 }
|
||||
@@ -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<String>) -> Error {
|
||||
Error::Malformed { what, detail: detail.into() }
|
||||
}
|
||||
|
||||
pub fn invalid(what: &'static str, detail: impl Into<String>) -> 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<T> = std::result::Result<T, Error>;
|
||||
@@ -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<Envelope>;
|
||||
|
||||
/// Send invitations and move the envelope to [`EnvelopeStatus::Sent`].
|
||||
fn send(&self, envelope: &str) -> Result<Envelope>;
|
||||
|
||||
/// Current status, including per-recipient progress.
|
||||
fn status(&self, envelope: &str) -> Result<Envelope>;
|
||||
|
||||
/// 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<CompletedDocument>;
|
||||
|
||||
/// 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<String> {
|
||||
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<Vec<EnvelopeEvent>>;
|
||||
}
|
||||
|
||||
/// 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<EsignCapability>;
|
||||
|
||||
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<Envelope> {
|
||||
Err(Error::Unsupported("create"))
|
||||
}
|
||||
|
||||
fn send(&self, _: &str) -> Result<Envelope> {
|
||||
Err(Error::Unsupported("send"))
|
||||
}
|
||||
|
||||
fn status(&self, _: &str) -> Result<Envelope> {
|
||||
Err(Error::Unsupported("status"))
|
||||
}
|
||||
|
||||
fn completed(&self, _: &str) -> Result<CompletedDocument> {
|
||||
Err(Error::Unsupported("completed"))
|
||||
}
|
||||
}
|
||||
|
||||
impl EventIntake for RefuseAll {
|
||||
fn verify_event(&self, _: &[(String, String)], _: &[u8]) -> Result<Vec<EnvelopeEvent>> {
|
||||
Err(Error::Unsupported("webhooks"))
|
||||
}
|
||||
}
|
||||
|
||||
impl SigningService for RefuseAll {
|
||||
fn id(&self) -> &str {
|
||||
"refuse"
|
||||
}
|
||||
|
||||
fn capabilities(&self) -> Vec<EsignCapability> {
|
||||
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<Option<Vec<u8>>>,
|
||||
}
|
||||
|
||||
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<Envelope> {
|
||||
*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<Envelope> {
|
||||
self.status(envelope)
|
||||
}
|
||||
|
||||
fn status(&self, envelope: &str) -> Result<Envelope> {
|
||||
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<CompletedDocument> {
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -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<String>,
|
||||
/// 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<String>,
|
||||
pub document_etag: Option<String>,
|
||||
pub recipients: Vec<Recipient>,
|
||||
pub placements: Vec<FieldPlacement>,
|
||||
/// `YYYY-MM-DD`. After this the envelope expires if still open.
|
||||
pub expires: Option<String>,
|
||||
}
|
||||
|
||||
/// 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<String>,
|
||||
pub sender: Identity,
|
||||
pub document_id: Option<String>,
|
||||
pub document_etag: Option<String>,
|
||||
/// SHA-256 of the document bytes at create time, lowercase hex.
|
||||
pub content_sha256: String,
|
||||
pub recipients: Vec<Recipient>,
|
||||
pub placements: Vec<FieldPlacement>,
|
||||
pub status: EnvelopeStatus,
|
||||
pub expires: Option<String>,
|
||||
/// RFC 3339.
|
||||
pub created: Option<String>,
|
||||
/// RFC 3339 when status became [`EnvelopeStatus::Completed`].
|
||||
pub completed_at: Option<String>,
|
||||
}
|
||||
|
||||
/// 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<u8>,
|
||||
/// 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<u8>,
|
||||
}
|
||||
|
||||
/// 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<String>,
|
||||
/// RFC 3339.
|
||||
pub at: Option<String>,
|
||||
pub detail: Option<String>,
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -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<f32>,
|
||||
/// 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() });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+128
-14
@@ -55,6 +55,27 @@ struct TableB {
|
||||
row: Option<Vec<Cell>>,
|
||||
/// The table or one of its cells asks for borders.
|
||||
bordered: bool,
|
||||
/// Explicit column widths from `<col>` and childless `<colgroup>`.
|
||||
col_widths: Vec<Option<f32>>,
|
||||
/// Pending `<colgroup>`: `(span, width, has_child_cols)`.
|
||||
pending_colgroup: Option<(usize, Option<f32>, bool)>,
|
||||
}
|
||||
|
||||
impl TableB {
|
||||
/// Commit pending colgroup widths: if childless, push span columns with group width.
|
||||
/// When child `<col>` elements are present, they have already received the group width
|
||||
/// during `<col>` 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 `<colgroup>` 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 `<tr>`.
|
||||
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 `<colgroup>`, 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::<usize>().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::<usize>().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::<f32>().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::<u32>().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::<u32>().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)
|
||||
|
||||
@@ -263,21 +263,87 @@ fn para_html(p: &Para) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// Render an HTML table element, emitting `<colgroup>` column widths and cell attributes.
|
||||
fn table_html(t: &FTable, out: &mut String, depth: usize) {
|
||||
out.push_str("<table style=\"border-collapse:collapse\">\n");
|
||||
for row in &t.rows {
|
||||
out.push_str("<tr>");
|
||||
for c in row {
|
||||
if c.covered {
|
||||
if !t.widths.is_empty() {
|
||||
out.push_str("<colgroup>\n");
|
||||
for w in &t.widths {
|
||||
out.push_str(&format!("<col style=\"width:{w:.2}pt\">\n"));
|
||||
}
|
||||
out.push_str("</colgroup>\n");
|
||||
}
|
||||
let nrows = t.rows.len();
|
||||
let grid_cols: Vec<Vec<usize>> = 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<usize> { 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<Vec<bool>> = t.rows.iter().map(|r| vec![false; r.len()]).collect();
|
||||
let mut rowspans: Vec<Vec<u32>> = 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("<tr>");
|
||||
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()));
|
||||
}
|
||||
|
||||
@@ -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("<table><colgroup><col width=100><col style='width: 150pt'></colgroup><tr><td>A</td><td>B</td></tr></table>");
|
||||
let FBlock::Table(t) = &f.blocks[0] else { panic!() };
|
||||
assert_eq!(t.widths, [75.0, 150.0]);
|
||||
|
||||
// col with span
|
||||
let f2 = parse(
|
||||
"<table><colgroup><col span=2 style='width: 72pt'><col style='width: 144pt'></colgroup><tr><td>1</td><td>2</td><td>3</td></tr></table>",
|
||||
);
|
||||
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("<table><colgroup span=2 width=100></colgroup><tr><td>1</td><td>2</td></tr></table>");
|
||||
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("<table><colgroup width=100><col width=200></colgroup><tr><td>1</td></tr></table>");
|
||||
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(
|
||||
"<table><colgroup span=1 width=100></colgroup><colgroup><col style='width: 200pt'><col style='width: 300pt'></colgroup><tr><td>1</td><td>2</td><td>3</td></tr></table>",
|
||||
);
|
||||
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("<table><colgroup width=120><col><col></colgroup><tr><td>1</td><td>2</td></tr></table>");
|
||||
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("<table><colgroup width=120><col width=200><col></colgroup><tr><td>1</td><td>2</td></tr></table>");
|
||||
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("<table><colgroup><col style='width: 100pt'><col></colgroup><tr><td>1</td><td>2</td></tr></table>");
|
||||
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("<colgroup>"), "html export includes colgroup: {html}");
|
||||
assert!(html.contains("<col style=\"width:75.00pt\">"), "{html}");
|
||||
assert!(html.contains("<col style=\"width:150.00pt\">"), "{html}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn word_html_vertical_merge_is_preserved() {
|
||||
use craft_wordmodel::props::VMerge;
|
||||
let html = "<table>\
|
||||
<tr><td style='mso-yfti-vmerge:restart'>Top</td><td>B1</td></tr>\
|
||||
<tr><td style='mso-yfti-vmerge:continue'>Cont</td><td>B2</td></tr>\
|
||||
</table>";
|
||||
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 = "<table>\
|
||||
<colgroup><col></colgroup>\
|
||||
<colgroup style='width: 200pt'><col style='width: 50pt'></colgroup>\
|
||||
<tr><td>1</td><td>2</td></tr>\
|
||||
</table>";
|
||||
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 = "<table>\
|
||||
<tr><td rowspan=2 style='mso-yfti-vmerge:restart'>A</td><td>B1</td></tr>\
|
||||
<tr><td style='mso-yfti-vmerge:continue'>A_cont</td><td>B2</td></tr>\
|
||||
</table>";
|
||||
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 = "<table>\
|
||||
<tr><td style='mso-yfti-vmerge:continue'>TopCont</td><td>B1</td></tr>\
|
||||
<tr><td style='mso-yfti-vmerge:continue'>BottomCont</td><td>B2</td></tr>\
|
||||
</table>";
|
||||
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 = "<table>\
|
||||
<tr><td style='mso-yfti-vmerge:continue'>SoloCont</td><td>B1</td></tr>\
|
||||
</table>";
|
||||
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 = "<table>\
|
||||
<tr><td>A0</td><td style='mso-yfti-vmerge:continue'>B0</td></tr>\
|
||||
<tr><td colspan='2' style='mso-yfti-vmerge:continue'>SpanCont</td></tr>\
|
||||
</table>";
|
||||
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 = "<table>\
|
||||
<tr><td style='mso-yfti-vmerge:restart'>Top</td><td>B0</td></tr>\
|
||||
<tr><td rowspan='2' style='mso-yfti-vmerge:continue'>Mid</td><td>B1</td></tr>\
|
||||
<tr><td>B2</td></tr>\
|
||||
</table>";
|
||||
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 `<td>` in row 1.
|
||||
#[test]
|
||||
fn rowspan_before_explicit_vmerge_continue_keeps_grid_columns() {
|
||||
use craft_wordmodel::props::VMerge;
|
||||
let html = "<table>\
|
||||
<tr><td rowspan='2'>A</td><td rowspan='2' style='mso-yfti-vmerge:restart'>B</td><td>D</td></tr>\
|
||||
<tr><td style='mso-yfti-vmerge:continue'>B_cont</td><td>D1</td></tr>\
|
||||
</table>";
|
||||
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 = "<table><tr><td style='mso-yfti-vmerge: continue; mso-yfti-vmerge: restart'>A</td></tr></table>";
|
||||
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 = "<table><tr><td style='mso-yfti-vmerge: restart; mso-yfti-vmerge: continue'>B</td></tr></table>";
|
||||
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 = "<table>\
|
||||
<tr><td style='mso-yfti-vmerge:restart'>Top</td><td>B1</td></tr>\
|
||||
<tr><td style='mso-yfti-vmerge:continue'>Cont</td><td>B2</td></tr>\
|
||||
</table>";
|
||||
let f = parse(html);
|
||||
let exported = export_flow(&f, "en");
|
||||
assert!(exported.contains("<td rowspan=\"2\""), "must derive rowspan=\"2\" for restart cell: {exported}");
|
||||
assert!(!exported.contains("Cont</td>"), "covered continuation cell should not be emitted: {exported}");
|
||||
assert!(exported.contains(">B1</td>"), "{exported}");
|
||||
assert!(exported.contains(">B2</td>"), "{exported}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_flow_preserves_orphan_covered_continuation_content() {
|
||||
let html = "<table>\
|
||||
<tr><td style='mso-yfti-vmerge:continue'>Orphan0</td><td>B0</td></tr>\
|
||||
<tr><td>A1</td><td>B1</td></tr>\
|
||||
</table>";
|
||||
let f = parse(html);
|
||||
let exported = export_flow(&f, "en");
|
||||
assert!(exported.contains("Orphan0</td>"), "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 = "<table>\
|
||||
<colgroup><col style='width: 80pt'></colgroup>\
|
||||
<colgroup><col style='width: 120pt'></colgroup>\
|
||||
<tr><td style='mso-yfti-vmerge:restart'>MergeA</td><td>B1</td></tr>\
|
||||
<tr><td style='mso-yfti-vmerge:continue'>MergeA_cont</td><td>B2</td></tr>\
|
||||
</table>";
|
||||
|
||||
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("<colgroup>"), "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 = "<table>\
|
||||
<tr><td style='mso-yfti-vmerge:restart'>Top</td></tr>\
|
||||
<tr><td style='mso-yfti-vmerge:continue'>Cont</td></tr>\
|
||||
<tr><td>Bottom</td></tr>\
|
||||
</table>";
|
||||
|
||||
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("<tr></tr>"), "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("<col style=\"width:40.00pt\">"), "must contain col 0 width: {html}");
|
||||
assert!(html.contains("<col style=\"width:80.00pt\">"), "must contain col 1 width: {html}");
|
||||
assert!(html.contains("<col style=\"width:120.00pt\">"), "must contain col 2 width: {html}");
|
||||
assert!(html.contains(">D</td>"), "must contain cell D: {html}");
|
||||
assert!(html.contains(">E</td>"), "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]
|
||||
|
||||
+7
-14
@@ -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.
|
||||
+200
-157
@@ -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<MapEntry>,
|
||||
#[serde(default)]
|
||||
pub parameters: Vec<Value>,
|
||||
#[serde(default)]
|
||||
pub inputs: Vec<Value>,
|
||||
#[serde(default)]
|
||||
pub presets: Vec<Value>,
|
||||
pub source: String,
|
||||
#[serde(flatten)]
|
||||
pub extra: BTreeMap<String, Value>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct MapEntry {
|
||||
pub usage: String,
|
||||
pub file: String,
|
||||
#[serde(flatten)]
|
||||
pub extra: BTreeMap<String, Value>,
|
||||
}
|
||||
|
||||
/// 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<Self, Error> {
|
||||
#[derive(Debug)]
|
||||
pub struct Material {
|
||||
pub source: Vec<u8>,
|
||||
/// Keys are paths relative to source.sbs, including the resources/ prefix.
|
||||
pub resources: BTreeMap<String, Vec<u8>>,
|
||||
}
|
||||
|
||||
impl Material {
|
||||
pub fn open(bytes: &[u8], limits: Limits) -> Result<Self, Error> {
|
||||
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<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
|
||||
let mut version = None;
|
||||
let mut extra = false;
|
||||
while let Some(key) = map.next_key::<String>()? {
|
||||
if key == "version" {
|
||||
if version.is_some() {
|
||||
return Err(serde::de::Error::duplicate_field("version"));
|
||||
}
|
||||
version = Some(map.next_value::<u32>()?);
|
||||
} else {
|
||||
map.next_value::<IgnoredAny>()?;
|
||||
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<Vec<u8>, 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<Vec<u8>, 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<u8>)], source: &[u8]) -> Result<Vec<u8>, 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<Item = (&'a str, &'a [u8])>) -> Result<Vec<u8>, 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<u8>)], 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"<package/>", [("resources/oak.png", b"image".as_slice())]).unwrap();
|
||||
let pkg = Material::open(&bytes, Limits::default()).unwrap();
|
||||
assert_eq!(pkg.source, b"<package/>");
|
||||
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"<package/>", [("resources/shape.svg", b"<svg/>".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"<package/>".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());
|
||||
}
|
||||
}
|
||||
@@ -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> {
|
||||
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<u8> {
|
||||
let b = s.as_bytes();
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
@@ -63,6 +63,27 @@ pub struct CertificateList {
|
||||
pub revoked: Vec<(Vec<u8>, 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<u8>,
|
||||
pub sig_alg: Vec<u8>,
|
||||
pub signature: Vec<u8>,
|
||||
pub issuer_raw: Vec<u8>,
|
||||
pub this_update: Time,
|
||||
pub next_update: Option<Time>,
|
||||
/// (serial, revocation date), top to bottom.
|
||||
pub revoked: Vec<(Vec<u8>, Time)>,
|
||||
}
|
||||
|
||||
impl CertificateList {
|
||||
/// Move parsed fields into a caller-owned representation; verification remains separate.
|
||||
pub fn into_parts(self) -> CertificateListParts {
|
||||
let Self { tbs, sig_alg, signature, issuer_raw, this_update, next_update, revoked } = self;
|
||||
CertificateListParts { tbs, sig_alg, signature, issuer_raw, this_update, next_update, revoked }
|
||||
}
|
||||
}
|
||||
|
||||
impl CertificateList {
|
||||
pub fn parse(bytes: &[u8]) -> Result<CertificateList, Error> {
|
||||
if bytes.is_empty() || bytes.len() > MAX_EVIDENCE {
|
||||
@@ -144,7 +165,8 @@ impl CertId {
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
enum CertStatus {
|
||||
/// Parsed certificate status; not authenticated until the response is verified.
|
||||
pub enum CertStatus {
|
||||
Good,
|
||||
Revoked(Time),
|
||||
Unknown,
|
||||
@@ -159,7 +181,15 @@ pub struct SingleResponse {
|
||||
pub next_update: Option<Time>,
|
||||
}
|
||||
|
||||
enum ResponderId {
|
||||
impl SingleResponse {
|
||||
/// Consume this unverified record without cloning its owned identifier fields.
|
||||
pub fn into_parts(self) -> (CertId, CertStatus, Time, Option<Time>) {
|
||||
(self.cert_id, self.status, self.this_update, self.next_update)
|
||||
}
|
||||
}
|
||||
|
||||
/// Parsed OCSP responder identifier, not proof of identity.
|
||||
pub enum ResponderId {
|
||||
ByName(Vec<u8>),
|
||||
ByKey(Vec<u8>),
|
||||
}
|
||||
@@ -175,6 +205,25 @@ pub struct OcspResponse {
|
||||
responder_cert: Option<Certificate>,
|
||||
}
|
||||
|
||||
/// 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 OcspResponseParts {
|
||||
pub tbs: Vec<u8>,
|
||||
pub sig_alg: Vec<u8>,
|
||||
pub signature: Vec<u8>,
|
||||
pub responder_id: ResponderId,
|
||||
pub responses: Vec<SingleResponse>,
|
||||
pub responder_cert: Option<Certificate>,
|
||||
}
|
||||
|
||||
impl OcspResponse {
|
||||
/// Move parsed fields into a caller-owned representation; verification remains separate.
|
||||
pub fn into_parts(self) -> OcspResponseParts {
|
||||
let Self { tbs, sig_alg, signature, responder_id, responses, responder_cert } = self;
|
||||
OcspResponseParts { tbs, sig_alg, signature, responder_id, responses, responder_cert }
|
||||
}
|
||||
}
|
||||
|
||||
impl OcspResponse {
|
||||
pub fn parse(bytes: &[u8]) -> Result<OcspResponse, Error> {
|
||||
if bytes.is_empty() || bytes.len() > MAX_EVIDENCE {
|
||||
|
||||
@@ -106,9 +106,39 @@ impl Name {
|
||||
}
|
||||
}
|
||||
|
||||
/// A parsed certificate.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Certificate {
|
||||
// One field schema keeps the parsed representation and consuming adapter in sync.
|
||||
// Visibility belongs to Certificate; parts are explicitly unverified public data.
|
||||
macro_rules! certificate_representations {
|
||||
($( $(#[$attr:meta])* $vis:vis $field:ident: $ty:ty, )*) => {
|
||||
/// A parsed certificate. Signed material remains private until consumed.
|
||||
///
|
||||
/// ```compile_fail
|
||||
/// fn replace_signed_bytes(cert: &mut craft_pkcs7::x509::Certificate) {
|
||||
/// cert.tbs.clear();
|
||||
/// }
|
||||
/// ```
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Certificate {
|
||||
$( $(#[$attr])* $vis $field: $ty, )*
|
||||
}
|
||||
|
||||
/// 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 CertificateParts {
|
||||
$( $(#[$attr])* pub $field: $ty, )*
|
||||
}
|
||||
|
||||
impl Certificate {
|
||||
/// Move parsed fields into a caller-owned representation; verification remains separate.
|
||||
pub fn into_parts(self) -> CertificateParts {
|
||||
let Self { $( $field, )* } = self;
|
||||
CertificateParts { $( $field, )* }
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
certificate_representations! {
|
||||
/// The whole DER encoding.
|
||||
pub raw: Vec<u8>,
|
||||
tbs: Vec<u8>,
|
||||
|
||||
@@ -810,3 +810,56 @@ fn verifies_ecdsa_on_p521_and_the_brainpool_curves() {
|
||||
assert!(!key.verify(Scheme::Ecdsa, alg, &digest[..digest.len() / 2], &sig).unwrap(), "{name}: short digest");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parsed_parts_preserve_owned_bytes_and_unverified_fields() {
|
||||
use craft_pkcs7::revocation::{CertStatus, ResponderId};
|
||||
let id = pkcs12::open(&data("ec-p256.p12"), "test").unwrap();
|
||||
let cert = craft_pkcs7::x509::Certificate::parse(&id.certificate.raw).unwrap();
|
||||
let raw_pointer = cert.raw.as_ptr();
|
||||
let expected = cert.clone();
|
||||
let parts = cert.into_parts();
|
||||
assert_eq!(parts.raw.as_ptr(), raw_pointer);
|
||||
assert_eq!(parts.raw, expected.raw);
|
||||
assert_eq!(parts.subject, expected.subject);
|
||||
assert_eq!(parts.issuer, expected.issuer);
|
||||
assert_eq!(parts.public_key, expected.public_key);
|
||||
assert_eq!(parts.serial, expected.serial);
|
||||
let der = der::Tlv::parse_all(&parts.raw).unwrap().children().unwrap();
|
||||
assert_eq!(parts.tbs, der[0].raw);
|
||||
assert_eq!(parts.sig_alg, der[1].raw);
|
||||
assert_eq!(parts.signature, der[2].bits().unwrap());
|
||||
let this = mid_june();
|
||||
let bytes = crl(&id, Some((&id.certificate.serial, this)), this, this);
|
||||
let crl = CertificateList::parse(&bytes).unwrap();
|
||||
let revoked_pointer = crl.revoked.as_ptr();
|
||||
let parts = crl.into_parts();
|
||||
assert_eq!(parts.revoked.as_ptr(), revoked_pointer);
|
||||
assert_eq!(parts.revoked, vec![(id.certificate.serial.iter().copied().skip_while(|b| *b == 0).collect(), this)]);
|
||||
assert_eq!(parts.this_update, this);
|
||||
assert_eq!(parts.next_update, Some(this));
|
||||
assert_eq!(parts.issuer_raw, id.certificate.subject.raw);
|
||||
let der = der::Tlv::parse_all(&bytes).unwrap().children().unwrap();
|
||||
assert_eq!(parts.tbs, der[0].raw);
|
||||
assert_eq!(parts.sig_alg, der[1].raw);
|
||||
assert_eq!(parts.signature, der[2].bits().unwrap());
|
||||
for status in [RevocationStatus::Good, RevocationStatus::Unknown, RevocationStatus::Revoked { at: this }] {
|
||||
let response = OcspResponse::parse(&ocsp(&id, status.clone(), this, this)).unwrap();
|
||||
let responses_pointer = response.responses.as_ptr();
|
||||
let parts = response.into_parts();
|
||||
assert_eq!(parts.responses.as_ptr(), responses_pointer);
|
||||
assert!(matches!(&parts.responder_id, ResponderId::ByName(name) if *name == id.certificate.subject.raw));
|
||||
assert!(parts.responder_cert.is_none());
|
||||
let (cert_id, parsed, date, next) = parts.responses.into_iter().next().unwrap().into_parts();
|
||||
assert_eq!(cert_id, craft_pkcs7::revocation::CertId::build(&id.certificate, &id.certificate, DigestAlg::Sha1));
|
||||
assert_eq!((date, next), (this, Some(this)));
|
||||
assert_eq!(
|
||||
parsed,
|
||||
match status {
|
||||
RevocationStatus::Good => CertStatus::Good,
|
||||
RevocationStatus::Unknown => CertStatus::Unknown,
|
||||
RevocationStatus::Revoked { at } => CertStatus::Revoked(at),
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
+49
-5
@@ -16,6 +16,7 @@ craft-proof = { git = "https://github.com/storytold/craft-libs", rev = "<commit>
|
||||
| English (en-US, en-CA, en-AU, en-GB and the British-spelling Englishes such as en-NZ) | SCOWL 2026 Hunspell dictionary per English + `en-extra.txt`, dialect policy (`en-variants.txt`); a dictionaries-folder English first; without SCOWL the installed Hunspell English, else the built-in Moby list ([below](#english-is-always-checked)) | yes | Moby list, our patterns, heuristic |
|
||||
| Polish, Portuguese, Italian | the installed Hunspell dictionary | yes | TeX patterns (embedded, or a Language pack) |
|
||||
| Croatian, Turkish, Russian, Czech, Indonesian, Spanish (es, es-MX, es-419, es-UY) | the installed Hunspell dictionary (Russian also `ru-extra.txt`) | yes | Turkish and Russian rules; English fallback otherwise |
|
||||
| French (fr-FR, fr-CA and other French pack locales) | the installed Language pack or Hunspell dictionary; dictionary-driven elisions and accent-oriented suggestions | conservative typography and basic checks, with Quebec punctuation spacing in fr-CA | the Language pack (generic fr fallback) |
|
||||
| German | — | — | TeX patterns (embedded, or a Language pack) |
|
||||
| Bulgarian | — | — | syllable rules |
|
||||
|
||||
@@ -41,6 +42,12 @@ application data (`%LOCALAPPDATA%\WordCraft\dictionaries` and `%APPDATA%\WordCra
|
||||
`~/Library/Application Support/WordCraft/dictionaries`, `$XDG_DATA_HOME/wordcraft/dictionaries`),
|
||||
then the usual Hunspell and LibreOffice locations. None on the web.
|
||||
|
||||
French remains a `ProofLang::Pack` locale: use its full `tag()` for settings and issue identity.
|
||||
The shared pack loader keeps regional dictionary overrides, fallback to `fr`, reloads and its
|
||||
memory budget; no separate French dictionary slot or embedded French patterns are added.
|
||||
Only French packs receive the French spelling tuning and typography; other pack languages
|
||||
keep their existing behavior. French agreement and conjugation are outside these checks.
|
||||
|
||||
State is process-wide: `add_word`, `ignore_word`, `set_dictionaries_folder`,
|
||||
`load_user_dictionary`/`save_user_dictionary`. The crate reads no document model; callers pass
|
||||
plain text and language spans.
|
||||
@@ -82,19 +89,22 @@ pub fn load_errors() -> Vec<(String, String)>; // + (locale or folder,
|
||||
pub fn embedded_locales() -> &'static [&'static str]; // + locales with embedded upstream data, not our supplements ("en-us", "en-gb", "en-ca", "en-au", "pl", "pt", "it", "de" by default; the four English ones with CRAFT_PROOF_EMBED=en)
|
||||
|
||||
// craft_proof (crate root)
|
||||
pub enum ProofLang { …, Pack(PackLocale), Other } // + Pack: any language without tools of its own (nl, fr, sr-Latn…)
|
||||
pub enum ProofLang { …, Pack(PackLocale), Other } // + Pack: a language without a dedicated built-in variant (nl, fr, sr-Latn…)
|
||||
pub struct PackLocale; // + Copy; PackLocale::new(tag) -> Option<Self>, .as_str() "nl-nl", .primary() "nl", Display
|
||||
impl ProofLang { pub fn pack_locale(self) -> Option<PackLocale>; } // +
|
||||
pub fn pack_dictionary_file(lang: ProofLang) -> Option<PathBuf>; // + the .dic a Pack language reads now; None = unchecked
|
||||
```
|
||||
|
||||
`ProofLang::from_tag` now gives `Pack(locale)` for every valid language tag it has no tools for
|
||||
`ProofLang::from_tag` now gives `Pack(locale)` for every valid language tag without a dedicated built-in variant
|
||||
(`nl-NL` → `Pack("nl-nl")`, `fr-FR`, `ja-JP`, `sr-Latn`…); `Other` is left for `x-none`, `und`,
|
||||
`zxx`, `mul`, `mis`, `i-…` and malformed tags. A `Pack` language is spell-checked and given
|
||||
suggestions from its Hunspell dictionary (dictionaries folder → installed pack → system Hunspell)
|
||||
through the shared affix engine with default tuning, and hyphenated from its pack's
|
||||
`hyphenation.pat`; it has no grammar rules and the generic English spelling message. Without a
|
||||
dictionary or pack it behaves exactly as `Other` did (no marks, English hyphenation fallback).
|
||||
through the shared affix engine with default tuning (French tuning for `fr` packs), and
|
||||
hyphenated from its pack's `hyphenation.pat`. Most pack languages use no dedicated grammar
|
||||
rules; regional variants can reuse a built-in language's rules. French packs use the French
|
||||
spelling message and the conservative French grammar and typography described above. Without a dictionary or pack,
|
||||
spelling has no marks and hyphenation falls back to English; French grammar and typography
|
||||
still apply independently of a spelling dictionary.
|
||||
`has_dictionary(tag)` / `ProofLang::is_proofed()` say whether a `Pack` language has a dictionary
|
||||
now (read on first use, cached). Loaded `Pack` dictionaries share a 256 MB budget (estimated from their files); the least recently used goes first, but never one used in the paragraph being checked, and languages with no dictionary take no room. Downstream `match`es on `ProofLang` need a `Pack(_)` arm; `code()` stays `&'static str`
|
||||
and is `""` for it, as for `Other`: anything that keys, saves or reports a language (settings, caches, JSON/MCP output) uses `tag()`, which is `code()` for the built-ins and the locale (`nl`, `fr-fr`) for a pack language.
|
||||
@@ -221,6 +231,40 @@ CI: `.github/workflows/proof.yml`.
|
||||
|
||||
storytold/craft-libs#30/#31 by brzuchal (Michał Marcin Brzuchalski) started the shared crate.
|
||||
|
||||
### French adaptation validation
|
||||
|
||||
The French rules and original synthetic fixtures are adapted from
|
||||
[totoz64’s WordCraft contribution #3185](https://github.com/storytold/wordcraft/pull/3185).
|
||||
They use the shared affix reader and Language pack cache; WCAFF1 remains deliberately rejected.
|
||||
The historical text fixtures retain their original expected data. Three observations for
|
||||
Indonesian `bermainkanlah` are explicitly updated in the compatibility test because the
|
||||
shared reader already supports that prefix plus two suffixes. This is a finite regression
|
||||
check, not a universal compatibility claim.
|
||||
|
||||
The ordinary tests cover French packs, regional overrides and reloads, options, user words,
|
||||
NFC/NFD lookup with original ranges, suggestions and pack hyphenation. The opt-in real French
|
||||
dictionary gate fails when its input is missing; it never silently skips its assertions:
|
||||
|
||||
```sh
|
||||
WORDCRAFT_DICTIONARIES=/absolute/isolated/french-dictionary cargo test -p craft-proof --test french_dictionary -- --ignored
|
||||
```
|
||||
|
||||
For a reproducible real-dictionary run, use Dicollecte 7.7 from LibreOffice/dictionaries
|
||||
revision `67032ee957631908098a72edf48dc81cac27e369`:
|
||||
[fr.aff](https://raw.githubusercontent.com/LibreOffice/dictionaries/67032ee957631908098a72edf48dc81cac27e369/fr_FR/dictionaries/fr.aff) and
|
||||
[fr.dic](https://raw.githubusercontent.com/LibreOffice/dictionaries/67032ee957631908098a72edf48dc81cac27e369/fr_FR/dictionaries/fr.dic).
|
||||
Verify SHA-256 before invoking the gate (the test checks location and behavior, not hashes):
|
||||
|
||||
| File | SHA-256 |
|
||||
|---|---|
|
||||
| fr.aff | `c176610cd5dc4846806a65ddd029f422d87978bf58f224aa44222662a16a2de5` |
|
||||
| fr.dic | `b78a868e31dd6e373b6c3217969afb898a9acde828a5e7ef97308da42218c88c` |
|
||||
|
||||
Use a dedicated directory containing only the intended `fr.aff`/`fr.dic` pair (or explicit
|
||||
regional pairs for both regions). The gate requires more than 50,000 dictionary entries and
|
||||
checks the actual source folder, spelling, accent/elision suggestions, regional dispatch,
|
||||
combining-mark ranges and hyphenated compounds. No real dictionary is committed here.
|
||||
|
||||
## Owners
|
||||
|
||||
WordCraft maintainers: echelon, dylanmtaylor, aiongg.
|
||||
|
||||
@@ -2227,6 +2227,38 @@ impl AffixDict {
|
||||
self.check_except(w, self.excluded(true))
|
||||
}
|
||||
|
||||
/// Validate a collected suggestion in its displayed case, before OCONV. Only identity,
|
||||
/// first-letter and uppercase variants are allowed (including uppercase that keeps sharp s).
|
||||
/// An exact target excluded from suggestions cannot be rescued by a lowercase fallback.
|
||||
/// This preserves the checker's homonym, compound and CHECKSHARPS rules without scanning
|
||||
/// stems or changing which words the spelling checker accepts.
|
||||
pub(crate) fn can_suggest_cased(&self, original: &str, changed: &str) -> bool {
|
||||
if original.len() > MAX_INPUT_BYTES || changed.len() > MAX_INPUT_BYTES {
|
||||
return false;
|
||||
}
|
||||
if changed != original
|
||||
&& changed != capitalize(original)
|
||||
&& changed != original.to_uppercase()
|
||||
&& changed != original.split('ß').map(str::to_uppercase).collect::<Vec<_>>().join("ß")
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let target = self.normalize(changed);
|
||||
if self.is_forbidden(&target) {
|
||||
return false;
|
||||
}
|
||||
// The exact simple-word path includes affixes; asking with no exclusions detects a
|
||||
// target that may carry NOSUGGEST, SUBSTANDARD or FORBIDDENWORD. An eligible exact
|
||||
// compound derivation still counts, but a lowercase fallback must not rescue it. Spend
|
||||
// the same shared suggestion budget as the normal checker, and abstain if it runs out.
|
||||
match self.simple_word_budgeted(&target, Excluded::default(), true) {
|
||||
None => return false,
|
||||
Some(true) if !self.contains_except(&target, self.excluded(true)) => return false,
|
||||
_ => {}
|
||||
}
|
||||
self.can_suggest(changed)
|
||||
}
|
||||
|
||||
/// Whether `w` is a word only through a `KEEPCASE` stem, so it is correct in this letter case
|
||||
/// alone (`km` from `km/K`, which `Km` and `KM` are not).
|
||||
pub(crate) fn case_locked(&self, w: &str) -> bool {
|
||||
@@ -3313,6 +3345,41 @@ pub(crate) mod tests {
|
||||
assert!(d.check("ASSASSASSASSASS") && !d.check(&"SS".repeat(60)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn displayed_casing_rejects_exact_exclusions_before_case_fallback() {
|
||||
for flag in ["N", "F", "S"] {
|
||||
let aff = "SET UTF-8\nNOSUGGEST N\nFORBIDDENWORD F\nSUBSTANDARD S\nSFX A Y 1\nSFX A 0 s .\nSFX B Y 1\nSFX B 0 S .\n";
|
||||
let dic = format!("5\nnormal/A\nNORMAL/{flag}B\nmixCase\npour\nkm/K\n");
|
||||
let d = AffixDict::from_hunspell(&format!("{aff}KEEPCASE K\n"), &dic, &[]).unwrap();
|
||||
for (original, changed) in [("normal", "NORMAL"), ("normals", "NORMALS")] {
|
||||
assert!(!d.can_suggest_cased(changed, changed), "{flag}: {changed}");
|
||||
assert!(!d.can_suggest_cased(original, changed), "{flag}: {original} → {changed}");
|
||||
}
|
||||
assert!(d.can_suggest_cased("normal", "Normal"));
|
||||
assert!(d.can_suggest_cased("mixCase", "MIXCASE"));
|
||||
assert!(d.can_suggest_cased("km", "km") && !d.can_suggest_cased("km", "KM"));
|
||||
assert!(!d.can_suggest_cased("normal", "pour"), "no arbitrary replacement");
|
||||
let back = AffixDict::from_bytes(&d.to_bytes().unwrap()).unwrap();
|
||||
assert!(!back.can_suggest_cased("normal", "NORMAL"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn displayed_casing_uses_normalization_and_native_homonym_policy() {
|
||||
let aff = "SET UTF-8\nNOSUGGEST N\nSUBSTANDARD S\nIGNORE ()\nICONV 1\nICONV Q NORMAL\n";
|
||||
for flag in ["N", "S"] {
|
||||
let d = AffixDict::from_hunspell(aff, &format!("3\nnormal\nNORMAL/{flag}\nNORMAL\n"), &[]).unwrap();
|
||||
// Native homonyms carry exclusions: a second entry does not erase NOSUGGEST.
|
||||
assert!(!d.contains_suggestible("NORMAL"));
|
||||
assert!(!d.can_suggest_cased("(normal)", "(NORMAL)"));
|
||||
assert!(!d.can_suggest_cased("Q", "Q"));
|
||||
}
|
||||
let plain = AffixDict::from_hunspell(aff, "3\nnormal\nNORMAL\nNORMAL\n", &[]).unwrap();
|
||||
assert!(plain.can_suggest_cased("normal", "NORMAL"));
|
||||
assert!(plain.can_suggest_cased("Q", "Q"));
|
||||
assert!(!plain.can_suggest_cased(&"x".repeat(MAX_INPUT_BYTES + 1), "NORMAL"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oconv_converts_suggestions_only() {
|
||||
// Answers as Hunspell 1.7 gives them on the same files: `kbt` → `k’t`.
|
||||
|
||||
@@ -248,7 +248,8 @@ impl Collector<'_> {
|
||||
|
||||
/// Keep a suggestion known to be correct, unless the dictionary says never to offer it.
|
||||
fn keep(&mut self, text: String, cost: u32) {
|
||||
if !text.split(' ').all(|part| self.d.can_suggest(part)) {
|
||||
// Reject exact excluded spellings at admission, before later candidates spend the budget.
|
||||
if !text.split(' ').all(|part| self.d.can_suggest_cased(part, part)) {
|
||||
return;
|
||||
}
|
||||
self.seq += 1;
|
||||
@@ -447,6 +448,14 @@ pub(crate) fn suggest_in(d: &AffixDict, word: &str, max: usize, t: &Tuning) -> V
|
||||
_ => vec![text.clone()],
|
||||
};
|
||||
for t in recased {
|
||||
let eligible = |candidate: &str| {
|
||||
let original: Vec<_> = text.split(' ').collect();
|
||||
let changed: Vec<_> = candidate.split(' ').collect();
|
||||
original.len() == changed.len() && original.iter().zip(changed).all(|(a, b)| d.can_suggest_cased(a, b))
|
||||
};
|
||||
// Collector::keep already accepted text. Collection may have exhausted the shared
|
||||
// affix budget, so recheck only a changed case and otherwise retain that accepted form.
|
||||
let t = if t == text || eligible(&t) { t } else { text.clone() };
|
||||
// Shown as the dictionary's OCONV table writes it (`'` → `’` in French).
|
||||
let t = d.output(&t).into_owned();
|
||||
if t != word && !out.contains(&t) {
|
||||
@@ -795,6 +804,38 @@ mod tests {
|
||||
assert_eq!(suggest_in(&d, "Piesx", 4, &Tuning::DEFAULT).first().map(String::as_str), Some("Pies"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recasing_keeps_valid_original_when_exact_target_is_excluded() {
|
||||
for flag in ["N", "F", "S"] {
|
||||
let aff = "SET UTF-8\nNOSUGGEST N\nFORBIDDENWORD F\nSUBSTANDARD S\nTRY normal\n";
|
||||
let d = AffixDict::from_hunspell(aff, &format!("2\nnormal\nNORMAL/{flag}\n"), &[]).unwrap();
|
||||
let got = suggest_in(&d, "NORMALL", 4, &Tuning::DEFAULT);
|
||||
assert!(got.iter().any(|w| w == "normal"), "{flag}: {got:?}");
|
||||
assert!(!got.iter().any(|w| w == "NORMAL"), "{flag}: {got:?}");
|
||||
let split = AffixDict::from_hunspell(aff, &format!("3\nnormal\nNORMAL/{flag}\npour\n"), &[]).unwrap();
|
||||
let got = suggest_in(&split, "NORMALPOUR", 4, &Tuning::DEFAULT);
|
||||
assert!(got.iter().any(|w| w == "normal pour"), "{flag}: {got:?}");
|
||||
assert!(!got.iter().any(|w| w == "NORMAL POUR"), "{flag}: {got:?}");
|
||||
}
|
||||
let d = AffixDict::from_hunspell("NOSUGGEST N\n", "3\nnormal\nNORMAL/N\npour\n", &[]).unwrap();
|
||||
assert!(!d.can_suggest_cased("normal", "NORMAL"));
|
||||
assert!(!d.can_suggest_cased("normal", "pour"));
|
||||
}
|
||||
|
||||
/// An excluded simple entry does not exclude an eligible exact COMPOUNDRULE derivation.
|
||||
#[test]
|
||||
fn rep_keeps_eligible_exact_compound_beside_an_excluded_simple_entry() {
|
||||
for flag in ["N", "S", "F"] {
|
||||
let aff = "SET UTF-8\nNOSUGGEST N\nSUBSTANDARD S\nFORBIDDENWORD F\nCOMPOUNDRULE ab\nREP 1\nREP zz foobar\n";
|
||||
let d = AffixDict::from_hunspell(aff, &format!("3\nfoobar/{flag}\nfoo/a\nbar/b\n"), &[]).unwrap();
|
||||
for d in [&d, &AffixDict::from_bytes(&d.to_bytes().unwrap()).unwrap()] {
|
||||
assert_eq!(d.contains_suggestible("foobar"), flag != "F", "{flag}: exact compound eligibility");
|
||||
let got = suggest_in(d, "zz", 4, &Tuning::DEFAULT);
|
||||
assert_eq!(got.iter().any(|w| w == "foobar"), flag != "F", "{flag}: {got:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A language's tables come after its dictionary's, a TRY alphabet stands in for a missing TRY
|
||||
/// line, and a split rule decides which missing spaces are offered.
|
||||
#[test]
|
||||
@@ -874,4 +915,34 @@ mod tests {
|
||||
assert!(suggest_in(&d, "neer", 4, &english).contains(&"ne'er".to_string()));
|
||||
assert_eq!(suggest_in(&d, "neer", 4, &Tuning::DEFAULT).first().map(String::as_str), Some("ne'er"), "an elision");
|
||||
}
|
||||
/// A REP candidate is admitted before costly TRY checks consume the normal shared budget.
|
||||
/// Finalization must retain that accepted affixed word, including a conservative case fallback.
|
||||
#[test]
|
||||
fn accepted_affixed_suggestions_survive_exhausted_collection_budget() {
|
||||
let input = format!("{}x{}", "a".repeat(20), "a".repeat(19));
|
||||
let mut aff = String::from("SET UTF-8\nFLAG num\nTRY ");
|
||||
aff.extend(('a'..='z').chain((0x100..0x166).filter_map(char::from_u32)));
|
||||
aff.push_str(&format!("\nREP 1\nREP {input} kots\n"));
|
||||
// The bounded adversarial rule shape of the existing shared-budget regression.
|
||||
for f in 1..=1000u32 {
|
||||
let c = char::from_u32(0x4e00 + f).unwrap();
|
||||
aff.push_str(&format!("PFX {f} Y 1\nPFX {f} {c} 0 .\n"));
|
||||
}
|
||||
let conts: Vec<String> = (0..286).map(|k| (5000 + k * 7).to_string()).collect();
|
||||
for len in 1..=40 {
|
||||
for k in 0..50 {
|
||||
let f = 5000 + (len - 1) * 50 + k;
|
||||
aff.push_str(&format!("SFX {f} Y 1\nSFX {f} 0 {}/{} .\n", "a".repeat(len), conts.join(",")));
|
||||
}
|
||||
}
|
||||
aff.push_str("SFX 9000 Y 1\nSFX 9000 0 s .\n");
|
||||
let d = AffixDict::from_hunspell(&aff, "3\nb/1,5000\nab/2\nkot/9000\n", &[]).unwrap();
|
||||
assert!(!d.stems().any(|s| s == "kots") && d.can_suggest("kots"));
|
||||
for word in [input.clone(), input.to_uppercase()] {
|
||||
let got = suggest_in(&d, &word, 1, &Tuning::DEFAULT);
|
||||
assert_eq!(got.len(), 1, "accepted affixed candidate lost: {word}: {got:?}");
|
||||
assert!(got[0].eq_ignore_ascii_case("kots"), "{word}: {got:?}");
|
||||
assert!(d.can_suggest(&got[0]));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,665 @@
|
||||
//! French grammar and typography checks: cheap, rule-based and tuned to stay quiet when unsure
|
||||
//! (a missed mistake costs less than a wrong mark on correct text). Messages are in French.
|
||||
//!
|
||||
//! - **Space before `;` `!` `?` `:`**: French typography puts a non-breaking space there — a
|
||||
//! narrow one (U+202F) before `;` `!` `?`, a full one (U+00A0) before `:`. Only a missing
|
||||
//! space is flagged (`Bonjour!`): an ordinary one stays quiet until typing turns it into a
|
||||
//! non-breaking one (no French AutoFormat yet). Quebec French (`fr-CA`) has no space before
|
||||
//! `;` `!` `?`, only before `:`. Addresses (`https://…`) and times (`10:30`) are left alone.
|
||||
//! - **Space inside `« »`**: a missing one after `«` or before `»` (`«oui»`) → U+00A0.
|
||||
//! - **Straight double quotes** around a phrase (`"bonjour"`) → `« bonjour »`; inch marks
|
||||
//! (`27"`) and unbalanced quotes are left alone.
|
||||
//! - **Repeated word** (`le le`, `que que`), except repetitions French makes on purpose
|
||||
//! (`nous nous lavons`, `vous vous trompez`, `si si`, interjections) and a proper noun after
|
||||
//! the same lower-case word (`de De…`).
|
||||
//! - **Capital letter at the start of a sentence** after `.` `!` `?`, knowing French
|
||||
//! abbreviations (`etc.`, `M.`, `p.`, `cf.`), initials, numbers, ellipses, addresses,
|
||||
//! dialogue (`« Tu viens ? » demanda-t-elle`), inversions (`Quoi ? dit-il`) and exclamations
|
||||
//! after an interjection (`Ah ! que c'est beau`).
|
||||
//! - **Elision** (`de avoir` → `d’avoir`, `je ai` → `j’ai`, `le homme` → `l’homme`) for `le`,
|
||||
//! `la`, `de`, `je`, `me`, `te`, `se`, `ne`, `que` before a vowel. Before an `h` only for words
|
||||
//! known to have a mute `h`, so aspirated ones (`le hibou`, `la hache`, `le héros`) stay quiet;
|
||||
//! never before a proper noun, `onze`, `oui`, `y…` words (`le yaourt`) or `la une`.
|
||||
//!
|
||||
//! No agreement or conjugation rule, and no English rule (such as `a`/`an`), applies to French
|
||||
//! text.
|
||||
|
||||
use crate::{Issue, IssueKind, ProofLang, words};
|
||||
|
||||
/// Non-breaking space, before `:` and inside `« »`.
|
||||
const NBSP: char = '\u{A0}';
|
||||
/// Narrow non-breaking space, before `;` `!` `?`.
|
||||
const NNBSP: char = '\u{202F}';
|
||||
|
||||
/// Words French repeats on purpose: pronominal verbs (`nous nous lavons`), emphasis,
|
||||
/// interjections, onomatopoeia.
|
||||
const ALLOWED_REPEATS: &[&str] = &[
|
||||
"nous", "vous", "si", "oui", "non", "très", "bon", "vite", "là", "ah", "oh", "eh", "ha", "hé", "ho", "hi", "bla", "chut", "toc", "pan", "bravo",
|
||||
"merci", "allez", "encore", "beaucoup", "fort", "tchin", "bye", "couci", "tam", "miam", "glou",
|
||||
];
|
||||
|
||||
/// Abbreviations written with a final period after which a sentence goes on in lower case
|
||||
/// (lower case, without the period).
|
||||
const ABBREVIATIONS: &[&str] = &[
|
||||
"etc", "cf", "ex", "env", "av", "apr", "mm", "mme", "mmes", "mlle", "mlles", "mgr", "dr", "pr", "me", "st", "ste", "sts", "pp", "vol", "chap",
|
||||
"fig", "éd", "coll", "trad", "réf", "tél", "art", "al", "op", "cit", "ibid", "id", "resp", "min", "max", "sq", "sqq", "suiv", "hab", "janv",
|
||||
"févr", "avr", "juil", "sept", "oct", "nov", "déc", "bd", "boul", "cie", "éts", "vve", "nb", "ps", "no", "nos", "vs", "qqch", "qqn", "ca",
|
||||
"approx", "prof", "dir", "sté", "dépt", "adj", "adv", "fém", "masc", "sing", "plur", "à-d", "ms", "mss", "éds", "trim", "hôp",
|
||||
];
|
||||
|
||||
/// Words after which `!` or `?` doesn't end the sentence (`Ah ! que c'est beau`, `Eh bien ?
|
||||
/// et alors`).
|
||||
const INTERJECTIONS: &[&str] = &[
|
||||
"ah", "oh", "eh", "hé", "hein", "hélas", "bah", "ô", "aïe", "ouf", "oups", "quoi", "comment", "ha", "ho", "bon", "tiens", "allons", "zut",
|
||||
"chut", "bravo", "hourra", "dame", "bien", "là", "oui", "non", "pardon", "voyons",
|
||||
];
|
||||
|
||||
/// Pronouns ending an inversion (`dit-il`, `demanda-t-elle`): after one, a `!` or `?` doesn't
|
||||
/// end the sentence (`Quoi ? dit-il`).
|
||||
const INVERTED: &[&str] = &["-il", "-elle", "-on", "-ils", "-elles", "-je", "-tu", "-nous", "-vous"];
|
||||
|
||||
/// Speech verbs of a dialogue tag: after one, a `!` or `?` doesn't end the sentence (`— Tu
|
||||
/// viens ? demanda le voisin`).
|
||||
const SPEECH_VERBS: &[&str] = &[
|
||||
"dit",
|
||||
"demanda",
|
||||
"répondit",
|
||||
"cria",
|
||||
"murmura",
|
||||
"ajouta",
|
||||
"reprit",
|
||||
"fit",
|
||||
"lança",
|
||||
"souffla",
|
||||
"répliqua",
|
||||
"interrogea",
|
||||
"hurla",
|
||||
"poursuivit",
|
||||
"continua",
|
||||
"déclara",
|
||||
"expliqua",
|
||||
"protesta",
|
||||
"soupira",
|
||||
"chuchota",
|
||||
"insista",
|
||||
"s'écria",
|
||||
"s’écria",
|
||||
"s'exclama",
|
||||
"s’exclama",
|
||||
"objecta",
|
||||
"conclut",
|
||||
"dis",
|
||||
"dit-on",
|
||||
];
|
||||
|
||||
/// The words that elide before a vowel, and their elided form.
|
||||
const ELIDING: &[(&str, &str)] =
|
||||
&[("le", "l"), ("la", "l"), ("de", "d"), ("je", "j"), ("me", "m"), ("te", "t"), ("se", "s"), ("ne", "n"), ("que", "qu")];
|
||||
|
||||
/// Words starting with a vowel that don't take an elision (`le onze`, `le oui`, `de ouate`).
|
||||
const NO_ELISION: &[&str] = &["onze", "onzième", "onzièmes", "oui", "ouistiti", "ouistitis", "ouate", "ouates", "uhlan", "uhlans"];
|
||||
|
||||
/// Words with a mute `h`, which take an elision (`l’homme`, `d’habitude`, `j’habite`). Only these
|
||||
/// are flagged: an `h` word outside the list may be aspirated (`le hibou`, `la hache`, `le
|
||||
/// héros`), and staying quiet is the safe side.
|
||||
const MUTE_H: &[&str] = &[
|
||||
"homme",
|
||||
"hommes",
|
||||
"heure",
|
||||
"heures",
|
||||
"histoire",
|
||||
"histoires",
|
||||
"hiver",
|
||||
"hivers",
|
||||
"hôtel",
|
||||
"hôtels",
|
||||
"herbe",
|
||||
"herbes",
|
||||
"habitude",
|
||||
"habitudes",
|
||||
"habitant",
|
||||
"habitants",
|
||||
"habit",
|
||||
"habits",
|
||||
"hôpital",
|
||||
"hôpitaux",
|
||||
"humain",
|
||||
"humains",
|
||||
"humanité",
|
||||
"honneur",
|
||||
"honneurs",
|
||||
"horizon",
|
||||
"horizons",
|
||||
"huile",
|
||||
"huiles",
|
||||
"hypothèse",
|
||||
"hypothèses",
|
||||
"harmonie",
|
||||
"héritage",
|
||||
"héroïne",
|
||||
"héroïnes",
|
||||
"hésitation",
|
||||
"hommage",
|
||||
"hommages",
|
||||
"horaire",
|
||||
"horaires",
|
||||
"horreur",
|
||||
"horreurs",
|
||||
"humeur",
|
||||
"humour",
|
||||
"hygiène",
|
||||
"hymne",
|
||||
"habiter",
|
||||
"hériter",
|
||||
"hésiter",
|
||||
"habiller",
|
||||
"honorer",
|
||||
"habite",
|
||||
"habites",
|
||||
"habitent",
|
||||
"habitais",
|
||||
"habitait",
|
||||
"hésite",
|
||||
"hésites",
|
||||
"hésitent",
|
||||
"hésitais",
|
||||
"hésitait",
|
||||
"habille",
|
||||
"habillent",
|
||||
"honore",
|
||||
"hier",
|
||||
"hôte",
|
||||
"hôtes",
|
||||
"hôtesse",
|
||||
"humidité",
|
||||
"haleine",
|
||||
"hebdomadaire",
|
||||
"hectare",
|
||||
"hectares",
|
||||
"hélicoptère",
|
||||
"hémisphère",
|
||||
"heureux",
|
||||
"heureuse",
|
||||
"hippopotame",
|
||||
"hirondelle",
|
||||
"honnête",
|
||||
"honnêteté",
|
||||
"huître",
|
||||
"huîtres",
|
||||
"humble",
|
||||
"humilité",
|
||||
"hydrogène",
|
||||
"hypocrite",
|
||||
"horloge",
|
||||
"hôtellerie",
|
||||
"hérédité",
|
||||
"historien",
|
||||
"historique",
|
||||
"humanitaire",
|
||||
"hormone",
|
||||
"hormones",
|
||||
"hospitalité",
|
||||
];
|
||||
|
||||
fn issue(start: usize, end: usize, message: String, suggestions: Vec<String>) -> Issue {
|
||||
Issue { start, end, kind: IssueKind::Grammar, message, suggestions, lang: ProofLang::from_tag(Some("fr-FR")) }
|
||||
}
|
||||
|
||||
/// Is `c` a space that doesn't break (or a thin space some writers use instead)?
|
||||
fn is_fixed_space(c: char) -> bool {
|
||||
matches!(c, '\u{A0}' | '\u{202F}' | '\u{2007}' | '\u{2009}' | '\u{2060}')
|
||||
}
|
||||
|
||||
/// The byte range of the whitespace-delimited token around byte `i` of `text`.
|
||||
fn token_bounds(text: &str, i: usize) -> (usize, usize) {
|
||||
let start = text.get(..i).and_then(|t| t.char_indices().rev().find(|(_, c)| c.is_whitespace())).map_or(0, |(k, c)| k + c.len_utf8());
|
||||
let end = text.get(i..).and_then(|t| t.find(char::is_whitespace)).map_or(text.len(), |k| i + k);
|
||||
(start, end)
|
||||
}
|
||||
|
||||
/// The whitespace-delimited token around byte `i` of `text`.
|
||||
fn token_at(text: &str, i: usize) -> &str {
|
||||
let (start, end) = token_bounds(text, i);
|
||||
text.get(start..end).unwrap_or("")
|
||||
}
|
||||
|
||||
/// Is `token` a web or e-mail address, a path or an HTML entity, where punctuation isn't prose?
|
||||
fn is_address(token: &str) -> bool {
|
||||
token.contains("://") || token.contains('@') || token.starts_with("www.") || token.contains('&') || token.contains('\\')
|
||||
}
|
||||
|
||||
/// `«` + text + `»` in a message, with French spacing.
|
||||
fn quoted(s: &str) -> String {
|
||||
format!("«{NBSP}{s}{NBSP}»")
|
||||
}
|
||||
|
||||
/// `;` `!` `?` `:` without the non-breaking space French puts before them.
|
||||
/// Quebec typography (`quebec`) puts no space before `;` `!` `?`, only before `:`.
|
||||
fn high_punctuation(text: &str, quebec: bool, v: &mut Vec<Issue>) {
|
||||
let mut token: Option<(usize, usize, bool)> = None;
|
||||
for (i, p) in text.char_indices() {
|
||||
if !matches!(p, ';' | ':' | '!' | '?') || (quebec && p != ':') {
|
||||
continue;
|
||||
}
|
||||
let before = text.get(..i).and_then(|t| t.chars().next_back());
|
||||
let after = text.get(i + p.len_utf8()..).and_then(|t| t.chars().next());
|
||||
// One look per token, so a long run of marks stays linear.
|
||||
let address = match token {
|
||||
Some((start, end, address)) if start <= i && i < end => address,
|
||||
_ => {
|
||||
let (start, end) = token_bounds(text, i);
|
||||
let address = is_address(text.get(start..end).unwrap_or(""));
|
||||
token = Some((start, end, address));
|
||||
address
|
||||
}
|
||||
};
|
||||
if address {
|
||||
continue;
|
||||
}
|
||||
let (space, kind) = if p == ':' { (NBSP, "insécable") } else { (NNBSP, "fine insécable") };
|
||||
let message = format!("Espace {kind} attendue avant {}", quoted(&p.to_string()));
|
||||
let fix = format!("{space}{p}");
|
||||
// Only a missing space is flagged: an ordinary one stays quiet until typing turns it into
|
||||
// a non-breaking one by itself (French AutoFormat).
|
||||
if before.is_some_and(char::is_alphabetic) {
|
||||
// `10:30`, `a:b`, `C:` and `x;y` aren't prose: the mark must end the word.
|
||||
let ends = match p {
|
||||
':' => after.is_none_or(char::is_whitespace),
|
||||
_ => after.is_none_or(|a| a.is_whitespace() || matches!(a, '!' | '?' | '»' | '"' | '”' | ')')),
|
||||
};
|
||||
if ends {
|
||||
v.push(issue(i, i + p.len_utf8(), message, vec![fix]));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `«` and `»` without a non-breaking space inside.
|
||||
fn guillemets(text: &str, v: &mut Vec<Issue>) {
|
||||
for (i, c) in text.char_indices() {
|
||||
let len = c.len_utf8();
|
||||
match c {
|
||||
'«' => {
|
||||
let mut next = text.get(i + len..).unwrap_or("").chars();
|
||||
let message = format!("Espace insécable attendue après {}", quoted("«"));
|
||||
if next.next().is_some_and(char::is_alphanumeric) {
|
||||
v.push(issue(i, i + len, message, vec![format!("«{NBSP}")]));
|
||||
}
|
||||
}
|
||||
'»' => {
|
||||
let prev = text.get(..i).unwrap_or("").chars().next_back();
|
||||
let message = format!("Espace insécable attendue avant {}", quoted("»"));
|
||||
if prev.is_some_and(|n| n.is_alphanumeric() || matches!(n, '.' | '!' | '?' | '…')) {
|
||||
v.push(issue(i, i + len, message, vec![format!("{NBSP}»")]));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `"…"` around a phrase, where French uses `« … »`.
|
||||
fn straight_quotes(text: &str, v: &mut Vec<Issue>) {
|
||||
let quotes: Vec<usize> = text.match_indices('"').map(|(i, _)| i).collect();
|
||||
// An odd count leaves no telling which quote opens and which closes.
|
||||
if !quotes.len().is_multiple_of(2) {
|
||||
return;
|
||||
}
|
||||
for pair in quotes.chunks(2) {
|
||||
let [a, b] = pair else { continue };
|
||||
let (Some(inner), Some(before), Some(after)) = (text.get(a + 1..*b), text.get(..*a), text.get(b + 1..)) else { continue };
|
||||
let opens = before.chars().next_back().is_none_or(|c| c.is_whitespace() || matches!(c, '(' | '[' | '—' | '–'));
|
||||
let closes = after.chars().next().is_none_or(|c| c.is_whitespace() || matches!(c, '.' | ',' | ';' | ':' | '!' | '?' | ')' | ']' | '…'));
|
||||
let phrase = inner.trim();
|
||||
if !opens || !closes || !phrase.chars().any(char::is_alphabetic) || phrase.chars().count() > 120 || phrase.contains('\n') {
|
||||
continue;
|
||||
}
|
||||
v.push(issue(*a, b + 1, format!("Guillemets français attendus{NBSP}: {}", quoted(phrase)), vec![quoted(phrase)]));
|
||||
}
|
||||
}
|
||||
|
||||
fn repeated_words(text: &str, ws: &[(usize, usize)], v: &mut Vec<Issue>) {
|
||||
for pair in ws.windows(2) {
|
||||
let [(a0, b0), (a1, b1)] = pair else { continue };
|
||||
let (Some(w0), Some(w1), Some(gap)) = (text.get(*a0..*b0), text.get(*a1..*b1), text.get(*b0..*a1)) else { continue };
|
||||
let lower = w0.to_lowercase();
|
||||
let starts_upper = |w: &str| w.chars().next().is_some_and(char::is_uppercase);
|
||||
if !gap.is_empty()
|
||||
&& gap.chars().all(char::is_whitespace)
|
||||
&& w0.chars().all(char::is_alphabetic)
|
||||
&& lower == w1.to_lowercase()
|
||||
&& !ALLOWED_REPEATS.contains(&lower.as_str())
|
||||
// `de De…`, `Bora Bora`: a capitalized second word is a name.
|
||||
&& !starts_upper(w1)
|
||||
{
|
||||
v.push(issue(*a0, *b1, format!("Mot répété{NBSP}: {}", quoted(w1)), vec![w0.to_string()]));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Is `prev`, before a period, an abbreviation, an initial, a number or a Roman numeral (after
|
||||
/// which a lower-case word doesn't start a sentence)?
|
||||
fn abbreviation_or_number(prev: &str) -> bool {
|
||||
prev.chars().count() <= 1
|
||||
|| prev.chars().any(|c| c.is_ascii_digit())
|
||||
|| prev.chars().all(|c| matches!(c, 'I' | 'V' | 'X' | 'L' | 'C' | 'D' | 'M'))
|
||||
|| ABBREVIATIONS.contains(&prev.to_lowercase().as_str())
|
||||
}
|
||||
|
||||
/// Does `gap`, between the words `prev` and `next`, end a sentence: a `.`, `!` or `?` (French
|
||||
/// puts a space before the last two), then a space, with only quotes and brackets around? Not
|
||||
/// an ellipsis, not after an abbreviation; for `!` and `?`, not after an interjection, not before
|
||||
/// a closing quote (dialogue goes on: `« Tu viens ? » demanda-t-elle`), not before an inversion
|
||||
/// or a speech verb (`Quoi ? dit-il`, `— Viens ! cria-t-on`), and never in a `dialogue` line (one
|
||||
/// opening with a dash).
|
||||
fn ends_sentence(gap: &str, prev: &str, next: &str, dialogue: bool) -> bool {
|
||||
let closing = ['"', '”', '’', '\'', ')', '»', ']'];
|
||||
let t = gap.trim_start_matches(|c: char| c.is_whitespace() || is_fixed_space(c) || closing.contains(&c));
|
||||
let Some(end) = t.chars().next() else { return false };
|
||||
if !matches!(end, '.' | '!' | '?') || t.starts_with("..") {
|
||||
return false;
|
||||
}
|
||||
if end == '.' && abbreviation_or_number(prev) {
|
||||
return false;
|
||||
}
|
||||
let exclamation = end != '.';
|
||||
let lower_next = next.to_lowercase();
|
||||
if exclamation
|
||||
&& (dialogue
|
||||
|| INTERJECTIONS.contains(&prev.to_lowercase().as_str())
|
||||
|| INVERTED.iter().any(|p| lower_next.ends_with(p))
|
||||
|| SPEECH_VERBS.contains(&lower_next.as_str()))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let rest = t.trim_start_matches(['.', '!', '?']);
|
||||
let after_marks = rest.trim_start_matches(is_fixed_space);
|
||||
if after_marks.starts_with(closing) {
|
||||
if exclamation {
|
||||
return false;
|
||||
}
|
||||
return ends_sentence_after(after_marks.trim_start_matches(|c: char| closing.contains(&c) || is_fixed_space(c)));
|
||||
}
|
||||
ends_sentence_after(rest)
|
||||
}
|
||||
|
||||
/// Is `rest` (after the final mark) a space, then nothing but opening quotes and brackets?
|
||||
fn ends_sentence_after(rest: &str) -> bool {
|
||||
rest.starts_with(char::is_whitespace)
|
||||
&& rest.trim_start().chars().all(|c| c.is_whitespace() || is_fixed_space(c) || matches!(c, '"' | '“' | '«' | '(' | '[' | '—' | '–'))
|
||||
}
|
||||
|
||||
fn sentence_capitals(text: &str, ws: &[(usize, usize)], v: &mut Vec<Issue>) {
|
||||
let dialogue = text.trim_start().starts_with(['—', '–']);
|
||||
for pair in ws.windows(2) {
|
||||
let [(a0, b0), (a1, b1)] = pair else { continue };
|
||||
let (Some(prev), Some(gap), Some(w)) = (text.get(*a0..*b0), text.get(*b0..*a1), text.get(*a1..*b1)) else { continue };
|
||||
let word_like = w.chars().all(|c| c.is_alphabetic() || matches!(c, '\'' | '’' | '-'));
|
||||
if word_like && w.chars().next().is_some_and(char::is_lowercase) && ends_sentence(gap, prev, w, dialogue) && !is_address(token_at(text, *a1))
|
||||
{
|
||||
let fixed: String = w.chars().next().map(|f| f.to_uppercase().chain(w.chars().skip(1)).collect()).unwrap_or_default();
|
||||
v.push(issue(*a1, *b1, "Majuscule attendue en début de phrase".into(), vec![fixed]));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Does `w` (lower case) start with a sound that makes `le`, `de`, `que`… elide?
|
||||
fn takes_elision(w: &str) -> bool {
|
||||
let Some(first) = w.chars().next() else { return false };
|
||||
if NO_ELISION.contains(&w) {
|
||||
return false;
|
||||
}
|
||||
match first {
|
||||
'a' | 'à' | 'â' | 'ä' | 'e' | 'é' | 'è' | 'ê' | 'ë' | 'i' | 'î' | 'ï' | 'o' | 'ô' | 'ö' | 'u' | 'ù' | 'û' | 'ü' | 'œ' | 'æ' => {
|
||||
true
|
||||
}
|
||||
'h' => MUTE_H.contains(&w),
|
||||
// Only `y` itself (`j’y vais`): `le yaourt`, `de yoga`.
|
||||
'y' => w == "y",
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
fn elisions(text: &str, ws: &[(usize, usize)], v: &mut Vec<Issue>) {
|
||||
for pair in ws.windows(2) {
|
||||
let [(a0, b0), (a1, b1)] = pair else { continue };
|
||||
let (Some(w0), Some(w1), Some(gap)) = (text.get(*a0..*b0), text.get(*a1..*b1), text.get(*b0..*a1)) else { continue };
|
||||
if gap.is_empty() || !gap.chars().all(|c| c == ' ') {
|
||||
continue;
|
||||
}
|
||||
let lower0 = w0.to_lowercase();
|
||||
let Some((_, elided)) = ELIDING.iter().find(|(full, _)| *full == lower0) else { continue };
|
||||
// `le`/`Le` only, not `LE`; never before a proper noun (`de Orléans`) or a capital.
|
||||
let capital = w0.chars().next().is_some_and(char::is_uppercase);
|
||||
if w0.chars().skip(1).any(char::is_uppercase) || !w1.chars().next().is_some_and(char::is_lowercase) {
|
||||
continue;
|
||||
}
|
||||
if !w1.chars().all(|c| c.is_alphabetic() || c == '-') {
|
||||
continue;
|
||||
}
|
||||
let lower1 = w1.to_lowercase();
|
||||
// `le un`, `la une` (the number, the front page); a single letter only where it is a word
|
||||
// the elision is certain for (`n’a`, `qu’a`, `j’y`).
|
||||
if matches!(lower0.as_str(), "le" | "la") && matches!(lower1.as_str(), "un" | "une") {
|
||||
continue;
|
||||
}
|
||||
let certain = (lower1 == "y" && matches!(lower0.as_str(), "je" | "me" | "te" | "se" | "ne"))
|
||||
|| (lower1 == "a" && matches!(lower0.as_str(), "ne" | "que"));
|
||||
if lower1.chars().count() == 1 && !certain {
|
||||
continue;
|
||||
}
|
||||
if !takes_elision(&lower1) {
|
||||
continue;
|
||||
}
|
||||
let head = if capital { crate::affix::capitalize(elided) } else { (*elided).to_string() };
|
||||
let fixed = format!("{head}’{w1}");
|
||||
v.push(issue(*a0, *b1, format!("Élision{NBSP}: {}", quoted(&fixed)), vec![fixed]));
|
||||
}
|
||||
}
|
||||
|
||||
/// Grammar issues in a paragraph of French text (France's typography), in order.
|
||||
pub fn check(text: &str) -> Vec<Issue> {
|
||||
check_in(text, ProofLang::from_tag(Some("fr-FR")))
|
||||
}
|
||||
|
||||
/// Grammar issues in a French Language pack locale, with Quebec typography in `fr-CA`.
|
||||
/// Other locales have no French issues; the original locale is retained on every issue.
|
||||
pub fn check_in(text: &str, lang: ProofLang) -> Vec<Issue> {
|
||||
let Some(locale) = lang.pack_locale().filter(|l| l.primary() == "fr") else { return Vec::new() };
|
||||
let ws: Vec<(usize, usize)> = words(text);
|
||||
let mut v = Vec::new();
|
||||
high_punctuation(text, crate::lang::region(locale.as_str()).is_some_and(|r| r.eq_ignore_ascii_case("CA")), &mut v);
|
||||
guillemets(text, &mut v);
|
||||
straight_quotes(text, &mut v);
|
||||
repeated_words(text, &ws, &mut v);
|
||||
sentence_capitals(text, &ws, &mut v);
|
||||
elisions(text, &ws, &mut v);
|
||||
for i in &mut v {
|
||||
i.lang = lang;
|
||||
}
|
||||
v.sort_by_key(|i| (i.start, i.end));
|
||||
v
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The issues of `text` as (flagged text, first suggestion).
|
||||
fn found(text: &str) -> Vec<(String, String)> {
|
||||
check(text)
|
||||
.iter()
|
||||
.map(|i| (text.get(i.start..i.end).unwrap_or("?").to_string(), i.suggestions.first().cloned().unwrap_or_default()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn quiet(text: &str) {
|
||||
let v = check(text);
|
||||
assert!(v.is_empty(), "{text:?} → {v:?}");
|
||||
}
|
||||
|
||||
fn one(text: &str, flagged: &str, fix: &str) {
|
||||
assert_eq!(found(text), [(flagged.to_string(), fix.to_string())], "{text:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_space_before_high_punctuation() {
|
||||
one("Bonjour!", "!", "\u{202F}!");
|
||||
one("Tu viens?", "?", "\u{202F}?");
|
||||
one("Il pleut; il vente.", ";", "\u{202F};");
|
||||
one("Note: rien.", ":", "\u{A0}:");
|
||||
// `?!`: only the first mark needs the space.
|
||||
one("Quoi?!", "?", "\u{202F}?");
|
||||
assert!(check("Bonjour!").iter().all(|i| i.lang == ProofLang::from_tag(Some("fr-FR")) && i.message.contains("fine insécable")));
|
||||
assert!(check("Note: rien.").iter().all(|i| i.message.contains("insécable") && !i.message.contains("fine")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ordinary_space_stays_quiet_until_french_autoformat() {
|
||||
// Typing can't produce a non-breaking space yet, so an ordinary one is accepted.
|
||||
quiet("Vraiment ? Bonjour ! Il pleut ; note : rien.");
|
||||
quiet("Il dit « oui » hier.");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quebec_has_no_space_before_semicolon_exclamation_and_question() {
|
||||
let fr_ca = |t: &str| check_in(t, ProofLang::from_tag(Some("fr-CA")));
|
||||
assert!(fr_ca("Bonjour! Tu viens? Il pleut; il vente.").is_empty(), "{:?}", fr_ca("Bonjour! Tu viens?"));
|
||||
// The colon and the guillemets still want their space in Quebec.
|
||||
let v = fr_ca("Note: «oui».");
|
||||
assert_eq!(v.len(), 3, "{v:?}");
|
||||
assert!(v.iter().all(|i| i.lang == ProofLang::from_tag(Some("fr-CA"))), "{v:?}");
|
||||
assert_eq!(check_in("Bonjour!", ProofLang::from_tag(Some("fr-FR"))).len(), 1, "France still wants the space");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn high_punctuation_stays_quiet() {
|
||||
quiet("Bonjour\u{202F}! Tu viens\u{202F}? Il pleut\u{202F}; note\u{A0}: rien.");
|
||||
quiet("Bonjour\u{A0}! Quoi\u{202F}?! Ah\u{2009}!");
|
||||
quiet("Il est 10:30.");
|
||||
quiet("Voir https://exemple.org:8080/a?b=c pour la suite.");
|
||||
quiet("Écrire à contact@exemple.org!");
|
||||
quiet("Super :) et ;-) aussi :D");
|
||||
quiet("a:b et x;y");
|
||||
quiet("Le fichier C:\\dossier est là.");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_space_inside_guillemets() {
|
||||
assert_eq!(found("Il dit «oui» hier."), [("«".to_string(), "«\u{A0}".to_string()), ("»".to_string(), "\u{A0}»".to_string())]);
|
||||
quiet("Il dit «\u{A0}oui\u{A0}» hier.");
|
||||
quiet("Il dit «\u{202F}oui\u{202F}» hier.");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn straight_quotes_become_guillemets() {
|
||||
one("Il a dit \"bonjour\" hier.", "\"bonjour\"", "«\u{A0}bonjour\u{A0}»");
|
||||
one("\"Bonne idée\", dit-elle.", "\"Bonne idée\"", "«\u{A0}Bonne idée\u{A0}»");
|
||||
// Inch marks and unbalanced quotes are left alone.
|
||||
quiet("Un écran de 27\" et un de 32\" ici.");
|
||||
quiet("Il a dit \"bonjour hier.");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeated_words_are_flagged() {
|
||||
one("Le le chat dort.", "Le le", "Le");
|
||||
one("Je pense que que tu viens.", "que que", "que");
|
||||
one("Il mange la la pomme.", "la la", "la");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deliberate_repetitions_stay_quiet() {
|
||||
quiet("Nous nous lavons et vous vous trompez.");
|
||||
quiet("Si si, très très bien.");
|
||||
quiet("Ah ah, bla bla.");
|
||||
quiet("Je crois que qu’il viendra.");
|
||||
quiet("Le livre de De Gaulle.");
|
||||
quiet("Nous partons à Bora Bora.");
|
||||
quiet("Ils ont dit bye bye. Tchin tchin\u{202F}!");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sentence_capitals_are_flagged() {
|
||||
one("Il pleut. il fait froid.", "il", "Il");
|
||||
one("Il pleut\u{202F}! il fait froid.", "il", "Il");
|
||||
one("Tu viens\u{202F}? on part.", "on", "On");
|
||||
one("Il pleut. l’orage arrive.", "l’orage", "L’orage");
|
||||
one("Il pleut. «\u{A0}tout va bien\u{A0}», dit-il.", "tout", "Tout");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sentence_capitals_stay_quiet() {
|
||||
quiet("Voir p. 12 et cf. la note, etc. puis la suite.");
|
||||
quiet("M. le maire est là.");
|
||||
quiet("Il attend… puis part. Il attend... puis part.");
|
||||
quiet("«\u{A0}Tu viens\u{202F}?\u{A0}» demanda-t-elle.");
|
||||
quiet("Ah\u{202F}! que c’est beau.");
|
||||
quiet("Quoi\u{202F}? dit-il.");
|
||||
quiet("Tu viens\u{202F}? demanda le voisin.");
|
||||
quiet("— Tu viens\u{202F}? reprends-tu, inquiet.");
|
||||
quiet("– Viens\u{202F}! on part.");
|
||||
quiet("Voir www.exemple.fr pour la suite.");
|
||||
quiet("En 2026. ensuite rien.");
|
||||
quiet("il commence en minuscule.");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_elisions_are_flagged() {
|
||||
one("Il refuse de avoir peur.", "de avoir", "d’avoir");
|
||||
one("Je ai faim.", "Je ai", "J’ai");
|
||||
one("Voici le homme.", "le homme", "l’homme");
|
||||
one("Je sais que il viendra.", "que il", "qu’il");
|
||||
one("Le arbre est grand.", "Le arbre", "L’arbre");
|
||||
one("Il ne a pas faim.", "ne a", "n’a");
|
||||
one("Bon, je y vais.", "je y", "j’y");
|
||||
one("Il se est levé.", "se est", "s’est");
|
||||
one("Voici la école.", "la école", "l’école");
|
||||
one("Il me aime.", "me aime", "m’aime");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aspirated_h_and_other_exceptions_stay_quiet() {
|
||||
for w in [
|
||||
"hibou",
|
||||
"héros",
|
||||
"haricot",
|
||||
"hasard",
|
||||
"haut",
|
||||
"hall",
|
||||
"hamac",
|
||||
"hangar",
|
||||
"hockey",
|
||||
"homard",
|
||||
"huit",
|
||||
"hérisson",
|
||||
"hors-jeu",
|
||||
"onze",
|
||||
"oui",
|
||||
"yaourt",
|
||||
] {
|
||||
quiet(&format!("Voici le {w}."));
|
||||
}
|
||||
// hiérarchie has an aspirated h, despite the mute h in hiéroglyphe:
|
||||
// https://www.academie-francaise.fr/le-hieroglyphe-pour-lhieroglyphe
|
||||
for w in ["honte", "hache", "harpe", "hausse", "hiérarchie"] {
|
||||
quiet(&format!("Voici la {w}."));
|
||||
}
|
||||
quiet("Une question de hiérarchie.");
|
||||
quiet("Le onze de France. À la une du journal.");
|
||||
quiet("Il vient de Orléans.");
|
||||
quiet("De a à z, le a et le b.");
|
||||
quiet("Le y et le x sont des variables. La dérivée de y.");
|
||||
quiet("Je mange de la viande.");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_input_never_panics() {
|
||||
for t in ["", " ", "!", " !", "«", "»", " »", "« ", "\"", "\"\"", ". a", "de", "de ", "\u{202F}?", "é!é", "« » « »", ":", " :", "a :)"]
|
||||
{
|
||||
let _ = check(t);
|
||||
}
|
||||
// A long run of marks in one token: linear, not one token scan per mark.
|
||||
let run = format!("mot{}", "?".repeat(200_000));
|
||||
assert_eq!(check(&run).len(), 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
//! French proofing through the shared Language pack cache.
|
||||
//!
|
||||
//! A French locale remains [`ProofLang::Pack`]: dictionary selection, installation, reloads,
|
||||
//! memory limits and hyphenation use the same paths as other packs. This module adds French
|
||||
//! elisions, accent-oriented suggestions and conservative typography, including Quebec spacing.
|
||||
//! No dictionary or hyphenation data is bundled here.
|
||||
|
||||
pub mod grammar;
|
||||
mod suggest;
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::unwrap_used)]
|
||||
pub(crate) mod test_dict;
|
||||
|
||||
use crate::affix::AffixDict;
|
||||
use crate::{Options, ProofLang};
|
||||
|
||||
pub use suggest::suggest_in;
|
||||
|
||||
/// Words after whose elision a user-dictionary entry is accepted. Ordinary words and their
|
||||
/// elisions are always decided by the dictionary (`l'arbre`, but not `l'arbres`).
|
||||
const ELISIONS: &[&str] = &["l", "d", "j", "m", "t", "s", "n", "c", "qu", "jusqu", "lorsqu", "puisqu", "quoiqu", "presqu", "quelqu"];
|
||||
|
||||
/// Check French spelling in the installed France/generic pack, with the default options.
|
||||
/// Regional callers should use [`crate::is_correct_in`] with their full locale.
|
||||
pub fn is_correct(word: &str) -> bool {
|
||||
crate::is_correct_in(word, ProofLang::from_tag(Some("fr-FR")))
|
||||
}
|
||||
|
||||
/// French suggestions from the installed France/generic pack, best first, at most `max`.
|
||||
/// Regional callers should use [`crate::suggest_in`] with their full locale.
|
||||
pub fn suggest(word: &str, max: usize) -> Vec<String> {
|
||||
crate::suggest_in(word, max, ProofLang::from_tag(Some("fr-FR")))
|
||||
}
|
||||
|
||||
/// Check against a supplied dictionary, without changing any installed pack or cache.
|
||||
pub fn is_correct_with(d: &AffixDict, word: &str) -> bool {
|
||||
check(d, &crate::composed(word), &Options::default())
|
||||
}
|
||||
|
||||
pub(crate) fn check(d: &AffixDict, word: &str, opts: &Options) -> bool {
|
||||
let Some(w) = crate::spelling::word_to_check(d, word, opts) else { return true };
|
||||
// A regional dictionary may store the curly apostrophe without ICONV. Honor that entry
|
||||
// before the French ASCII-apostrophe fallback.
|
||||
if known(d, w) {
|
||||
return true;
|
||||
}
|
||||
let original = w;
|
||||
let w = w.replace('’', "'");
|
||||
if known(d, &w) {
|
||||
return true;
|
||||
}
|
||||
if let Some((head, tail)) = w.split_once('\'')
|
||||
&& ELISIONS.contains(&head.to_lowercase().as_str())
|
||||
&& !tail.is_empty()
|
||||
&& !tail.contains('\'')
|
||||
&& crate::in_user_dictionary(&tail.to_lowercase())
|
||||
{
|
||||
return true;
|
||||
}
|
||||
original.contains('-') && original.split('-').all(|p| !p.is_empty() && (p.chars().count() <= 1 || known(d, p) || known(d, &p.replace('’', "'"))))
|
||||
}
|
||||
|
||||
fn known(d: &AffixDict, word: &str) -> bool {
|
||||
d.check(word) || crate::in_user_dictionary(&word.to_lowercase())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn original_french_words_and_elisions() {
|
||||
let d = test_dict::dictionary();
|
||||
for word in [
|
||||
"maison",
|
||||
"maisons",
|
||||
"école",
|
||||
"écoles",
|
||||
"grand",
|
||||
"grande",
|
||||
"grands",
|
||||
"grandes",
|
||||
"aimer",
|
||||
"aime",
|
||||
"aimons",
|
||||
"aiment",
|
||||
"suis",
|
||||
"est",
|
||||
"sommes",
|
||||
"sont",
|
||||
"a",
|
||||
"avons",
|
||||
"ont",
|
||||
"Paris",
|
||||
"Montréal",
|
||||
"œuvre",
|
||||
"sœur",
|
||||
"aujourd'hui",
|
||||
"aujourd’hui",
|
||||
"peut-être",
|
||||
"arc-en-ciel",
|
||||
"km",
|
||||
"Maison",
|
||||
"MAISON",
|
||||
"SNCF",
|
||||
"2026",
|
||||
"très",
|
||||
"rivière",
|
||||
"l'arbre",
|
||||
"l’arbre",
|
||||
"L'arbre",
|
||||
"d'enfants",
|
||||
"l'homme",
|
||||
"qu'elle",
|
||||
"qu’il",
|
||||
"j'aime",
|
||||
"j’ai",
|
||||
"d'avoir",
|
||||
"l'école",
|
||||
"jusqu'à",
|
||||
"maison-école",
|
||||
"est-il",
|
||||
"a-t-il",
|
||||
] {
|
||||
assert!(is_correct_with(&d, word), "{word}");
|
||||
}
|
||||
for word in [
|
||||
"maisonn",
|
||||
"ecole",
|
||||
"arbrre",
|
||||
"beaucoups",
|
||||
"aimmer",
|
||||
"soeur",
|
||||
"Km",
|
||||
"grandd",
|
||||
"aim",
|
||||
"l'hasard",
|
||||
"l'chat",
|
||||
"l'arbres",
|
||||
"l'arbrre",
|
||||
"qu'maison",
|
||||
"maison-ecole",
|
||||
"maison--école",
|
||||
] {
|
||||
assert!(!is_correct_with(&d, word), "{word}");
|
||||
}
|
||||
assert!(is_correct_with(&d, "e\u{301}cole"));
|
||||
assert!(!is_correct_with(&d, "maison\u{338}"), "a trailing mark is part of the word");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curly_apostrophes_in_compounds_keep_exact_dictionary_parts() {
|
||||
let d = AffixDict::from_hunspell("SET UTF-8\n", "4\naujourd’hui\nécole\ncafé\nl'école\n", &[]).unwrap();
|
||||
for word in ["aujourd’hui-école", "aujourd’hui-e\u{301}cole", "café-aujourd’hui", "l’école-aujourd’hui"] {
|
||||
assert!(is_correct_with(&d, word), "{word}");
|
||||
}
|
||||
for word in ["aujourd’hui-écolle", "aujourd’hui--école", "aujourd'hui-école"] {
|
||||
assert!(!is_correct_with(&d, word), "{word}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_curly_apostrophe_without_iconv() {
|
||||
let d = AffixDict::from_hunspell("SET UTF-8\n", "1\naujourd’hui\n", &[]).unwrap();
|
||||
assert!(is_correct_with(&d, "aujourd’hui"));
|
||||
assert!(!is_correct_with(&d, "aujourd’huui"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn user_word_after_an_elision() {
|
||||
let d = test_dict::dictionary();
|
||||
let word = "zxqmotadaptfr";
|
||||
assert!(!is_correct_with(&d, word) && !is_correct_with(&d, &format!("l'{word}")));
|
||||
crate::add_word(word);
|
||||
assert!(is_correct_with(&d, word) && is_correct_with(&d, &format!("l'{word}")) && is_correct_with(&d, &format!("d’{word}")));
|
||||
assert!(!is_correct_with(&d, &format!("chat'{word}")));
|
||||
crate::remove_word(word);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn options_and_missing_dictionary() {
|
||||
let d = test_dict::dictionary();
|
||||
let defaults = Options::default();
|
||||
let strict = Options { ignore_uppercase: false, ignore_numbers: false, ..defaults };
|
||||
assert!(check(&d, "SNCF", &defaults) && check(&d, "mp3x", &defaults));
|
||||
assert!(!check(&d, "SNCF", &strict) && !check(&d, "mp3x", &strict));
|
||||
assert!(check(&d, "MAISON", &strict) && check(&d, "2026", &strict));
|
||||
for word in ["école", "l'arbre", "xqzv", "SNCF", ""] {
|
||||
assert!(check(&AffixDict::default(), word, &strict));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
//! French tuning of the shared, bounded affix suggestion engine.
|
||||
|
||||
use crate::affix::AffixDict;
|
||||
use crate::affix_suggest::{Split, Tuning};
|
||||
|
||||
/// Short words often run into the next one (`et la`, `de Paris`, `pour moi`).
|
||||
const LEADING_WORDS: &[&str] = &[
|
||||
"à", "a", "au", "aux", "de", "du", "des", "le", "la", "les", "un", "une", "et", "ou", "où", "en", "y", "ce", "se", "ne", "je", "tu", "il", "on",
|
||||
"nous", "vous", "ils", "elle", "par", "pour", "sur", "sous", "dans", "avec", "sans", "chez", "vers", "entre", "très", "plus", "moins", "bien",
|
||||
"pas", "que", "qui", "mais", "donc", "car", "si", "son", "sa", "ses", "mon", "ma", "mes", "ton", "ta", "tes", "est", "tout", "tous", "toute",
|
||||
"comme", "quand", "puis", "encore", "déjà", "jamais", "toujours",
|
||||
];
|
||||
/// Short words often run into the one before (`dis-moi` without the hyphen, `là-bas`, or a
|
||||
/// dropped space: `pourmoi` → `pour moi`).
|
||||
const TRAILING_WORDS: &[&str] =
|
||||
&["moi", "toi", "lui", "elle", "nous", "vous", "eux", "le", "la", "les", "en", "y", "là", "ci", "il", "on", "ils", "elles", "est", "et"];
|
||||
|
||||
const TUNING: Tuning = Tuning {
|
||||
split: Split::Near { leading: LEADING_WORDS, trailing: TRAILING_WORDS },
|
||||
alphabet: "esaitnrulodcpmévqfbghjàxèêyçôîâûùœ",
|
||||
..Tuning::DEFAULT
|
||||
};
|
||||
|
||||
/// French suggestions from a supplied dictionary; keeps the writer's apostrophe and case.
|
||||
/// Without a typed apostrophe, keep the dictionary's OCONV output unchanged.
|
||||
pub fn suggest_in(d: &AffixDict, word: &str, max: usize) -> Vec<String> {
|
||||
let word = crate::composed(word);
|
||||
let apostrophe = if word.contains('’') {
|
||||
Some('’')
|
||||
} else if word.contains('\'') {
|
||||
Some('\'')
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let mut out = Vec::new();
|
||||
for text in crate::affix_suggest::suggest_in(d, &word, max, &TUNING) {
|
||||
let styled: String = text.chars().map(|c| if c == '\'' || c == '’' { apostrophe.unwrap_or(c) } else { c }).collect();
|
||||
// A pack may spell only one apostrophe and have no ICONV. Keep its valid output
|
||||
// rather than turn it back into the spelling mistake the caller is correcting.
|
||||
let text = if styled.split(' ').all(|p| d.can_suggest_cased(p, p)) { styled } else { text };
|
||||
if text != word && !out.contains(&text) {
|
||||
out.push(text);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn french_accents_confusions_splits_and_elisions() {
|
||||
let d = super::super::test_dict::dictionary();
|
||||
for (typo, expected) in [
|
||||
("ecole", "école"),
|
||||
("riviere", "rivière"),
|
||||
("soeur", "sœur"),
|
||||
("maisonn", "maison"),
|
||||
("pourmoi", "pour moi"),
|
||||
("l'arbrre", "l'arbre"),
|
||||
("l’arbrre", "l’arbre"),
|
||||
] {
|
||||
let got = suggest_in(&d, typo, 8);
|
||||
assert!(got.iter().any(|s| s == expected), "{typo}: {got:?}");
|
||||
}
|
||||
assert!(suggest_in(&d, "e\u{301}cole", 4).iter().all(|s| s != "école"));
|
||||
assert!(suggest_in(&d, "ecole", 0).is_empty());
|
||||
assert!(suggest_in(&d, &"a".repeat(41), 4).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curly_dictionary_without_iconv_remains_suggestible() {
|
||||
let d = AffixDict::from_hunspell("SET UTF-8\n", "1\naujourd’hui\n", &[]).unwrap();
|
||||
assert!(suggest_in(&d, "aujourd’huui", 4).iter().any(|s| s == "aujourd’hui"));
|
||||
assert!(suggest_in(&d, "aujourd'hui", 4).iter().any(|s| s == "aujourd’hui"));
|
||||
}
|
||||
|
||||
/// The French wrapper must retain the shared engine's missing-apostrophe fix and the
|
||||
/// dictionary's output conversion when the writer supplied no apostrophe style.
|
||||
#[test]
|
||||
fn missing_apostrophe_keeps_dictionary_output_and_shared_ranking() {
|
||||
let aff = "SET UTF-8\nFLAG long\nWORDCHARS -’'\nICONV 1\nICONV ’ '\nOCONV 1\nOCONV ' ’\n\
|
||||
PFX j' Y 1\nPFX j' 0 j' .\nPFX l' Y 1\nPFX l' 0 l' .\n";
|
||||
let d = AffixDict::from_hunspell(aff, "5\nadore/j'\nami/l'\njade\nj\nl\n", &[]).unwrap();
|
||||
for (word, want, space) in
|
||||
[("Jadore", "J’adore", "J adore"), ("jadore", "j’adore", "j adore"), ("JADORE", "J’ADORE", "J ADORE"), ("lami", "l’ami", "l ami")]
|
||||
{
|
||||
for max in [0, 1, 6] {
|
||||
let got = suggest_in(&d, word, max);
|
||||
assert!(got.len() <= max, "{word}: {got:?}");
|
||||
if max == 0 {
|
||||
assert!(got.is_empty());
|
||||
} else {
|
||||
assert_eq!(got.first().map(String::as_str), Some(want), "{word}: {got:?}");
|
||||
if let Some(at) = got.iter().position(|s| s == space) {
|
||||
assert!(at > 0, "elision before split: {word}: {got:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for (word, want) in [("j'adorr", "j'adore"), ("j’adorr", "j’adore"), ("J'adorr", "J'adore")] {
|
||||
let got = suggest_in(&d, word, 6);
|
||||
assert!(got.iter().any(|s| s == want), "typed apostrophe: {word}: {got:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn output_conversion_preserves_typed_apostrophe() {
|
||||
let d = AffixDict::from_hunspell("SET UTF-8\nICONV 1\nICONV ’ '\nOCONV 1\nOCONV ' ’\n", "1\nl'arbre\n", &[]).unwrap();
|
||||
assert!(suggest_in(&d, "l'arbrre", 4).iter().any(|s| s == "l'arbre"));
|
||||
assert!(suggest_in(&d, "l’arbrre", 4).iter().any(|s| s == "l’arbre"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
//! A tiny synthetic French Hunspell dictionary for tests (written for these tests; not taken
|
||||
//! from any real dictionary). Real dictionaries are installed on the system, never bundled.
|
||||
//!
|
||||
//! It exercises what the Dicollecte French dictionary uses: two-character flags (`FLAG long`),
|
||||
//! stems that need an affix (`NEEDAFFIX`, with an empty suffix for the singular), elisions as
|
||||
//! prefixes licensed by a suffix's continuation (`l'arbre` but not `l'arbres`), irregular verbs
|
||||
//! through `FULLSTRIP` (`être` → `suis`), `KEEPCASE` (`km`), `NOSUGGEST` (`bah`), `ICONV` (`’`
|
||||
//! read as `'`) and the
|
||||
//! suggestion tables (`TRY`, `MAP` for accents, `REP` for common confusions).
|
||||
|
||||
pub const AFF: &str = "SET UTF-8
|
||||
FLAG long
|
||||
NEEDAFFIX ()
|
||||
KEEPCASE ||
|
||||
NOSUGGEST --
|
||||
FULLSTRIP
|
||||
ICONV 1
|
||||
ICONV ’ '
|
||||
TRY esaitnrulodcpmévqfbghjàxèêyçôîâûùœ
|
||||
MAP 6
|
||||
MAP aàâä
|
||||
MAP eéèêë
|
||||
MAP iîï
|
||||
MAP oôö
|
||||
MAP uùûü
|
||||
MAP cç
|
||||
REP 3
|
||||
REP oe œ
|
||||
REP ph f
|
||||
REP f ph
|
||||
PFX L' Y 1
|
||||
PFX L' 0 l' [aàâeéèêiîoôuœh]
|
||||
PFX D' Y 1
|
||||
PFX D' 0 d' [aàâeéèêiîoôuœh]
|
||||
PFX Q' Y 1
|
||||
PFX Q' 0 qu' [aàâeéèêiîoôuœh]
|
||||
PFX J' Y 1
|
||||
PFX J' 0 j' [aàâeéèêiîoôuœhy]
|
||||
SFX S. Y 2
|
||||
SFX S. 0 0/L'D'Q' [^sxz]
|
||||
SFX S. 0 s/D'Q' [^sxz]
|
||||
SFX S= Y 2
|
||||
SFX S= 0 0 [^sxz]
|
||||
SFX S= 0 s [^sxz]
|
||||
SFX F. Y 4
|
||||
SFX F. 0 0/L'D'Q' .
|
||||
SFX F. 0 e/L'D'Q' .
|
||||
SFX F. 0 s/D'Q' .
|
||||
SFX F. 0 es/D'Q' .
|
||||
SFX Er Y 6
|
||||
SFX Er er er/D' er
|
||||
SFX Er er e/J' er
|
||||
SFX Er er es er
|
||||
SFX Er er ons er
|
||||
SFX Er er ez er
|
||||
SFX Er er ent er
|
||||
SFX Et N 7
|
||||
SFX Et être être être
|
||||
SFX Et être suis être
|
||||
SFX Et être es être
|
||||
SFX Et être est être
|
||||
SFX Et être sommes être
|
||||
SFX Et être êtes être
|
||||
SFX Et être sont être
|
||||
SFX Av N 7
|
||||
SFX Av avoir avoir/D' avoir
|
||||
SFX Av avoir ai/J' avoir
|
||||
SFX Av avoir as avoir
|
||||
SFX Av avoir a avoir
|
||||
SFX Av avoir avons avoir
|
||||
SFX Av avoir avez avoir
|
||||
SFX Av avoir ont/Q' avoir
|
||||
";
|
||||
|
||||
/// Stems (the count line first, as in Hunspell files).
|
||||
pub const DIC: &str = "150
|
||||
maison/S.()
|
||||
arbre/S.()
|
||||
enfant/S.()
|
||||
ami/S.()
|
||||
amie/S.()
|
||||
homme/S.()
|
||||
école/S.()
|
||||
café/S.()
|
||||
chat/S.()
|
||||
rivière/S.()
|
||||
ville/S.()
|
||||
heure/S.()
|
||||
histoire/S.()
|
||||
sœur/S.()
|
||||
œuvre/S.()
|
||||
photo/S.()
|
||||
téléphone/S.()
|
||||
année/S.()
|
||||
vie/S.()
|
||||
livre/S.()
|
||||
table/S.()
|
||||
porte/S.()
|
||||
femme/S.()
|
||||
garçon/S.()
|
||||
fille/S.()
|
||||
père/S.()
|
||||
mère/S.()
|
||||
langue/S.()
|
||||
mot/S.()
|
||||
texte/S.()
|
||||
phrase/S.()
|
||||
exemple/S.()
|
||||
jour/S.()
|
||||
nuit/S.()
|
||||
monde/S.()
|
||||
hasard/S=()
|
||||
haricot/S=()
|
||||
grand/F.()
|
||||
petit/F.()
|
||||
noir/F.()
|
||||
aimer/Er()
|
||||
parler/Er()
|
||||
chanter/Er()
|
||||
arriver/Er()
|
||||
être/Et()
|
||||
avoir/Av()
|
||||
il/Q'
|
||||
ils/Q'
|
||||
elle/Q'
|
||||
elles/Q'
|
||||
on/Q'L'
|
||||
un/D'Q'L'
|
||||
une/D'Q'L'
|
||||
en/Q'J'
|
||||
y/J'
|
||||
à/Q'
|
||||
jusqu'à
|
||||
aujourd'hui/D'
|
||||
peut-être
|
||||
arc-en-ciel
|
||||
km/||
|
||||
bah/--
|
||||
Paris
|
||||
France
|
||||
Montréal
|
||||
le
|
||||
la
|
||||
les
|
||||
de
|
||||
des
|
||||
du
|
||||
et
|
||||
à
|
||||
je
|
||||
tu
|
||||
nous
|
||||
vous
|
||||
que
|
||||
qui
|
||||
ne
|
||||
pas
|
||||
se
|
||||
me
|
||||
te
|
||||
ce
|
||||
ça
|
||||
avec
|
||||
pour
|
||||
dans
|
||||
sur
|
||||
sous
|
||||
très
|
||||
près
|
||||
beaucoup
|
||||
si
|
||||
oui
|
||||
non
|
||||
mais
|
||||
ou
|
||||
où
|
||||
dit
|
||||
demanda
|
||||
quand
|
||||
comme
|
||||
plus
|
||||
bien
|
||||
tout
|
||||
toujours
|
||||
jamais
|
||||
ici
|
||||
là
|
||||
alors
|
||||
donc
|
||||
aussi
|
||||
encore
|
||||
déjà
|
||||
mon
|
||||
ma
|
||||
mes
|
||||
son
|
||||
sa
|
||||
ses
|
||||
notre
|
||||
votre
|
||||
leur
|
||||
cette
|
||||
ces
|
||||
au
|
||||
aux
|
||||
par
|
||||
entre
|
||||
vers
|
||||
chez
|
||||
sans
|
||||
moi
|
||||
toi
|
||||
lui
|
||||
rien
|
||||
chose
|
||||
temps
|
||||
fois
|
||||
eau
|
||||
voici
|
||||
voilà
|
||||
bonjour
|
||||
merci
|
||||
beau
|
||||
belle
|
||||
la
|
||||
etc
|
||||
M
|
||||
p
|
||||
";
|
||||
|
||||
/// The original synthetic fixture, parsed independently of the installed pack cache.
|
||||
pub fn dictionary() -> crate::affix::AffixDict {
|
||||
crate::affix::AffixDict::from_hunspell(AFF, DIC, &[]).unwrap()
|
||||
}
|
||||
@@ -42,6 +42,9 @@
|
||||
//! existing English fallback.
|
||||
//! - **German** ([`ProofLang::De`]): hyphenation by `hyph-utf8`'s German patterns (reformed
|
||||
//! spelling, MIT); no spelling or grammar marks yet.
|
||||
//! - **French** (a [`ProofLang::Pack`] locale; module [`fr`]): the pack dictionary with French
|
||||
//! elisions and accent-oriented suggestions, plus conservative typography and basic checks.
|
||||
//! France and Canada retain their regional tags; Quebec uses its own punctuation spacing.
|
||||
//! - **Any other language** ([`ProofLang::Pack`], module [`packs`]): spelling and suggestions
|
||||
//! from its Hunspell dictionary (an installed Language pack, the dictionaries folder or the
|
||||
//! system's) with default tuning, hyphenation from its pack, no grammar rules; without a
|
||||
@@ -73,6 +76,7 @@ pub mod dict;
|
||||
pub mod en_variants;
|
||||
mod english;
|
||||
pub mod es;
|
||||
pub mod fr;
|
||||
pub mod hr;
|
||||
pub mod hunspell;
|
||||
pub mod hyphen;
|
||||
@@ -976,6 +980,7 @@ fn grammar_in(text: &str, lang: ProofLang, capital_first: bool) -> Vec<Issue> {
|
||||
match lang {
|
||||
ProofLang::En => grammar_en(text, capital_first),
|
||||
ProofLang::EnGb | ProofLang::EnAu | ProofLang::EnCa => grammar_en(text, capital_first).into_iter().map(|i| Issue { lang, ..i }).collect(),
|
||||
ProofLang::Pack(locale) if locale.primary() == "fr" => fr::grammar::check_in(text, lang),
|
||||
// `pt-pt` shares Portuguese's rules, its issues in its own language.
|
||||
_ => language(lang.built_in())
|
||||
.map_or_else(Vec::new, |l| (l.grammar)(text, lang, capital_first).into_iter().map(|i| Issue { lang, ..i }).collect()),
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Proofing for any language by its locale ([`crate::ProofLang::Pack`]): its Hunspell dictionary (the
|
||||
//! dictionaries folder, then an installed Language pack, then the system's), read by the shared
|
||||
//! affix engine, with default suggestion tuning and no grammar rules.
|
||||
//! affix engine. Most use default suggestion tuning and no grammar rules; French locales add
|
||||
//! the spelling tuning and conservative typography in [`crate::fr`] without a separate cache.
|
||||
//!
|
||||
//! The loaded dictionaries share a memory budget ([`MAX_LOADED_BYTES`], estimated from their
|
||||
//! files); the one used least recently goes first, but never one used during the current
|
||||
@@ -337,6 +338,9 @@ pub(crate) fn is_correct(word: &str, locale: PackLocale, opts: &crate::Options)
|
||||
if other_script(w, &scripts) {
|
||||
return true;
|
||||
}
|
||||
if locale.primary() == "fr" {
|
||||
return crate::fr::check(&d, w, opts);
|
||||
}
|
||||
let known = |w: &str| d.check(w) || crate::in_user_dictionary(&w.to_lowercase());
|
||||
if w.contains('-') && !known(w) {
|
||||
return w.split('-').all(|p| p.chars().count() <= 1 || known(p));
|
||||
@@ -350,7 +354,7 @@ pub(crate) fn suggest(word: &str, max: usize, locale: PackLocale) -> Vec<String>
|
||||
if d.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
crate::affix_suggest::suggest_in(&d, word, max, &Tuning::DEFAULT)
|
||||
if locale.primary() == "fr" { crate::fr::suggest_in(&d, word, max) } else { crate::affix_suggest::suggest_in(&d, word, max, &Tuning::DEFAULT) }
|
||||
}
|
||||
|
||||
/// The pack locales whose hyphenation patterns serve a [`crate::ProofLang::Pack`] language: the locale,
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
//! Frozen public output from the pre-French shared affix engine at upstream
|
||||
//! e6c5a701ddff5be16e266028168c70658aae39d9, using original synthetic fixtures.
|
||||
//! Do not regenerate expectations from the new implementation: they establish the baseline.
|
||||
//! Legacy WCAFF1 bytes remain frozen, but are explicitly refused by the WCAFF2 engine.
|
||||
|
||||
use craft_proof::affix::{AffixDict, capitalize};
|
||||
use std::fmt::Write;
|
||||
|
||||
#[path = "fixtures/affix_compatibility_cases.rs"]
|
||||
mod fixtures;
|
||||
|
||||
fn snapshot(case: &fixtures::Case, dict: &AffixDict) -> String {
|
||||
let mut out = format!("{}\nlen={} rules={}\n", case.name, dict.len(), dict.rule_count());
|
||||
writeln!(out, "try={:?} key={:?} map={:?} rep={:?} comments={:?}", dict.try_chars(), dict.key(), dict.map(), dict.rep(), dict.comments())
|
||||
.unwrap();
|
||||
let mut stems: Vec<_> = dict.stems().collect();
|
||||
stems.sort_unstable();
|
||||
for stem in &stems {
|
||||
let mut forms = dict.forms(stem);
|
||||
forms.sort_unstable();
|
||||
forms.dedup();
|
||||
writeln!(out, "forms {stem:?}: {forms:?}").unwrap();
|
||||
}
|
||||
let mut probes: Vec<String> = case.probes.iter().map(|word| (*word).to_string()).collect();
|
||||
for stem in stems {
|
||||
probes.extend(dict.forms(stem));
|
||||
}
|
||||
let originals = probes.clone();
|
||||
for word in originals {
|
||||
probes.extend([word.to_uppercase(), word.to_lowercase(), capitalize(&word)]);
|
||||
}
|
||||
probes.sort_unstable();
|
||||
probes.dedup();
|
||||
for word in probes {
|
||||
writeln!(
|
||||
out,
|
||||
"{word:?}: contains={} check={} suggest={} raw_suggest={}",
|
||||
dict.contains(&word),
|
||||
dict.check(&word),
|
||||
dict.can_suggest(&word),
|
||||
dict.contains_suggestible(&word)
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_french_affix_outputs_match_pre_french_baseline() {
|
||||
let expected = include_str!("fixtures/affix_compatibility.expected");
|
||||
let mut actual = String::new();
|
||||
for case in fixtures::cases() {
|
||||
let dict = AffixDict::from_hunspell(&case.aff, &case.dic, &["original compatibility fixture"]).unwrap();
|
||||
let result = snapshot(&case, &dict);
|
||||
let restored = AffixDict::from_bytes(&dict.to_bytes().unwrap()).unwrap();
|
||||
assert_eq!(snapshot(&case, &restored), result, "current compact round trip: {}", case.name);
|
||||
actual.push_str(&result);
|
||||
}
|
||||
// craft-libs 55332dd predates this adaptation and supports a prefix plus a two-suffix
|
||||
// chain (native test affix::tests::a_prefix_with_a_suffix_chain). The old Indonesian
|
||||
// fixture's bermain + kan + lah therefore became a word, in these three cases only.
|
||||
// Keep the frozen historical file untouched and assert every explicit transition once.
|
||||
// Normalize only checkout line endings; the frozen fixture and its observations stay unchanged.
|
||||
let mut expected = expected.replace("\r\n", "\n");
|
||||
let mut transitions = 0;
|
||||
for word in ["BERMAINKANLAH", "Bermainkanlah", "bermainkanlah"] {
|
||||
let before = format!("{word:?}: contains=false check=false suggest=false raw_suggest=false\n");
|
||||
let after = if word == "bermainkanlah" {
|
||||
format!("{word:?}: contains=true check=true suggest=true raw_suggest=true\n")
|
||||
} else {
|
||||
format!("{word:?}: contains=false check=true suggest=true raw_suggest=false\n")
|
||||
};
|
||||
assert_eq!(expected.matches(&before).count(), 1, "one historical observable: {word}");
|
||||
expected = expected.replacen(&before, &after, 1);
|
||||
transitions += 1;
|
||||
}
|
||||
assert_eq!(transitions, 3, "the documented upstream exception has exactly three observables");
|
||||
assert_eq!(actual, expected, "shared engine output changed beyond the explicit upstream chain exception");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_compact_data_is_refused_without_reinterpreting_homonyms() {
|
||||
let encoded = include_str!("fixtures/affix_compatibility.compact");
|
||||
let cases = fixtures::cases();
|
||||
let lines: Vec<_> = encoded.lines().collect();
|
||||
assert_eq!(lines.len(), cases.len());
|
||||
for (case, hex) in cases.iter().zip(lines) {
|
||||
assert_eq!(hex.len() % 2, 0);
|
||||
let bytes: Vec<_> =
|
||||
hex.as_bytes().as_chunks::<2>().0.iter().map(|pair| u8::from_str_radix(std::str::from_utf8(pair).unwrap(), 16).unwrap()).collect();
|
||||
let raw = miniz_oxide::inflate::decompress_to_vec(&bytes).unwrap();
|
||||
assert!(raw.starts_with(b"WCAFF1\n"), "fixture must contain WCAFF1 data: {}", case.name);
|
||||
assert!(AffixDict::from_bytes(&bytes).is_err(), "WCAFF1 must be regenerated as WCAFF2: {}", case.name);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
4d8bc10a825014446b7bbf62a07dd62744e5ae120b2ca2e02aafb8bceac54b295d067e91db76ea7f2516d16666ce30138c47ae3ba41e8c95a35cf884c89caf1c4b282789531ce4112756d1cadf809591a47e6a4bb39107aef2d64d5924e44f3dd42fd8ac4d09ca823c778d101b0c7011853e2d1be696536cf7e9ee57280dcd8dfe2dd4f97b88306faa2a0753b0f0274bea046c6f19dfd989a8a34dec70485d6b3e7c157553da617a03
|
||||
1d8c410e82301045bb9e534ce2deea11a8d8c48d10304196058b990418534aa25ec7852770e9aa17b3b27c79ffbf6a9768bd8515b2a32b8da6c796879bf1d4504ffe811dddfdec2c9c8a1a8d259ec33bbcc2077456a8439aee8f5556a418be90eb33e658e3069dc535941193888c462ae485d5a2a768ffa71244c32379968902d19a290e4174e6699dcc41d0308f17962aa67f
|
||||
1dc7410ac2301005d0ace7141fdc1b3d42aa64a9a15d5497d392ca40eac818416f6fe8eaf1c65388f1483ba8c9439e5c30ebfae22a9314a93f2cf2ad1fcb94e20d09771c60823d0dada15521d06d1d2e6064308dd7fe3c90eb75657233bfd97789dcc2967db3c864ea03fd01
|
||||
1d8a3d0a02311406b77ea7f8c0dee8114437651453ac220a51a33cc88fc408e62c9e451bf55e1bb6199861baf94cca298d10135f39188753f43793f9c88e73c1859ff9912cade4060a5b4c102cc6a4abea410b7687b21f425b0f83df0b86bae57aa1a9f1ce9cbf6fa1a8b9e714bd50b51551f1ffd860444b3d
|
||||
1d8c310e82401444b1dd53fcc45ef408282cb11008ab414b346a3641310413ed0cad95072034f450488c46f10a7f6fe4aeddcc9bcc0b4606a503d28538e15bbe0f2358c5bb4398f2258f787a860d3fa5c7644d268607d8881ba1ae3f1c9ba6e504ae6f0296c471d9ccb62d3605cc8947e780052ca00ff8c1067a842952fd89b8caae6e8c6878c716df3a56a4f3c01abfe222ed998ea5222f6c552e64d64426e7a794d53ae612fc00
|
||||
2dc84b0e8230100050d6738a49dc8b1e0114589800a11864398522c3a768a951120f2f212edf2b4e5e181e618793e13b6b1ab09ac60759963cb05db0e18f7d1905795622c9aa56dc6bb804253edfcad8e54b73dd4016a45877d8419c886b140522c718d2f08629967840a90cee41acf636f7a45dff3ffe3603b5ab8b243b0b702455e47ae08cc4daf552700cb534f37a31fc00
|
||||
35c7b98e82600045e1a9790a92e967dc97d20df71515b51345455114c1ed6d2616c6c2cad8d8fe2f36e67269cec9a7e5328a1296be65db31e7e6666cc9137bbd1dbba66e5aa67b9667e6c9f51c435295813c961b72e8d31f4887746a024da82934a50cc8a066d08c9a43736a012d281332a925b4a456d08ab2208b5a436b6a036d281bb2a92db4a576d08e722087da437bca855cca833cea001da82374a44ed0893a4367ea025da80c94a1b25096ca41392a0fe5a90254a01448a18a50912a4125aa0c95a90a54a1aa5095aa4135aa0ed5a906d4a09a50936a412daa0db5a90ed4a15448a5ba5097ea413daa0ff5290dd2a80134a086d0901a41232a0485a83014a62250848a42512a06c5a83814a71250824a42492a05a5a83494a6c41ff8197df77d0ffcf0fd08fcf4fd0cfcf6fd0e7cf37d0b7cf57d0dfcf2fdfa586b76f2aaf4657bae63ff8a97f475301cddfe0d8523d1583c914ca533d95cbea0144be54ab5566f345bed8edaedf5b5c17034d6275363365f98cb95b5ded8db9db377bdc3f174be883f71153771170ff1142ff196fe01
|
||||
@@ -0,0 +1,497 @@
|
||||
pl: conditional strip, prefix cross products, diacritics
|
||||
len=4 rules=5
|
||||
try="aeoiułkr" key="" map=[['a', 'ą'], ['o', 'ó', 'u']] rep=[("ż", "rz"), ("u", "ó")] comments=["original compatibility fixture"]
|
||||
forms "Warszawa": ["Warszawa", "Warszawą"]
|
||||
forms "kot": ["kot", "kotem", "koty", "niekot", "niekotem", "niekoty"]
|
||||
forms "krowa": ["krowa", "krową"]
|
||||
forms "piesek": ["piesek", "piesekem", "pieseky", "pieska"]
|
||||
"": contains=false check=false suggest=false raw_suggest=false
|
||||
"KOT": contains=false check=true suggest=true raw_suggest=false
|
||||
"KOTEM": contains=false check=true suggest=true raw_suggest=false
|
||||
"KOTY": contains=false check=true suggest=true raw_suggest=false
|
||||
"KOTĄ": contains=false check=false suggest=false raw_suggest=false
|
||||
"KROWA": contains=false check=true suggest=true raw_suggest=false
|
||||
"KROWY": contains=false check=false suggest=false raw_suggest=false
|
||||
"KROWĄ": contains=false check=true suggest=true raw_suggest=false
|
||||
"Kot": contains=false check=true suggest=true raw_suggest=false
|
||||
"Kotem": contains=false check=true suggest=true raw_suggest=false
|
||||
"Koty": contains=false check=true suggest=true raw_suggest=false
|
||||
"Kotą": contains=false check=false suggest=false raw_suggest=false
|
||||
"Krowa": contains=false check=true suggest=true raw_suggest=false
|
||||
"Krowy": contains=false check=false suggest=false raw_suggest=false
|
||||
"Krową": contains=false check=true suggest=true raw_suggest=false
|
||||
"NIE": contains=false check=false suggest=false raw_suggest=false
|
||||
"NIEKOT": contains=false check=true suggest=true raw_suggest=false
|
||||
"NIEKOTEM": contains=false check=true suggest=true raw_suggest=false
|
||||
"NIEKOTY": contains=false check=true suggest=true raw_suggest=false
|
||||
"NIEPIESKA": contains=false check=false suggest=false raw_suggest=false
|
||||
"Nie": contains=false check=false suggest=false raw_suggest=false
|
||||
"Niekot": contains=false check=true suggest=true raw_suggest=false
|
||||
"Niekotem": contains=false check=true suggest=true raw_suggest=false
|
||||
"Niekoty": contains=false check=true suggest=true raw_suggest=false
|
||||
"Niepieska": contains=false check=false suggest=false raw_suggest=false
|
||||
"PIESEK": contains=false check=true suggest=true raw_suggest=false
|
||||
"PIESEKA": contains=false check=false suggest=false raw_suggest=false
|
||||
"PIESEKEM": contains=false check=true suggest=true raw_suggest=false
|
||||
"PIESEKY": contains=false check=true suggest=true raw_suggest=false
|
||||
"PIESKA": contains=false check=true suggest=true raw_suggest=false
|
||||
"Piesek": contains=false check=true suggest=true raw_suggest=false
|
||||
"Pieseka": contains=false check=false suggest=false raw_suggest=false
|
||||
"Piesekem": contains=false check=true suggest=true raw_suggest=false
|
||||
"Pieseky": contains=false check=true suggest=true raw_suggest=false
|
||||
"Pieska": contains=false check=true suggest=true raw_suggest=false
|
||||
"WARSZAWA": contains=false check=true suggest=true raw_suggest=false
|
||||
"WARSZAWĄ": contains=false check=true suggest=true raw_suggest=false
|
||||
"Warszawa": contains=true check=true suggest=true raw_suggest=true
|
||||
"Warszawą": contains=true check=true suggest=true raw_suggest=true
|
||||
"kot": contains=true check=true suggest=true raw_suggest=true
|
||||
"kotem": contains=true check=true suggest=true raw_suggest=true
|
||||
"koty": contains=true check=true suggest=true raw_suggest=true
|
||||
"kotą": contains=false check=false suggest=false raw_suggest=false
|
||||
"krowa": contains=true check=true suggest=true raw_suggest=true
|
||||
"krowy": contains=false check=false suggest=false raw_suggest=false
|
||||
"krową": contains=true check=true suggest=true raw_suggest=true
|
||||
"nie": contains=false check=false suggest=false raw_suggest=false
|
||||
"niekot": contains=true check=true suggest=true raw_suggest=true
|
||||
"niekotem": contains=true check=true suggest=true raw_suggest=true
|
||||
"niekoty": contains=true check=true suggest=true raw_suggest=true
|
||||
"niepieska": contains=false check=false suggest=false raw_suggest=false
|
||||
"piesek": contains=true check=true suggest=true raw_suggest=true
|
||||
"pieseka": contains=false check=false suggest=false raw_suggest=false
|
||||
"piesekem": contains=true check=true suggest=true raw_suggest=true
|
||||
"pieseky": contains=true check=true suggest=true raw_suggest=true
|
||||
"pieska": contains=true check=true suggest=true raw_suggest=true
|
||||
"warszawa": contains=false check=false suggest=false raw_suggest=false
|
||||
"warszawą": contains=false check=false suggest=false raw_suggest=false
|
||||
pt: UTF-8 flags, forbidden words, two suffixes
|
||||
len=4 rules=3
|
||||
try="aeiouçãõ" key="" map=[] rep=[] comments=["original compatibility fixture"]
|
||||
forms "bonito": ["bonita", "bonitas", "bonito", "bonitos"]
|
||||
forms "casa": ["casa", "casas"]
|
||||
forms "fazer": ["fazer", "refazer"]
|
||||
forms "imundo": []
|
||||
"BONITA": contains=false check=true suggest=true raw_suggest=false
|
||||
"BONITAS": contains=false check=true suggest=true raw_suggest=false
|
||||
"BONITASS": contains=false check=false suggest=false raw_suggest=false
|
||||
"BONITO": contains=false check=true suggest=true raw_suggest=false
|
||||
"BONITOS": contains=false check=true suggest=true raw_suggest=false
|
||||
"Bonita": contains=false check=true suggest=true raw_suggest=false
|
||||
"Bonitas": contains=false check=true suggest=true raw_suggest=false
|
||||
"Bonitass": contains=false check=false suggest=false raw_suggest=false
|
||||
"Bonito": contains=false check=true suggest=true raw_suggest=false
|
||||
"Bonitos": contains=false check=true suggest=true raw_suggest=false
|
||||
"CASA": contains=false check=true suggest=true raw_suggest=false
|
||||
"CASAA": contains=false check=false suggest=false raw_suggest=false
|
||||
"CASAS": contains=false check=true suggest=true raw_suggest=false
|
||||
"Casa": contains=false check=true suggest=true raw_suggest=false
|
||||
"Casaa": contains=false check=false suggest=false raw_suggest=false
|
||||
"Casas": contains=false check=true suggest=true raw_suggest=false
|
||||
"FAZER": contains=false check=true suggest=true raw_suggest=false
|
||||
"Fazer": contains=false check=true suggest=true raw_suggest=false
|
||||
"IMUNDO": contains=false check=false suggest=false raw_suggest=false
|
||||
"IMUNDOS": contains=false check=false suggest=false raw_suggest=false
|
||||
"Imundo": contains=false check=false suggest=false raw_suggest=false
|
||||
"Imundos": contains=false check=false suggest=false raw_suggest=false
|
||||
"RECASAS": contains=false check=false suggest=false raw_suggest=false
|
||||
"REFAZER": contains=false check=true suggest=true raw_suggest=false
|
||||
"Recasas": contains=false check=false suggest=false raw_suggest=false
|
||||
"Refazer": contains=false check=true suggest=true raw_suggest=false
|
||||
"bonita": contains=true check=true suggest=true raw_suggest=true
|
||||
"bonitas": contains=true check=true suggest=true raw_suggest=true
|
||||
"bonitass": contains=false check=false suggest=false raw_suggest=false
|
||||
"bonito": contains=true check=true suggest=true raw_suggest=true
|
||||
"bonitos": contains=true check=true suggest=true raw_suggest=true
|
||||
"casa": contains=true check=true suggest=true raw_suggest=true
|
||||
"casaa": contains=false check=false suggest=false raw_suggest=false
|
||||
"casas": contains=true check=true suggest=true raw_suggest=true
|
||||
"fazer": contains=true check=true suggest=true raw_suggest=true
|
||||
"imundo": contains=false check=false suggest=false raw_suggest=false
|
||||
"imundos": contains=false check=false suggest=false raw_suggest=false
|
||||
"recasas": contains=false check=false suggest=false raw_suggest=false
|
||||
"refazer": contains=true check=true suggest=true raw_suggest=true
|
||||
it: stripping, non-crossing suffix, proper-name casing
|
||||
len=4 rules=3
|
||||
try="" key="" map=[] rep=[] comments=["original compatibility fixture"]
|
||||
forms "Roma": ["Roma"]
|
||||
forms "casa": ["casa", "case", "ricasa"]
|
||||
forms "fare": ["fare", "rifare"]
|
||||
forms "libro": ["libri", "libro"]
|
||||
"": contains=false check=false suggest=false raw_suggest=false
|
||||
"CASA": contains=false check=true suggest=true raw_suggest=false
|
||||
"CASE": contains=false check=true suggest=true raw_suggest=false
|
||||
"Casa": contains=false check=true suggest=true raw_suggest=false
|
||||
"Case": contains=false check=true suggest=true raw_suggest=false
|
||||
"FARE": contains=false check=true suggest=true raw_suggest=false
|
||||
"Fare": contains=false check=true suggest=true raw_suggest=false
|
||||
"LIBRI": contains=false check=true suggest=true raw_suggest=false
|
||||
"LIBRO": contains=false check=true suggest=true raw_suggest=false
|
||||
"LIBROS": contains=false check=false suggest=false raw_suggest=false
|
||||
"Libri": contains=false check=true suggest=true raw_suggest=false
|
||||
"Libro": contains=false check=true suggest=true raw_suggest=false
|
||||
"Libros": contains=false check=false suggest=false raw_suggest=false
|
||||
"R ILIBRI": contains=false check=false suggest=false raw_suggest=false
|
||||
"R ilibri": contains=false check=false suggest=false raw_suggest=false
|
||||
"RICAS A": contains=false check=false suggest=false raw_suggest=false
|
||||
"RICASA": contains=false check=true suggest=true raw_suggest=false
|
||||
"RICASE": contains=false check=false suggest=false raw_suggest=false
|
||||
"RIFARE": contains=false check=true suggest=true raw_suggest=false
|
||||
"ROMA": contains=false check=true suggest=true raw_suggest=false
|
||||
"Ricas a": contains=false check=false suggest=false raw_suggest=false
|
||||
"Ricasa": contains=false check=true suggest=true raw_suggest=false
|
||||
"Ricase": contains=false check=false suggest=false raw_suggest=false
|
||||
"Rifare": contains=false check=true suggest=true raw_suggest=false
|
||||
"Roma": contains=true check=true suggest=true raw_suggest=true
|
||||
"casa": contains=true check=true suggest=true raw_suggest=true
|
||||
"case": contains=true check=true suggest=true raw_suggest=true
|
||||
"fare": contains=true check=true suggest=true raw_suggest=true
|
||||
"libri": contains=true check=true suggest=true raw_suggest=true
|
||||
"libro": contains=true check=true suggest=true raw_suggest=true
|
||||
"libros": contains=false check=false suggest=false raw_suggest=false
|
||||
"r ilibri": contains=false check=false suggest=false raw_suggest=false
|
||||
"ricas a": contains=false check=false suggest=false raw_suggest=false
|
||||
"ricasa": contains=true check=true suggest=true raw_suggest=true
|
||||
"ricase": contains=false check=false suggest=false raw_suggest=false
|
||||
"rifare": contains=true check=true suggest=true raw_suggest=true
|
||||
"roma": contains=false check=false suggest=false raw_suggest=false
|
||||
cs: negated conditions and shared Unicode stems
|
||||
len=4 rules=3
|
||||
try="" key="" map=[] rep=[] comments=["original compatibility fixture"]
|
||||
forms "mladý": ["mladý", "nemladý"]
|
||||
forms "strom": ["nestrom", "nestromy", "strom", "stromy"]
|
||||
forms "y": ["y"]
|
||||
forms "žena": ["žena", "ženě"]
|
||||
"MLADÝ": contains=false check=true suggest=true raw_suggest=false
|
||||
"MLADÝY": contains=false check=false suggest=false raw_suggest=false
|
||||
"Mladý": contains=false check=true suggest=true raw_suggest=false
|
||||
"Mladýy": contains=false check=false suggest=false raw_suggest=false
|
||||
"NEMLADÝ": contains=false check=true suggest=true raw_suggest=false
|
||||
"NESTROM": contains=false check=true suggest=true raw_suggest=false
|
||||
"NESTROMY": contains=false check=true suggest=true raw_suggest=false
|
||||
"NEŽENĚ": contains=false check=false suggest=false raw_suggest=false
|
||||
"Nemladý": contains=false check=true suggest=true raw_suggest=false
|
||||
"Nestrom": contains=false check=true suggest=true raw_suggest=false
|
||||
"Nestromy": contains=false check=true suggest=true raw_suggest=false
|
||||
"Neženě": contains=false check=false suggest=false raw_suggest=false
|
||||
"STROM": contains=false check=true suggest=true raw_suggest=false
|
||||
"STROMY": contains=false check=true suggest=true raw_suggest=false
|
||||
"Strom": contains=false check=true suggest=true raw_suggest=false
|
||||
"Stromy": contains=false check=true suggest=true raw_suggest=false
|
||||
"Y": contains=false check=true suggest=true raw_suggest=false
|
||||
"YY": contains=false check=false suggest=false raw_suggest=false
|
||||
"Yy": contains=false check=false suggest=false raw_suggest=false
|
||||
"mladý": contains=true check=true suggest=true raw_suggest=true
|
||||
"mladýy": contains=false check=false suggest=false raw_suggest=false
|
||||
"nemladý": contains=true check=true suggest=true raw_suggest=true
|
||||
"nestrom": contains=true check=true suggest=true raw_suggest=true
|
||||
"nestromy": contains=true check=true suggest=true raw_suggest=true
|
||||
"neženě": contains=false check=false suggest=false raw_suggest=false
|
||||
"strom": contains=true check=true suggest=true raw_suggest=true
|
||||
"stromy": contains=true check=true suggest=true raw_suggest=true
|
||||
"y": contains=true check=true suggest=true raw_suggest=true
|
||||
"yy": contains=false check=false suggest=false raw_suggest=false
|
||||
"ŽENA": contains=false check=true suggest=true raw_suggest=false
|
||||
"ŽENY": contains=false check=false suggest=false raw_suggest=false
|
||||
"ŽENĚ": contains=false check=true suggest=true raw_suggest=false
|
||||
"Žena": contains=false check=true suggest=true raw_suggest=false
|
||||
"Ženy": contains=false check=false suggest=false raw_suggest=false
|
||||
"Ženě": contains=false check=true suggest=true raw_suggest=false
|
||||
"žena": contains=true check=true suggest=true raw_suggest=true
|
||||
"ženy": contains=false check=false suggest=false raw_suggest=false
|
||||
"ženě": contains=true check=true suggest=true raw_suggest=true
|
||||
ru: Cyrillic flags and suggestions exclusion
|
||||
len=4 rules=2
|
||||
try="" key="" map=[['е', 'ё']] rep=[] comments=["original compatibility fixture"]
|
||||
forms "дом": ["дом", "домы"]
|
||||
forms "запрет": []
|
||||
forms "кот": ["кот", "коты", "некот", "некоты"]
|
||||
forms "тайна": ["тайна", "тайнаы"]
|
||||
"ДОМ": contains=false check=true suggest=true raw_suggest=false
|
||||
"ДОМЫ": contains=false check=true suggest=true raw_suggest=false
|
||||
"Дом": contains=false check=true suggest=true raw_suggest=false
|
||||
"Домы": contains=false check=true suggest=true raw_suggest=false
|
||||
"ЗАПРЕТ": contains=false check=false suggest=false raw_suggest=false
|
||||
"ЗАПРЕТЫ": contains=false check=false suggest=false raw_suggest=false
|
||||
"Запрет": contains=false check=false suggest=false raw_suggest=false
|
||||
"Запреты": contains=false check=false suggest=false raw_suggest=false
|
||||
"КОТ": contains=false check=true suggest=true raw_suggest=false
|
||||
"КОТЫ": contains=false check=true suggest=true raw_suggest=false
|
||||
"КОт": contains=false check=false suggest=false raw_suggest=false
|
||||
"Кот": contains=false check=true suggest=true raw_suggest=false
|
||||
"Коты": contains=false check=true suggest=true raw_suggest=false
|
||||
"НЕДОМЫ": contains=false check=false suggest=false raw_suggest=false
|
||||
"НЕКОТ": contains=false check=true suggest=true raw_suggest=false
|
||||
"НЕКОТЫ": contains=false check=true suggest=true raw_suggest=false
|
||||
"Недомы": contains=false check=false suggest=false raw_suggest=false
|
||||
"Некот": contains=false check=true suggest=true raw_suggest=false
|
||||
"Некоты": contains=false check=true suggest=true raw_suggest=false
|
||||
"ТАЙНА": contains=false check=true suggest=false raw_suggest=false
|
||||
"ТАЙНАЫ": contains=false check=true suggest=false raw_suggest=false
|
||||
"Тайна": contains=false check=true suggest=false raw_suggest=false
|
||||
"Тайнаы": contains=false check=true suggest=false raw_suggest=false
|
||||
"дом": contains=true check=true suggest=true raw_suggest=true
|
||||
"домы": contains=true check=true suggest=true raw_suggest=true
|
||||
"запрет": contains=false check=false suggest=false raw_suggest=false
|
||||
"запреты": contains=false check=false suggest=false raw_suggest=false
|
||||
"кОт": contains=false check=false suggest=false raw_suggest=false
|
||||
"кот": contains=true check=true suggest=true raw_suggest=true
|
||||
"коты": contains=true check=true suggest=true raw_suggest=true
|
||||
"недомы": contains=false check=false suggest=false raw_suggest=false
|
||||
"некот": contains=true check=true suggest=true raw_suggest=true
|
||||
"некоты": contains=true check=true suggest=true raw_suggest=true
|
||||
"тайна": contains=true check=true suggest=false raw_suggest=false
|
||||
"тайнаы": contains=true check=true suggest=false raw_suggest=false
|
||||
id: continuation and NOSUGGEST through derivations
|
||||
len=3 rules=3
|
||||
try="abcdeikn" key="qwerty|asdf" map=[] rep=[("dj", "j")] comments=["original compatibility fixture"]
|
||||
forms "baca": ["baca", "bacakan", "bacakanlah"]
|
||||
forms "main": ["bermain", "bermainkan", "main", "mainkan", "mainkanlah"]
|
||||
forms "rahasia": ["rahasia", "rahasiakan", "rahasiakanlah"]
|
||||
"BACA": contains=false check=true suggest=true raw_suggest=false
|
||||
"BACAKAN": contains=false check=true suggest=true raw_suggest=false
|
||||
"BACAKANLAH": contains=false check=true suggest=true raw_suggest=false
|
||||
"BERBACA": contains=false check=false suggest=false raw_suggest=false
|
||||
"BERMAIN": contains=false check=true suggest=true raw_suggest=false
|
||||
"BERMAINKAN": contains=false check=true suggest=true raw_suggest=false
|
||||
"BERMAINKANLAH": contains=false check=false suggest=false raw_suggest=false
|
||||
"Baca": contains=false check=true suggest=true raw_suggest=false
|
||||
"Bacakan": contains=false check=true suggest=true raw_suggest=false
|
||||
"Bacakanlah": contains=false check=true suggest=true raw_suggest=false
|
||||
"Berbaca": contains=false check=false suggest=false raw_suggest=false
|
||||
"Bermain": contains=false check=true suggest=true raw_suggest=false
|
||||
"Bermainkan": contains=false check=true suggest=true raw_suggest=false
|
||||
"Bermainkanlah": contains=false check=false suggest=false raw_suggest=false
|
||||
"MAIN": contains=false check=true suggest=true raw_suggest=false
|
||||
"MAINKAN": contains=false check=true suggest=true raw_suggest=false
|
||||
"MAINKANLAH": contains=false check=true suggest=true raw_suggest=false
|
||||
"MAINKANLAHLAH": contains=false check=false suggest=false raw_suggest=false
|
||||
"MAINLAH": contains=false check=false suggest=false raw_suggest=false
|
||||
"Main": contains=false check=true suggest=true raw_suggest=false
|
||||
"Mainkan": contains=false check=true suggest=true raw_suggest=false
|
||||
"Mainkanlah": contains=false check=true suggest=true raw_suggest=false
|
||||
"Mainkanlahlah": contains=false check=false suggest=false raw_suggest=false
|
||||
"Mainlah": contains=false check=false suggest=false raw_suggest=false
|
||||
"RAHASIA": contains=false check=true suggest=false raw_suggest=false
|
||||
"RAHASIAKAN": contains=false check=true suggest=false raw_suggest=false
|
||||
"RAHASIAKANLAH": contains=false check=true suggest=false raw_suggest=false
|
||||
"Rahasia": contains=false check=true suggest=false raw_suggest=false
|
||||
"Rahasiakan": contains=false check=true suggest=false raw_suggest=false
|
||||
"Rahasiakanlah": contains=false check=true suggest=false raw_suggest=false
|
||||
"baca": contains=true check=true suggest=true raw_suggest=true
|
||||
"bacakan": contains=true check=true suggest=true raw_suggest=true
|
||||
"bacakanlah": contains=true check=true suggest=true raw_suggest=true
|
||||
"berbaca": contains=false check=false suggest=false raw_suggest=false
|
||||
"bermain": contains=true check=true suggest=true raw_suggest=true
|
||||
"bermainkan": contains=true check=true suggest=true raw_suggest=true
|
||||
"bermainkanlah": contains=false check=false suggest=false raw_suggest=false
|
||||
"main": contains=true check=true suggest=true raw_suggest=true
|
||||
"mainkan": contains=true check=true suggest=true raw_suggest=true
|
||||
"mainkanlah": contains=true check=true suggest=true raw_suggest=true
|
||||
"mainkanlahlah": contains=false check=false suggest=false raw_suggest=false
|
||||
"mainlah": contains=false check=false suggest=false raw_suggest=false
|
||||
"rahasia": contains=true check=true suggest=false raw_suggest=false
|
||||
"rahasiakan": contains=true check=true suggest=false raw_suggest=false
|
||||
"rahasiakanlah": contains=true check=true suggest=false raw_suggest=false
|
||||
pt-sized: 70 distinct flags across the old u128 boundary
|
||||
len=2 rules=70
|
||||
try="" key="" map=[] rep=[] comments=["original compatibility fixture"]
|
||||
forms "outro": ["outro", "outroõ"]
|
||||
forms "verbo": ["verbo", "verbo1", "verbo2", "verbo3", "verbo4", "verbo5", "verbo6", "verbo7", "verbo8", "verbo9", "verboA", "verboB", "verboC", "verboD", "verboE", "verboF", "verboG", "verboH", "verboI", "verboJ", "verboK", "verboL", "verboM", "verboN", "verboO", "verboP", "verboQ", "verboR", "verboS", "verboT", "verboU", "verboV", "verboW", "verboX", "verboY", "verboZ", "verboa", "verbob", "verboc", "verbod", "verboe", "verbof", "verbog", "verboh", "verboi", "verboj", "verbok", "verbol", "verbom", "verbon", "verboo", "verbop", "verboq", "verbor", "verbos", "verbot", "verbou", "verbov", "verbow", "verbox", "verboy", "verboz", "verboá", "verboã", "verboç", "verboé", "verboí", "verboó", "verboõ", "verboú"]
|
||||
"OUTRO": contains=false check=true suggest=true raw_suggest=false
|
||||
"OUTROA": contains=false check=false suggest=false raw_suggest=false
|
||||
"OUTROÕ": contains=false check=true suggest=true raw_suggest=false
|
||||
"Outro": contains=false check=true suggest=true raw_suggest=false
|
||||
"Outroa": contains=false check=false suggest=false raw_suggest=false
|
||||
"Outroõ": contains=false check=true suggest=true raw_suggest=false
|
||||
"VERBO": contains=false check=true suggest=true raw_suggest=false
|
||||
"VERBO0": contains=false check=false suggest=false raw_suggest=false
|
||||
"VERBO1": contains=false check=true suggest=true raw_suggest=false
|
||||
"VERBO2": contains=false check=true suggest=true raw_suggest=false
|
||||
"VERBO3": contains=false check=true suggest=true raw_suggest=false
|
||||
"VERBO4": contains=false check=true suggest=true raw_suggest=false
|
||||
"VERBO5": contains=false check=true suggest=true raw_suggest=false
|
||||
"VERBO6": contains=false check=true suggest=true raw_suggest=false
|
||||
"VERBO7": contains=false check=true suggest=true raw_suggest=false
|
||||
"VERBO8": contains=false check=true suggest=true raw_suggest=false
|
||||
"VERBO9": contains=false check=true suggest=true raw_suggest=false
|
||||
"VERBOA": contains=false check=true suggest=true raw_suggest=false
|
||||
"VERBOB": contains=false check=true suggest=true raw_suggest=false
|
||||
"VERBOC": contains=false check=true suggest=true raw_suggest=false
|
||||
"VERBOD": contains=false check=true suggest=true raw_suggest=false
|
||||
"VERBOE": contains=false check=true suggest=true raw_suggest=false
|
||||
"VERBOF": contains=false check=true suggest=true raw_suggest=false
|
||||
"VERBOG": contains=false check=true suggest=true raw_suggest=false
|
||||
"VERBOH": contains=false check=true suggest=true raw_suggest=false
|
||||
"VERBOI": contains=false check=true suggest=true raw_suggest=false
|
||||
"VERBOJ": contains=false check=true suggest=true raw_suggest=false
|
||||
"VERBOK": contains=false check=true suggest=true raw_suggest=false
|
||||
"VERBOL": contains=false check=true suggest=true raw_suggest=false
|
||||
"VERBOM": contains=false check=true suggest=true raw_suggest=false
|
||||
"VERBON": contains=false check=true suggest=true raw_suggest=false
|
||||
"VERBOO": contains=false check=true suggest=true raw_suggest=false
|
||||
"VERBOP": contains=false check=true suggest=true raw_suggest=false
|
||||
"VERBOQ": contains=false check=true suggest=true raw_suggest=false
|
||||
"VERBOR": contains=false check=true suggest=true raw_suggest=false
|
||||
"VERBOS": contains=false check=true suggest=true raw_suggest=false
|
||||
"VERBOSS": contains=false check=false suggest=false raw_suggest=false
|
||||
"VERBOT": contains=false check=true suggest=true raw_suggest=false
|
||||
"VERBOU": contains=false check=true suggest=true raw_suggest=false
|
||||
"VERBOV": contains=false check=true suggest=true raw_suggest=false
|
||||
"VERBOW": contains=false check=true suggest=true raw_suggest=false
|
||||
"VERBOX": contains=false check=true suggest=true raw_suggest=false
|
||||
"VERBOY": contains=false check=true suggest=true raw_suggest=false
|
||||
"VERBOZ": contains=false check=true suggest=true raw_suggest=false
|
||||
"VERBOÁ": contains=false check=true suggest=true raw_suggest=false
|
||||
"VERBOÃ": contains=false check=true suggest=true raw_suggest=false
|
||||
"VERBOÇ": contains=false check=true suggest=true raw_suggest=false
|
||||
"VERBOÉ": contains=false check=true suggest=true raw_suggest=false
|
||||
"VERBOÍ": contains=false check=true suggest=true raw_suggest=false
|
||||
"VERBOÓ": contains=false check=true suggest=true raw_suggest=false
|
||||
"VERBOÕ": contains=false check=true suggest=true raw_suggest=false
|
||||
"VERBOÚ": contains=false check=true suggest=true raw_suggest=false
|
||||
"Verbo": contains=false check=true suggest=true raw_suggest=false
|
||||
"Verbo0": contains=false check=false suggest=false raw_suggest=false
|
||||
"Verbo1": contains=false check=true suggest=true raw_suggest=false
|
||||
"Verbo2": contains=false check=true suggest=true raw_suggest=false
|
||||
"Verbo3": contains=false check=true suggest=true raw_suggest=false
|
||||
"Verbo4": contains=false check=true suggest=true raw_suggest=false
|
||||
"Verbo5": contains=false check=true suggest=true raw_suggest=false
|
||||
"Verbo6": contains=false check=true suggest=true raw_suggest=false
|
||||
"Verbo7": contains=false check=true suggest=true raw_suggest=false
|
||||
"Verbo8": contains=false check=true suggest=true raw_suggest=false
|
||||
"Verbo9": contains=false check=true suggest=true raw_suggest=false
|
||||
"VerboA": contains=false check=false suggest=false raw_suggest=false
|
||||
"VerboB": contains=false check=false suggest=false raw_suggest=false
|
||||
"VerboC": contains=false check=false suggest=false raw_suggest=false
|
||||
"VerboD": contains=false check=false suggest=false raw_suggest=false
|
||||
"VerboE": contains=false check=false suggest=false raw_suggest=false
|
||||
"VerboF": contains=false check=false suggest=false raw_suggest=false
|
||||
"VerboG": contains=false check=false suggest=false raw_suggest=false
|
||||
"VerboH": contains=false check=false suggest=false raw_suggest=false
|
||||
"VerboI": contains=false check=false suggest=false raw_suggest=false
|
||||
"VerboJ": contains=false check=false suggest=false raw_suggest=false
|
||||
"VerboK": contains=false check=false suggest=false raw_suggest=false
|
||||
"VerboL": contains=false check=false suggest=false raw_suggest=false
|
||||
"VerboM": contains=false check=false suggest=false raw_suggest=false
|
||||
"VerboN": contains=false check=false suggest=false raw_suggest=false
|
||||
"VerboO": contains=false check=false suggest=false raw_suggest=false
|
||||
"VerboP": contains=false check=false suggest=false raw_suggest=false
|
||||
"VerboQ": contains=false check=false suggest=false raw_suggest=false
|
||||
"VerboR": contains=false check=false suggest=false raw_suggest=false
|
||||
"VerboS": contains=false check=false suggest=false raw_suggest=false
|
||||
"VerboT": contains=false check=false suggest=false raw_suggest=false
|
||||
"VerboU": contains=false check=false suggest=false raw_suggest=false
|
||||
"VerboV": contains=false check=false suggest=false raw_suggest=false
|
||||
"VerboW": contains=false check=false suggest=false raw_suggest=false
|
||||
"VerboX": contains=false check=false suggest=false raw_suggest=false
|
||||
"VerboY": contains=false check=false suggest=false raw_suggest=false
|
||||
"VerboZ": contains=false check=false suggest=false raw_suggest=false
|
||||
"Verboa": contains=false check=true suggest=true raw_suggest=false
|
||||
"Verbob": contains=false check=true suggest=true raw_suggest=false
|
||||
"Verboc": contains=false check=true suggest=true raw_suggest=false
|
||||
"Verbod": contains=false check=true suggest=true raw_suggest=false
|
||||
"Verboe": contains=false check=true suggest=true raw_suggest=false
|
||||
"Verbof": contains=false check=true suggest=true raw_suggest=false
|
||||
"Verbog": contains=false check=true suggest=true raw_suggest=false
|
||||
"Verboh": contains=false check=true suggest=true raw_suggest=false
|
||||
"Verboi": contains=false check=true suggest=true raw_suggest=false
|
||||
"Verboj": contains=false check=true suggest=true raw_suggest=false
|
||||
"Verbok": contains=false check=true suggest=true raw_suggest=false
|
||||
"Verbol": contains=false check=true suggest=true raw_suggest=false
|
||||
"Verbom": contains=false check=true suggest=true raw_suggest=false
|
||||
"Verbon": contains=false check=true suggest=true raw_suggest=false
|
||||
"Verboo": contains=false check=true suggest=true raw_suggest=false
|
||||
"Verbop": contains=false check=true suggest=true raw_suggest=false
|
||||
"Verboq": contains=false check=true suggest=true raw_suggest=false
|
||||
"Verbor": contains=false check=true suggest=true raw_suggest=false
|
||||
"Verbos": contains=false check=true suggest=true raw_suggest=false
|
||||
"Verbot": contains=false check=true suggest=true raw_suggest=false
|
||||
"Verbou": contains=false check=true suggest=true raw_suggest=false
|
||||
"Verbov": contains=false check=true suggest=true raw_suggest=false
|
||||
"Verbow": contains=false check=true suggest=true raw_suggest=false
|
||||
"Verbox": contains=false check=true suggest=true raw_suggest=false
|
||||
"Verboy": contains=false check=true suggest=true raw_suggest=false
|
||||
"Verboz": contains=false check=true suggest=true raw_suggest=false
|
||||
"Verboß": contains=false check=false suggest=false raw_suggest=false
|
||||
"Verboá": contains=false check=true suggest=true raw_suggest=false
|
||||
"Verboã": contains=false check=true suggest=true raw_suggest=false
|
||||
"Verboç": contains=false check=true suggest=true raw_suggest=false
|
||||
"Verboé": contains=false check=true suggest=true raw_suggest=false
|
||||
"Verboí": contains=false check=true suggest=true raw_suggest=false
|
||||
"Verboó": contains=false check=true suggest=true raw_suggest=false
|
||||
"Verboõ": contains=false check=true suggest=true raw_suggest=false
|
||||
"Verboú": contains=false check=true suggest=true raw_suggest=false
|
||||
"outro": contains=true check=true suggest=true raw_suggest=true
|
||||
"outroa": contains=false check=false suggest=false raw_suggest=false
|
||||
"outroõ": contains=true check=true suggest=true raw_suggest=true
|
||||
"verbo": contains=true check=true suggest=true raw_suggest=true
|
||||
"verbo0": contains=false check=false suggest=false raw_suggest=false
|
||||
"verbo1": contains=true check=true suggest=true raw_suggest=true
|
||||
"verbo2": contains=true check=true suggest=true raw_suggest=true
|
||||
"verbo3": contains=true check=true suggest=true raw_suggest=true
|
||||
"verbo4": contains=true check=true suggest=true raw_suggest=true
|
||||
"verbo5": contains=true check=true suggest=true raw_suggest=true
|
||||
"verbo6": contains=true check=true suggest=true raw_suggest=true
|
||||
"verbo7": contains=true check=true suggest=true raw_suggest=true
|
||||
"verbo8": contains=true check=true suggest=true raw_suggest=true
|
||||
"verbo9": contains=true check=true suggest=true raw_suggest=true
|
||||
"verboA": contains=true check=true suggest=true raw_suggest=true
|
||||
"verboB": contains=true check=true suggest=true raw_suggest=true
|
||||
"verboC": contains=true check=true suggest=true raw_suggest=true
|
||||
"verboD": contains=true check=true suggest=true raw_suggest=true
|
||||
"verboE": contains=true check=true suggest=true raw_suggest=true
|
||||
"verboF": contains=true check=true suggest=true raw_suggest=true
|
||||
"verboG": contains=true check=true suggest=true raw_suggest=true
|
||||
"verboH": contains=true check=true suggest=true raw_suggest=true
|
||||
"verboI": contains=true check=true suggest=true raw_suggest=true
|
||||
"verboJ": contains=true check=true suggest=true raw_suggest=true
|
||||
"verboK": contains=true check=true suggest=true raw_suggest=true
|
||||
"verboL": contains=true check=true suggest=true raw_suggest=true
|
||||
"verboM": contains=true check=true suggest=true raw_suggest=true
|
||||
"verboN": contains=true check=true suggest=true raw_suggest=true
|
||||
"verboO": contains=true check=true suggest=true raw_suggest=true
|
||||
"verboP": contains=true check=true suggest=true raw_suggest=true
|
||||
"verboQ": contains=true check=true suggest=true raw_suggest=true
|
||||
"verboR": contains=true check=true suggest=true raw_suggest=true
|
||||
"verboS": contains=true check=true suggest=true raw_suggest=true
|
||||
"verboT": contains=true check=true suggest=true raw_suggest=true
|
||||
"verboU": contains=true check=true suggest=true raw_suggest=true
|
||||
"verboV": contains=true check=true suggest=true raw_suggest=true
|
||||
"verboW": contains=true check=true suggest=true raw_suggest=true
|
||||
"verboX": contains=true check=true suggest=true raw_suggest=true
|
||||
"verboY": contains=true check=true suggest=true raw_suggest=true
|
||||
"verboZ": contains=true check=true suggest=true raw_suggest=true
|
||||
"verboa": contains=true check=true suggest=true raw_suggest=true
|
||||
"verbob": contains=true check=true suggest=true raw_suggest=true
|
||||
"verboc": contains=true check=true suggest=true raw_suggest=true
|
||||
"verbod": contains=true check=true suggest=true raw_suggest=true
|
||||
"verboe": contains=true check=true suggest=true raw_suggest=true
|
||||
"verbof": contains=true check=true suggest=true raw_suggest=true
|
||||
"verbog": contains=true check=true suggest=true raw_suggest=true
|
||||
"verboh": contains=true check=true suggest=true raw_suggest=true
|
||||
"verboi": contains=true check=true suggest=true raw_suggest=true
|
||||
"verboj": contains=true check=true suggest=true raw_suggest=true
|
||||
"verbok": contains=true check=true suggest=true raw_suggest=true
|
||||
"verbol": contains=true check=true suggest=true raw_suggest=true
|
||||
"verbom": contains=true check=true suggest=true raw_suggest=true
|
||||
"verbon": contains=true check=true suggest=true raw_suggest=true
|
||||
"verboo": contains=true check=true suggest=true raw_suggest=true
|
||||
"verbop": contains=true check=true suggest=true raw_suggest=true
|
||||
"verboq": contains=true check=true suggest=true raw_suggest=true
|
||||
"verbor": contains=true check=true suggest=true raw_suggest=true
|
||||
"verbos": contains=true check=true suggest=true raw_suggest=true
|
||||
"verbot": contains=true check=true suggest=true raw_suggest=true
|
||||
"verbou": contains=true check=true suggest=true raw_suggest=true
|
||||
"verbov": contains=true check=true suggest=true raw_suggest=true
|
||||
"verbow": contains=true check=true suggest=true raw_suggest=true
|
||||
"verbox": contains=true check=true suggest=true raw_suggest=true
|
||||
"verboy": contains=true check=true suggest=true raw_suggest=true
|
||||
"verboz": contains=true check=true suggest=true raw_suggest=true
|
||||
"verboß": contains=false check=false suggest=false raw_suggest=false
|
||||
"verboá": contains=true check=true suggest=true raw_suggest=true
|
||||
"verboã": contains=true check=true suggest=true raw_suggest=true
|
||||
"verboç": contains=true check=true suggest=true raw_suggest=true
|
||||
"verboé": contains=true check=true suggest=true raw_suggest=true
|
||||
"verboí": contains=true check=true suggest=true raw_suggest=true
|
||||
"verboó": contains=true check=true suggest=true raw_suggest=true
|
||||
"verboõ": contains=true check=true suggest=true raw_suggest=true
|
||||
"verboú": contains=true check=true suggest=true raw_suggest=true
|
||||
@@ -0,0 +1,61 @@
|
||||
// Original, deliberately small fixtures for behavior supported before French proofing.
|
||||
// These are not extracts from installed dictionaries and do not claim full language coverage.
|
||||
pub struct Case {
|
||||
pub name: &'static str,
|
||||
pub aff: String,
|
||||
pub dic: String,
|
||||
pub probes: Vec<&'static str>,
|
||||
}
|
||||
|
||||
pub fn cases() -> Vec<Case> {
|
||||
let mut out = vec![
|
||||
Case {
|
||||
name: "pl: conditional strip, prefix cross products, diacritics",
|
||||
aff: "SET UTF-8\nTRY aeoiułkr\nPFX b Y 1\nPFX b 0 nie .\nSFX a Y 3\nSFX a 0 y [^y]\nSFX a ek ka ek\nSFX a 0 em .\nSFX c N 1\nSFX c a ą a\nMAP 2\nMAP aą\nMAP oóu\nREP 2\nREP ż rz\nREP u ó\n".into(),
|
||||
dic: "4\nkot/ab\npiesek/a\nkrowa/c\nWarszawa/c\n".into(),
|
||||
probes: vec!["kot", "koty", "kotem", "niekoty", "pieska", "pieseka", "niepieska", "krową", "krowy", "Warszawą", "warszawą", "kotą", "nie", ""],
|
||||
},
|
||||
Case {
|
||||
name: "pt: UTF-8 flags, forbidden words, two suffixes",
|
||||
aff: "SET UTF-8\nFLAG UTF-8\nFORBIDDENWORD ý\nTRY aeiouçãõ\nSFX A Y 1\nSFX A o a/B o\nSFX B Y 1\nSFX B 0 s .\nPFX P Y 1\nPFX P 0 re .\n".into(),
|
||||
dic: "4\nbonito/AB\ncasa/B\nfazer/P\nimundo/ýB\n".into(),
|
||||
probes: vec!["bonito", "bonita", "bonitos", "bonitas", "bonitass", "casa", "casas", "casaa", "refazer", "recasas", "imundo", "imundos", "Imundo", "IMUNDO"],
|
||||
},
|
||||
Case {
|
||||
name: "it: stripping, non-crossing suffix, proper-name casing",
|
||||
aff: "SET UTF-8\nSFX A Y 1\nSFX A o i o\nSFX B N 1\nSFX B a e a\nPFX P Y 1\nPFX P 0 ri .\n".into(),
|
||||
dic: "4\nlibro/A\ncasa/BP\nfare/P\nRoma\n".into(),
|
||||
probes: vec!["libri", "libros", "case", "ricas a", "ricasa", "ricase", "rifare", "r ilibri", "Roma", "roma", "ROMA", ""],
|
||||
},
|
||||
Case {
|
||||
name: "cs: negated conditions and shared Unicode stems",
|
||||
aff: "SET UTF-8\nPFX N Y 1\nPFX N 0 ne .\nSFX S Y 1\nSFX S 0 y [^y]\nSFX E N 1\nSFX E a ě a\n".into(),
|
||||
dic: "4\nstrom/NS\nžena/E\nmladý/N\ny/S\n".into(),
|
||||
probes: vec!["stromy", "nestromy", "nestrom", "ženě", "ženy", "neženě", "nemladý", "mladýy", "yy", "Ženě", "STROMY"],
|
||||
},
|
||||
Case {
|
||||
name: "ru: Cyrillic flags and suggestions exclusion",
|
||||
aff: "SET UTF-8\nFLAG UTF-8\nNOSUGGEST Н\nFORBIDDENWORD Ф\nSFX Я Y 1\nSFX Я 0 ы .\nPFX П Y 1\nPFX П 0 не .\nMAP 1\nMAP её\n".into(),
|
||||
dic: "4\nкот/ЯП\nдом/Я\nтайна/НЯ\nзапрет/ФЯ\n".into(),
|
||||
probes: vec!["кот", "коты", "некоты", "домы", "недомы", "тайна", "тайнаы", "ТАЙНАЫ", "запрет", "запреты", "КОТЫ", "кОт"],
|
||||
},
|
||||
Case {
|
||||
name: "id: continuation and NOSUGGEST through derivations",
|
||||
aff: "SET UTF-8\nNOSUGGEST N\nKEY qwerty|asdf\nTRY abcdeikn\nREP 1\nREP dj j\nPFX P Y 1\nPFX P 0 ber .\nSFX A Y 1\nSFX A 0 kan/B .\nSFX B Y 1\nSFX B 0 lah .\n".into(),
|
||||
dic: "3\nmain/PA\nbaca/A\nrahasia/NA\n".into(),
|
||||
probes: vec!["main", "bermain", "mainkan", "mainkanlah", "bermainkanlah", "mainlah", "mainkanlahlah", "bacakanlah", "berbaca", "rahasia", "rahasiakan", "RAHASIAKANLAH"],
|
||||
},
|
||||
];
|
||||
let flags: Vec<char> = ('a'..='z').chain('A'..='Z').chain('0'..='9').chain(['á', 'é', 'í', 'ó', 'ú', 'ç', 'ã', 'õ']).collect();
|
||||
let mut aff = String::from("SET UTF-8\nFLAG UTF-8\n");
|
||||
for flag in &flags {
|
||||
aff.push_str(&format!("SFX {flag} N 1\nSFX {flag} 0 {flag} .\n"));
|
||||
}
|
||||
out.push(Case {
|
||||
name: "pt-sized: 70 distinct flags across the old u128 boundary",
|
||||
aff,
|
||||
dic: format!("2\nverbo/{}\noutro/õ\n", flags.iter().collect::<String>()),
|
||||
probes: vec!["verboa", "verboz", "verboA", "verboZ", "verbo0", "verbo9", "verboç", "verboõ", "verboß", "outroõ", "outroa"],
|
||||
});
|
||||
out
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
//! Explicit manual real-dictionary gate. Verify the pinned runtime inputs as documented in
|
||||
//! crates/proof/README.md before running with `--ignored`. Missing data is a failure,
|
||||
//! never a silently successful test that checked nothing.
|
||||
|
||||
#![cfg(not(target_arch = "wasm32"))]
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used)]
|
||||
|
||||
use craft_proof::{IssueKind, Options, ProofLang, fr};
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires a real French dictionary in WORDCRAFT_DICTIONARIES"]
|
||||
fn real_french_dictionary_spelling_suggestions_and_dispatch() {
|
||||
let directory = std::env::var_os("WORDCRAFT_DICTIONARIES").expect("set WORDCRAFT_DICTIONARIES to the test dictionary folder");
|
||||
craft_proof::set_dictionaries_folder(Some(std::path::PathBuf::from(&directory)));
|
||||
let french = ProofLang::from_tag(Some("fr-FR"));
|
||||
let installed = craft_proof::pack_dictionary_file(french).expect("the real French dictionary must be installed");
|
||||
assert_eq!(installed.parent(), Some(std::path::Path::new(&directory)), "do not silently use another system dictionary");
|
||||
let aff = installed.with_extension("aff");
|
||||
let dictionary = craft_proof::hunspell::load(&aff, &installed).expect("the real French dictionary loads");
|
||||
assert!(dictionary.len() > 50_000, "expected Dicollecte, not the synthetic fixture: {}", dictionary.len());
|
||||
for word in [
|
||||
"maison",
|
||||
"maisons",
|
||||
"Paris",
|
||||
"mangeons",
|
||||
"finissaient",
|
||||
"étaient",
|
||||
"l'arbre",
|
||||
"l’arbre",
|
||||
"qu'elles",
|
||||
"école",
|
||||
"œuvre",
|
||||
"aujourd'hui",
|
||||
"chevaux",
|
||||
"heureuse",
|
||||
"va-t-il",
|
||||
] {
|
||||
assert!(fr::is_correct(word), "correct French word: {word}");
|
||||
}
|
||||
for (typo, expected) in [("maisonn", "maison"), ("ecole", "école"), ("l’ecole", "l’école"), ("documant", "document")] {
|
||||
assert!(!fr::is_correct(typo), "misspelling: {typo}");
|
||||
let suggestions = fr::suggest(typo, 8);
|
||||
assert!(suggestions.iter().any(|s| s == expected), "{typo} -> {suggestions:?}, expected {expected}");
|
||||
}
|
||||
let text = "Une maisonn près de l’école.";
|
||||
for lang in [ProofLang::from_tag(Some("fr-FR")), ProofLang::from_tag(Some("fr-CA"))] {
|
||||
let issues = craft_proof::check_text(text, &[(0..text.len(), lang)]);
|
||||
assert_eq!(issues.len(), 1, "{lang:?}: {issues:?}");
|
||||
let issue = &issues[0];
|
||||
assert_eq!(&text[issue.start..issue.end], "maisonn");
|
||||
assert_eq!(issue.lang, lang);
|
||||
assert_eq!(issue.message, "Faute d’orthographe possible");
|
||||
}
|
||||
check_combining_marks_and_compounds(&dictionary);
|
||||
assert!(craft_proof::dictionary_load_error(ProofLang::from_tag(Some("fr-FR"))).is_none());
|
||||
}
|
||||
|
||||
fn check_combining_marks_and_compounds(dictionary: &craft_proof::affix::AffixDict) {
|
||||
let spelling = |text: &str, spans: &[(std::ops::Range<usize>, ProofLang)]| {
|
||||
craft_proof::check_text_with(text, spans, &Options::default(), false, false)
|
||||
.into_iter()
|
||||
.filter(|i| i.kind == IssueKind::Spelling)
|
||||
.map(|i| (i.start, i.end, i.lang))
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
let mut failures = Vec::new();
|
||||
for lang in [ProofLang::from_tag(Some("fr-FR")), ProofLang::from_tag(Some("fr-CA"))] {
|
||||
for text in
|
||||
["école", "e\u{301}cole", "l’école", "l’e\u{301}cole", "café", "cafe\u{301}", "porte-monnaie", "va-t-il", "a-t-il", "maison-école"]
|
||||
{
|
||||
assert!(
|
||||
fr::is_correct_with(dictionary, text) || ["va-t-il", "a-t-il", "maison-école"].contains(&text),
|
||||
"real dictionary recognizes {text:?}"
|
||||
);
|
||||
let issues = spelling(text, &[(0..text.len(), lang)]);
|
||||
if !issues.is_empty() {
|
||||
failures.push(format!("correct {lang:?} {text:?}: {issues:?}"));
|
||||
}
|
||||
}
|
||||
for text in ["porte--monnaie", "va--t-il", "maison--école", "e\u{301}colllle", "cafffe\u{301}"] {
|
||||
assert!(!fr::is_correct_with(dictionary, text), "the explicit dictionary entry must not already accept {text:?}");
|
||||
let issues = spelling(text, &[(0..text.len(), lang)]);
|
||||
let expected = vec![(0, text.len(), lang)];
|
||||
if issues != expected {
|
||||
failures.push(format!("typo {lang:?} {text:?}: {issues:?}, wanted {expected:?}"));
|
||||
}
|
||||
}
|
||||
let text = "e\u{301}cole cafe\u{301} xyzxyz porte--monnaie";
|
||||
let foreign = text.find("xyzxyz").unwrap();
|
||||
let compound = text.find("porte").unwrap();
|
||||
let spans = [(0..foreign, lang), (foreign..compound, ProofLang::Other), (compound..text.len(), lang)];
|
||||
let issues = spelling(text, &spans);
|
||||
if issues != [(compound, text.len(), lang)] {
|
||||
failures.push(format!("mixed {lang:?}: {issues:?}"));
|
||||
}
|
||||
assert!(spelling(text, &[(0..text.len(), ProofLang::Other)]).is_empty());
|
||||
// An English word remains in its own dictionary next to the original French bytes.
|
||||
let text = "e\u{301}cole hello cafe\u{301}";
|
||||
let en = text.find("hello").unwrap();
|
||||
let spans = [(0..en, lang), (en..en + 5, ProofLang::En), (en + 5..text.len(), lang)];
|
||||
let issues = spelling(text, &spans);
|
||||
if !issues.is_empty() {
|
||||
failures.push(format!("English boundary {lang:?}: {issues:?}"));
|
||||
}
|
||||
}
|
||||
assert!(failures.is_empty(), "{}", failures.join("\n"));
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
//! French uses ordinary Language packs and keeps each regional locale at the public API.
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used)]
|
||||
|
||||
use craft_proof::affix;
|
||||
use craft_proof::{IssueKind, Options, ProofLang, check_text_with, is_correct_in_with, suggest_in};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
#[path = "../src/fr/test_dict.rs"]
|
||||
mod fixture;
|
||||
|
||||
struct Tools(PathBuf);
|
||||
impl Drop for Tools {
|
||||
fn drop(&mut self) {
|
||||
craft_proof::set_dictionaries_folder(None);
|
||||
craft_proof::packs::set_packs_dir(None);
|
||||
craft_proof::remove_word("zxqrechargefr");
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
fn pair(dir: &Path, name: &str, aff: &str, dic: &str) {
|
||||
std::fs::create_dir_all(dir).unwrap();
|
||||
std::fs::write(dir.join(format!("{name}.aff")), aff).unwrap();
|
||||
std::fs::write(dir.join(format!("{name}.dic")), dic).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn french_packs_regions_reload_and_original_ranges() {
|
||||
assert!(!fixture::dictionary().is_empty());
|
||||
let root = std::env::temp_dir().join(format!("craft-fr-packs-{}", std::process::id()));
|
||||
let _tools = Tools(root.clone());
|
||||
let pack = root.join("packs/fr");
|
||||
pair(&pack, "spelling", fixture::AFF, fixture::DIC);
|
||||
std::fs::write(pack.join("pack.toml"), "locale = 'fr'\nname = 'Français'\nlicence = 'MIT'\n").unwrap();
|
||||
std::fs::write(pack.join("hyphenation.pat"), "ma1ison\n").unwrap();
|
||||
let folder = root.join("dictionaries");
|
||||
std::fs::create_dir_all(&folder).unwrap();
|
||||
craft_proof::packs::set_packs_dir(Some(root.join("packs")));
|
||||
craft_proof::set_dictionaries_folder(Some(folder.clone()));
|
||||
let defaults = Options::default();
|
||||
let strict = Options { ignore_uppercase: false, ignore_numbers: false, ..defaults };
|
||||
check_locales(defaults, strict);
|
||||
check_typography(strict);
|
||||
let fr = ProofLang::from_tag(Some("fr-FR"));
|
||||
let ca = ProofLang::from_tag(Some("fr-CA"));
|
||||
check_user_word(fr, ca, strict);
|
||||
check_overrides(folder, fr, ca, strict);
|
||||
}
|
||||
|
||||
fn check_locales(defaults: Options, strict: Options) {
|
||||
for tag in ["fr", "fr-FR", "fr-CA", "fr-BE", "fr-CA-u-nu-latn", "fr-u-ca-gregory"] {
|
||||
let lang = ProofLang::from_tag(Some(tag));
|
||||
assert!(matches!(lang, ProofLang::Pack(_)), "{tag}");
|
||||
assert!(craft_proof::has_dictionary(Some(tag)), "{tag}");
|
||||
assert!(craft_proof::pack_dictionary_file(lang).unwrap().ends_with("fr/spelling.dic"), "{tag}");
|
||||
for word in ["école", "e\u{301}cole", "l'arbre", "l’arbre", "maison-école"] {
|
||||
assert!(is_correct_in_with(word, lang, &strict), "{tag}: {word}");
|
||||
}
|
||||
assert!(!is_correct_in_with("maison--école", lang, &strict));
|
||||
assert!(!is_correct_in_with("l'arbres", lang, &strict));
|
||||
assert!(is_correct_in_with("SNCF", lang, &defaults));
|
||||
assert!(!is_correct_in_with("SNCF", lang, &strict));
|
||||
assert!(is_correct_in_with("mp3x", lang, &defaults));
|
||||
assert!(!is_correct_in_with("mp3x", lang, &strict));
|
||||
assert!(suggest_in("ecole", 6, lang).iter().any(|s| s == "école"));
|
||||
let text = "🙂 maison\u{338} école";
|
||||
let issues = check_text_with(text, &[(0..text.len(), lang)], &strict, false, false);
|
||||
assert_eq!(issues.len(), 1, "{tag}: {issues:?}");
|
||||
assert_eq!(&text[issues[0].start..issues[0].end], "maison\u{338}");
|
||||
assert_eq!(issues[0].lang, lang);
|
||||
assert_eq!(issues[0].kind, IssueKind::Spelling);
|
||||
assert_eq!(issues[0].message, "Faute d’orthographe possible");
|
||||
}
|
||||
}
|
||||
|
||||
fn check_typography(strict: Options) {
|
||||
let fr = ProofLang::from_tag(Some("fr-FR"));
|
||||
let ca = ProofLang::from_tag(Some("fr-CA"));
|
||||
for lang in [fr, ca] {
|
||||
assert_eq!(craft_proof::hyphen::hyphen_points_in("maison", &craft_proof::hyphen::Limits::default(), lang), [2]);
|
||||
}
|
||||
for tag in ["fr-FR", "fr-BE", "fr-u-ca-gregory", "fr-FR-u-rg-cazzzz"] {
|
||||
let issues = craft_proof::check_grammar_in("Bonjour!", ProofLang::from_tag(Some(tag)));
|
||||
assert_eq!(issues.len(), 1, "{tag}: {issues:?}");
|
||||
assert_eq!(issues[0].suggestions, ["\u{202f}!"]);
|
||||
}
|
||||
assert!(craft_proof::check_grammar_in("Bonjour!", ca).is_empty());
|
||||
assert!(craft_proof::check_grammar_in("Bonjour!", ProofLang::from_tag(Some("fr-Latn-CA"))).is_empty());
|
||||
assert!(craft_proof::check_grammar_in("Bonjour!", ProofLang::from_tag(Some("nl-NL"))).is_empty());
|
||||
assert!(craft_proof::fr::grammar::check_in("Bonjour!", ProofLang::En).is_empty());
|
||||
let text = "Bonjour! Salut!";
|
||||
let issues = check_text_with(text, &[(0..8, fr), (8..text.len(), ca)], &strict, true, false);
|
||||
let spacing: Vec<_> = issues.iter().filter(|i| i.kind == IssueKind::Grammar && i.message.contains("fine insécable")).collect();
|
||||
assert_eq!(spacing.len(), 1, "{issues:?}");
|
||||
assert_eq!(spacing[0].lang, fr);
|
||||
}
|
||||
|
||||
fn check_user_word(fr: ProofLang, ca: ProofLang, strict: Options) {
|
||||
craft_proof::add_word("zxqrechargefr");
|
||||
for lang in [fr, ca] {
|
||||
assert!(is_correct_in_with("l’zxqrechargefr", lang, &strict));
|
||||
}
|
||||
craft_proof::remove_word("zxqrechargefr");
|
||||
assert!(!is_correct_in_with("l’zxqrechargefr", ca, &strict));
|
||||
}
|
||||
|
||||
fn check_overrides(folder: PathBuf, fr: ProofLang, ca: ProofLang, strict: Options) {
|
||||
// Regional overrides keep the generic pack fallback and the shared reload generation.
|
||||
pair(&folder, "fr_FR", "SET UTF-8\n", "1\nhexagonefixture\n");
|
||||
pair(&folder, "fr_CA", "SET UTF-8\n", "1\nquebecfixture\n");
|
||||
let generation = craft_proof::dictionary_generation();
|
||||
craft_proof::set_dictionaries_folder(Some(folder.clone()));
|
||||
assert!(craft_proof::dictionary_generation() > generation);
|
||||
assert!(is_correct_in_with("hexagonefixture", fr, &strict));
|
||||
assert!(!is_correct_in_with("hexagonefixture", ca, &strict));
|
||||
assert!(is_correct_in_with("quebecfixture", ca, &strict));
|
||||
assert!(!is_correct_in_with("quebecfixture", fr, &strict));
|
||||
assert!(craft_proof::pack_dictionary_file(ca).unwrap().ends_with("fr_CA.dic"));
|
||||
std::fs::remove_file(folder.join("fr_CA.dic")).unwrap();
|
||||
std::fs::remove_file(folder.join("fr_CA.aff")).unwrap();
|
||||
craft_proof::set_dictionaries_folder(Some(folder));
|
||||
assert!(is_correct_in_with("école", ca, &strict), "removed regional override falls back to fr pack");
|
||||
assert!(craft_proof::pack_dictionary_file(ca).unwrap().ends_with("fr/spelling.dic"));
|
||||
}
|
||||
+52
-11
@@ -188,6 +188,10 @@ fn string(srcs: &mut Sources, src: usize) -> Result<Vec<u8>, String> {
|
||||
}
|
||||
|
||||
fn hex(srcs: &mut Sources, src: usize) -> Result<Vec<u8>, String> {
|
||||
hex_with_limit(srcs, src, MAX_TOKEN)
|
||||
}
|
||||
|
||||
fn hex_with_limit(srcs: &mut Sources, src: usize, max: usize) -> Result<Vec<u8>, String> {
|
||||
let mut out = Vec::new();
|
||||
let mut hi: Option<u8> = None;
|
||||
loop {
|
||||
@@ -205,20 +209,21 @@ fn hex(srcs: &mut Sources, src: usize) -> Result<Vec<u8>, String> {
|
||||
_ => return Err("bad hex string".into()),
|
||||
};
|
||||
match hi.take() {
|
||||
Some(h) => out.push(h << 4 | v),
|
||||
Some(h) => append_string_bytes(&mut out, &[h << 4 | v], max)?,
|
||||
None => hi = Some(v),
|
||||
}
|
||||
if out.len() > MAX_TOKEN {
|
||||
return Err("string too long".into());
|
||||
}
|
||||
}
|
||||
if let Some(h) = hi {
|
||||
out.push(h << 4);
|
||||
append_string_bytes(&mut out, &[h << 4], max)?;
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn ascii85(srcs: &mut Sources, src: usize) -> Result<Vec<u8>, String> {
|
||||
ascii85_with_limit(srcs, src, MAX_TOKEN)
|
||||
}
|
||||
|
||||
fn ascii85_with_limit(srcs: &mut Sources, src: usize, max: usize) -> Result<Vec<u8>, String> {
|
||||
let mut out = Vec::new();
|
||||
let mut group = [0u64; 5];
|
||||
let mut n = 0;
|
||||
@@ -234,7 +239,7 @@ fn ascii85(srcs: &mut Sources, src: usize) -> Result<Vec<u8>, String> {
|
||||
break;
|
||||
}
|
||||
if c == b'z' && n == 0 {
|
||||
out.extend([0; 4]);
|
||||
append_string_bytes(&mut out, &[0; 4], max)?;
|
||||
continue;
|
||||
}
|
||||
if !(b'!'..=b'u').contains(&c) {
|
||||
@@ -246,12 +251,9 @@ fn ascii85(srcs: &mut Sources, src: usize) -> Result<Vec<u8>, String> {
|
||||
n += 1;
|
||||
if n == 5 {
|
||||
let v = group.iter().fold(0u64, |a, d| a * 85 + d);
|
||||
out.extend(u32::try_from(v).map_err(|_| "ASCII85 overflow")?.to_be_bytes());
|
||||
append_string_bytes(&mut out, &u32::try_from(v).map_err(|_| "ASCII85 overflow")?.to_be_bytes(), max)?;
|
||||
n = 0;
|
||||
}
|
||||
if out.len() > MAX_TOKEN {
|
||||
return Err("string too long".into());
|
||||
}
|
||||
}
|
||||
if n > 1 {
|
||||
for g in group.iter_mut().skip(n) {
|
||||
@@ -259,11 +261,21 @@ fn ascii85(srcs: &mut Sources, src: usize) -> Result<Vec<u8>, String> {
|
||||
}
|
||||
let v = group.iter().fold(0u64, |a, d| a * 85 + d).min(u64::from(u32::MAX));
|
||||
let v = u32::try_from(v).unwrap_or(u32::MAX);
|
||||
out.extend(v.to_be_bytes().iter().take(n - 1));
|
||||
append_string_bytes(&mut out, v.to_be_bytes().get(..n - 1).unwrap_or_default(), max)?;
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
// Check before every decoded append: zero shorthand and final partial groups can
|
||||
// produce bytes without passing through the ordinary complete-group branch.
|
||||
fn append_string_bytes(out: &mut Vec<u8>, bytes: &[u8], max: usize) -> Result<(), String> {
|
||||
if bytes.len() > max.saturating_sub(out.len()) {
|
||||
return Err("string too long".into());
|
||||
}
|
||||
out.extend_from_slice(bytes);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// An integer, radix number (`16#FF`) or real; None for anything else.
|
||||
pub fn number(t: &[u8]) -> Option<Obj> {
|
||||
let s = std::str::from_utf8(t).ok()?;
|
||||
@@ -321,6 +333,35 @@ mod tests {
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encoded_strings_obey_the_decoded_budget_at_every_append() {
|
||||
fn decode(input: &[u8], max: usize, ascii85: bool) -> Result<Vec<u8>, String> {
|
||||
let mut sources = Sources::default();
|
||||
let id = sources.add(Source::bytes(input.to_vec()));
|
||||
if ascii85 { ascii85_with_limit(&mut sources, id, max) } else { hex_with_limit(&mut sources, id, max) }
|
||||
}
|
||||
for (input, expected) in [
|
||||
(b"~>".as_slice(), vec![]),
|
||||
(b"z~>", vec![0; 4]),
|
||||
(b"zz~>", vec![0; 8]),
|
||||
(b"!!!!!~>", vec![0; 4]),
|
||||
(b"z!!~>", vec![0; 5]),
|
||||
(b"!!!!!!!!~>", vec![0; 6]),
|
||||
(b"!!!!~>", vec![0; 3]),
|
||||
] {
|
||||
assert_eq!(decode(input, expected.len(), true).unwrap(), expected);
|
||||
if !expected.is_empty() {
|
||||
assert_eq!(decode(input, expected.len() - 1, true).unwrap_err(), "string too long");
|
||||
}
|
||||
}
|
||||
for (input, expected) in [(b">".as_slice(), vec![]), (b"41>", vec![0x41]), (b"414>", vec![0x41, 0x40]), (b"4>", vec![0x40])] {
|
||||
assert_eq!(decode(input, expected.len(), false).unwrap(), expected);
|
||||
if !expected.is_empty() {
|
||||
assert_eq!(decode(input, expected.len() - 1, false).unwrap_err(), "string too long");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scans_the_token_kinds() {
|
||||
let t = all(b"12 -3.5 1e3 16#FF /lit name (a\\(b\\)\\101\\\n c) <41 42> <~87cURDZ~> {1 {2} add} //x [ ] << >> % note\n.5 1.e2 -.");
|
||||
|
||||
@@ -438,7 +438,9 @@ fn read_descriptor(r: &mut Reader<'_>, depth: usize, limits: ParseLimits) -> Res
|
||||
let mut items = vec_for_count(n);
|
||||
for _ in 0..n {
|
||||
let key = Id::read(r)?;
|
||||
let v = read_value(r, depth + 1, limits)?;
|
||||
// A descriptor item is not another container; Objc/GlbO/ObAr and lists
|
||||
// charge their nested containers exactly once below.
|
||||
let v = read_value(r, depth, limits)?;
|
||||
items.push((key, v));
|
||||
}
|
||||
Ok(Descriptor { name, class_id, items })
|
||||
@@ -837,6 +839,30 @@ mod tests {
|
||||
assert!(matches!(Descriptor::from_bytes(&b), Err(PsdError::Unsupported(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn container_depth_is_charged_once_and_still_bounded() {
|
||||
for kind in ["Objc", "GlbO", "ObAr", "VlLs"] {
|
||||
for count in [33, MAX_DEPTH, MAX_DEPTH + 1] {
|
||||
let mut value = Value::Integer(1);
|
||||
for _ in 0..count {
|
||||
value = match kind {
|
||||
"GlbO" => Value::GlobalObject(Descriptor::new("null").with("next", value)),
|
||||
"ObAr" => Value::ObjectArray(ObjectArray { prefix: 16, body: Descriptor::new("null").with("next", value) }),
|
||||
"VlLs" => Value::List(vec![value]),
|
||||
_ => Value::Descriptor(Descriptor::new("null").with("next", value)),
|
||||
};
|
||||
}
|
||||
let bytes = Descriptor::new("null").with("root", value).to_bytes();
|
||||
let result = Descriptor::from_bytes(&bytes);
|
||||
if count <= MAX_DEPTH {
|
||||
assert!(result.is_ok(), "{kind} depth {count}: {result:?}");
|
||||
} else {
|
||||
assert!(matches!(result, Err(PsdError::LimitExceeded(_))), "{kind} depth {count}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deep_nesting_is_limited() {
|
||||
let mut d = Descriptor::new("null");
|
||||
|
||||
+414
-19
@@ -8,7 +8,8 @@
|
||||
//! bicubic Bézier patches.
|
||||
//!
|
||||
//! The custom mesh is evaluated exactly (bicubic Bézier patches over `meshPoints`, split by
|
||||
//! `quiltSliceX` / `quiltSliceY`). Photoshop does not publish the curves of its named styles;
|
||||
//! equally spaced `quiltSliceX` / `quiltSliceY`). Unequal divisions are rejected by the
|
||||
//! fallible placement reader. Photoshop does not publish the curves of its named styles;
|
||||
//! the styles here are clean-room geometric definitions of what each name describes (Arc,
|
||||
//! Arch, Bulge, Shell, Flag, Wave, Fish, Rise, Fisheye, Inflate, Squeeze, Twist), matched by
|
||||
//! behaviour, not numerically.
|
||||
@@ -59,9 +60,31 @@ pub struct Warp {
|
||||
|
||||
/// The eight numbers of a transform entry (`Trnf`, `nonAffineTransform`), when it has exactly eight.
|
||||
fn eight(d: &Descriptor, key: &str) -> Option<[f64; 8]> {
|
||||
d.get_numbers(key).try_into().ok()
|
||||
d.get_numbers(key).into_iter().map(finite).collect::<Vec<_>>().try_into().ok()
|
||||
}
|
||||
|
||||
fn finite(value: f64) -> f64 {
|
||||
if value.is_finite() { value } else { 0.0 }
|
||||
}
|
||||
|
||||
/// A usable normalization rectangle needs finite positive extents on both axes.
|
||||
fn valid_bounds([l, t, r, b]: [f64; 4]) -> bool {
|
||||
[l, t, r, b].iter().all(|v| v.is_finite()) && (r - l).is_finite() && r > l && (b - t).is_finite() && b > t
|
||||
}
|
||||
/// Explicit quilt rectangles must be complete even without subdivision keys.
|
||||
fn validate_quilt_bounds(d: &Descriptor) -> Result<()> {
|
||||
if d.get("bounds").is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
let bounds = d
|
||||
.get_object("bounds")
|
||||
.and_then(|b| Some([b.get_number("Left")?, b.get_number("Top ")?, b.get_number("Rght")?, b.get_number("Btom")?]))
|
||||
.ok_or_else(|| PsdError::Unsupported("incomplete explicit quilt bounds".into()))?;
|
||||
if !valid_bounds(bounds.map(finite)) {
|
||||
return Err(PsdError::Unsupported("invalid explicit quilt bounds".into()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// The corner quad (top-left, top-right, bottom-right, bottom-left) from x0 y0 … x3 y3.
|
||||
fn quad_from(t: [f64; 8]) -> [[f64; 2]; 4] {
|
||||
[[t[0], t[1]], [t[2], t[3]], [t[4], t[5]], [t[6], t[7]]]
|
||||
@@ -69,24 +92,76 @@ fn quad_from(t: [f64; 8]) -> [[f64; 2]; 4] {
|
||||
|
||||
/// The patch boundaries of a custom envelope: a list of numbers, or (as Photoshop writes a
|
||||
/// `quiltWarp`) an object array whose body holds them under the same key.
|
||||
fn quilt_slices(env: &Descriptor, key: &str) -> Vec<f64> {
|
||||
match env.get(key) {
|
||||
Some(Value::ObjectArray(o)) => o.body.get_numbers(key),
|
||||
_ => env.get_numbers(key),
|
||||
}
|
||||
fn quilt_slices(env: &Descriptor, key: &str) -> Result<Vec<f64>> {
|
||||
let Some(value) = env.get(key) else { return Ok(vec![]) };
|
||||
// Filtering nonnumbers would change the number and positions of patches.
|
||||
// Only absence, not a malformed or empty present value, means one patch.
|
||||
let value = if let Value::ObjectArray(o) = value { o.body.get(key) } else { Some(value) };
|
||||
let values = match value {
|
||||
Some(Value::UnitFloats { values, .. }) => Some(values.clone()),
|
||||
Some(Value::List(values)) => values.iter().map(Value::as_number).collect::<Option<Vec<_>>>(),
|
||||
_ => None,
|
||||
};
|
||||
values.filter(|values| !values.is_empty()).ok_or_else(|| PsdError::Unsupported("invalid quilt slice values".into()))
|
||||
}
|
||||
|
||||
/// The public mesh has no slice coordinates, so only uniform divisions can be
|
||||
/// represented faithfully. Keep the legacy absent-slices single-patch convention.
|
||||
fn quilt_patches(slices: &[f64]) -> Result<usize> {
|
||||
if slices.is_empty() {
|
||||
return Ok(1);
|
||||
}
|
||||
if slices.len() < 2 || slices.iter().any(|v| !v.is_finite()) {
|
||||
return Err(PsdError::Unsupported("invalid quilt divisions".into()));
|
||||
}
|
||||
let patches = slices.len() - 1;
|
||||
let extent = slices[patches] - slices[0];
|
||||
if !extent.is_finite() || extent <= 0.0 {
|
||||
return Err(PsdError::Unsupported("invalid quilt divisions".into()));
|
||||
}
|
||||
// Compare against the same endpoint interpolation the writer uses. At large
|
||||
// coordinate offsets a uniform grid can have differently rounded adjacent widths,
|
||||
// including coincident boundaries. Only canonical rounded positions are accepted;
|
||||
// the model keeps the patch count and evaluates in its uniform parameter domain.
|
||||
let tolerance = (extent / patches as f64) * 1e-9;
|
||||
if slices.windows(2).any(|pair| pair[1] < pair[0])
|
||||
|| slices.iter().enumerate().take(patches).skip(1).any(|(i, value)| {
|
||||
let expected = slices[0] + extent * (i as f64 / patches as f64);
|
||||
!expected.is_finite() || (value - expected).abs() > tolerance
|
||||
})
|
||||
{
|
||||
return Err(PsdError::Unsupported("unequal quilt divisions".into()));
|
||||
}
|
||||
Ok(patches)
|
||||
}
|
||||
impl Warp {
|
||||
/// Reads a `warp` descriptor; `None` for no warp (the identity, or a custom warp without a
|
||||
/// usable mesh).
|
||||
/// usable mesh), or an unsupported quilt. Use [`Self::try_from_descriptor`] to report unsupported geometry.
|
||||
pub fn from_descriptor(d: &Descriptor) -> Option<Warp> {
|
||||
Self::try_from_descriptor(d).ok().flatten()
|
||||
}
|
||||
|
||||
/// Reads a warp, rejecting unequal or invalid quilt divisions rather than
|
||||
/// interpreting them as equal-sized patches. Canonical uniform boundaries may coincide
|
||||
/// after floating-point rounding; their patch count is retained. This is the internal
|
||||
/// uniform-model contract, not a guarantee of other readers' handling of coincident slices.
|
||||
/// Nonfinite geometry becomes zero.
|
||||
pub fn try_from_descriptor(d: &Descriptor) -> Result<Option<Warp>> {
|
||||
Self::try_from_descriptor_kind(d, d.class_id.is("quiltWarp"))
|
||||
}
|
||||
|
||||
// The containing SoLd key is authoritative even if an embedded class differs.
|
||||
fn try_from_descriptor_kind(d: &Descriptor, quilt: bool) -> Result<Option<Warp>> {
|
||||
if quilt {
|
||||
validate_quilt_bounds(d)?;
|
||||
}
|
||||
let style = d.get_enum("warpStyle").unwrap_or_else(|| "warpNone".to_string());
|
||||
let side = |b: &Descriptor, k: &str| b.get_number(k).unwrap_or(0.0);
|
||||
let side = |b: &Descriptor, k: &str| finite(b.get_number(k).unwrap_or(0.0));
|
||||
let bounds = d.get_object("bounds").map_or([0.0; 4], |b| [side(b, "Left"), side(b, "Top "), side(b, "Rght"), side(b, "Btom")]);
|
||||
let mut w = Warp {
|
||||
bend: d.get_number("warpValue").unwrap_or(0.0),
|
||||
horizontal: d.get_number("warpPerspective").unwrap_or(0.0),
|
||||
vertical: d.get_number("warpPerspectiveOther").unwrap_or(0.0),
|
||||
bend: finite(d.get_number("warpValue").unwrap_or(0.0)),
|
||||
horizontal: finite(d.get_number("warpPerspective").unwrap_or(0.0)),
|
||||
vertical: finite(d.get_number("warpPerspectiveOther").unwrap_or(0.0)),
|
||||
rotate_vertical: d.get_enum("warpRotate").as_deref() == Some("Vrtc"),
|
||||
bounds,
|
||||
cols: 1,
|
||||
@@ -95,8 +170,41 @@ impl Warp {
|
||||
style,
|
||||
};
|
||||
if let Some(env) = d.get_object("customEnvelopeWarp") {
|
||||
let cols = quilt_slices(env, "quiltSliceX").len().saturating_sub(1).max(1);
|
||||
let rows = quilt_slices(env, "quiltSliceY").len().saturating_sub(1).max(1);
|
||||
let slice_x = quilt_slices(env, "quiltSliceX")?;
|
||||
let slice_y = quilt_slices(env, "quiltSliceY")?;
|
||||
let cols = quilt_patches(&slice_x)?;
|
||||
let rows = quilt_patches(&slice_y)?;
|
||||
if !slice_x.is_empty() || !slice_y.is_empty() {
|
||||
validate_quilt_bounds(d)?;
|
||||
|
||||
// The evaluator normalizes over bounds, not stored slice coordinates.
|
||||
// Infer an absent rectangle only when both explicit axes define it.
|
||||
if !valid_bounds(w.bounds) {
|
||||
if d.get("bounds").is_some() {
|
||||
return Err(PsdError::Unsupported("invalid explicit quilt bounds".into()));
|
||||
}
|
||||
let (Some(&left), Some(&right), Some(&top), Some(&bottom)) = (slice_x.first(), slice_x.last(), slice_y.first(), slice_y.last())
|
||||
else {
|
||||
return Err(PsdError::Unsupported("quilt divisions need bounds or both axes".into()));
|
||||
};
|
||||
w.bounds = [left, top, right, bottom];
|
||||
if !valid_bounds(w.bounds) {
|
||||
return Err(PsdError::Unsupported("invalid inferred quilt bounds".into()));
|
||||
}
|
||||
}
|
||||
for (slices, start, end) in [(&slice_x, w.bounds[0], w.bounds[2]), (&slice_y, w.bounds[1], w.bounds[3])] {
|
||||
if let (Some(&first), Some(&last)) = (slices.first(), slices.last()) {
|
||||
let extent = end - start;
|
||||
if !extent.is_finite() {
|
||||
return Err(PsdError::Unsupported("quilt bounds overflow".into()));
|
||||
}
|
||||
let tolerance = extent.abs() * 1e-9;
|
||||
if (first - start).abs() > tolerance || (last - end).abs() > tolerance {
|
||||
return Err(PsdError::Unsupported("quilt divisions do not match warp bounds".into()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(Value::ObjectArray(pts)) = env.get("meshPoints") {
|
||||
let xs = pts.body.get_numbers("Hrzn");
|
||||
let ys = pts.body.get_numbers("Vrtc");
|
||||
@@ -104,18 +212,18 @@ impl Warp {
|
||||
if n.is_some_and(|n| xs.len() == n && ys.len() == n) {
|
||||
w.cols = cols;
|
||||
w.rows = rows;
|
||||
w.mesh = xs.into_iter().zip(ys).map(|(x, y)| [x, y]).collect();
|
||||
w.mesh = xs.into_iter().zip(ys).map(|(x, y)| [finite(x), finite(y)]).collect();
|
||||
}
|
||||
}
|
||||
}
|
||||
let identity = w.style == "warpNone" || (w.style != "warpCustom" && w.bend == 0.0 && w.horizontal == 0.0 && w.vertical == 0.0);
|
||||
let custom_ok = w.style != "warpCustom" || !w.mesh.is_empty();
|
||||
(!identity && custom_ok).then_some(w)
|
||||
Ok((!identity && custom_ok).then_some(w))
|
||||
}
|
||||
|
||||
/// The warp of a content point (content pixels → content pixels).
|
||||
pub fn apply(&self, p: [f64; 2], w: f64, h: f64) -> [f64; 2] {
|
||||
let [l, t, r, b] = if self.bounds[2] > self.bounds[0] && self.bounds[3] > self.bounds[1] { self.bounds } else { [0.0, 0.0, w, h] };
|
||||
let [l, t, r, b] = if valid_bounds(self.bounds) { self.bounds } else { [0.0, 0.0, w, h] };
|
||||
let (bw, bh) = (r - l, b - t);
|
||||
let (u, v) = ((p[0] - l) / bw, (p[1] - t) / bh);
|
||||
if self.style == "warpCustom" {
|
||||
@@ -273,9 +381,12 @@ impl SmartObject {
|
||||
let t = eight(&d, "Trnf").unwrap_or([0.0; 8]);
|
||||
// The non-affine transform when present (perspective), else the transform.
|
||||
let t = eight(&d, "nonAffineTransform").unwrap_or(t);
|
||||
let size = d.get_object("Sz ").and_then(|s| Some([s.get_number("Wdth")?, s.get_number("Hght")?]));
|
||||
let size = d.get_object("Sz ").and_then(|s| Some([finite(s.get_number("Wdth")?), finite(s.get_number("Hght")?)]));
|
||||
// A split warp is in `quiltWarp`, with `warp` holding none.
|
||||
let warp = d.get_object("quiltWarp").and_then(Warp::from_descriptor).or_else(|| d.get_object("warp").and_then(Warp::from_descriptor));
|
||||
let mut warp = d.get_object("quiltWarp").map(|q| Warp::try_from_descriptor_kind(q, true)).transpose()?.flatten();
|
||||
if warp.is_none() {
|
||||
warp = d.get_object("warp").map(|w| Warp::try_from_descriptor_kind(w, false)).transpose()?.flatten();
|
||||
}
|
||||
Ok(SmartObject { uuid, quad: quad_from(t), size, warp })
|
||||
}
|
||||
|
||||
@@ -949,6 +1060,290 @@ mod tests {
|
||||
assert!(select_linked_records(&unicode, &|uuid, _| uuid == "\u{fffd}").unwrap().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn placement_normalizes_nonfinite_geometry_before_classification() {
|
||||
let data = placed_layer_data("finite", [f64::NAN, 0.0, 20.0, 0.0, 20.0, 10.0, 0.0, 10.0], |d| {
|
||||
let warp = Descriptor::new("warp")
|
||||
.with("warpStyle", Value::Enumerated { type_id: Id::new("warpStyle"), value: Id::new("warpArc") })
|
||||
.with("warpValue", Value::Double(f64::NAN))
|
||||
.with("warpPerspective", Value::Double(f64::INFINITY))
|
||||
.with("warpPerspectiveOther", Value::Double(f64::NEG_INFINITY));
|
||||
let size = Descriptor::new("Pnt ").with("Wdth", Value::Double(f64::INFINITY)).with("Hght", Value::Double(10.0));
|
||||
d.with("warp", Value::Descriptor(warp)).with("Sz ", Value::Descriptor(size))
|
||||
});
|
||||
let object = SmartObject::from_placed_layer_data(&data).unwrap();
|
||||
assert_eq!(object.quad, [[0.0, 0.0], [20.0, 0.0], [20.0, 10.0], [0.0, 10.0]]);
|
||||
assert_eq!(object.size, Some([0.0, 10.0]));
|
||||
assert!(!object.needs_bake());
|
||||
assert_eq!(object.map([5.0, 5.0], 20.0, 10.0), [5.0, 5.0]);
|
||||
}
|
||||
|
||||
fn quilt_descriptor(xs: Vec<f64>, ys: Vec<f64>) -> Descriptor {
|
||||
let unfl = |values| Value::UnitFloats { unit: *b"#Pxl", values };
|
||||
// Identity control points for a 7 x 4 mesh with a split at x=5.
|
||||
let x = [0.0, 5.0 / 3.0, 10.0 / 3.0, 5.0, 10.0, 15.0, 20.0];
|
||||
let body = Descriptor::new("rationalPoint")
|
||||
.with("Hrzn", unfl((0..4).flat_map(|_| x).collect()))
|
||||
.with("Vrtc", unfl((0..4).flat_map(|j| [j as f64 * 10.0 / 3.0; 7]).collect()));
|
||||
let env = Descriptor::new("customEnvelopeWarp")
|
||||
.with("quiltSliceX", unfl(xs))
|
||||
.with("quiltSliceY", unfl(ys))
|
||||
.with("meshPoints", Value::ObjectArray(ObjectArray { prefix: 16, body }));
|
||||
Descriptor::new("warp")
|
||||
.with("warpStyle", Value::Enumerated { type_id: Id::new("warpStyle"), value: Id::new("warpCustom") })
|
||||
.with("customEnvelopeWarp", Value::Descriptor(env))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unequal_quilts_are_errors_not_uniform_meshes_or_fallback_warps() {
|
||||
for (xs, ys) in [(vec![0.0, 5.0, 20.0], vec![0.0, 10.0]), (vec![0.0, 10.0, 20.0], vec![0.0, 2.0, 10.0])] {
|
||||
let warp = quilt_descriptor(xs, ys);
|
||||
assert!(matches!(Warp::try_from_descriptor(&warp), Err(PsdError::Unsupported(_))));
|
||||
for key in ["warp", "quiltWarp"] {
|
||||
let data = placed_layer_data("quilt", [0.0; 8], |d| {
|
||||
let d = if key == "quiltWarp" { d.with("warp", Value::Descriptor(Descriptor::new("warp"))) } else { d };
|
||||
d.with(key, Value::Descriptor(warp.clone()))
|
||||
});
|
||||
assert!(matches!(SmartObject::from_placed_layer_data(&data), Err(PsdError::Unsupported(_))));
|
||||
}
|
||||
}
|
||||
for slices in [vec![0.0], vec![0.0, 0.0], vec![10.0, 0.0], vec![0.0, f64::NAN]] {
|
||||
assert!(quilt_patches(&slices).is_err());
|
||||
}
|
||||
assert_eq!(quilt_patches(&[]).unwrap(), 1);
|
||||
assert_eq!(quilt_patches(&[0.0, 10.0, 20.0]).unwrap(), 2);
|
||||
assert_eq!(quilt_patches(&[1e16, 1e16 + 2.0, 1e16 + 6.0, 1e16 + 8.0]).unwrap(), 3);
|
||||
assert!(quilt_patches(&[1e16, 1e16 + 4.0, 1e16 + 6.0, 1e16 + 8.0]).is_err());
|
||||
let lo = 3.0 * 2.0_f64.powi(970);
|
||||
assert!((f64::MAX - lo).is_finite());
|
||||
assert!((lo + (f64::MAX - lo)).is_infinite());
|
||||
assert_eq!(quilt_patches(&[lo, f64::MAX]).unwrap(), 1);
|
||||
assert_eq!(quilt_patches(&[1e16, 1e16, 1e16, 1e16 + 2.0, 1e16 + 2.0]).unwrap(), 4);
|
||||
for invalid in [vec![0.0, 0.0, 20.0], vec![0.0, 10.0, 10.0, 20.0], vec![1e16, 1e16 + 2.0, 1e16, 1e16 + 2.0]] {
|
||||
assert!(quilt_patches(&invalid).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quilt_slice_values_are_strict_in_lists_and_object_arrays() {
|
||||
let list = Value::List(vec![Value::Integer(0), Value::Double(10.0), Value::UnitFloat { unit: *b"#Pxl", value: 20.0 }]);
|
||||
let unfl = Value::UnitFloats { unit: *b"#Pxl", values: vec![0.0, 10.0, 20.0] };
|
||||
let bad_list = Value::List(vec![Value::Double(0.0), Value::Text(UnicodeString::new("bad")), Value::Double(10.0), Value::Double(20.0)]);
|
||||
for wrapped in [false, true] {
|
||||
for (value, valid) in [
|
||||
(list.clone(), true),
|
||||
(unfl.clone(), true),
|
||||
(bad_list.clone(), false),
|
||||
(Value::List(vec![]), false),
|
||||
(Value::UnitFloats { unit: *b"#Pxl", values: vec![] }, false),
|
||||
(Value::Integer(1), false),
|
||||
] {
|
||||
let value = if wrapped {
|
||||
Value::ObjectArray(ObjectArray { prefix: 3, body: Descriptor::new("UntF").with("quiltSliceX", value) })
|
||||
} else {
|
||||
value
|
||||
};
|
||||
let mut d = quilt_descriptor(vec![0.0, 10.0, 20.0], vec![0.0, 10.0]);
|
||||
let Value::Descriptor(env) = &mut d.items.iter_mut().find(|(key, _)| key.is("customEnvelopeWarp")).unwrap().1 else {
|
||||
panic!("envelope")
|
||||
};
|
||||
env.items.iter_mut().find(|(key, _)| key.is("quiltSliceX")).unwrap().1 = value;
|
||||
assert_eq!(Warp::try_from_descriptor(&d).is_ok(), valid);
|
||||
let bytes = placed_layer_data("slices", [0.0; 8], |parent| parent.with("quiltWarp", Value::Descriptor(d)));
|
||||
assert_eq!(SmartObject::from_placed_layer_data(&bytes).is_ok(), valid);
|
||||
}
|
||||
}
|
||||
let absent = Descriptor::new("customEnvelopeWarp");
|
||||
assert!(quilt_slices(&absent, "quiltSliceX").unwrap().is_empty());
|
||||
let missing_body = absent.with("quiltSliceX", Value::ObjectArray(ObjectArray { prefix: 0, body: Descriptor::new("UntF") }));
|
||||
assert!(quilt_slices(&missing_body, "quiltSliceX").is_err());
|
||||
}
|
||||
#[test]
|
||||
fn quilt_endpoints_define_or_match_the_normalization_bounds() {
|
||||
let equal = quilt_descriptor(vec![0.0, 10.0, 20.0], vec![0.0, 10.0]);
|
||||
assert_eq!(Warp::try_from_descriptor(&equal).unwrap().unwrap().bounds, [0.0, 0.0, 20.0, 10.0]);
|
||||
let bounds = Descriptor::new("bounds")
|
||||
.with("Left", Value::Double(0.0))
|
||||
.with("Top ", Value::Double(0.0))
|
||||
.with("Rght", Value::Double(40.0))
|
||||
.with("Btom", Value::Double(10.0));
|
||||
assert!(Warp::try_from_descriptor(&equal.with("bounds", Value::Descriptor(bounds))).is_err());
|
||||
let wrong_type = quilt_descriptor(vec![0.0, 10.0, 20.0], vec![0.0, 10.0]).with("bounds", Value::Integer(1));
|
||||
assert!(Warp::try_from_descriptor(&wrong_type).is_err());
|
||||
let invalid_bounds = Descriptor::new("bounds")
|
||||
.with("Left", Value::Double(0.0))
|
||||
.with("Top ", Value::Double(0.0))
|
||||
.with("Rght", Value::Double(40.0))
|
||||
.with("Btom", Value::Double(0.0));
|
||||
let explicit_invalid = quilt_descriptor(vec![0.0, 10.0, 20.0], vec![0.0, 10.0]).with("bounds", Value::Descriptor(invalid_bounds));
|
||||
assert!(Warp::try_from_descriptor(&explicit_invalid).is_err());
|
||||
let data = placed_layer_data("invalid bounds", [0.0; 8], |d| d.with("quiltWarp", Value::Descriptor(explicit_invalid)));
|
||||
assert!(matches!(SmartObject::from_placed_layer_data(&data), Err(PsdError::Unsupported(_))));
|
||||
let mut missing = quilt_descriptor(vec![0.0, 10.0, 20.0], vec![0.0, 10.0]);
|
||||
let Value::Descriptor(env) = &mut missing.items.iter_mut().find(|(key, _)| key.is("customEnvelopeWarp")).unwrap().1 else {
|
||||
panic!("envelope")
|
||||
};
|
||||
env.items.retain(|(key, _)| !key.is("quiltSliceY"));
|
||||
assert!(Warp::try_from_descriptor(&missing).is_err());
|
||||
let bounds = |top, bottom| {
|
||||
Descriptor::new("bounds")
|
||||
.with("Left", Value::Double(0.0))
|
||||
.with("Top ", Value::Double(top))
|
||||
.with("Rght", Value::Double(20.0))
|
||||
.with("Btom", Value::Double(bottom))
|
||||
};
|
||||
let present = missing.clone().with("bounds", Value::Descriptor(bounds(0.0, 10.0)));
|
||||
let parsed = Warp::try_from_descriptor(&present).unwrap().unwrap();
|
||||
assert_eq!((parsed.cols, parsed.rows), (2, 1));
|
||||
assert_eq!(parsed.bounds, [0.0, 0.0, 20.0, 10.0]);
|
||||
// Even the absent slice axis needs a finite normalization extent.
|
||||
let overflow = missing.with("bounds", Value::Descriptor(bounds(-f64::MAX, f64::MAX)));
|
||||
assert!(Warp::try_from_descriptor(&overflow).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn quilt_bounds_policy_covers_every_slice_axis_and_descriptor_context() {
|
||||
let rect = |l, t, r, b| {
|
||||
Value::Descriptor(
|
||||
Descriptor::new("bounds")
|
||||
.with("Left", Value::Double(l))
|
||||
.with("Top ", Value::Double(t))
|
||||
.with("Rght", Value::Double(r))
|
||||
.with("Btom", Value::Double(b)),
|
||||
)
|
||||
};
|
||||
let cases = [
|
||||
(None, true),
|
||||
(Some(rect(0.0, 0.0, 20.0, 10.0)), true),
|
||||
(Some(Value::Integer(0)), false),
|
||||
(
|
||||
Some(Value::Descriptor(
|
||||
Descriptor::new("bounds").with("Left", Value::Double(0.0)).with("Rght", Value::Double(20.0)).with("Btom", Value::Double(10.0)),
|
||||
)),
|
||||
false,
|
||||
),
|
||||
(
|
||||
Some(Value::Descriptor(
|
||||
Descriptor::new("bounds")
|
||||
.with("Left", Value::Double(0.0))
|
||||
.with("Top ", Value::Text(UnicodeString::new("bad")))
|
||||
.with("Rght", Value::Double(20.0))
|
||||
.with("Btom", Value::Double(10.0)),
|
||||
)),
|
||||
false,
|
||||
),
|
||||
(Some(rect(0.0, 10.0, 20.0, 10.0)), false),
|
||||
(Some(rect(0.0, -f64::MAX, 20.0, f64::MAX)), false),
|
||||
(Some(rect(f64::NAN, f64::NEG_INFINITY, 20.0, 10.0)), true),
|
||||
];
|
||||
for axes in 0..4 {
|
||||
for class in ["warp", "quiltWarp"] {
|
||||
for (bounds, valid) in &cases {
|
||||
let mut d = Warp {
|
||||
style: "warpCustom".into(),
|
||||
cols: 1,
|
||||
rows: 1,
|
||||
mesh: (0..4).flat_map(|y| (0..4).map(move |x| [x as f64 * 20.0 / 3.0, y as f64 * 10.0 / 3.0])).collect(),
|
||||
..Warp::default()
|
||||
}
|
||||
.to_descriptor();
|
||||
d.class_id = Id::new(class);
|
||||
d.items.retain(|(key, _)| !key.is("bounds"));
|
||||
if let Some(bounds) = bounds {
|
||||
d.items.push((Id::new("bounds"), bounds.clone()));
|
||||
}
|
||||
let Value::Descriptor(env) = &mut d.items.iter_mut().find(|(key, _)| key.is("customEnvelopeWarp")).unwrap().1 else {
|
||||
panic!("envelope")
|
||||
};
|
||||
for (bit, key, end) in [(1, "quiltSliceX", 20.0), (2, "quiltSliceY", 10.0)] {
|
||||
if axes & bit != 0 {
|
||||
env.items.push((Id::new(key), Value::UnitFloats { unit: *b"#Pxl", values: vec![0.0, end] }));
|
||||
}
|
||||
}
|
||||
let expected = |quilt: bool| {
|
||||
if bounds.is_none() { axes == 0 || axes == 3 } else { *valid || (!quilt && axes == 0) }
|
||||
};
|
||||
assert_eq!(
|
||||
Warp::try_from_descriptor(&d).is_ok(),
|
||||
expected(class == "quiltWarp"),
|
||||
"direct {class}, axes={axes}, bounds={bounds:?}"
|
||||
);
|
||||
for field in ["warp", "quiltWarp"] {
|
||||
let bytes = placed_layer_data("context", [0.0; 8], |parent| parent.with(field, Value::Descriptor(d.clone())));
|
||||
assert_eq!(
|
||||
SmartObject::from_placed_layer_data(&bytes).is_ok(),
|
||||
expected(field == "quiltWarp"),
|
||||
"{field}/{class}, axes={axes}, bounds={bounds:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// No envelope and identity style must not bypass explicit quilt bounds.
|
||||
for class in ["warp", "quiltWarp"] {
|
||||
let d = Descriptor::new(class).with("bounds", rect(0.0, 10.0, 20.0, 10.0));
|
||||
assert_eq!(Warp::try_from_descriptor(&d).is_ok(), class == "warp");
|
||||
let bytes = placed_layer_data("identity", [0.0; 8], |parent| parent.with("quiltWarp", Value::Descriptor(d)));
|
||||
assert!(SmartObject::from_placed_layer_data(&bytes).is_err());
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn explicit_quilt_bounds_require_every_numeric_side() {
|
||||
let sides = [("Left", 0.0), ("Top ", 0.0), ("Rght", 20.0), ("Btom", 10.0)];
|
||||
for omit_y in [false, true] {
|
||||
let mut quilt = quilt_descriptor(vec![0.0, 10.0, 20.0], vec![0.0, 10.0]);
|
||||
if omit_y {
|
||||
let Value::Descriptor(env) = &mut quilt.items.iter_mut().find(|(key, _)| key.is("customEnvelopeWarp")).unwrap().1 else {
|
||||
panic!("envelope")
|
||||
};
|
||||
env.items.retain(|(key, _)| !key.is("quiltSliceY"));
|
||||
}
|
||||
let complete = sides.iter().fold(Descriptor::new("bounds"), |d, (key, value)| d.with(key, Value::Double(*value)));
|
||||
assert!(Warp::try_from_descriptor(&quilt.clone().with("bounds", Value::Descriptor(complete))).unwrap().is_some());
|
||||
for (side, _) in sides {
|
||||
for missing in [true, false] {
|
||||
let bounds = sides.iter().fold(Descriptor::new("bounds"), |d, (key, value)| {
|
||||
if *key != side {
|
||||
d.with(key, Value::Double(*value))
|
||||
} else if missing {
|
||||
d
|
||||
} else {
|
||||
d.with(key, Value::Text(UnicodeString::new("not a number")))
|
||||
}
|
||||
});
|
||||
let invalid = quilt.clone().with("bounds", Value::Descriptor(bounds));
|
||||
assert!(
|
||||
matches!(Warp::try_from_descriptor(&invalid), Err(PsdError::Unsupported(_))),
|
||||
"{side}, missing={missing}, omit_y={omit_y}"
|
||||
);
|
||||
let bytes = placed_layer_data("incomplete", [0.0; 8], |d| d.with("quiltWarp", Value::Descriptor(invalid)));
|
||||
assert!(matches!(SmartObject::from_placed_layer_data(&bytes), Err(PsdError::Unsupported(_))));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn finite_warp_views_preserve_raw_descriptor_values() {
|
||||
let mut warp = quilt_descriptor(vec![0.0, 10.0, 20.0], vec![0.0, 10.0]);
|
||||
let bounds = Descriptor::new("bounds")
|
||||
.with("Left", Value::Double(f64::NAN))
|
||||
.with("Top ", Value::Double(f64::NEG_INFINITY))
|
||||
.with("Rght", Value::Double(20.0))
|
||||
.with("Btom", Value::Double(10.0));
|
||||
warp = warp.with("bounds", Value::Descriptor(bounds));
|
||||
let env = warp.items.iter_mut().find(|(key, _)| key.as_bytes() == b"customEnvelopeWarp").unwrap();
|
||||
let Value::Descriptor(env) = &mut env.1 else { panic!("envelope") };
|
||||
let points = env.items.iter_mut().find(|(key, _)| key.as_bytes() == b"meshPoints").unwrap();
|
||||
let Value::ObjectArray(points) = &mut points.1 else { panic!("mesh") };
|
||||
let values = &mut points.body.items[0].1;
|
||||
let Value::UnitFloats { values, .. } = values else { panic!("coordinates") };
|
||||
values[0] = f64::NAN;
|
||||
let bytes = warp.to_bytes();
|
||||
let view = Warp::try_from_descriptor(&warp).unwrap().unwrap();
|
||||
assert_eq!(view.bounds, [0.0, 0.0, 20.0, 10.0]);
|
||||
assert_eq!(view.mesh[0], [0.0, 0.0]);
|
||||
assert_eq!(warp.to_bytes(), bytes);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn placed_layer_data_gives_the_id_quad_size_and_warp() {
|
||||
let quad = [20.0, 4.0, 40.0, 4.0, 40.0, 44.0, 20.0, 44.0];
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
//! read back. Came from PhotoCraft's `crates/io/src/smart_map/placed.rs`, on this crate's
|
||||
//! placement types: the caller works out the quad and the warp from its own geometry.
|
||||
|
||||
use super::{SmartObject, Warp};
|
||||
use super::{SmartObject, Warp, valid_bounds};
|
||||
use crate::descriptor::{Descriptor, Id, ObjectArray, UnicodeString, Value, VersionedDescriptor};
|
||||
use crate::io::WriteExt;
|
||||
|
||||
@@ -78,7 +78,10 @@ impl Warp {
|
||||
/// Style, bend, distortions, axis, bounds and order: the keys a `warp` and a `quiltWarp`
|
||||
/// share, in Photoshop's order.
|
||||
fn head(&self, class: &str) -> Descriptor {
|
||||
let [l, t, r, b] = self.bounds;
|
||||
self.head_with_bounds(class, self.bounds)
|
||||
}
|
||||
|
||||
fn head_with_bounds(&self, class: &str, [l, t, r, b]: [f64; 4]) -> Descriptor {
|
||||
let bounds = Descriptor::new("classFloatRect")
|
||||
.with("Top ", Value::Double(t))
|
||||
.with("Left", Value::Double(l))
|
||||
@@ -119,15 +122,32 @@ impl Warp {
|
||||
|
||||
/// The `quiltWarp` descriptor of a split warp, in Photoshop's layout: the control points,
|
||||
/// `deformNumCols` × `deformNumRows` of them, and the patch boundaries (`quiltSliceX` /
|
||||
/// `quiltSliceY`) evenly across the warp's bounds. `None` for any other warp.
|
||||
/// `quiltSliceY`) evenly across the warp's bounds. Invalid axes use 0..1 because this standalone
|
||||
/// method has no content size; the placed-layer writer supplies that size when available.
|
||||
/// Canonical boundaries may coincide after rounding at large offsets. The shared reader
|
||||
/// preserves their uniform-model parameterization; external reader interoperability for
|
||||
/// coincident slices is not guaranteed. `None` for any other warp.
|
||||
pub fn quilt_descriptor(&self) -> Option<Descriptor> {
|
||||
if !self.is_split() {
|
||||
return None;
|
||||
}
|
||||
let [l, t, r, b] = self.bounds;
|
||||
// The header and the divisions must describe the same rectangle, including
|
||||
// when a caller leaves bounds at their default or supplies an invalid axis.
|
||||
let axis = |lo: f64, hi: f64| if (hi - lo).is_finite() && hi > lo { (lo, hi) } else { (0.0, 1.0) };
|
||||
let (l, r) = axis(self.bounds[0], self.bounds[2]);
|
||||
let (t, b) = axis(self.bounds[1], self.bounds[3]);
|
||||
let slices = |key: &str, n: usize, lo: f64, hi: f64| {
|
||||
let (lo, hi) = if (hi - lo).is_finite() && hi > lo { (lo, hi) } else { (0.0, 1.0) };
|
||||
let values: Vec<f64> = (0..=n).map(|i| lo + (hi - lo) * i as f64 / n as f64).collect();
|
||||
let values: Vec<f64> = (0..=n)
|
||||
.map(|i| {
|
||||
if i == 0 {
|
||||
lo
|
||||
} else if i == n {
|
||||
hi
|
||||
} else {
|
||||
lo + (hi - lo) * (i as f64 / n as f64)
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let prefix = values.len() as u32;
|
||||
Value::ObjectArray(ObjectArray { prefix, body: Descriptor::new("UntF").with(key, Value::UnitFloats { unit: *b"#Pxl", values }) })
|
||||
};
|
||||
@@ -137,7 +157,7 @@ impl Warp {
|
||||
.with("meshPoints", self.mesh_points());
|
||||
let count = |n: usize| Value::Integer(i32::try_from(n.saturating_mul(3).saturating_add(1)).unwrap_or(i32::MAX));
|
||||
Some(
|
||||
self.head("quiltWarp")
|
||||
self.head_with_bounds("quiltWarp", [l, t, r, b])
|
||||
.with("deformNumRows", count(self.rows))
|
||||
.with("deformNumCols", count(self.cols))
|
||||
.with("customEnvelopeWarp", Value::Descriptor(envelope)),
|
||||
@@ -159,7 +179,13 @@ impl SmartObject {
|
||||
/// The warp written, over the content (or `[0, 0, 0, 0]` without a size) when there is none.
|
||||
fn warp_or_none(&self) -> Warp {
|
||||
let [w, h] = self.size.unwrap_or([0.0; 2]);
|
||||
self.warp.clone().unwrap_or_else(|| Warp::none([0.0, 0.0, w, h]))
|
||||
let mut warp = self.warp.clone().unwrap_or_else(|| Warp::none([0.0, 0.0, w, h]));
|
||||
// Match Warp::apply's whole-rectangle fallback before encoding explicit
|
||||
// quilt slices. Otherwise default bounds would change the mapping on readback.
|
||||
if warp.is_split() && !valid_bounds(warp.bounds) {
|
||||
warp.bounds = [0.0, 0.0, w, h];
|
||||
}
|
||||
warp
|
||||
}
|
||||
|
||||
/// The data of a `SoLd` block (`soLD`, version 4, a version-16 descriptor, padded to 4).
|
||||
@@ -180,7 +206,9 @@ impl SmartObject {
|
||||
}
|
||||
set(&mut d, "warp", Value::Descriptor(warp.to_descriptor()));
|
||||
// The imported `quiltWarp` stays while it still says what the warp is.
|
||||
let kept = t.get_object("quiltWarp").is_some_and(|q| Warp::from_descriptor(q).as_ref() == self.warp.as_ref());
|
||||
let kept = t
|
||||
.get_object("quiltWarp")
|
||||
.is_some_and(|q| Warp::try_from_descriptor_kind(q, true).is_ok_and(|parsed| parsed.as_ref() == self.warp.as_ref()));
|
||||
if !kept {
|
||||
match quilt {
|
||||
Some(q) => set_before(&mut d, "quiltWarp", Value::Descriptor(q), "warp"),
|
||||
@@ -289,6 +317,108 @@ mod tests {
|
||||
]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quilt_writer_uses_one_rectangle_for_header_slices_and_roundtrip() {
|
||||
for (bounds, expected) in [
|
||||
([0.0; 4], [0.0, 0.0, 1.0, 1.0]),
|
||||
([2.0, 3.0, 22.0, 13.0], [2.0, 3.0, 22.0, 13.0]),
|
||||
([2.0, 3.0, 22.0, 3.0], [2.0, 0.0, 22.0, 1.0]),
|
||||
([f64::NAN, 3.0, 22.0, 13.0], [0.0, 3.0, 1.0, 13.0]),
|
||||
([-f64::MAX, 0.0, f64::MAX, 1.0], [0.0, 0.0, 1.0, 1.0]),
|
||||
([0.0, 0.0, 1e308, 10.0], [0.0, 0.0, 1e308, 10.0]),
|
||||
([3.0 * 2.0_f64.powi(970), 0.0, f64::MAX, 10.0], [3.0 * 2.0_f64.powi(970), 0.0, f64::MAX, 10.0]),
|
||||
] {
|
||||
let warp = Warp { style: "warpCustom".into(), bounds, cols: 2, rows: 1, mesh: grid(2, 1, 20.0, 10.0), ..Warp::default() };
|
||||
let descriptor = warp.quilt_descriptor().unwrap();
|
||||
let back = Warp::try_from_descriptor(&descriptor).unwrap().unwrap();
|
||||
assert_eq!(back.bounds, expected);
|
||||
assert_eq!((back.cols, back.rows, &back.mesh), (2, 1, &warp.mesh));
|
||||
assert_eq!(back.quilt_descriptor().unwrap(), descriptor);
|
||||
}
|
||||
let high_offset = Warp {
|
||||
style: "warpCustom".into(),
|
||||
bounds: [1e16, 0.0, 1e16 + 8.0, 10.0],
|
||||
cols: 3,
|
||||
rows: 1,
|
||||
mesh: grid(3, 1, 20.0, 10.0),
|
||||
..Warp::default()
|
||||
};
|
||||
assert_eq!(Warp::try_from_descriptor(&high_offset.quilt_descriptor().unwrap()).unwrap(), Some(high_offset));
|
||||
// At the placed-layer boundary content size is available: preserve the
|
||||
// evaluator's fallback mapping, not merely the ability to parse the output.
|
||||
for bounds in [[0.0; 4], [2.0, 3.0, 22.0, 3.0], [f64::NAN, 0.0, 20.0, 10.0], [-f64::MAX, 0.0, f64::MAX, 10.0]] {
|
||||
let warp = Warp { style: "warpCustom".into(), bounds, cols: 2, rows: 1, mesh: grid(2, 1, 20.0, 10.0), ..Warp::default() };
|
||||
let so = SmartObject { size: Some([20.0, 10.0]), ..placed(Some(warp.clone())) };
|
||||
let bytes = so.to_placed_layer_data(&PlacedLayerOptions::default());
|
||||
let back = SmartObject::from_placed_layer_data(&bytes).unwrap();
|
||||
let parsed = back.warp.as_ref().unwrap();
|
||||
assert_eq!(parsed.bounds, [0.0, 0.0, 20.0, 10.0]);
|
||||
for p in [[0.0, 0.0], [5.0, 4.0], [10.0, 5.0], [20.0, 10.0]] {
|
||||
assert_eq!(parsed.apply(p, 20.0, 10.0), warp.apply(p, 20.0, 10.0));
|
||||
}
|
||||
let template = VersionedDescriptor::parse_prefix(&bytes[8..]).unwrap().0.descriptor;
|
||||
let rewritten = back.to_placed_layer_data(&PlacedLayerOptions { template: Some(&template), ..Default::default() });
|
||||
assert_eq!(SmartObject::from_placed_layer_data(&rewritten).unwrap(), back);
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn canonically_collapsed_boundaries_preserve_both_axes_mapping() {
|
||||
let lo = 1e16;
|
||||
let hi = lo + 2.0;
|
||||
for (cols, rows, bounds, axis) in
|
||||
[(4, 1, [lo, 0.0, hi, 10.0], "quiltSliceX"), (1, 4, [0.0, lo, 20.0, hi], "quiltSliceY"), (4, 4, [lo, lo, hi, hi], "quiltSliceX")]
|
||||
{
|
||||
let warp = Warp { style: "warpCustom".into(), bounds, cols, rows, mesh: grid(cols, rows, 20.0, 10.0), ..Warp::default() };
|
||||
let descriptor = warp.quilt_descriptor().unwrap();
|
||||
let env = descriptor.get_object("customEnvelopeWarp").unwrap();
|
||||
let Value::ObjectArray(slices) = env.get(axis).unwrap() else { panic!("slices") };
|
||||
let values = slices.body.get_numbers(axis);
|
||||
assert_eq!(values, vec![lo, lo, lo, hi, hi]);
|
||||
// The first, middle and last intervals all have rounded coincident endpoints.
|
||||
assert_eq!(values[0], values[1]);
|
||||
assert_eq!(values[1], values[2]);
|
||||
assert_eq!(values[3], values[4]);
|
||||
let so = placed(Some(warp.clone()));
|
||||
let bytes = so.to_placed_layer_data(&PlacedLayerOptions::default());
|
||||
let back = SmartObject::from_placed_layer_data(&bytes).unwrap();
|
||||
assert_eq!(back.warp, Some(warp.clone()));
|
||||
let parsed = back.warp.as_ref().unwrap();
|
||||
for p in [[bounds[0], bounds[1]], [bounds[2], bounds[1]], [bounds[0], bounds[3]], [bounds[2], bounds[3]]] {
|
||||
assert_eq!(parsed.apply(p, 20.0, 10.0), warp.apply(p, 20.0, 10.0));
|
||||
}
|
||||
let template = VersionedDescriptor::parse_prefix(&bytes[8..]).unwrap().0.descriptor;
|
||||
let rewritten = back.to_placed_layer_data(&PlacedLayerOptions { template: Some(&template), ..Default::default() });
|
||||
assert_eq!(SmartObject::from_placed_layer_data(&rewritten).unwrap(), back);
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn templates_drop_unsupported_quilts_but_retain_valid_none() {
|
||||
let bounds = [0.0, 0.0, 20.0, 10.0];
|
||||
let unfl = |values| Value::UnitFloats { unit: *b"#Pxl", values };
|
||||
let unequal =
|
||||
Descriptor::new("warp").with("warpStyle", Value::Enumerated { type_id: Id::new("warpStyle"), value: Id::new("warpCustom") }).with(
|
||||
"customEnvelopeWarp",
|
||||
Value::Descriptor(
|
||||
Descriptor::new("customEnvelopeWarp").with("quiltSliceX", unfl(vec![0.0, 5.0, 20.0])).with("quiltSliceY", unfl(vec![0.0, 10.0])),
|
||||
),
|
||||
);
|
||||
assert!(Warp::try_from_descriptor(&unequal).is_err());
|
||||
let valid_none = Warp::none(bounds).to_descriptor();
|
||||
assert!(matches!(Warp::try_from_descriptor(&valid_none), Ok(None)));
|
||||
let invalid_none = Warp::none([0.0, 10.0, 20.0, 10.0]).to_descriptor();
|
||||
for (quilt, keep) in [(unequal, false), (valid_none, true), (invalid_none, false)] {
|
||||
let template = Descriptor::new("null").with("quiltWarp", Value::Descriptor(quilt.clone()));
|
||||
let bytes = placed(None).to_placed_layer_data(&PlacedLayerOptions {
|
||||
placed: "layer",
|
||||
resolution: 72.0,
|
||||
filter_fx: None,
|
||||
template: Some(&template),
|
||||
});
|
||||
let written = VersionedDescriptor::parse_prefix(&bytes[8..]).unwrap().0.descriptor;
|
||||
assert_eq!(written.get_object("quiltWarp"), keep.then_some(&quilt));
|
||||
assert!(SmartObject::from_placed_layer_data(&bytes).unwrap().warp.is_none());
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn placed_layer_data_reads_back_and_passes_the_strict_check() {
|
||||
let filter = Descriptor::new("filterFX")
|
||||
|
||||
@@ -22,7 +22,10 @@
|
||||
//! code page's bytes stream through one decoder, so a lead byte and its trail byte decode
|
||||
//! together and a run that looks like a UTF-8 BOM is not mistaken for one; the formatting words
|
||||
//! above, stylesheet-based
|
||||
//! headings and `\outlinelevel`, lists through `\ls`/`\ilvl`, fields, bookmarks, pictures and
|
||||
//! headings and `\outlinelevel`, lists through `\ls`/`\ilvl`, fields (in `import`, a page field
|
||||
//! such as `PAGE` or `NUMPAGES` whose result is plain text in one paragraph stays a field,
|
||||
//! `\fldlock` locking it, and `\chpgn` is a `PAGE` field; otherwise a field is its result's text),
|
||||
//! bookmarks, pictures and
|
||||
//! tables, footnotes, endnotes (`\footnote` with `\ftnalt`) and comments (author, initials, date,
|
||||
//! text, the commented range). Group nesting, picture sizes and the number of notes and comments
|
||||
//! are capped. Not kept: custom note marks, comment replies (`\atnparent`), notes inside
|
||||
@@ -38,6 +41,7 @@ use craft_flow::{self as model, Cell, FBlock, FTable, Flow, Fmt, Inline, Kind, L
|
||||
|
||||
use crate::date;
|
||||
mod export;
|
||||
mod field;
|
||||
mod parse;
|
||||
mod reader;
|
||||
mod state;
|
||||
@@ -58,3 +62,5 @@ use word::hyperlink;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
#[cfg(test)]
|
||||
mod tests_fields;
|
||||
@@ -0,0 +1,152 @@
|
||||
//! Page fields kept as fields (#6222). The reader writes a field's result (`\fldrslt`) into the
|
||||
//! paragraph like any text, which for a page number is the number Word last stored. When the
|
||||
//! group of a field the layout works out from where it lands closes (`PAGE`, `NUMPAGES`,
|
||||
//! `SECTIONPAGES`, `SECTION`, `PAGEREF`), a result that is plain text in one formatting, in the
|
||||
//! paragraph the field started in, is replaced by an [`Inline::Field`] holding the instruction
|
||||
//! (`\fldinst`) and that result, as for a DOCX field. Any other field, a result over several
|
||||
//! paragraphs or formats, or one holding pictures or other objects stays what the reader made of
|
||||
//! it: a field's result is drawn as one piece that does not wrap, so a long `MERGEFIELD` result
|
||||
//! in a narrow table cell would overflow it. Only `import` keeps fields: `parse`, the flow
|
||||
//! reader, reads their results as text.
|
||||
|
||||
use super::reader::Reader;
|
||||
use super::state::Dest;
|
||||
use super::{Fmt, Inline};
|
||||
|
||||
/// The open fields read so far; deeper nesting keeps its results as text.
|
||||
const MAX_OPEN: usize = 32;
|
||||
|
||||
/// A field being read in the body text.
|
||||
pub(super) struct OpenField {
|
||||
/// The depth of the `{\field` group.
|
||||
depth: usize,
|
||||
/// Its instruction, in [`Reader::fields`].
|
||||
index: usize,
|
||||
/// The paragraph it started in ([`Reader::para_seq`]).
|
||||
para: u64,
|
||||
/// The paragraph's inlines when it started, and the length of the last one when that was
|
||||
/// text: a result in the same formatting runs on in that text.
|
||||
start: usize,
|
||||
tail_from: Option<usize>,
|
||||
/// Its result group was met in the text (not inside another field's instruction).
|
||||
result: bool,
|
||||
locked: bool,
|
||||
/// Hidden text of its result was left out: the result is not what showed.
|
||||
hidden: bool,
|
||||
}
|
||||
|
||||
impl Reader {
|
||||
/// `\field`, after its instruction slot is made: note where its result starts.
|
||||
pub(super) fn open_field(&mut self) {
|
||||
// Hidden text drops the result: the field stays hidden with it.
|
||||
if !self.marks_on || self.st.dest != Dest::Body || self.st.hidden || self.open_fields.len() >= MAX_OPEN {
|
||||
return;
|
||||
}
|
||||
let Some(index) = self.st.field else { return };
|
||||
let tail_from = match self.para.inlines.last() {
|
||||
Some(Inline::Text(t, _)) => Some(t.len()),
|
||||
_ => None,
|
||||
};
|
||||
let (depth, para, start) = (self.depth(), self.para_seq, self.para.inlines.len());
|
||||
self.open_fields.push(OpenField { depth, index, para, start, tail_from, result: false, locked: false, hidden: false });
|
||||
}
|
||||
|
||||
/// `\fldrslt` and `\fldlock`, read in a field's group.
|
||||
pub(super) fn field_word(&mut self, w: &str) {
|
||||
let (depth, field, body) = (self.depth(), self.st.field, self.st.dest == Dest::Body);
|
||||
let Some(f) = self.open_fields.last_mut() else { return };
|
||||
match w {
|
||||
"fldrslt" if body && field == Some(f.index) && depth == f.depth + 1 => f.result = true,
|
||||
"fldlock" if depth == f.depth => f.locked = true,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// `\chpgn`, the current page number: a `PAGE` field.
|
||||
pub(super) fn page_number_symbol(&mut self) {
|
||||
if self.st.dest == Dest::Body && self.st.hidden {
|
||||
self.hidden_text_dropped();
|
||||
return;
|
||||
}
|
||||
if self.marks_on && self.st.dest == Dest::Body {
|
||||
// Tracked like text, so Accept and Reject apply to it.
|
||||
let fmt = self.text_fmt();
|
||||
self.para.inlines.push(Inline::Field { instr: "PAGE".into(), result: String::new(), fmt, locked: false });
|
||||
self.para_has = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// Hidden text left out of the body: an open field's result is then not what showed, and the
|
||||
/// field is left as read rather than made a field that would show.
|
||||
pub(super) fn hidden_text_dropped(&mut self) {
|
||||
// An omitted nested result is also omitted from each enclosing result.
|
||||
for f in &mut self.open_fields {
|
||||
if f.result {
|
||||
f.hidden = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A group closes: if it is an open field's, make the field.
|
||||
pub(super) fn close_field_group(&mut self) {
|
||||
if self.open_fields.last().is_none_or(|f| f.depth != self.depth()) {
|
||||
return;
|
||||
}
|
||||
let Some(f) = self.open_fields.pop() else { return };
|
||||
if !f.result || f.hidden || f.para != self.para_seq {
|
||||
return;
|
||||
}
|
||||
let instr = self.fields.get(f.index).map_or("", |s| s.trim());
|
||||
if !page_dependent(instr) {
|
||||
return;
|
||||
}
|
||||
let instr = instr.to_string();
|
||||
// An empty result has no run to carry the group's revision marks.
|
||||
let group = self.text_fmt();
|
||||
let Some((result, fmt)) = result_text(&self.para.inlines, &f, &group) else { return };
|
||||
let field = Inline::Field { instr, result, fmt, locked: f.locked };
|
||||
let inlines = &mut self.para.inlines;
|
||||
inlines.truncate(f.start);
|
||||
if let (Some(n), Some(Inline::Text(t, _))) = (f.tail_from, inlines.last_mut()) {
|
||||
t.truncate(n);
|
||||
}
|
||||
inlines.push(field);
|
||||
self.para_has = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// A field whose result the layout works out from the page it lands on. `STYLEREF` is not one
|
||||
/// here: the layout looks its style up by name, and a running head whose style the RTF names
|
||||
/// differently would show an error instead of Word's text.
|
||||
fn page_dependent(instr: &str) -> bool {
|
||||
let name = instr.split_whitespace().next().unwrap_or("");
|
||||
["PAGE", "NUMPAGES", "SECTIONPAGES", "SECTION", "PAGEREF"].iter().any(|n| name.eq_ignore_ascii_case(n))
|
||||
}
|
||||
|
||||
/// The text the field's result added to the paragraph and its formatting, when that is plain
|
||||
/// text in one formatting with no tracked change; `None` otherwise. An empty result takes the
|
||||
/// field group's formatting.
|
||||
fn result_text(inlines: &[Inline], f: &OpenField, group: &Fmt) -> Option<(String, Fmt)> {
|
||||
if inlines.len() < f.start {
|
||||
return None;
|
||||
}
|
||||
let mut runs: Vec<(&str, &Fmt)> = Vec::new();
|
||||
if let Some(n) = f.tail_from {
|
||||
let Some(Inline::Text(t, fmt)) = f.start.checked_sub(1).and_then(|i| inlines.get(i)) else { return None };
|
||||
let tail = t.get(n..)?;
|
||||
if !tail.is_empty() {
|
||||
runs.push((tail, fmt));
|
||||
}
|
||||
}
|
||||
for i in inlines.get(f.start..)? {
|
||||
match i {
|
||||
Inline::Text(t, fmt) => runs.push((t, fmt)),
|
||||
_ => return None,
|
||||
}
|
||||
}
|
||||
match runs.as_slice() {
|
||||
[] => Some((String::new(), group.clone())),
|
||||
[(t, fmt)] if fmt.ins.is_none() && fmt.del.is_none() && fmt.fmt_change.is_none() => Some(((*t).to_string(), (*fmt).clone())),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -56,6 +56,10 @@ pub(super) struct Reader {
|
||||
pub(super) ov_list: i32,
|
||||
pub(super) ov_ls: i32,
|
||||
pub(super) fields: Vec<String>,
|
||||
/// The fields being read in the text, innermost last (`import` only).
|
||||
pub(super) open_fields: Vec<super::field::OpenField>,
|
||||
/// Counts the paragraphs ended, so a field knows whether its result stayed in one.
|
||||
pub(super) para_seq: u64,
|
||||
// Picture being read.
|
||||
pub(super) pict_depth: Option<usize>,
|
||||
pub(super) pict_hex: Vec<u8>,
|
||||
@@ -344,6 +348,7 @@ impl Reader {
|
||||
if self.sub.as_ref().is_some_and(|s| s.depth == self.depth()) {
|
||||
self.end_sub();
|
||||
}
|
||||
self.close_field_group();
|
||||
let closing = self.st.dest;
|
||||
// Destination-level commits.
|
||||
match closing {
|
||||
@@ -428,6 +433,7 @@ impl Reader {
|
||||
|
||||
/// End the current paragraph (`\par`, `\cell`).
|
||||
pub(super) fn end_para(&mut self, in_cell: bool) {
|
||||
self.para_seq += 1;
|
||||
let read = std::mem::take(&mut self.para);
|
||||
let props = self.para_props(&self.st);
|
||||
let mut p = Para { inlines: read.inlines, mark_ins: read.mark_ins, mark_del: read.mark_del, ..props };
|
||||
|
||||
@@ -0,0 +1,235 @@
|
||||
//! Page fields read from RTF (#6222): a page-dependent field whose result is plain text in one
|
||||
//! paragraph comes in as a field, so the layout works out its number; other fields stay their
|
||||
//! result's text. Written by hand from the RTF specification's `\field`, `\fldinst`, `\fldrslt`,
|
||||
//! `\fldlock` and `\chpgn`.
|
||||
|
||||
use super::*;
|
||||
use craft_wordmodel::para::InlineObject;
|
||||
|
||||
/// The fields of each paragraph of a story, with the paragraph's text.
|
||||
/// A paragraph's text with its fields (code, result, locked).
|
||||
type ParaFields = (String, Vec<(String, String, bool)>);
|
||||
|
||||
fn fields_of(blocks: &craft_wordmodel::Blocks) -> Vec<ParaFields> {
|
||||
blocks
|
||||
.iter()
|
||||
.filter_map(|b| if let craft_wordmodel::Block::Para(p) = &**b { Some(p) } else { None })
|
||||
.map(|p| {
|
||||
let fields = p
|
||||
.objects
|
||||
.iter()
|
||||
.filter_map(|o| match o {
|
||||
InlineObject::Field { instr, result, locked, .. } => Some((instr.clone(), result.clone(), *locked)),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
(p.text.clone(), fields)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn footer(d: &craft_wordmodel::Document) -> Vec<ParaFields> {
|
||||
let id = d.last_section.footers.default.expect("a footer");
|
||||
fields_of(&d.parts[&id].blocks)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_page_field_in_the_footer_is_a_field_not_its_stored_number() {
|
||||
// As Word writes it: the text before the field has the same formatting as its result.
|
||||
let rtf = br"{\rtf1\ansi\sectd
|
||||
{\footerr \pard {\fs16 Pag. }{\field{\*\fldinst {\fs16 PAGE }}{\fldrslt {\fs16 2}}}\sectd \ltrsect{\par}}
|
||||
\pard One\page Two\par}";
|
||||
let d = import(rtf).unwrap();
|
||||
let f = footer(&d);
|
||||
assert_eq!(f.len(), 1, "{f:?}");
|
||||
assert_eq!(f[0].1, [("PAGE".to_string(), "2".to_string(), false)], "{f:?}");
|
||||
// "Pag. " stays text before the field: the result's run did not take it along.
|
||||
assert!(f[0].0.starts_with("Pag. "), "{f:?}");
|
||||
assert_eq!(f[0].0.matches("Pag. ").count(), 1, "{f:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_fields_in_the_body_keep_their_code_result_and_lock() {
|
||||
let rtf = br#"{\rtf1\ansi
|
||||
\pard Page {\field{\*\fldinst PAGE \\* roman}{\fldrslt ii}} of {\field\fldlock{\*\fldinst NUMPAGES}{\fldrslt 4}}\par
|
||||
\pard {\field{\*\fldinst SECTIONPAGES}{\fldrslt }}x\par}"#;
|
||||
let d = import(rtf).unwrap();
|
||||
let f = fields_of(&d.body);
|
||||
assert_eq!(f[0].1, [("PAGE \\* roman".to_string(), "ii".to_string(), false), ("NUMPAGES".to_string(), "4".to_string(), true)], "{f:?}");
|
||||
assert!(f[0].0.starts_with("Page ") && f[0].0.contains(" of "), "{f:?}");
|
||||
// An empty result is still a field: the layout fills it in.
|
||||
assert_eq!(f[1].1, [("SECTIONPAGES".to_string(), String::new(), false)], "{f:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_fields_stay_the_text_of_their_result() {
|
||||
// A field's result is drawn as one piece that does not wrap: a long merge field in a narrow
|
||||
// cell keeps its text, which wraps, as before.
|
||||
let rtf = br#"{\rtf1\ansi
|
||||
\pard Before {\field{\*\fldinst DATE \\@ "dd/MM/yyyy"}{\fldrslt 11/11/2026}} after\par
|
||||
\trowd\cellx600\pard\intbl {\field{\*\fldinst MERGEFIELD Approvato}{\fldrslt Presidente della Rete (Rossi Mario)}}\cell\row
|
||||
\pard {\field{\*\fldinst AUTHOR}{\fldrslt }}x\par}"#;
|
||||
let d = import(rtf).unwrap();
|
||||
let f = fields_of(&d.body);
|
||||
assert_eq!((f[0].0.as_str(), f[0].1.len()), ("Before 11/11/2026 after", 0), "{f:?}");
|
||||
let cell = d.body.iter().find_map(|b| b.as_table()).and_then(|t| t.rows.first()).and_then(|r| r.cells.first()).unwrap();
|
||||
let cf = fields_of(&cell.blocks);
|
||||
assert_eq!((cf[0].0.as_str(), cf[0].1.len()), ("Presidente della Rete (Rossi Mario)", 0), "{cf:?}");
|
||||
assert!(f.last().is_some_and(|(t, fl)| t == "x" && fl.is_empty()), "{f:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fields_that_cannot_be_one_field_stay_text() {
|
||||
let rtf = br#"{\rtf1\ansi
|
||||
\pard {\field{\*\fldinst{HYPERLINK "http://a.b"}}{\fldrslt{link}}}\par
|
||||
\pard {\field{\*\fldinst TOC \\o "1-3"}{\fldrslt {Heading one\tab 1\par Heading two\tab 2}}}\par
|
||||
\pard {\field{\*\fldinst PAGEREF a}{\fldrslt {\b 1}2}}\par
|
||||
\pard {\field{\*\fldinst IF {\field{\*\fldinst PAGE}{\fldrslt 1}} = 1 "one" "many"}{\fldrslt one}}\par
|
||||
\pard {\field{\*\fldinst PAGE}}\par
|
||||
\pard {\field{\*\fldinst PAGE}{\fldrslt 1\par 2}}\par}"#;
|
||||
let d = import(rtf).unwrap();
|
||||
let f = fields_of(&d.body);
|
||||
let texts: Vec<&str> = f.iter().map(|(t, _)| t.as_str()).collect();
|
||||
// A link stays a link; a result over two paragraphs or in two formats stays its text.
|
||||
assert_eq!(&texts[..4], ["link", "Heading one\t1", "Heading two\t2", "12"], "{f:?}");
|
||||
// The PAGE inside IF's instruction is part of the code, not a field of the paragraph.
|
||||
assert_eq!(texts[4], "one", "{f:?}");
|
||||
// A field with no result group at all is left as it was (nothing).
|
||||
assert!(f[5].0.is_empty(), "{f:?}");
|
||||
assert_eq!(&texts[6..8], ["1", "2"], "{f:?}");
|
||||
assert!(f.iter().all(|(_, fl)| fl.is_empty()), "{f:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_table_of_contents_keeps_its_links_and_its_page_numbers_become_fields() {
|
||||
// The shape Word writes: the TOC result spans paragraphs; each entry is a link around its
|
||||
// text and a PAGEREF to the heading's bookmark.
|
||||
let rtf = br#"{\rtf1\ansi
|
||||
\pard {\field{\*\fldinst TOC \\o "1-3" \\h}{\fldrslt {\field{\*\fldinst HYPERLINK \\l "_Toc1"}{\fldrslt {One\tab {\field{\*\fldinst PAGEREF _Toc1 \\h}{\fldrslt 3}}}}}\par
|
||||
{\field{\*\fldinst HYPERLINK \\l "_Toc2"}{\fldrslt {Two\tab {\field{\*\fldinst PAGEREF _Toc2 \\h}{\fldrslt 5}}}}}}}\par
|
||||
\pard {\*\bkmkstart _Toc1}Heading{\*\bkmkend _Toc1}\par}"#;
|
||||
let d = import(rtf).unwrap();
|
||||
let f = fields_of(&d.body);
|
||||
assert_eq!(f[0].1, [("PAGEREF _Toc1 \\h".to_string(), "3".to_string(), false)], "{f:?}");
|
||||
assert_eq!(f[1].1, [("PAGEREF _Toc2 \\h".to_string(), "5".to_string(), false)], "{f:?}");
|
||||
assert!(f[0].0.starts_with("One\t") && f[1].0.starts_with("Two\t"), "{f:?}");
|
||||
// The entry text still links to its heading.
|
||||
let p = d.body[0].as_para().unwrap();
|
||||
assert!(p.props_at(0).link.is_some(), "{:?}", p.runs);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hidden_styleref_tracked_and_object_results_stay_as_read() {
|
||||
let rtf = br#"{\rtf1\ansi{\*\revtbl{Unknown;}{Ann;}}
|
||||
\pard a{\v {\field{\*\fldinst PAGE}{\fldrslt 2}}}b\par
|
||||
\pard {\field{\*\fldinst STYLEREF "heading 1"}{\fldrslt Intro}}\par
|
||||
\pard {\field{\*\fldinst PAGE}{\fldrslt {\revised\revauth1 2}}}\par
|
||||
\pard {\field{\*\fldinst PAGE}{\fldrslt A{\*\bkmkstart m}B{\*\bkmkend m}}}\par}"#;
|
||||
let d = import(rtf).unwrap();
|
||||
let f = fields_of(&d.body);
|
||||
// Hidden: neither the result nor a field.
|
||||
assert_eq!((f[0].0.as_str(), f[0].1.len()), ("ab", 0), "{f:?}");
|
||||
// STYLEREF keeps Word's text.
|
||||
assert_eq!((f[1].0.as_str(), f[1].1.len()), ("Intro", 0), "{f:?}");
|
||||
// A tracked result and one holding a bookmark stay text.
|
||||
assert_eq!((f[2].0.as_str(), f[2].1.len()), ("2", 0), "{f:?}");
|
||||
// (The bookmark's start and end are object characters in the paragraph's text.)
|
||||
assert_eq!((f[3].0.replace('\u{FFFC}', ""), f[3].1.len()), ("AB".to_string(), 0), "{f:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_page_number_symbol_is_a_page_field() {
|
||||
let d = import(br"{\rtf1\ansi{\footer \pard Page \chpgn\par}\pard Body\par}").unwrap();
|
||||
let f = footer(&d);
|
||||
assert_eq!(f[0].1, [("PAGE".to_string(), String::new(), false)], "{f:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncated_and_hostile_fields_do_not_crash() {
|
||||
for rtf in [
|
||||
&br"{\rtf1{\field{\*\fldinst PAGE}{\fldrslt 2"[..],
|
||||
br"{\rtf1{\field{\*\fldinst PAGE}{\fldrslt 2}",
|
||||
br"{\rtf1{\field\field\field{\*\fldinst PAGE}}}}",
|
||||
br"{\rtf1{\field{\fldrslt x}{\*\fldinst PAGE}}\par}",
|
||||
br"{\rtf1 a{\field{\*\fldinst PAGE}{\fldrslt 1\par 2}}\par}",
|
||||
] {
|
||||
let _ = import(rtf);
|
||||
}
|
||||
let mut deep = String::from(r"{\rtf1 ");
|
||||
for _ in 0..300 {
|
||||
deep.push_str(r"{\field{\*\fldinst PAGE}{\fldrslt ");
|
||||
}
|
||||
deep.push('x');
|
||||
let _ = import(deep.as_bytes());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_flow_reader_keeps_field_results_as_text() {
|
||||
// `parse` asks for no fields, as before: the result is the paragraph's text.
|
||||
let f = parse(br"{\rtf1\ansi\pard Pag. {\field{\*\fldinst PAGE}{\fldrslt 2}}\par}").unwrap();
|
||||
match &f.blocks[0] {
|
||||
FBlock::Para(p) => {
|
||||
assert!(p.inlines.iter().all(|i| matches!(i, Inline::Text(..))), "{:?}", p.inlines);
|
||||
assert_eq!(p.text(), "Pag. 2");
|
||||
}
|
||||
b => panic!("{b:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tracked_page_symbol_keeps_its_insertion_and_deletion() {
|
||||
let rtf = br"{\rtf1\ansi{\*\revtbl{Unknown;}{Ann;}}
|
||||
\pard Page {\revised\revauth1 \chpgn}\par
|
||||
\pard Page {\deleted\revauthdel1 \chpgn}\par}";
|
||||
let d = import(rtf).unwrap();
|
||||
let f = fields_of(&d.body);
|
||||
assert_eq!(f[0].1.len(), 1, "{f:?}");
|
||||
assert_eq!(f[1].1.len(), 1, "{f:?}");
|
||||
// Each field sits in a run carrying its tracked change, so Accept and Reject apply to it.
|
||||
let marked = |i: usize, ins: bool| {
|
||||
let p = d.body[i].as_para().unwrap();
|
||||
p.runs.iter().any(|r| if ins { r.props.ins.is_some() } else { r.props.del.is_some() })
|
||||
};
|
||||
assert!(marked(0, true), "{:?}", d.body[0].as_para().unwrap().runs);
|
||||
assert!(marked(1, false), "{:?}", d.body[1].as_para().unwrap().runs);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_result_whose_text_is_hidden_inside_it_stays_as_read() {
|
||||
// `\v` inside the result: what showed was nothing, so no field that would show a number.
|
||||
let rtf = br"{\rtf1\ansi
|
||||
\pard x{\field{\*\fldinst PAGE}{\fldrslt \v 2}}y\par
|
||||
\pard x{\field{\*\fldinst PAGE}{\fldrslt }}y\par}";
|
||||
let d = import(rtf).unwrap();
|
||||
let f = fields_of(&d.body);
|
||||
assert_eq!((f[0].0.as_str(), f[0].1.len()), ("xy", 0), "{f:?}");
|
||||
// A result that is really empty is still a field.
|
||||
assert_eq!(f[1].1.len(), 1, "{f:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hidden_page_symbols_and_nested_results_do_not_reappear_as_fields() {
|
||||
for result in [r"{\v\chpgn}", r"{\field{\*\fldinst DATE}{\fldrslt {\v 2}}}"] {
|
||||
let rtf = format!(r"{{\rtf1\ansi\pard x{{\field{{\*\fldinst PAGE}}{{\fldrslt {result}}}}}y\par}}");
|
||||
let d = import(rtf.as_bytes()).unwrap();
|
||||
let f = fields_of(&d.body);
|
||||
assert_eq!(f[0], ("xy".into(), Vec::new()), "{result}: {f:?}");
|
||||
}
|
||||
// A visible nested result remains eligible for conversion by its enclosing PAGE field.
|
||||
let d = import(br"{\rtf1\ansi{\field{\*\fldinst PAGE}{\fldrslt {\field{\*\fldinst DATE}{\fldrslt 2}}}}\par}").unwrap();
|
||||
assert_eq!(fields_of(&d.body)[0].1, [("PAGE".into(), "2".into(), false)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_page_fields_keep_insertion_and_deletion_marks() {
|
||||
for (mark, insertion) in [(r"\revised\revauth1", true), (r"\deleted\revauthdel1", false)] {
|
||||
let rtf = format!(r"{{\rtf1\ansi{{\*\revtbl{{Unknown;}}{{Ann;}}}}\pard {{{mark}{{\field{{\*\fldinst PAGE}}{{\fldrslt }}}}}}\par}}");
|
||||
let d = import(rtf.as_bytes()).unwrap();
|
||||
let fields = fields_of(&d.body);
|
||||
assert_eq!(fields[0].1, [("PAGE".into(), String::new(), false)]);
|
||||
let p = d.body[0].as_para().unwrap();
|
||||
assert_eq!(p.text, "\u{FFFC}", "the sole character is the field marker");
|
||||
let props = p.props_at(0);
|
||||
assert!(if insertion { props.ins.is_some() } else { props.del.is_some() }, "{mark}: {props:?}");
|
||||
}
|
||||
}
|
||||
+22
-14
@@ -189,31 +189,39 @@ impl Reader {
|
||||
}
|
||||
}
|
||||
|
||||
/// The current formatting with its tracked changes (insertion, deletion, formatting change).
|
||||
pub(super) fn text_fmt(&mut self) -> Fmt {
|
||||
let mut f = self.st.fmt.clone();
|
||||
let r = self.st.rev;
|
||||
if r.ins {
|
||||
f.ins = Some(self.rev_mark(r.auth, r.dttm));
|
||||
}
|
||||
if r.del {
|
||||
f.del = Some(self.rev_mark(r.authdel, r.dttmdel));
|
||||
}
|
||||
let c = &self.st.chg_c;
|
||||
if let Some(words) = c.old.clone() {
|
||||
let mark = self.rev_mark(c.auth, c.date);
|
||||
let old = self.old_fmt(&words);
|
||||
f.fmt_change = Some(Box::new(model::FmtChange { mark, old }));
|
||||
}
|
||||
f
|
||||
}
|
||||
|
||||
pub(super) fn text(&mut self, s: &str) {
|
||||
match self.st.dest {
|
||||
Dest::Body => {
|
||||
if self.st.hidden {
|
||||
self.hidden_text_dropped();
|
||||
return;
|
||||
}
|
||||
let mut f = self.st.fmt.clone();
|
||||
if s.contains([MARK_OPEN, MARK_CLOSE]) {
|
||||
let f = self.st.fmt.clone();
|
||||
self.para.push_text(&s.replace([MARK_OPEN, MARK_CLOSE], "\u{FFFD}"), &f);
|
||||
self.para_has = true;
|
||||
return;
|
||||
}
|
||||
let r = self.st.rev;
|
||||
if r.ins {
|
||||
f.ins = Some(self.rev_mark(r.auth, r.dttm));
|
||||
}
|
||||
if r.del {
|
||||
f.del = Some(self.rev_mark(r.authdel, r.dttmdel));
|
||||
}
|
||||
let c = &self.st.chg_c;
|
||||
if let Some(words) = c.old.clone() {
|
||||
let mark = self.rev_mark(c.auth, c.date);
|
||||
let old = self.old_fmt(&words);
|
||||
f.fmt_change = Some(Box::new(model::FmtChange { mark, old }));
|
||||
}
|
||||
let f = self.text_fmt();
|
||||
self.para.push_text(s, &f);
|
||||
self.para_has = true;
|
||||
}
|
||||
|
||||
@@ -75,6 +75,7 @@ impl Reader {
|
||||
"row" => self.end_row(),
|
||||
"line" | "softline" => self.ch('\n'),
|
||||
"tab" => self.ch('\t'),
|
||||
"chpgn" => self.page_number_symbol(),
|
||||
"page" | "softpage" => self.ch('\u{000C}'),
|
||||
"column" => self.ch('\u{000E}'),
|
||||
"emdash" => self.ch('—'),
|
||||
@@ -283,8 +284,13 @@ impl Reader {
|
||||
self.defs.push(d);
|
||||
}
|
||||
}
|
||||
"field" => self.start_field(),
|
||||
"field" => {
|
||||
self.start_field();
|
||||
self.open_field();
|
||||
}
|
||||
"fldlock" => self.field_word(w),
|
||||
"fldrslt" => {
|
||||
self.field_word(w);
|
||||
let link = self.st.field.and_then(|i| self.fields.get(i)).and_then(|s| hyperlink(s));
|
||||
if link.is_some() {
|
||||
self.st.fmt.link = link.as_deref().and_then(model::kept_link);
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
[package]
|
||||
name = "craft-suite-account"
|
||||
description = "Shared suite-level account store: who is signed in, kept once for the whole Craft suite, with the token in the operating system's keychain"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
repository.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
log = "0.4"
|
||||
# Non-wasm only: no per-user config dir in the browser.
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
dirs = "7"
|
||||
# The account handle is a digest of the service and the user, so the same account always lands on
|
||||
# the same keychain entry and a second sign-in replaces it instead of leaving one behind.
|
||||
sha2 = "0.10"
|
||||
# Overwrites a token's bytes when the value is dropped. Pure Rust, safe API, so the
|
||||
# workspace's `unsafe_code = "forbid"` still holds.
|
||||
zeroize = { version = "1", features = ["alloc"] }
|
||||
# Windows Credential Manager, the macOS Keychain and the Secret Service, behind one API. The `v1`
|
||||
# default feature picks the right one per platform and pins `crypto-rust` for the Secret Service,
|
||||
# so no OpenSSL and no C toolchain comes in.
|
||||
keyring = "4.2"
|
||||
# The entry constructor that takes store modifiers, which is how a Windows credential asks for
|
||||
# machine-local persistence. `keyring` installs the platform store; this reads it.
|
||||
keyring-core = "1"
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
@@ -0,0 +1,342 @@
|
||||
//! The accounts file: who has signed in and at which deployment.
|
||||
//!
|
||||
//! No token is in here. Every field is something a user interface shows, or something needed to
|
||||
//! find the token in the keychain. See [`crate::store`] for the token itself.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
use crate::error::Error;
|
||||
|
||||
/// The format this code writes. A reader that does not recognise the number leaves the file alone.
|
||||
pub const FORMAT: u32 = 1;
|
||||
|
||||
/// The largest accounts file that will be read. A suite account list is a few hundred bytes. A
|
||||
/// megabyte is already far past anything legitimate.
|
||||
const MAX_BYTES: u64 = 1 << 20;
|
||||
|
||||
/// One account, as the suite remembers it.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct Account {
|
||||
/// The handle for this account inside the suite. It is also the keychain entry's user name.
|
||||
///
|
||||
/// A digest of `service` and `user` (see [`handle`]). Signing in again as the same person at
|
||||
/// the same deployment therefore lands on the same keychain entry. No stale entry is left
|
||||
/// behind.
|
||||
pub id: String,
|
||||
/// The deployment this account signs in to, as a base URL with no trailing slash.
|
||||
pub service: String,
|
||||
/// The deployment's own identifier for this account: the OIDC subject, never an address.
|
||||
pub user: String,
|
||||
/// What to show a person. Never an identity: two people can share a display name.
|
||||
pub display: String,
|
||||
pub email: Option<String>,
|
||||
/// Unix seconds when this account was first stored here.
|
||||
pub added: i64,
|
||||
/// Unix seconds when an application last used it.
|
||||
pub last_used: i64,
|
||||
/// Whether cloud storage is linked, as recorded by [`crate::NewAccount::linked`] at sign-in.
|
||||
/// For a user interface only; the deployment is the authority and is asked again on each
|
||||
/// start.
|
||||
pub linked: bool,
|
||||
/// Bumped every time this row's content changes: a sign-in that replaces the entry, or (per
|
||||
/// RFC-0025's cross-app lifecycle guarantees) a removal. A caller that read the account before
|
||||
/// one of those passes its generation back on a later write; [`crate::Store::update_token`]
|
||||
/// refuses a write made against a generation that is no longer current, so a refresh started
|
||||
/// before a change completes can never land after it and overwrite something newer.
|
||||
pub generation: u32,
|
||||
}
|
||||
|
||||
/// What is left behind when an account is removed: the generation it reached, so a re-add or a
|
||||
/// stale write can never land before it.
|
||||
///
|
||||
/// RFC-0025's "Cross-app lifecycle guarantees" (point 2): generations are monotonic across removal
|
||||
/// and re-add. Without this, a removed-and-re-added account restarted at generation 0, so a stale
|
||||
/// refresh from before the removal passed the generation check against the new session and
|
||||
/// replaced its token; a refresh racing a removal could even put a keychain entry back after the
|
||||
/// removal deleted it. See [`Located::Tombstoned`] and [`crate::Store::update_token`].
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct Tombstone {
|
||||
pub id: String,
|
||||
/// The generation the account reached, bumped once more by the removal itself. A write
|
||||
/// against any generation at or before this one is stale.
|
||||
pub generation: u32,
|
||||
}
|
||||
|
||||
/// Where [`Accounts::locate`] found (or didn't find) an id.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Located<'a> {
|
||||
/// A row is on the list.
|
||||
Active(&'a Account),
|
||||
/// No row, but a tombstone: the account was removed and holds this generation. A write against
|
||||
/// it is stale, never [`crate::Error::Unknown`]; see [`crate::Store::update_token`].
|
||||
Tombstoned(u32),
|
||||
/// Neither. This handle has never been on this list.
|
||||
Unknown,
|
||||
}
|
||||
|
||||
/// The whole file.
|
||||
///
|
||||
/// `format` has no `#[serde(default)]` of its own, unlike every other field here. A container-
|
||||
/// level default would fill a missing `format` key in from this struct's own `Default` impl,
|
||||
/// which answers [`FORMAT`]: a file that never said what format it was would then read as
|
||||
/// exactly the format this build understands. Requiring the key keeps a file that never
|
||||
/// declared a format from passing as one that did.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Accounts {
|
||||
pub format: u32,
|
||||
#[serde(default)]
|
||||
pub accounts: Vec<Account>,
|
||||
/// The account an application should use when it has no reason to prefer another.
|
||||
#[serde(default)]
|
||||
pub active: Option<String>,
|
||||
/// Removed accounts, holding the generation they reached. See [`Tombstone`].
|
||||
#[serde(default)]
|
||||
pub tombstones: Vec<Tombstone>,
|
||||
}
|
||||
|
||||
impl Default for Accounts {
|
||||
fn default() -> Accounts {
|
||||
Accounts { format: FORMAT, accounts: Vec::new(), active: None, tombstones: Vec::new() }
|
||||
}
|
||||
}
|
||||
|
||||
impl Accounts {
|
||||
pub fn get(&self, id: &str) -> Option<&Account> {
|
||||
self.accounts.iter().find(|a| a.id == id)
|
||||
}
|
||||
|
||||
/// The generation a tombstone for `id` holds, when there is one.
|
||||
pub fn tombstone_generation(&self, id: &str) -> Option<u32> {
|
||||
self.tombstones.iter().find(|t| t.id == id).map(|t| t.generation)
|
||||
}
|
||||
|
||||
/// Finds `id` as an active row, a tombstone, or neither. The one lookup
|
||||
/// [`crate::Store::update_token`] needs to answer a write with the right error: a stale
|
||||
/// generation against a row that is still there, a stale generation against one that was
|
||||
/// removed, or a handle that was never on this list at all.
|
||||
pub fn locate(&self, id: &str) -> Located<'_> {
|
||||
match self.get(id) {
|
||||
Some(account) => Located::Active(account),
|
||||
None => match self.tombstone_generation(id) {
|
||||
Some(generation) => Located::Tombstoned(generation),
|
||||
None => Located::Unknown,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// The active account, when one is named and still on the list.
|
||||
///
|
||||
/// An `active` naming an account that is gone gives the ordinary answer of `None`. A
|
||||
/// half-finished sign-out on another machine must not stop an application starting.
|
||||
pub fn current(&self) -> Option<&Account> {
|
||||
self.active.as_deref().and_then(|id| self.get(id))
|
||||
}
|
||||
|
||||
/// Adds or replaces an account. The account then becomes the active one.
|
||||
///
|
||||
/// Clears any tombstone for this id: the account is current again, so nothing should still
|
||||
/// answer a write against it with "removed".
|
||||
///
|
||||
/// For a sign-in. [`Store::set_active`] is the other caller allowed to change `active`; a
|
||||
/// background refresh never should. See [`Accounts::refresh_in_place`].
|
||||
///
|
||||
/// [`Store::set_active`]: crate::Store::set_active
|
||||
pub fn put(&mut self, account: Account) {
|
||||
self.tombstones.retain(|t| t.id != account.id);
|
||||
self.active = Some(account.id.clone());
|
||||
match self.accounts.iter_mut().find(|a| a.id == account.id) {
|
||||
Some(existing) => *existing = account,
|
||||
None => self.accounts.push(account),
|
||||
}
|
||||
}
|
||||
|
||||
/// Replaces an active row's content without touching which account is current.
|
||||
///
|
||||
/// For [`Store::update_token`]: a refresh is maintenance a person never asked for by name. It
|
||||
/// must not steal the selection away from whichever account they actually picked, the way
|
||||
/// [`Accounts::put`] would. Does nothing when `id` no longer names an active row; the caller
|
||||
/// has already confirmed it does, under the same lock, right before calling this.
|
||||
///
|
||||
/// [`Store::update_token`]: crate::Store::update_token
|
||||
pub fn refresh_in_place(&mut self, id: &str, account: Account) {
|
||||
if let Some(existing) = self.accounts.iter_mut().find(|a| a.id == id) {
|
||||
*existing = account;
|
||||
}
|
||||
}
|
||||
|
||||
/// Drops an account and leaves a tombstone holding its generation, bumped once more by the
|
||||
/// removal itself (RFC-0025 lifecycle guarantee 2). Whoever is left over, if anybody, becomes
|
||||
/// active.
|
||||
///
|
||||
/// Refuses with [`Error::GenerationExhausted`] when `generation` is already `u32::MAX`.
|
||||
/// Wrapping past it would hand out a small number again. A stale caller's check against that
|
||||
/// small number would then pass. Monotonic generations exist to rule that out.
|
||||
pub fn remove_with_tombstone(&mut self, id: &str, generation: u32) -> Result<(), Error> {
|
||||
let bumped = generation.checked_add(1).ok_or_else(|| Error::GenerationExhausted(id.to_owned()))?;
|
||||
self.accounts.retain(|a| a.id != id);
|
||||
if self.active.as_deref() == Some(id) {
|
||||
self.active = self.accounts.first().map(|a| a.id.clone());
|
||||
}
|
||||
match self.tombstones.iter_mut().find(|t| t.id == id) {
|
||||
Some(existing) => existing.generation = bumped,
|
||||
None => self.tombstones.push(Tombstone { id: id.to_owned(), generation: bumped }),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// The handle for an account at a deployment.
|
||||
///
|
||||
/// A digest, with the address and the subject kept out of it. The digest is stable. One account
|
||||
/// therefore stays on one keychain entry however many times somebody signs in. The handle is also
|
||||
/// opaque. A credential manager window puts the handle on screen. Nobody's address belongs in that
|
||||
/// list.
|
||||
pub fn handle(service: &str, user: &str) -> String {
|
||||
let mut hash = Sha256::new();
|
||||
hash.update(normalise(service).as_bytes());
|
||||
hash.update(b"\n");
|
||||
hash.update(user.as_bytes());
|
||||
let digest = hash.finalize();
|
||||
digest.iter().take(12).map(|b| format!("{b:02x}")).collect()
|
||||
}
|
||||
|
||||
/// A deployment's base URL with any trailing slashes taken off. One deployment is then one account
|
||||
/// however the URL was typed.
|
||||
pub fn normalise(service: &str) -> String {
|
||||
service.trim().trim_end_matches('/').to_owned()
|
||||
}
|
||||
|
||||
/// Just the file's name, for an error a log might show.
|
||||
///
|
||||
/// The full path sits under a user's profile folder and names them. [`Store::shared`] logs a
|
||||
/// read failure at `warn`. Every message built here therefore says only the file, never the
|
||||
/// path it lived under. The name alone is enough to say which file failed and why.
|
||||
///
|
||||
/// [`Store::shared`]: crate::Store::shared
|
||||
fn named(path: &Path) -> &str {
|
||||
path.file_name().and_then(|n| n.to_str()).unwrap_or("the accounts file")
|
||||
}
|
||||
|
||||
/// Reads the file. A missing file is an empty list. That is what "nobody has signed in" looks like.
|
||||
///
|
||||
/// Accepts only a file that explicitly declares this exact [`FORMAT`]. `format` carries no
|
||||
/// `#[serde(default)]` (see [`Accounts`]). A file with no `format` key therefore fails to parse
|
||||
/// here. It never quietly reads as [`FORMAT`] through [`Accounts`]'s own `Default` impl. A file
|
||||
/// that spells out `"format": 0` parses fine. The check just below rejects it there, the same as
|
||||
/// any other value [`FORMAT`] does not name. Without both checks, an unrelated JSON file that
|
||||
/// happens to parse into this permissive shape (every other field here defaults) could be read
|
||||
/// as an empty account list and then overwritten outright by the next sign-in, a format this
|
||||
/// reader never actually established.
|
||||
pub fn read(path: &Path) -> Result<Accounts, Error> {
|
||||
let bytes = match std::fs::metadata(path) {
|
||||
Ok(meta) if meta.len() > MAX_BYTES => {
|
||||
return Err(Error::Malformed(format!("{} is {} bytes, too large to be an account list", named(path), meta.len())));
|
||||
}
|
||||
Ok(_) => std::fs::read(path),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Accounts::default()),
|
||||
Err(e) => return Err(Error::Io(format!("couldn't read {} ({e})", named(path)))),
|
||||
};
|
||||
let bytes = bytes.map_err(|e| Error::Io(format!("couldn't read {} ({e})", named(path))))?;
|
||||
let parsed: Accounts = serde_json::from_slice(&bytes).map_err(|e| Error::Malformed(format!("{} didn't parse ({e})", named(path))))?;
|
||||
if parsed.format != FORMAT {
|
||||
return Err(Error::Malformed(format!(
|
||||
"{} declares format {}. This build writes and reads only format {FORMAT}. A missing or unrecognised marker is never read as an account list.",
|
||||
named(path),
|
||||
parsed.format
|
||||
)));
|
||||
}
|
||||
Ok(parsed)
|
||||
}
|
||||
|
||||
/// Writes the file through a temporary file and a rename. The rename is atomic: a reader never
|
||||
/// sees a half-written file, only the previous write or this one, never a mix of both.
|
||||
///
|
||||
/// That atomicity is not durability. The temporary file is flushed to disk with `sync_all` before
|
||||
/// the rename. The rename itself then never promotes data the disk has not actually taken yet.
|
||||
/// Without that flush, power loss right after the rename could still leave an empty or truncated
|
||||
/// file on a filesystem that reorders writes behind a rename. [`read`] would then answer
|
||||
/// [`Error::Malformed`] forever. Every mutation here reads the file first. There would be
|
||||
/// nothing left to repair it with.
|
||||
///
|
||||
/// Readable by this user alone where the platform has file modes. The file holds no token. It does
|
||||
/// say who is signed in. That is nobody else's business.
|
||||
///
|
||||
/// Refuses a list that would serialize past [`MAX_BYTES`], before any file is touched. [`read`]
|
||||
/// rejects a file that large; writing one anyway would succeed here and then make every later
|
||||
/// read of this list fail, including the reads every other mutation needs before it can repair
|
||||
/// anything. An oversized `display` or `email` on one account is the realistic way to reach this,
|
||||
/// not the ordinary handful of accounts a suite ever holds.
|
||||
pub fn write(path: &Path, accounts: &Accounts) -> Result<(), Error> {
|
||||
let dir = path.parent().ok_or_else(|| Error::Io(format!("{} has no parent folder", path.display())))?;
|
||||
let json = serde_json::to_vec_pretty(accounts).map_err(|e| Error::Malformed(e.to_string()))?;
|
||||
if json.len() as u64 > MAX_BYTES {
|
||||
return Err(Error::Malformed(format!(
|
||||
"the account list would be {} bytes, too large to write; {} would reject it unread",
|
||||
json.len(),
|
||||
path.display()
|
||||
)));
|
||||
}
|
||||
std::fs::create_dir_all(dir).map_err(|e| Error::Io(format!("couldn't create {} ({e})", dir.display())))?;
|
||||
use std::io::Write;
|
||||
|
||||
let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0);
|
||||
let pid = std::process::id();
|
||||
let tmp = dir.join(format!(".{}.{}.{}.tmp", path.file_name().and_then(|n| n.to_str()).unwrap_or("accounts"), stamp, pid));
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::fs::OpenOptions;
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
let mut file = OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.mode(0o600)
|
||||
.open(&tmp)
|
||||
.map_err(|e| Error::Io(format!("couldn't create {} ({e})", tmp.display())))?;
|
||||
file.write_all(&json).map_err(|e| Error::Io(format!("couldn't write {} ({e})", tmp.display())))?;
|
||||
file.sync_all().map_err(|e| Error::Io(format!("couldn't flush {} ({e})", tmp.display())))?;
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
{
|
||||
use std::fs::OpenOptions;
|
||||
let mut file =
|
||||
OpenOptions::new().write(true).create_new(true).open(&tmp).map_err(|e| Error::Io(format!("couldn't create {} ({e})", tmp.display())))?;
|
||||
file.write_all(&json).map_err(|e| Error::Io(format!("couldn't write {} ({e})", tmp.display())))?;
|
||||
file.sync_all().map_err(|e| Error::Io(format!("couldn't flush {} ({e})", tmp.display())))?;
|
||||
restrict(&tmp)?;
|
||||
}
|
||||
std::fs::rename(&tmp, path).map_err(|e| Error::Io(format!("couldn't replace {} ({e})", path.display())))?;
|
||||
// The flush above persisted the file's bytes. The rename changed a directory entry, and that
|
||||
// entry has its own durability: on Linux, power loss after this function returned could
|
||||
// otherwise resurrect the older list, losing a tombstone a discard already reported written.
|
||||
// Directories open and sync on unix only; elsewhere the rename's own guarantees stand alone.
|
||||
#[cfg(unix)]
|
||||
{
|
||||
if let Some(parent) = path.parent() {
|
||||
let dir = std::fs::File::open(parent).map_err(|e| Error::Io(format!("couldn't open {} ({e})", parent.display())))?;
|
||||
dir.sync_all().map_err(|e| Error::Io(format!("couldn't flush {} ({e})", parent.display())))?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
fn restrict(_path: &Path) -> Result<(), Error> {
|
||||
// A no-op today. That is a real gap this comment used to paper over. A new file in the
|
||||
// platform configuration folder (the default `paths::Rule::Platform` home) inherits that
|
||||
// folder's own, profile-scoped access rules. The account list is this user's alone there.
|
||||
// `paths::Rule::Portable` and `paths::Rule::EnvVar` point `write` at whatever folder the
|
||||
// caller named. A new file there inherits that folder's own Windows access control list,
|
||||
// whatever it is. A shared or loosely permissioned folder in either of those two cases
|
||||
// leaves the account list (subjects, display names, emails, never a token) readable by
|
||||
// anyone else with access to it. Narrowing that needs a per-user Windows DACL on the file,
|
||||
// set through the Win32 authorization API. Every binding for that API is an `unsafe fn`.
|
||||
// This workspace forbids `unsafe_code` outright. Closing this for real needs either a
|
||||
// maintainer-approved exception for one call site or a vetted dependency that wraps that API
|
||||
// safely. Both are decisions for a dedicated PR. See `paths::Rule`.
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
//! What can go wrong.
|
||||
|
||||
/// A failure in the shared account store.
|
||||
///
|
||||
/// None of these is "nobody is signed in". That is an ordinary answer. It comes back as
|
||||
/// [`crate::Shared::None`].
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Error {
|
||||
/// This process reads and writes nothing: `ARTCRAFT_SUITE_DIR` is set and empty, or the system
|
||||
/// has no per-user configuration folder.
|
||||
Isolated,
|
||||
Io(String),
|
||||
/// The accounts file is in a format this build does not know, or is not an accounts file.
|
||||
Malformed(String),
|
||||
/// The operating system's keychain refused.
|
||||
Keychain(String),
|
||||
/// No account on file has that handle.
|
||||
Unknown(String),
|
||||
/// A write named a generation the account has already moved past: another sign-in or removal
|
||||
/// landed first. See RFC-0025's "Cross-app lifecycle guarantees".
|
||||
StaleGeneration {
|
||||
id: String,
|
||||
expected: u32,
|
||||
current: u32,
|
||||
},
|
||||
/// This handle has reached the highest generation `u32` can hold. Nothing can bump it
|
||||
/// further. The write that would have is refused. Wrapping back to a small generation would
|
||||
/// let a stale caller pass the check again. Reaching this needs about four billion sign-ins
|
||||
/// or removals of the same handle.
|
||||
GenerationExhausted(String),
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Error {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Error::Isolated => f.write_str("this process keeps no shared account"),
|
||||
Error::Io(why) | Error::Malformed(why) => f.write_str(why),
|
||||
Error::Keychain(why) => write!(f, "the keychain refused: {why}"),
|
||||
Error::Unknown(id) => write!(f, "no account {id} is signed in"),
|
||||
Error::StaleGeneration { id, expected, current } => {
|
||||
write!(
|
||||
f,
|
||||
"account {id} moved from generation {expected} to {current}; this write was made against a generation that is no longer current"
|
||||
)
|
||||
}
|
||||
Error::GenerationExhausted(id) => write!(f, "account {id} has reached the highest generation this build can record"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for Error {}
|
||||
@@ -0,0 +1,455 @@
|
||||
//! The Craft App Suite's shared account store: the suite's keychain.
|
||||
//!
|
||||
//! Somebody signs in once and every Craft App acts as them. Before this, each application kept its
|
||||
//! own session file. Taken across the suite that meant a sign-in per application, a copy of a
|
||||
//! bearer token on disk per application, and a separate place to revoke per application.
|
||||
//!
|
||||
//! The store has two halves, kept deliberately apart:
|
||||
//!
|
||||
//! * The list of accounts is a small JSON file in one suite-level folder ([`paths`]). It names who
|
||||
//! has signed in, at which deployment, and which account is current. It holds no credential.
|
||||
//! * The token is in the operating system's keychain ([`store`]). Windows Credential Manager, the
|
||||
//! macOS Keychain, or the Secret Service.
|
||||
//!
|
||||
//! Nothing here is mandatory. An application asks [`Store::shared`] what the suite has to offer and
|
||||
//! gets one of three answers: somebody is signed in, nobody is signed in, or there is an account on
|
||||
//! file whose token could not be read. The second and third leave the application exactly as it was
|
||||
//! before this crate existed, offering its own sign-in. A machine with no keychain, a locked
|
||||
//! keychain, a missing folder and an empty suite all land on "nobody is signed in". None of them is
|
||||
//! an error that stops an application starting.
|
||||
//!
|
||||
//! [`Store::discard`] clears the keychain entry and then the row, for a session this machine
|
||||
//! should stop holding. [`Store::forget`] clears only the keychain entry, leaving the row for a
|
||||
//! user interface to still show (and, say, offer "sign in again" on). Neither talks to the
|
||||
//! deployment: ending the session there, so every machine the person left one on drops it too, is
|
||||
//! a distinct operation that belongs to the provider adapter that knows how to ask the deployment
|
||||
//! for that, per RFC-0025's "Cross-app lifecycle guarantees" (point 4: forgetting is local,
|
||||
//! revoking is at the provider). A consumer that wants both calls its own revoke, then
|
||||
//! [`Store::discard`].
|
||||
//!
|
||||
//! An application upgrading from its own session file calls [`migrate::adopt`] once at startup.
|
||||
//!
|
||||
//! ## Concurrent mutations and partial-failure recovery
|
||||
//!
|
||||
//! Several apps run at once against one account list and one keychain (RFC-0025's "Cross-app
|
||||
//! lifecycle guarantees"). Every mutation of the accounts file ([`Store::sign_in`],
|
||||
//! [`Store::update_token`], [`Store::discard`], [`Store::set_active`], [`Store::touch`]) therefore
|
||||
//! reads, changes and writes it under one OS-level file lock ([`lock::with_lock`]), never an
|
||||
//! unlocked read-modify-write. A pure read ([`Store::accounts`], [`Store::shared`]) does not take
|
||||
//! the lock; [`accounts::write`] already replaces the file through a temporary file and a rename,
|
||||
//! so a reader never sees a half-written file, only one write older than the latest.
|
||||
//!
|
||||
//! The lock does not wrap an unconditional keychain call. A keychain write or removal happens
|
||||
//! either entirely before the lock is taken or, for [`Store::discard`], [`Store::sign_in`]'s
|
||||
//! re-check and [`Store::update_token`]'s write, inside the same lock hold as the list change it
|
||||
//! belongs with. Each of those three is conditional on the list mutation it sits beside actually
|
||||
//! going ahead, never a call made regardless. A locked section is never held across a call into
|
||||
//! the keychain that another `Store` in this process could itself be waiting on; that would
|
||||
//! deadlock two `Store`s over one folder in a single process the same way two applications would
|
||||
//! be.
|
||||
//!
|
||||
//! Each operation's ordering is chosen so a crash, or another process winning a race, leaves a
|
||||
//! state the next reader detects and repairs rather than a silent mismatch (guarantee 1):
|
||||
//!
|
||||
//! * [`Store::sign_in`] writes the keychain token first, the list second. A crash in between
|
||||
//! leaves one keychain entry nothing on the list points at yet. Harmless: the account's handle
|
||||
//! is a digest of the deployment and the subject, so the next sign-in for the same account
|
||||
//! overwrites that same entry rather than minting a new one. A concurrent [`Store::discard`]
|
||||
//! for the same handle landing in that same window is not harmless the same way: it would
|
||||
//! delete the entry this call just wrote and then, moments later, this call would still commit
|
||||
//! a row claiming a session that no longer has a token behind it. The lock closure therefore
|
||||
//! re-checks the keychain just before committing the row. It writes the token again when
|
||||
//! something else has already changed it. The row this call reports `Ok` for then always has
|
||||
//! its token in place the moment it lands.
|
||||
//! * [`Store::discard`] removes the keychain entry and writes the list's tombstone under the same
|
||||
//! lock hold. A crash between them leaves a row on the list with no entry behind it; `shared()`
|
||||
//! already reads that as nobody signed in, and the next sign-in for that account tidies the row
|
||||
//! up.
|
||||
//! * [`Store::update_token`] checks the account's generation once, unlocked, purely to reject an
|
||||
//! already-stale caller cheaply before it ever takes the lock. The keychain write itself
|
||||
//! happens only under the lock, in the generation re-check's own success arm, immediately
|
||||
//! before the row commits. A sign-in, a discard, or a discard followed by a re-add can land in
|
||||
//! the window the unlocked check left open. The re-check exists to catch exactly that, whoever
|
||||
//! won it. Either way, this call answers [`Error::StaleGeneration`] (or [`Error::Unknown`], for
|
||||
//! a handle never on this list at all; see "Cross-app lifecycle guarantees" point 2 and
|
||||
//! [`accounts::Accounts::locate`]) having never touched the keychain. There is never a stale
|
||||
//! token left in it to clean up or weigh against the winner's own. A crash between the write
|
||||
//! and the commit, both now inside one lock hold, leaves the list one generation behind a
|
||||
//! keychain token that is already the
|
||||
//! newer one; the next successful `update_token` against that same, still-current generation
|
||||
//! simply writes through it again.
|
||||
//!
|
||||
//! ```no_run
|
||||
//! # fn main() -> Result<(), craft_suite_account::Error> {
|
||||
//! use craft_suite_account::{Shared, Store};
|
||||
//!
|
||||
//! let store = Store::open();
|
||||
//! match store.shared() {
|
||||
//! Shared::Session { account, token } => {
|
||||
//! // Use `token` as a bearer against `account.service`.
|
||||
//! let _ = (account, token);
|
||||
//! }
|
||||
//! // Offer this application's own sign-in, exactly as before.
|
||||
//! Shared::None => {}
|
||||
//! Shared::Unreadable { why, .. } => eprintln!("the shared sign-in could not be read: {why}"),
|
||||
//! }
|
||||
//! # Ok(()) }
|
||||
//! ```
|
||||
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
pub mod accounts;
|
||||
mod error;
|
||||
mod lock;
|
||||
pub mod migrate;
|
||||
pub mod paths;
|
||||
#[cfg(test)]
|
||||
mod race_hook;
|
||||
mod secret;
|
||||
pub mod store;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
pub use accounts::{Account, Accounts};
|
||||
pub use error::Error;
|
||||
pub use migrate::Adopted;
|
||||
pub use secret::Secret;
|
||||
pub use store::{KEYCHAIN_SERVICE, Keychain, Memory, TokenStore};
|
||||
|
||||
/// What the suite store has to offer.
|
||||
#[derive(Debug)]
|
||||
pub enum Shared {
|
||||
/// Somebody is signed in and the token came back.
|
||||
Session { account: Account, token: Secret },
|
||||
/// Nobody is signed in here. Offer a sign-in.
|
||||
None,
|
||||
/// An account is on file and its token could not be read: a locked keychain, a keychain this
|
||||
/// process may not reach, or an entry somebody deleted by hand.
|
||||
///
|
||||
/// Offer a sign-in. Say why the shared one did not come through. Quietly showing a signed-out
|
||||
/// window would leave somebody wondering where their account went.
|
||||
Unreadable { account: Account, why: String },
|
||||
}
|
||||
|
||||
/// A sign-in about to be recorded.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct NewAccount {
|
||||
/// The deployment's base URL.
|
||||
pub service: String,
|
||||
/// The deployment's identifier for the account: the OIDC subject.
|
||||
pub user: String,
|
||||
pub display: String,
|
||||
pub email: Option<String>,
|
||||
/// Whether cloud storage is linked. Recorded for a user interface; the deployment is the
|
||||
/// authority and is asked again on each start.
|
||||
pub linked: bool,
|
||||
}
|
||||
|
||||
/// The suite's account store.
|
||||
pub struct Store<S: TokenStore = Keychain> {
|
||||
/// The suite folder. `None` when this process keeps nothing.
|
||||
dir: Option<PathBuf>,
|
||||
tokens: S,
|
||||
/// This store's own test-only pause point (see [`race_hook`]). One per instance, never
|
||||
/// shared across stores, so two tests racing their own stores in parallel can never answer
|
||||
/// each other's pause.
|
||||
#[cfg(test)]
|
||||
race_hook: race_hook::Hook,
|
||||
}
|
||||
|
||||
impl Store<Keychain> {
|
||||
/// The real store: the suite folder for this platform and the platform's keychain.
|
||||
pub fn open() -> Store<Keychain> {
|
||||
Store::at(paths::resolve(&paths::Probe::default()).dir, Keychain)
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: TokenStore> Store<S> {
|
||||
/// A store over a given folder and token store. `None` keeps nothing.
|
||||
pub fn at(dir: Option<PathBuf>, tokens: S) -> Store<S> {
|
||||
Store {
|
||||
dir,
|
||||
tokens,
|
||||
#[cfg(test)]
|
||||
race_hook: race_hook::Hook::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Arms this store's own test-only pause point in [`Store::update_token`], between its
|
||||
/// first, unlocked check and the lock it takes for its second one. See [`race_hook`] for
|
||||
/// why the hook lives on the store rather than behind one shared slot.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn arm_race_hook(&self) -> race_hook::Handle {
|
||||
self.race_hook.arm()
|
||||
}
|
||||
|
||||
/// The suite folder, when there is one.
|
||||
pub fn dir(&self) -> Option<&Path> {
|
||||
self.dir.as_deref()
|
||||
}
|
||||
|
||||
/// The accounts file, when there is one.
|
||||
pub fn path(&self) -> Option<PathBuf> {
|
||||
self.dir.as_deref().map(paths::file)
|
||||
}
|
||||
|
||||
/// Whether this store can hold a session. It needs a folder. The machine needs a keychain.
|
||||
///
|
||||
/// Checked before a sign-in and before a migration. Neither then half-completes.
|
||||
pub fn usable(&self) -> Result<(), Error> {
|
||||
let _ = self.dir.as_deref().ok_or(Error::Isolated)?;
|
||||
self.tokens.available().map_err(Error::Keychain)
|
||||
}
|
||||
|
||||
/// Whether a readable token is stored for this account handle.
|
||||
///
|
||||
/// Checked against isolation first, the same as every call that reaches the keychain. An
|
||||
/// isolated store answers [`Error::Isolated`] here too, before any keychain read.
|
||||
pub fn has_token(&self, id: &str) -> Result<bool, Error> {
|
||||
let _ = self.dir.as_deref().ok_or(Error::Isolated)?;
|
||||
Ok(self.tokens.get(id).map_err(Error::Keychain)?.is_some())
|
||||
}
|
||||
|
||||
/// Every account on file. An isolated store has none.
|
||||
pub fn accounts(&self) -> Result<Accounts, Error> {
|
||||
match self.path() {
|
||||
Some(path) => accounts::read(&path),
|
||||
None => Ok(Accounts::default()),
|
||||
}
|
||||
}
|
||||
|
||||
/// What the suite has to offer. Never fails: absence of every kind is [`Shared::None`].
|
||||
///
|
||||
/// This is the call an application makes at startup. The answer decides whether it offers its
|
||||
/// own sign-in.
|
||||
pub fn shared(&self) -> Shared {
|
||||
let list = match self.accounts() {
|
||||
Ok(list) => list,
|
||||
Err(Error::Isolated) => return Shared::None,
|
||||
Err(e) => {
|
||||
log::warn!("the suite account list could not be read: {e}");
|
||||
return Shared::None;
|
||||
}
|
||||
};
|
||||
let Some(account) = list.current().cloned() else { return Shared::None };
|
||||
match self.tokens.get(&account.id) {
|
||||
Ok(Some(token)) => Shared::Session { account, token },
|
||||
// On file with no entry behind it. Somebody deleted the entry, or a sign-out got half
|
||||
// way. Either way nobody is signed in. The next sign-in tidies the row up.
|
||||
Ok(None) => Shared::None,
|
||||
Err(why) => Shared::Unreadable { account, why },
|
||||
}
|
||||
}
|
||||
|
||||
/// Records a sign-in: the token into the keychain, then the account onto the list, the latter
|
||||
/// as one locked read-change-write (see the module docs, "Concurrent mutations and
|
||||
/// partial-failure recovery").
|
||||
///
|
||||
/// The token goes first. A failed list write then leaves the previous state intact and one
|
||||
/// unreferenced keychain entry. The next sign-in for the same account overwrites that entry,
|
||||
/// because the handle is a digest of the deployment and the subject. Nothing fresh is minted
|
||||
/// each time. The other order would leave an account on the list with no token behind it.
|
||||
///
|
||||
/// A [`Store::discard`] for this same handle can still land between that first write and the
|
||||
/// lock below, taking the entry this call just placed with it. The lock closure re-checks the
|
||||
/// keychain right before it commits the row. It writes the token again when something else
|
||||
/// has already changed it. An `Ok` from this call then never reports a session with no token
|
||||
/// behind it.
|
||||
pub fn sign_in(&self, new: &NewAccount, token: &Secret, now: i64) -> Result<Account, Error> {
|
||||
self.usable()?;
|
||||
let path = self.path().ok_or(Error::Isolated)?;
|
||||
let service = accounts::normalise(&new.service);
|
||||
let id = accounts::handle(&service, &new.user);
|
||||
self.tokens.put(&id, token).map_err(Error::Keychain)?;
|
||||
lock::with_lock(&path, || {
|
||||
let mut list = accounts::read(&path)?;
|
||||
let existing = list.get(&id).cloned();
|
||||
let added = existing.as_ref().map_or(now, |a| a.added);
|
||||
// A fresh generation, continuing past whatever this handle last reached, whether that
|
||||
// was an active row (a sign-in replacing it) or a tombstone (a removal, per RFC-0025
|
||||
// lifecycle guarantee 2: generations are monotonic across removal and re-add, never
|
||||
// restarting at 0). Either way a write made against the generation this handle held a
|
||||
// moment ago is now stale. See [`Account::generation`].
|
||||
let generation = match &existing {
|
||||
Some(account) => account.generation.checked_add(1).ok_or_else(|| Error::GenerationExhausted(id.clone()))?,
|
||||
None => match list.tombstone_generation(&id) {
|
||||
Some(generation) => generation.checked_add(1).ok_or_else(|| Error::GenerationExhausted(id.clone()))?,
|
||||
None => 0,
|
||||
},
|
||||
};
|
||||
let account = Account {
|
||||
id: id.clone(),
|
||||
service: service.clone(),
|
||||
user: new.user.clone(),
|
||||
display: new.display.clone(),
|
||||
email: new.email.clone(),
|
||||
added,
|
||||
last_used: now,
|
||||
linked: new.linked,
|
||||
generation,
|
||||
};
|
||||
// A discard for this handle could have run entirely in the window between the
|
||||
// unlocked write above and this lock: it would have removed that entry on its way to
|
||||
// the tombstone this call just read past. Putting the token again here, still inside
|
||||
// the lock, closes that window: the row committed just below is never left pointing
|
||||
// at a keychain entry something else already took. Skipped when nothing changed it,
|
||||
// so the common, non-racing sign-in never pays for a second keychain write.
|
||||
if self.tokens.get(&id).map_err(Error::Keychain)?.as_ref() != Some(token) {
|
||||
self.tokens.put(&id, token).map_err(Error::Keychain)?;
|
||||
}
|
||||
list.put(account.clone());
|
||||
accounts::write(&path, &list)?;
|
||||
Ok(account)
|
||||
})
|
||||
}
|
||||
|
||||
/// Writes a refreshed token back, honouring the account's generation.
|
||||
///
|
||||
/// Updates this account's row in place. It never changes which account is active. A refresh
|
||||
/// runs in the background for whichever account needs one, including one the person did not
|
||||
/// select. It must never steal the selection away from the account they actually picked.
|
||||
/// [`Store::sign_in`] and [`Store::set_active`] are the only calls that change `active`.
|
||||
///
|
||||
/// `expected_generation` is the generation the caller last read the account at. A sign-in or a
|
||||
/// removal bumps the generation (see [`Account::generation`]); a refresh that was already in
|
||||
/// flight when one of those landed is then refused rather than silently overwriting something
|
||||
/// newer, per RFC-0025's "Cross-app lifecycle guarantees" (point 2: removal wins over refresh).
|
||||
/// An account that was removed answers [`Error::StaleGeneration`] holding the tombstone's
|
||||
/// generation, never [`Error::Unknown`] and never a silent recreation; only a handle that has
|
||||
/// never been on this list at all is `Unknown`. See [`accounts::Accounts::locate`].
|
||||
///
|
||||
/// Checked twice. The keychain is written only once, inside the lock, after the second check
|
||||
/// passes.
|
||||
///
|
||||
/// The first check, unlocked, is a fast rejection only. A caller already stale when it calls
|
||||
/// at all never even takes the lock. It writes nothing. The second check, under the accounts
|
||||
/// lock, is what the keychain write is actually conditioned on: `self.tokens.put` runs only
|
||||
/// in that check's own success arm, right before the row commits, both inside the one lock
|
||||
/// hold. A sign-in or a discard for the same handle can land in the window between the two
|
||||
/// checks. The second check exists to catch exactly that. By the time it runs, this call
|
||||
/// still has not touched the keychain at all. Every losing path, a newer sign-in, a discard,
|
||||
/// a discard followed by a re-add, answers [`Error::StaleGeneration`] (or [`Error::Unknown`])
|
||||
/// having written nothing. No stale token is ever left in the keychain for a cleanup step to
|
||||
/// weigh against a winner's. See the module docs ("Concurrent mutations and partial-failure
|
||||
/// recovery").
|
||||
pub fn update_token(&self, id: &str, expected_generation: u32, token: &Secret, now: i64) -> Result<Account, Error> {
|
||||
self.usable()?;
|
||||
let path = self.path().ok_or(Error::Isolated)?;
|
||||
|
||||
match accounts::read(&path)?.locate(id) {
|
||||
accounts::Located::Active(account) if account.generation == expected_generation => {}
|
||||
accounts::Located::Active(account) => {
|
||||
return Err(Error::StaleGeneration { id: id.to_owned(), expected: expected_generation, current: account.generation });
|
||||
}
|
||||
accounts::Located::Tombstoned(current) => {
|
||||
return Err(Error::StaleGeneration { id: id.to_owned(), expected: expected_generation, current });
|
||||
}
|
||||
accounts::Located::Unknown => return Err(Error::Unknown(id.to_owned())),
|
||||
}
|
||||
|
||||
// Test only, and a no-op unless a test armed this store's own hook (see `race_hook`):
|
||||
// holds here, right after the first check above has read the pre-race generation and
|
||||
// right before the lock for the second one, so a test can run a competing sign-in or a
|
||||
// discard and re-add to completion in between. Without this, a test that only lines
|
||||
// threads up at their start cannot tell a build that correctly rejects at the second,
|
||||
// locked check apart from a pre-fix build that got lucky and rejected at the first,
|
||||
// unlocked one instead.
|
||||
#[cfg(test)]
|
||||
self.race_hook.pause();
|
||||
|
||||
lock::with_lock(&path, || {
|
||||
let mut list = accounts::read(&path)?;
|
||||
match list.locate(id) {
|
||||
accounts::Located::Active(account) if account.generation == expected_generation => {
|
||||
let mut updated = account.clone();
|
||||
updated.generation = updated.generation.checked_add(1).ok_or_else(|| Error::GenerationExhausted(id.to_owned()))?;
|
||||
updated.last_used = now;
|
||||
// The write and the commit are one atomic step from here on, with respect to
|
||||
// every other mutator. sign_in and discard both take this same lock for
|
||||
// their own keychain and list changes. Nothing can land between this put and
|
||||
// this write.
|
||||
self.tokens.put(id, token).map_err(Error::Keychain)?;
|
||||
// Not `list.put`: a refresh is maintenance, never a reason to make this the
|
||||
// account a person selected. See [`accounts::Accounts::refresh_in_place`].
|
||||
list.refresh_in_place(id, updated.clone());
|
||||
accounts::write(&path, &list)?;
|
||||
Ok(updated)
|
||||
}
|
||||
accounts::Located::Active(account) => {
|
||||
Err(Error::StaleGeneration { id: id.to_owned(), expected: expected_generation, current: account.generation })
|
||||
}
|
||||
accounts::Located::Tombstoned(current) => Err(Error::StaleGeneration { id: id.to_owned(), expected: expected_generation, current }),
|
||||
accounts::Located::Unknown => Err(Error::Unknown(id.to_owned())),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Makes an account the current one.
|
||||
pub fn set_active(&self, id: &str) -> Result<(), Error> {
|
||||
let path = self.path().ok_or(Error::Isolated)?;
|
||||
lock::with_lock(&path, || {
|
||||
let mut list = accounts::read(&path)?;
|
||||
if list.get(id).is_none() {
|
||||
return Err(Error::Unknown(id.to_owned()));
|
||||
}
|
||||
list.active = Some(id.to_owned());
|
||||
accounts::write(&path, &list)
|
||||
})
|
||||
}
|
||||
|
||||
/// Records that an application used the account, for a list that can show the most recent one.
|
||||
pub fn touch(&self, id: &str, now: i64) -> Result<(), Error> {
|
||||
let path = self.path().ok_or(Error::Isolated)?;
|
||||
lock::with_lock(&path, || {
|
||||
let mut list = accounts::read(&path)?;
|
||||
let Some(account) = list.accounts.iter_mut().find(|a| a.id == id) else {
|
||||
return Err(Error::Unknown(id.to_owned()));
|
||||
};
|
||||
account.last_used = now;
|
||||
accounts::write(&path, &list)
|
||||
})
|
||||
}
|
||||
|
||||
/// Clears an account here: the keychain entry and the row's tombstone, under one lock hold.
|
||||
///
|
||||
/// This is the local half of a sign-out only. Ending the session at the deployment, so every
|
||||
/// machine the person left one on drops it too, is a distinct call on the provider adapter; a
|
||||
/// consumer that wants both makes that call first, while the token can still be read, and then
|
||||
/// calls this. See the module documentation and RFC-0025's "Cross-app lifecycle guarantees".
|
||||
///
|
||||
/// The keychain removal happens inside the same lock hold as the list write, not before it: a
|
||||
/// refresh racing this discard (see [`Store::update_token`]'s second check) must never be able
|
||||
/// to land its own keychain write back in between this call's keychain removal and its list
|
||||
/// write and so put the entry right back.
|
||||
pub fn discard(&self, id: &str) -> Result<(), Error> {
|
||||
let path = self.path().ok_or(Error::Isolated)?;
|
||||
lock::with_lock(&path, || {
|
||||
let mut list = accounts::read(&path)?;
|
||||
if let Some(account) = list.get(id).cloned() {
|
||||
self.tokens.remove(id).map_err(Error::Keychain)?;
|
||||
list.remove_with_tombstone(id, account.generation)?;
|
||||
accounts::write(&path, &list)?;
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
/// Clears the keychain entry for an account, leaving the list alone.
|
||||
///
|
||||
/// Checked against isolation first. `Store::at(None, _)` keeps nothing; without this check an
|
||||
/// isolated store could still reach into the keychain and delete another application's
|
||||
/// shared credential on this same machine.
|
||||
pub fn forget(&self, id: &str) -> Result<(), Error> {
|
||||
let _ = self.dir.as_deref().ok_or(Error::Isolated)?;
|
||||
self.tokens.remove(id).map_err(Error::Keychain)
|
||||
}
|
||||
}
|
||||
|
||||
impl<S: TokenStore + std::fmt::Debug> std::fmt::Debug for Store<S> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("Store").field("dir", &self.dir).field("tokens", &self.tokens).finish()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
//! A cross-process lock beside the accounts file.
|
||||
//!
|
||||
//! Every mutation of `accounts.json`, a sign-in, a token refresh, a removal, an active-account
|
||||
//! change, a touch, goes through [`with_lock`]. Without it every mutation is an unlocked
|
||||
//! read-modify-write: two processes each completing 100 sign-ins into one folder left 101 rows on
|
||||
//! file instead of 200, because the second writer's read missed the first writer's row. A pure
|
||||
//! read (`Store::accounts`, `Store::shared`) does not need the lock. [`crate::accounts::write`]
|
||||
//! already writes through a temporary file and a rename, so a reader never sees a torn file; it
|
||||
//! can only see a list that is one write older than the latest.
|
||||
//!
|
||||
//! This matches the mechanism `craft-ai-integrations`'s own secret store already uses for the same
|
||||
//! problem: a sibling `.lock` file, taken with `std::fs::File::try_lock` and a bounded retry,
|
||||
//! never a new dependency. RFC-0025's convergence note names that store's "locked read-change-
|
||||
//! write" as a requirement the shared crate adopts; this is that adoption, ahead of the
|
||||
//! convergence PR itself.
|
||||
|
||||
use std::fs::{self, File, OpenOptions};
|
||||
use std::io;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use crate::error::Error;
|
||||
|
||||
/// How long to wait for another process holding the lock before giving up. Long enough that a
|
||||
/// normal read-change-write of a few-hundred-byte file never times out under load; short enough
|
||||
/// that a process holding the lock across a crash does not wedge every other app indefinitely.
|
||||
const LOCK_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
const POLL_INTERVAL: Duration = Duration::from_millis(20);
|
||||
|
||||
fn lock_path(path: &Path) -> PathBuf {
|
||||
let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("accounts.json");
|
||||
path.with_file_name(format!("{name}.lock"))
|
||||
}
|
||||
|
||||
fn open_lock_file(path: &Path) -> io::Result<File> {
|
||||
if let Some(dir) = path.parent() {
|
||||
fs::create_dir_all(dir)?;
|
||||
}
|
||||
OpenOptions::new().read(true).write(true).create(true).truncate(false).open(lock_path(path))
|
||||
}
|
||||
|
||||
/// Runs `f` while holding an exclusive, OS-level lock on `path`'s sibling `.lock` file.
|
||||
///
|
||||
/// `f` reads, changes and writes the accounts file; `with_lock` only ever wraps that, never a
|
||||
/// keychain call. A keychain is its own atomic resource per entry; serialising it behind this file
|
||||
/// lock would mean the two apps this guards could never run a keychain operation while either held
|
||||
/// the lock, which is exactly the deadlock a same-process caller (two `Store`s sharing one folder,
|
||||
/// as two applications in one process would be) could hit. Acquiring the lock itself fails only as
|
||||
/// [`Error::Io`]; `f` may return any [`Error`].
|
||||
pub(crate) fn with_lock<T>(path: &Path, f: impl FnOnce() -> Result<T, Error>) -> Result<T, Error> {
|
||||
let lock = open_lock_file(path).map_err(|e| Error::Io(format!("couldn't open the lock beside {} ({e})", path.display())))?;
|
||||
let start = Instant::now();
|
||||
loop {
|
||||
match lock.try_lock() {
|
||||
Ok(()) => break,
|
||||
Err(fs::TryLockError::WouldBlock) => {
|
||||
if start.elapsed() > LOCK_TIMEOUT {
|
||||
return Err(Error::Io(format!("timed out waiting for the accounts lock on {}", path.display())));
|
||||
}
|
||||
std::thread::sleep(POLL_INTERVAL);
|
||||
}
|
||||
Err(fs::TryLockError::Error(e)) => {
|
||||
return Err(Error::Io(format!("couldn't lock {} ({e})", path.display())));
|
||||
}
|
||||
}
|
||||
}
|
||||
let result = f();
|
||||
let _ = lock.unlock();
|
||||
result
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_lock_is_exclusive_while_held_and_released_after() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("accounts.json");
|
||||
let blocked = with_lock(&path, || {
|
||||
let other = open_lock_file(&path).unwrap();
|
||||
Ok(matches!(other.try_lock(), Err(fs::TryLockError::WouldBlock)))
|
||||
})
|
||||
.unwrap();
|
||||
assert!(blocked, "a second lock attempt should see the first one held");
|
||||
assert!(with_lock(&path, || Ok(true)).unwrap(), "the lock is free again once `with_lock` returns");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_error_from_the_closure_still_releases_the_lock() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("accounts.json");
|
||||
let _: Result<(), Error> = with_lock(&path, || Err(Error::Unknown("x".to_owned())));
|
||||
assert!(with_lock(&path, || Ok(true)).unwrap(), "a failed closure must not leave the lock held");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
//! Taking over a per-application session file.
|
||||
//!
|
||||
//! An application that signed in before the suite store existed wrote its own session beside its
|
||||
//! own settings, naming the file however it liked. GridCraft's was
|
||||
//! `%APPDATA%\GridCraft\legacy-session.json`. Upgrading must not sign anybody out. The application
|
||||
//! therefore hands that session to the suite store once and deletes the file. The token then lives
|
||||
//! in the keychain and the whole suite can use it.
|
||||
//!
|
||||
//! The application does this, never the launcher. The file belongs to the application. Nothing
|
||||
//! should reach into another application's folder to delete a file.
|
||||
//!
|
||||
//! The file is only deleted once the suite store holds the session. Where the suite store can keep
|
||||
//! nothing (no keychain on this machine, or this process is isolated) the file stays exactly where
|
||||
//! it is. Removing it would sign the user out. That is the one thing migration must not do.
|
||||
//!
|
||||
//! The earliest of these files held one key: `{"token": "..."}`. It names no deployment and no
|
||||
//! subject. There is nothing to key an account on. Such a file is left exactly where it is too. A
|
||||
//! made-up handle would file the token under something nothing ever looks up again. That reads as
|
||||
//! a silent sign-out. An application that rewrites the file with the deployment and the subject is
|
||||
//! adopted on the next startup. Adopting one launch late costs nothing.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use serde::Deserialize;
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
use crate::accounts::{self, Account};
|
||||
use crate::error::Error;
|
||||
use crate::secret::Secret;
|
||||
use crate::store::TokenStore;
|
||||
use crate::{NewAccount, Store};
|
||||
|
||||
/// What a legacy session file said.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Legacy {
|
||||
/// The deployment's base URL, with any trailing slash trimmed. Empty where the file predates
|
||||
/// the application recording it.
|
||||
pub service: String,
|
||||
/// The deployment's own identifier for the account: the OIDC subject. Empty where the file
|
||||
/// predates the application recording it.
|
||||
pub user: String,
|
||||
pub display: String,
|
||||
pub email: Option<String>,
|
||||
pub token: Secret,
|
||||
}
|
||||
|
||||
impl Legacy {
|
||||
/// What the file does not say yet, when it cannot be keyed to an account.
|
||||
///
|
||||
/// The account handle is a digest of the deployment and the subject. Both are therefore
|
||||
/// needed. A session written before the application recorded them carries a token alone.
|
||||
pub fn incomplete(&self) -> Option<&'static str> {
|
||||
if self.service.is_empty() {
|
||||
return Some("which deployment it belongs to");
|
||||
}
|
||||
if self.user.is_empty() {
|
||||
return Some("whose account it is");
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// What happened.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Adopted {
|
||||
/// There was no file. There is nothing to take over.
|
||||
Nothing,
|
||||
/// The session is in the suite store now. The file is gone.
|
||||
Taken(Account),
|
||||
/// The file was left exactly where it is. The application goes on reading it. `why` says
|
||||
/// which case it was: the suite store can keep nothing here, or the file does not yet say
|
||||
/// enough to key an account on.
|
||||
Kept { why: String },
|
||||
}
|
||||
|
||||
/// The shape on disk.
|
||||
///
|
||||
/// What an application writes today is `token`, `service`, `subject` and `display`. The file
|
||||
/// predates this crate. The aliases therefore cover the other plausible spellings.
|
||||
///
|
||||
/// The token is the only key that has to be there: a file without one carries no session at all.
|
||||
/// Everything else defaults. That is what lets the earliest `{"token": "..."}` file still parse.
|
||||
/// [`adopt`] then leaves such a file alone. Keying an account on nothing is the alternative.
|
||||
#[derive(Deserialize)]
|
||||
struct Stored {
|
||||
#[serde(alias = "session", alias = "session_token", alias = "bearer", alias = "access_token")]
|
||||
token: String,
|
||||
#[serde(default, alias = "base", alias = "base_url", alias = "url", alias = "service_url")]
|
||||
service: String,
|
||||
#[serde(default, alias = "id", alias = "sub", alias = "subject", alias = "user_id")]
|
||||
user: String,
|
||||
#[serde(default, alias = "name", alias = "display_name")]
|
||||
display: String,
|
||||
#[serde(default)]
|
||||
email: Option<String>,
|
||||
}
|
||||
|
||||
/// The largest session file that will be read.
|
||||
const MAX_BYTES: u64 = 64 << 10;
|
||||
|
||||
/// Reads a legacy session file. A missing file is `Ok(None)`.
|
||||
pub fn read(path: &Path) -> Result<Option<Legacy>, Error> {
|
||||
match std::fs::metadata(path) {
|
||||
Ok(meta) if meta.len() > MAX_BYTES => {
|
||||
return Err(Error::Malformed(format!("{} is {} bytes, too large to be a session", path.display(), meta.len())));
|
||||
}
|
||||
Ok(_) => {}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
||||
Err(e) => return Err(Error::Io(format!("couldn't read {} ({e})", path.display()))),
|
||||
}
|
||||
// The raw file bytes and the token `serde` deserializes both hold the token in plain text,
|
||||
// the same as the final `Secret` does. Dropping them ordinarily leaves that plain text for
|
||||
// the allocator, unzeroed; only `Secret`'s own copy would be covered. Wrapping both in
|
||||
// `Zeroizing` closes that gap. Destructuring `Stored` below moves `token` out whole, with no
|
||||
// clone and no second plain copy to forget about.
|
||||
let bytes = Zeroizing::new(std::fs::read(path).map_err(|e| Error::Io(format!("couldn't read {} ({e})", path.display())))?);
|
||||
let Stored { token, service, user, display, email } =
|
||||
serde_json::from_slice(&bytes).map_err(|e| Error::Malformed(format!("{} didn't parse ({e})", path.display())))?;
|
||||
let token = Zeroizing::new(token);
|
||||
if token.trim().is_empty() {
|
||||
return Err(Error::Malformed(format!("{} carries no session", path.display())));
|
||||
}
|
||||
let service = accounts::normalise(&service);
|
||||
// The subject is never stood in for. A handle built on anything else would file the token
|
||||
// where nothing looks for it. See [`Legacy::incomplete`].
|
||||
let user = user.trim().to_owned();
|
||||
let display = if display.trim().is_empty() { user.clone() } else { display };
|
||||
Ok(Some(Legacy { service, user, display, email, token: Secret::new(token.trim()) }))
|
||||
}
|
||||
|
||||
/// Hands a legacy session to the suite store and removes the file.
|
||||
///
|
||||
/// Call this once at startup, before asking the suite store who is signed in. Safe to call when
|
||||
/// there is no file. Safe to call again after it has run.
|
||||
pub fn adopt<S: TokenStore>(store: &Store<S>, path: &Path, now: i64) -> Result<Adopted, Error> {
|
||||
let Some(legacy) = read(path)? else { return Ok(Adopted::Nothing) };
|
||||
if let Some(unsaid) = legacy.incomplete() {
|
||||
return Ok(Adopted::Kept { why: format!("{} does not say {unsaid} yet", path.display()) });
|
||||
}
|
||||
if let Err(why) = store.usable() {
|
||||
return Ok(Adopted::Kept { why: why.to_string() });
|
||||
}
|
||||
let service = accounts::normalise(&legacy.service);
|
||||
let id = accounts::handle(&service, &legacy.user);
|
||||
let existing = if store.has_token(&id)? { store.accounts()?.get(&id).cloned() } else { None };
|
||||
if let Some(account) = existing {
|
||||
if file_still_holds(path, &legacy) {
|
||||
match std::fs::remove_file(path) {
|
||||
Ok(()) => {}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(e) => return Err(Error::Io(format!("the suite already holds this session. {} is still there ({e})", path.display()))),
|
||||
}
|
||||
}
|
||||
return Ok(Adopted::Taken(account));
|
||||
}
|
||||
let new = NewAccount {
|
||||
service: legacy.service.clone(),
|
||||
user: legacy.user.clone(),
|
||||
display: legacy.display.clone(),
|
||||
email: legacy.email.clone(),
|
||||
linked: false,
|
||||
};
|
||||
let account = store.sign_in(&new, &legacy.token, now)?;
|
||||
// Only now, with the session held somewhere better, does the file go. Something else may
|
||||
// have rewritten it in the meantime (another process still running the application's own,
|
||||
// now-superseded writer, mid-refresh); deleting that newer content would discard a session
|
||||
// nothing else holds a copy of. `file_still_holds` only lets the removal through when the
|
||||
// file is still exactly what was just adopted. Leaving it is always safe: the next startup's
|
||||
// `adopt` call sees it again and tries once more.
|
||||
if file_still_holds(path, &legacy) {
|
||||
match std::fs::remove_file(path) {
|
||||
Ok(()) => {}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(e) => return Err(Error::Io(format!("the session moved to the keychain. {} is still there ({e})", path.display()))),
|
||||
}
|
||||
}
|
||||
Ok(Adopted::Taken(account))
|
||||
}
|
||||
|
||||
/// Whether `path` still parses to exactly `adopted`, right before it would be removed.
|
||||
///
|
||||
/// Any other outcome, a changed file, a vanished file, or one that no longer parses, is treated
|
||||
/// the same: do not delete. A changed file holds something nothing else has adopted yet; a
|
||||
/// vanished one needs no removal; an unparseable one is not safe to reason about here at all.
|
||||
fn file_still_holds(path: &Path, adopted: &Legacy) -> bool {
|
||||
matches!(read(path), Ok(Some(current)) if current == *adopted)
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
//! Where the suite keeps its list of accounts.
|
||||
//!
|
||||
//! One folder for the whole Craft App Suite. It sits beside the per-application folders. It is not
|
||||
//! a child of any of them.
|
||||
//!
|
||||
//! `craft-settings` gives each application `<platform config dir>/<app id>`. That is the right home
|
||||
//! for that application's own preferences. An account is not one of those. The same person signs in
|
||||
//! once and every Craft App acts as them. The record therefore belongs to the suite. An account
|
||||
//! placed under one application's folder would make every other application read a folder it does
|
||||
//! not own.
|
||||
//! Removing that application would then sign everybody out. The launcher's own folder fails for the
|
||||
//! same reason. An application must not have to know the launcher exists.
|
||||
//!
|
||||
//! So: `<platform config dir>/ArtCraft` on Windows and macOS. `<platform config dir>/artcraft` on
|
||||
//! Linux and the BSDs. The launcher already spells its own folder that way per platform. Written
|
||||
//! out, those are `%APPDATA%\ArtCraft`, `~/Library/Application Support/ArtCraft` and
|
||||
//! `~/.config/artcraft`.
|
||||
//!
|
||||
//! It is the configuration folder. The record then follows a Windows profile the way a user would
|
||||
//! expect. The per-application session file this replaces lived in `%APPDATA%` too. The folder
|
||||
//! holds no secret. The token is in the keychain.
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// The suite folder's name, spelled the way the launcher spells its own per platform.
|
||||
pub const DIR: &str = if cfg!(any(target_os = "macos", target_os = "windows")) { "ArtCraft" } else { "artcraft" };
|
||||
|
||||
/// The file inside it.
|
||||
pub const FILE: &str = "accounts.json";
|
||||
|
||||
/// Points the suite folder somewhere else. Set and empty means read and write nothing.
|
||||
pub const ENV_VAR: &str = "ARTCRAFT_SUITE_DIR";
|
||||
|
||||
/// File names beside the executable that switch portable mode on. The launcher's Windows portable
|
||||
/// zip ships `portable.txt`. `portable` is `craft-settings`' own spelling.
|
||||
pub const PORTABLE_MARKERS: &[&str] = &["portable.txt", "portable"];
|
||||
|
||||
/// The folder a portable install keeps the suite's accounts in, beside the executable.
|
||||
pub const PORTABLE_DIR: &str = "ArtCraftSuite";
|
||||
|
||||
/// Which rule chose the folder.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Rule {
|
||||
/// [`ENV_VAR`] named it.
|
||||
EnvVar,
|
||||
/// [`ENV_VAR`] was set and empty. Nothing is read or written.
|
||||
Isolated,
|
||||
/// A portable marker beside the executable.
|
||||
Portable,
|
||||
/// The platform's configuration folder.
|
||||
Platform,
|
||||
/// This system has no per-user configuration folder. Nothing is read or written. A file in the
|
||||
/// current directory would be the wrong home for a record of who is signed in.
|
||||
Nowhere,
|
||||
}
|
||||
|
||||
/// A chosen folder and the rule behind it.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Resolved {
|
||||
/// The suite folder. `None` for [`Rule::Isolated`] and [`Rule::Nowhere`].
|
||||
pub dir: Option<PathBuf>,
|
||||
pub rule: Rule,
|
||||
}
|
||||
|
||||
/// Reads an environment variable by name.
|
||||
pub type EnvReader = Box<dyn Fn(&str) -> Option<OsString>>;
|
||||
|
||||
/// What the rules look at. The default reads the real process. Tests supply their own.
|
||||
pub struct Probe {
|
||||
pub env: EnvReader,
|
||||
/// The folder holding the executable, if known.
|
||||
pub exe_dir: Option<PathBuf>,
|
||||
/// The platform configuration folder (`%APPDATA%`, `Application Support`, `~/.config`).
|
||||
pub platform_config_dir: Option<PathBuf>,
|
||||
}
|
||||
|
||||
impl Default for Probe {
|
||||
fn default() -> Probe {
|
||||
Probe {
|
||||
env: Box::new(|name| std::env::var_os(name)),
|
||||
exe_dir: std::env::current_exe().ok().and_then(|p| p.parent().map(Path::to_path_buf)),
|
||||
platform_config_dir: dirs::config_dir(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Probe {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("Probe").field("exe_dir", &self.exe_dir).field("platform_config_dir", &self.platform_config_dir).finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
/// Applies the rules, first match winning.
|
||||
pub fn resolve(probe: &Probe) -> Resolved {
|
||||
if let Some(value) = (probe.env)(ENV_VAR) {
|
||||
if value.is_empty() {
|
||||
return Resolved { dir: None, rule: Rule::Isolated };
|
||||
}
|
||||
return Resolved { dir: Some(PathBuf::from(value)), rule: Rule::EnvVar };
|
||||
}
|
||||
if let Some(dir) = probe.exe_dir.as_deref().and_then(portable_dir) {
|
||||
return Resolved { dir: Some(dir), rule: Rule::Portable };
|
||||
}
|
||||
match &probe.platform_config_dir {
|
||||
Some(base) => Resolved { dir: Some(base.join(DIR)), rule: Rule::Platform },
|
||||
None => Resolved { dir: None, rule: Rule::Nowhere },
|
||||
}
|
||||
}
|
||||
|
||||
/// The accounts file inside a suite folder.
|
||||
pub fn file(dir: &Path) -> PathBuf {
|
||||
dir.join(FILE)
|
||||
}
|
||||
|
||||
/// The folder a portable marker points at, when `exe_dir` has one.
|
||||
///
|
||||
/// On macOS the executable sits in `X.app/Contents/MacOS`. The marker is therefore looked for
|
||||
/// beside the `.app` bundle. Writing inside a signed bundle breaks its signature.
|
||||
fn portable_dir(exe_dir: &Path) -> Option<PathBuf> {
|
||||
let base = bundle_parent(exe_dir).unwrap_or(exe_dir);
|
||||
PORTABLE_MARKERS.iter().any(|m| base.join(m).is_file()).then(|| base.join(PORTABLE_DIR))
|
||||
}
|
||||
|
||||
fn bundle_parent(exe_dir: &Path) -> Option<&Path> {
|
||||
if !cfg!(target_os = "macos") || exe_dir.file_name()? != "MacOS" {
|
||||
return None;
|
||||
}
|
||||
let contents = exe_dir.parent()?;
|
||||
if contents.file_name()? != "Contents" {
|
||||
return None;
|
||||
}
|
||||
let bundle = contents.parent()?;
|
||||
if bundle.extension()? != "app" {
|
||||
return None;
|
||||
}
|
||||
bundle.parent()
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
//! A synchronization point inside [`crate::Store::update_token`], between its first, unlocked
|
||||
//! generation check and the lock it takes for its second one. Test only, compiled for nothing
|
||||
//! but `cargo test`.
|
||||
//!
|
||||
//! Added for a review note on this crate's own race tests: a thread barrier only lines the
|
||||
//! refresh and a competing sign-in or discard-and-re-add up at their *start*. From there either
|
||||
//! one can finish first. A build that still has the bug this crate's tests guard against can
|
||||
//! then pass for the wrong reason, by rejecting at the first, unlocked check because the
|
||||
//! competing write happened to land first, never reaching the second, locked check the test is
|
||||
//! actually named for. [`Hook::arm`] and [`Hook::pause`] below pin that window instead: a test
|
||||
//! arms its own `Store`'s hook before starting the refresh on that same store, waits on the
|
||||
//! returned handle's `arrived` until the refresh has done its first check, runs the competing
|
||||
//! operation to completion, then sends on `go` to let the refresh continue into its second
|
||||
//! check.
|
||||
//!
|
||||
//! The hook lives on the `Store` instance, one [`Hook`] per store, rather than behind one shared
|
||||
//! slot for the whole process. The workspace's own CI runs this crate's suite with the default,
|
||||
//! parallel test runner, not the single-threaded invocation this crate's local gate had been
|
||||
//! using; a process-wide hook armed by two of this crate's race tests running at the same time
|
||||
//! answered each other's `pause`, so one test's release freed the other test's refresh early and
|
||||
//! the pinned ordering both tests rely on collapsed. Scoping the hook to the store a given test
|
||||
//! actually built means a concurrent test's hook can never be the one `update_token` reaches,
|
||||
//! because every store keeps its own, so there is nothing left to cross.
|
||||
//!
|
||||
//! Outside a test that calls `arm`, [`Hook::pause`] does nothing: every other `update_token`
|
||||
//! call, including every one outside this crate's own test suite, runs straight through.
|
||||
|
||||
use std::sync::Mutex;
|
||||
use std::sync::mpsc::{Receiver, SyncSender, sync_channel};
|
||||
|
||||
struct Gate {
|
||||
arrived: SyncSender<()>,
|
||||
go: Receiver<()>,
|
||||
}
|
||||
|
||||
/// One store's own pause point. `Store::at` creates one for every instance; most never arm it,
|
||||
/// so [`Hook::pause`] stays a no-op for them.
|
||||
pub(crate) struct Hook(Mutex<Option<Gate>>);
|
||||
|
||||
/// The test's half of the gate. `arrived.recv()` blocks until the refresh reaches the pause
|
||||
/// point on this same store; sending on `go` releases it to continue past it.
|
||||
pub(crate) struct Handle {
|
||||
pub(crate) arrived: Receiver<()>,
|
||||
pub(crate) go: SyncSender<()>,
|
||||
}
|
||||
|
||||
impl Hook {
|
||||
/// A fresh, disarmed hook, for `Store::at` to give every store it builds.
|
||||
pub(crate) fn new() -> Hook {
|
||||
Hook(Mutex::new(None))
|
||||
}
|
||||
|
||||
/// Arms this store's own pause point for the next call into its [`crate::Store::update_token`].
|
||||
/// A store this test never built, and so never raced on, keeps its own hook disarmed the
|
||||
/// whole time, whatever else is running in parallel.
|
||||
pub(crate) fn arm(&self) -> Handle {
|
||||
let (arrived_tx, arrived_rx) = sync_channel::<()>(0);
|
||||
let (go_tx, go_rx) = sync_channel::<()>(0);
|
||||
let mut guard = self.0.lock().unwrap_or_else(|e| e.into_inner());
|
||||
*guard = Some(Gate { arrived: arrived_tx, go: go_rx });
|
||||
Handle { arrived: arrived_rx, go: go_tx }
|
||||
}
|
||||
|
||||
/// `update_token`'s half. A no-op when this store's hook was never armed, which is every
|
||||
/// call outside a test that called `arm` on this exact store. When armed, tells the test it
|
||||
/// has just finished its first, unlocked check, then blocks until the test releases it.
|
||||
pub(crate) fn pause(&self) {
|
||||
let gate = self.0.lock().unwrap_or_else(|e| e.into_inner()).take();
|
||||
if let Some(gate) = gate {
|
||||
let _ = gate.arrived.send(());
|
||||
let _ = gate.go.recv();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
//! A credential held in memory.
|
||||
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
/// A bearer token, wrapped so it cannot be printed by accident.
|
||||
///
|
||||
/// There is no `Display` and no `Serialize`. [`Debug`] reports the length and nothing else. A token
|
||||
/// therefore never reaches a log line through a `{:?}` on some struct that happens to carry one.
|
||||
/// The bytes are overwritten when the value is dropped.
|
||||
///
|
||||
/// [`Secret::expose`] is the one way out. The only caller that needs it is the code building an
|
||||
/// `Authorization` header.
|
||||
#[derive(Clone)]
|
||||
pub struct Secret(Zeroizing<String>);
|
||||
|
||||
impl Secret {
|
||||
pub fn new(value: impl Into<String>) -> Secret {
|
||||
Secret(Zeroizing::new(value.into()))
|
||||
}
|
||||
|
||||
/// The bytes themselves. Send them. Never log them.
|
||||
pub fn expose(&self) -> &str {
|
||||
&self.0
|
||||
}
|
||||
|
||||
/// How many bytes the token is. A report names this and never the value.
|
||||
pub fn len(&self) -> usize {
|
||||
self.0.len()
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.0.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Secret {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "Secret({} bytes)", self.0.len())
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for Secret {
|
||||
fn eq(&self, other: &Secret) -> bool {
|
||||
*self.0 == *other.0
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for Secret {}
|
||||
@@ -0,0 +1,176 @@
|
||||
//! The token, in the operating system's own keychain.
|
||||
//!
|
||||
//! Windows Credential Manager, the macOS Keychain, or the Secret Service on Linux and the BSDs.
|
||||
//!
|
||||
//! A bearer token in a JSON file beside an application's settings is what this replaces. Such a
|
||||
//! file is readable by anything running as the user. It survives in backups. It leaves nothing for
|
||||
//! an administrator to revoke. A keychain entry is scoped to the one user. The platform encrypts it
|
||||
//! at rest. It can be deleted one entry at a time from the platform's own window.
|
||||
//!
|
||||
//! One service name covers the whole suite. Every entry the suite ever writes is therefore findable
|
||||
//! and removable in one place.
|
||||
//!
|
||||
//! ```text
|
||||
//! service ai.storyteller.artcraft.suite-account
|
||||
//! user the account handle (crate::accounts::handle: a digest of the deployment and the subject)
|
||||
//! secret a bearer token for that account, minted by whatever deployment the handle names
|
||||
//! ```
|
||||
//!
|
||||
//! On Windows that is a generic credential whose target name is
|
||||
//! `<handle>.ai.storyteller.artcraft.suite-account`, with machine-local persistence. A bearer token
|
||||
//! minted for this machine therefore stays on it. On macOS it is a generic password in the user's
|
||||
//! login keychain. On Linux and the BSDs it is a Secret Service item in the user's default
|
||||
//! collection. That collection is locked with the login session.
|
||||
//!
|
||||
//! [`TokenStore`] is a trait so everything above it can be tested without a keychain. [`Memory`] is
|
||||
//! the stand-in, the way `craft-nextcloud` drives a canned transport.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
|
||||
use crate::error::Error;
|
||||
use crate::secret::Secret;
|
||||
|
||||
/// The keychain service name every Craft App uses. One namespace, one place to revoke.
|
||||
pub const KEYCHAIN_SERVICE: &str = "ai.storyteller.artcraft.suite-account";
|
||||
|
||||
/// Reading and writing one token per account handle.
|
||||
pub trait TokenStore {
|
||||
/// Whether this machine has a keychain this process can use.
|
||||
///
|
||||
/// A headless Linux box with no Secret Service answers `Err`. The suite then behaves as though
|
||||
/// nobody is signed in. No token goes to a file.
|
||||
fn available(&self) -> Result<(), String>;
|
||||
/// The token for `handle`, or `Ok(None)` when there is no entry.
|
||||
fn get(&self, handle: &str) -> Result<Option<Secret>, String>;
|
||||
fn put(&self, handle: &str, token: &Secret) -> Result<(), String>;
|
||||
/// Removes the entry. Already gone is success.
|
||||
fn remove(&self, handle: &str) -> Result<(), String>;
|
||||
}
|
||||
|
||||
/// The platform's keychain.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub struct Keychain;
|
||||
|
||||
impl Keychain {
|
||||
fn entry(handle: &str) -> Result<keyring_core::Entry, Error> {
|
||||
// Installs the platform store on the first call, once per process.
|
||||
if let Err(e) = keyring::Entry::store_status() {
|
||||
return Err(Error::Keychain(e.to_string()));
|
||||
}
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
// Local, where the store's own default is Enterprise. An Enterprise credential is part
|
||||
// of the roaming profile. A bearer token minted for this machine has no business
|
||||
// travelling to another one.
|
||||
let modifiers = std::collections::HashMap::from([("persistence", "Local")]);
|
||||
keyring_core::Entry::new_with_modifiers(KEYCHAIN_SERVICE, handle, &modifiers).map_err(|e| Error::Keychain(e.to_string()))
|
||||
}
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
keyring_core::Entry::new(KEYCHAIN_SERVICE, handle).map_err(|e| Error::Keychain(e.to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
impl TokenStore for Keychain {
|
||||
fn available(&self) -> Result<(), String> {
|
||||
match keyring::Entry::store_status() {
|
||||
Ok(()) => Ok(()),
|
||||
Err(e) => Err(e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
fn get(&self, handle: &str) -> Result<Option<Secret>, String> {
|
||||
let entry = Keychain::entry(handle).map_err(|e| e.to_string())?;
|
||||
match entry.get_password() {
|
||||
Ok(token) => Ok(Some(Secret::new(token))),
|
||||
Err(keyring::Error::NoEntry) => Ok(None),
|
||||
Err(e) => Err(e.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
fn put(&self, handle: &str, token: &Secret) -> Result<(), String> {
|
||||
let entry = Keychain::entry(handle).map_err(|e| e.to_string())?;
|
||||
entry.set_password(token.expose()).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
fn remove(&self, handle: &str) -> Result<(), String> {
|
||||
let entry = Keychain::entry(handle).map_err(|e| e.to_string())?;
|
||||
match entry.delete_credential() {
|
||||
Ok(()) | Err(keyring::Error::NoEntry) => Ok(()),
|
||||
Err(e) => Err(e.to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A keychain stand-in that keeps entries in memory.
|
||||
///
|
||||
/// For tests. It also covers the answers a real keychain gives that are awkward to arrange: an
|
||||
/// entry is there, there is no keychain on this machine, the keychain is there and locked.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Memory {
|
||||
entries: Arc<Mutex<BTreeMap<String, Secret>>>,
|
||||
/// Why there is no usable keychain here, when there is not one.
|
||||
missing: Option<String>,
|
||||
/// Why every read and write fails, for a keychain that exists and refuses.
|
||||
refusing: Option<String>,
|
||||
}
|
||||
|
||||
impl Memory {
|
||||
pub fn new() -> Memory {
|
||||
Memory::default()
|
||||
}
|
||||
|
||||
/// A machine with no keychain at all.
|
||||
pub fn missing(why: impl Into<String>) -> Memory {
|
||||
Memory { missing: Some(why.into()), ..Memory::default() }
|
||||
}
|
||||
|
||||
/// A keychain that is there and refuses, the way a locked Secret Service does.
|
||||
pub fn refusing(why: impl Into<String>) -> Memory {
|
||||
Memory { refusing: Some(why.into()), ..Memory::default() }
|
||||
}
|
||||
|
||||
/// How many entries are held. Tests use it to show a sign-out removed one.
|
||||
pub fn count(&self) -> usize {
|
||||
self.entries.lock().unwrap_or_else(PoisonError::into_inner).len()
|
||||
}
|
||||
|
||||
pub fn has(&self, handle: &str) -> bool {
|
||||
self.entries.lock().unwrap_or_else(PoisonError::into_inner).contains_key(handle)
|
||||
}
|
||||
}
|
||||
|
||||
impl TokenStore for Memory {
|
||||
fn available(&self) -> Result<(), String> {
|
||||
match &self.missing {
|
||||
Some(why) => Err(why.clone()),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
fn get(&self, handle: &str) -> Result<Option<Secret>, String> {
|
||||
self.available()?;
|
||||
if let Some(why) = &self.refusing {
|
||||
return Err(why.clone());
|
||||
}
|
||||
Ok(self.entries.lock().unwrap_or_else(PoisonError::into_inner).get(handle).cloned())
|
||||
}
|
||||
|
||||
fn put(&self, handle: &str, token: &Secret) -> Result<(), String> {
|
||||
self.available()?;
|
||||
if let Some(why) = &self.refusing {
|
||||
return Err(why.clone());
|
||||
}
|
||||
self.entries.lock().unwrap_or_else(PoisonError::into_inner).insert(handle.to_owned(), token.clone());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn remove(&self, handle: &str) -> Result<(), String> {
|
||||
self.available()?;
|
||||
if let Some(why) = &self.refusing {
|
||||
return Err(why.clone());
|
||||
}
|
||||
self.entries.lock().unwrap_or_else(PoisonError::into_inner).remove(handle);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,939 @@
|
||||
//! Tests for the store, the migration and the fallback when nobody is signed in.
|
||||
//!
|
||||
//! A keychain is awkward to drive from a test. Everything above it therefore runs against
|
||||
//! [`Memory`](crate::store::Memory).
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use crate::accounts::{self, Account};
|
||||
use crate::paths::{self, Probe, Rule};
|
||||
use crate::store::{Memory, TokenStore};
|
||||
use crate::{Adopted, Error, NewAccount, Secret, Shared, Store};
|
||||
|
||||
const SERVICE: &str = "https://craft.example.com";
|
||||
const USER: &str = "e9b1c0e4-0000-4000-8000-000000000001";
|
||||
const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
|
||||
const NOW: i64 = 1_760_000_000;
|
||||
|
||||
fn probe(env: &[(&str, &str)], exe_dir: Option<&str>, config: Option<&str>) -> Probe {
|
||||
let env: Vec<(String, String)> = env.iter().map(|(k, v)| ((*k).to_owned(), (*v).to_owned())).collect();
|
||||
Probe {
|
||||
env: Box::new(move |name| env.iter().find(|(k, _)| k == name).map(|(_, v)| OsString::from(v))),
|
||||
exe_dir: exe_dir.map(PathBuf::from),
|
||||
platform_config_dir: config.map(PathBuf::from),
|
||||
}
|
||||
}
|
||||
|
||||
fn new_account() -> NewAccount {
|
||||
NewAccount { service: SERVICE.to_owned(), user: USER.to_owned(), display: "Ada Lovelace".to_owned(), email: None, linked: true }
|
||||
}
|
||||
|
||||
// ---- where the store lives -------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn the_variable_names_the_folder() {
|
||||
let r = paths::resolve(&probe(&[(paths::ENV_VAR, "/somewhere/else")], None, Some("/home/a/.config")));
|
||||
assert_eq!(r.rule, Rule::EnvVar);
|
||||
assert_eq!(r.dir.as_deref(), Some(Path::new("/somewhere/else")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_variable_keeps_nothing() {
|
||||
let r = paths::resolve(&probe(&[(paths::ENV_VAR, "")], None, Some("/home/a/.config")));
|
||||
assert_eq!(r.rule, Rule::Isolated);
|
||||
assert_eq!(r.dir, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_platform_folder_is_the_default() {
|
||||
let r = paths::resolve(&probe(&[], None, Some("/home/a/.config")));
|
||||
assert_eq!(r.rule, Rule::Platform);
|
||||
assert_eq!(r.dir.as_deref(), Some(Path::new("/home/a/.config").join(paths::DIR).as_path()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_portable_marker_wins_over_the_platform_folder() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
std::fs::write(dir.path().join("portable.txt"), b"").unwrap();
|
||||
let exe_dir = dir.path().display().to_string();
|
||||
let r = paths::resolve(&probe(&[], Some(&exe_dir), Some("/home/a/.config")));
|
||||
assert_eq!(r.rule, Rule::Portable);
|
||||
assert_eq!(r.dir.as_deref(), Some(dir.path().join(paths::PORTABLE_DIR).as_path()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_platform_folder_keeps_nothing() {
|
||||
let r = paths::resolve(&probe(&[], None, None));
|
||||
assert_eq!(r.rule, Rule::Nowhere);
|
||||
assert_eq!(r.dir, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_handle_is_stable_and_separates_accounts() {
|
||||
let a = accounts::handle(SERVICE, USER);
|
||||
assert_eq!(a, accounts::handle(SERVICE, USER), "the same account twice is the same entry");
|
||||
// A trailing slash is the same deployment typed differently.
|
||||
assert_eq!(a, accounts::handle("https://craft.example.com/", USER));
|
||||
assert_ne!(a, accounts::handle("https://other.example.com", USER), "another deployment is another account");
|
||||
assert_ne!(a, accounts::handle(SERVICE, "somebody-else"), "another person is another account");
|
||||
assert_eq!(a.len(), 24);
|
||||
assert!(a.chars().all(|c| c.is_ascii_hexdigit()));
|
||||
}
|
||||
|
||||
// ---- signing in and out ----------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_sign_in_can_be_read_back_by_the_next_application() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let keychain = Memory::new();
|
||||
let store = Store::at(Some(dir.path().to_path_buf()), keychain.clone());
|
||||
let account = store.sign_in(&new_account(), &Secret::new(TOKEN), NOW).unwrap();
|
||||
|
||||
// A second application, its own Store over the same folder and keychain.
|
||||
let other = Store::at(Some(dir.path().to_path_buf()), keychain);
|
||||
match other.shared() {
|
||||
Shared::Session { account: found, token } => {
|
||||
assert_eq!(found.id, account.id);
|
||||
assert_eq!(found.service, SERVICE);
|
||||
assert_eq!(found.display, "Ada Lovelace");
|
||||
assert_eq!(token, Secret::new(TOKEN));
|
||||
}
|
||||
other => panic!("expected a session, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_accounts_file_never_holds_the_token() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let store = Store::at(Some(dir.path().to_path_buf()), Memory::new());
|
||||
store.sign_in(&new_account(), &Secret::new(TOKEN), NOW).unwrap();
|
||||
let on_disk = std::fs::read_to_string(store.path().unwrap()).unwrap();
|
||||
assert!(!on_disk.contains(TOKEN), "the token reached the accounts file");
|
||||
assert!(on_disk.contains(SERVICE), "the file should still name the deployment");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn signing_in_again_replaces_the_entry_rather_than_adding_one() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let keychain = Memory::new();
|
||||
let store = Store::at(Some(dir.path().to_path_buf()), keychain.clone());
|
||||
let first = store.sign_in(&new_account(), &Secret::new(TOKEN), NOW).unwrap();
|
||||
let second = store.sign_in(&new_account(), &Secret::new("a-newer-token"), NOW + 60).unwrap();
|
||||
assert_eq!(first.id, second.id);
|
||||
assert_eq!(first.added, second.added, "the first sign-in's date is kept");
|
||||
assert_eq!(keychain.count(), 1);
|
||||
assert_eq!(store.accounts().unwrap().accounts.len(), 1);
|
||||
match store.shared() {
|
||||
Shared::Session { token, .. } => assert_eq!(token, Secret::new("a-newer-token")),
|
||||
other => panic!("expected a session, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_deployments_are_two_accounts() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let keychain = Memory::new();
|
||||
let store = Store::at(Some(dir.path().to_path_buf()), keychain.clone());
|
||||
store.sign_in(&new_account(), &Secret::new(TOKEN), NOW).unwrap();
|
||||
let elsewhere = NewAccount { service: "https://other.example.com".to_owned(), ..new_account() };
|
||||
let second = store.sign_in(&elsewhere, &Secret::new("another-token"), NOW).unwrap();
|
||||
assert_eq!(keychain.count(), 2);
|
||||
let list = store.accounts().unwrap();
|
||||
assert_eq!(list.accounts.len(), 2);
|
||||
assert_eq!(list.active.as_deref(), Some(second.id.as_str()), "the newest sign-in becomes current");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_linked_flag_is_persisted_and_read_back() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let store = Store::at(Some(dir.path().to_path_buf()), Memory::new());
|
||||
let linked = NewAccount { linked: true, ..new_account() };
|
||||
let account = store.sign_in(&linked, &Secret::new(TOKEN), NOW).unwrap();
|
||||
assert!(account.linked, "sign_in's own return value should carry it");
|
||||
assert!(store.accounts().unwrap().get(&account.id).unwrap().linked, "the row on file should carry it too");
|
||||
|
||||
let unlinked = NewAccount { linked: false, ..new_account() };
|
||||
let account = store.sign_in(&unlinked, &Secret::new(TOKEN), NOW + 1).unwrap();
|
||||
assert!(!account.linked, "a later sign-in's value replaces the earlier one");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn discarding_an_account_clears_both_the_entry_and_the_row() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let keychain = Memory::new();
|
||||
let store = Store::at(Some(dir.path().to_path_buf()), keychain.clone());
|
||||
let account = store.sign_in(&new_account(), &Secret::new(TOKEN), NOW).unwrap();
|
||||
|
||||
store.discard(&account.id).unwrap();
|
||||
assert!(!keychain.has(&account.id), "the keychain entry should be gone");
|
||||
assert!(store.accounts().unwrap().accounts.is_empty());
|
||||
assert!(matches!(store.shared(), Shared::None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn forgetting_an_account_clears_only_the_entry_and_leaves_the_row() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let keychain = Memory::new();
|
||||
let store = Store::at(Some(dir.path().to_path_buf()), keychain.clone());
|
||||
let account = store.sign_in(&new_account(), &Secret::new(TOKEN), NOW).unwrap();
|
||||
|
||||
store.forget(&account.id).unwrap();
|
||||
assert!(!keychain.has(&account.id), "the keychain entry should be gone");
|
||||
assert_eq!(store.accounts().unwrap().accounts.len(), 1, "forgetting leaves the row; discard removes it too");
|
||||
assert!(matches!(store.shared(), Shared::None), "no readable token behind the row still reads as nobody signed in");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_isolated_store_refuses_to_forget_a_credential_it_does_not_own() {
|
||||
let keychain = Memory::new();
|
||||
keychain.put("somebody-elses-handle", &Secret::new(TOKEN)).unwrap();
|
||||
let store: Store<Memory> = Store::at(None, keychain.clone());
|
||||
|
||||
assert_eq!(store.forget("somebody-elses-handle").unwrap_err(), Error::Isolated);
|
||||
assert!(keychain.has("somebody-elses-handle"), "an isolated store must never reach another application's entry");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_isolated_store_refuses_to_read_has_token_too() {
|
||||
let keychain = Memory::new();
|
||||
keychain.put("somebody-elses-handle", &Secret::new(TOKEN)).unwrap();
|
||||
let store: Store<Memory> = Store::at(None, keychain);
|
||||
|
||||
assert_eq!(store.has_token("somebody-elses-handle").unwrap_err(), Error::Isolated);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn discarding_an_unknown_account_is_a_quiet_no_op() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let store = Store::at(Some(dir.path().to_path_buf()), Memory::new());
|
||||
store.discard("nobody").unwrap();
|
||||
}
|
||||
|
||||
// ---- the generation guards a stale write -----------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_write_against_a_stale_generation_is_refused() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let keychain = Memory::new();
|
||||
let store = Store::at(Some(dir.path().to_path_buf()), keychain.clone());
|
||||
let first = store.sign_in(&new_account(), &Secret::new(TOKEN), NOW).unwrap();
|
||||
assert_eq!(first.generation, 0);
|
||||
|
||||
// Somebody else signs the same account in again, elsewhere, before the refresh below lands.
|
||||
let second = store.sign_in(&new_account(), &Secret::new("rotated-elsewhere"), NOW + 30).unwrap();
|
||||
assert_eq!(second.id, first.id);
|
||||
assert_eq!(second.generation, 1);
|
||||
|
||||
// A refresh that read the account before that second sign-in still carries generation 0.
|
||||
let stale = store.update_token(&first.id, first.generation, &Secret::new("late-refresh"), NOW + 60);
|
||||
assert_eq!(stale.unwrap_err(), Error::StaleGeneration { id: first.id.clone(), expected: 0, current: 1 });
|
||||
|
||||
// The write never landed: the token on file is still the one from the second sign-in.
|
||||
match store.shared() {
|
||||
Shared::Session { token, .. } => assert_eq!(token, Secret::new("rotated-elsewhere")),
|
||||
other => panic!("expected a session, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_write_against_the_current_generation_succeeds_and_advances_it() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let keychain = Memory::new();
|
||||
let store = Store::at(Some(dir.path().to_path_buf()), keychain.clone());
|
||||
let account = store.sign_in(&new_account(), &Secret::new(TOKEN), NOW).unwrap();
|
||||
|
||||
let updated = store.update_token(&account.id, account.generation, &Secret::new("refreshed-token"), NOW + 30).unwrap();
|
||||
assert_eq!(updated.generation, account.generation + 1);
|
||||
match store.shared() {
|
||||
Shared::Session { token, .. } => assert_eq!(token, Secret::new("refreshed-token")),
|
||||
other => panic!("expected a session, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refreshing_an_account_does_not_steal_activation_from_another() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let keychain = Memory::new();
|
||||
let store = Store::at(Some(dir.path().to_path_buf()), keychain.clone());
|
||||
let a = store.sign_in(&new_account(), &Secret::new("a-token"), NOW).unwrap();
|
||||
let elsewhere = NewAccount { service: "https://other.example.com".to_owned(), ..new_account() };
|
||||
let b = store.sign_in(&elsewhere, &Secret::new("b-token"), NOW + 1).unwrap();
|
||||
assert_eq!(store.accounts().unwrap().active.as_deref(), Some(b.id.as_str()), "B is the one picked by signing in last");
|
||||
|
||||
store.update_token(&a.id, a.generation, &Secret::new("a-token-refreshed"), NOW + 2).unwrap();
|
||||
|
||||
assert_eq!(store.accounts().unwrap().active.as_deref(), Some(b.id.as_str()), "refreshing A in the background must not steal B's selection");
|
||||
match store.shared() {
|
||||
Shared::Session { account, token } => {
|
||||
assert_eq!(account.id, b.id);
|
||||
assert_eq!(token, Secret::new("b-token"));
|
||||
}
|
||||
other => panic!("expected B's session, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_write_against_an_unknown_account_says_so_rather_than_claiming_a_stale_generation() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let store = Store::at(Some(dir.path().to_path_buf()), Memory::new());
|
||||
assert_eq!(store.update_token("nobody", 0, &Secret::new(TOKEN), NOW).unwrap_err(), Error::Unknown("nobody".to_owned()));
|
||||
}
|
||||
|
||||
// ---- a lost race never touches the keychain --------------------------------
|
||||
|
||||
/// A newer sign-in for the same handle must never let a stale refresh overwrite its token. The
|
||||
/// refresh is held at `race_hook`'s pause point right after its own first, unlocked look at the
|
||||
/// old generation. Only then does the newer sign-in run, and it always finishes before the pause
|
||||
/// lifts and the refresh takes its second, locked look. A plain start barrier cannot pin that
|
||||
/// ordering: it only lines both operations up at the beginning, so a build that still has the
|
||||
/// bug this test guards against could pass anyway, by rejecting at the first check because the
|
||||
/// sign-in happened to land first, never reaching the second check this test is named for.
|
||||
#[test]
|
||||
fn a_refresh_racing_a_newer_sign_in_for_the_same_handle_never_overwrites_its_token() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let keychain = Memory::new();
|
||||
let store = Store::at(Some(dir.path().to_path_buf()), keychain.clone());
|
||||
let first = store.sign_in(&new_account(), &Secret::new("session-1"), NOW).unwrap();
|
||||
let seen_generation = first.generation;
|
||||
|
||||
let gate = store.arm_race_hook();
|
||||
let winner_dir = dir.path().to_path_buf();
|
||||
let winner_keychain = keychain.clone();
|
||||
let winner = std::thread::spawn(move || -> Result<(), Error> {
|
||||
gate.arrived.recv().map_err(|_| Error::Unknown("the refresh never reached the pause point".to_owned()))?;
|
||||
Store::at(Some(winner_dir), winner_keychain).sign_in(&new_account(), &Secret::new("session-2"), NOW + 10)?;
|
||||
gate.go.send(()).map_err(|_| Error::Unknown("the refresh gave up waiting for the pause to lift".to_owned()))?;
|
||||
Ok(())
|
||||
});
|
||||
|
||||
let refresh = store.update_token(&first.id, seen_generation, &Secret::new("session-1-refreshed"), NOW + 20);
|
||||
winner.join().unwrap().unwrap();
|
||||
|
||||
assert!(matches!(refresh, Err(Error::StaleGeneration { .. })), "the refresh must lose to the newer sign-in: {refresh:?}");
|
||||
assert!(keychain.has(&first.id), "the new session's token must still be in the keychain");
|
||||
assert_eq!(
|
||||
keychain.get(&first.id).unwrap(),
|
||||
Some(Secret::new("session-2")),
|
||||
"the stale refresh must never have overwritten the new session's token"
|
||||
);
|
||||
match store.shared() {
|
||||
Shared::Session { token, .. } => assert_eq!(token, Secret::new("session-2")),
|
||||
other => panic!("expected session 2's session, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The same race, with the newer sign-in preceded by a discard: the handle is removed and
|
||||
/// tombstoned, then signed in again, both only after the refresh's first, unlocked check has
|
||||
/// already read the old generation, and both finished before the pause lifts for its second,
|
||||
/// locked one. Session two's token must be the one left standing either way, the same pin as
|
||||
/// the sign-in race above and for the same reason: a start barrier alone cannot tell a correct
|
||||
/// second check apart from a lucky early rejection at the first one.
|
||||
#[test]
|
||||
fn a_refresh_racing_a_discard_and_re_add_for_the_same_handle_never_overwrites_its_token() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let keychain = Memory::new();
|
||||
let store = Store::at(Some(dir.path().to_path_buf()), keychain.clone());
|
||||
let first = store.sign_in(&new_account(), &Secret::new("session-1"), NOW).unwrap();
|
||||
let seen_generation = first.generation;
|
||||
|
||||
let gate = store.arm_race_hook();
|
||||
let winner_dir = dir.path().to_path_buf();
|
||||
let winner_keychain = keychain.clone();
|
||||
let winner_id = first.id.clone();
|
||||
let winner = std::thread::spawn(move || -> Result<(), Error> {
|
||||
gate.arrived.recv().map_err(|_| Error::Unknown("the refresh never reached the pause point".to_owned()))?;
|
||||
let other = Store::at(Some(winner_dir), winner_keychain);
|
||||
other.discard(&winner_id)?;
|
||||
other.sign_in(&new_account(), &Secret::new("session-2"), NOW + 10)?;
|
||||
gate.go.send(()).map_err(|_| Error::Unknown("the refresh gave up waiting for the pause to lift".to_owned()))?;
|
||||
Ok(())
|
||||
});
|
||||
|
||||
let refresh = store.update_token(&first.id, seen_generation, &Secret::new("session-1-refreshed"), NOW + 20);
|
||||
winner.join().unwrap().unwrap();
|
||||
|
||||
assert!(refresh.is_err(), "the refresh must lose to the discard and re-add: {refresh:?}");
|
||||
assert!(keychain.has(&first.id), "the re-added session's token must still be in the keychain");
|
||||
assert_eq!(
|
||||
keychain.get(&first.id).unwrap(),
|
||||
Some(Secret::new("session-2")),
|
||||
"the stale refresh must never have overwritten the re-added session's token"
|
||||
);
|
||||
match store.shared() {
|
||||
Shared::Session { token, .. } => assert_eq!(token, Secret::new("session-2")),
|
||||
other => panic!("expected session 2's session, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sign_in_restores_its_token_when_a_concurrent_discard_takes_it_first() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let keychain = Memory::new();
|
||||
let plain = Store::at(Some(dir.path().to_path_buf()), keychain.clone());
|
||||
let first = plain.sign_in(&new_account(), &Secret::new("session-1"), NOW).unwrap();
|
||||
|
||||
/// Fires once, on this sign-in's own first token write, before it asks for the accounts
|
||||
/// lock: runs a full discard for the same handle, taking the entry this call just wrote with
|
||||
/// it and leaving a tombstone behind it. By the time the sign-in reaches its own lock, the
|
||||
/// row it is about to commit has no keychain entry behind it unless something restores one.
|
||||
///
|
||||
/// Armed for a single call only. The fix's own re-assertion put runs inside the lock and must
|
||||
/// land plainly. Firing discard again from inside it would try to take the same accounts
|
||||
/// lock this call already holds. That is the lock module's own deadlock case. This test
|
||||
/// means to cover a different race, the one between two separate lock holders.
|
||||
struct DiscardAfterPut {
|
||||
inner: Memory,
|
||||
dir: PathBuf,
|
||||
id: String,
|
||||
fired: std::sync::atomic::AtomicBool,
|
||||
}
|
||||
impl TokenStore for DiscardAfterPut {
|
||||
fn available(&self) -> Result<(), String> {
|
||||
self.inner.available()
|
||||
}
|
||||
fn get(&self, h: &str) -> Result<Option<Secret>, String> {
|
||||
self.inner.get(h)
|
||||
}
|
||||
fn put(&self, h: &str, t: &Secret) -> Result<(), String> {
|
||||
let r = self.inner.put(h, t);
|
||||
if !self.fired.swap(true, std::sync::atomic::Ordering::SeqCst) {
|
||||
Store::at(Some(self.dir.clone()), self.inner.clone()).discard(&self.id).unwrap();
|
||||
}
|
||||
r
|
||||
}
|
||||
fn remove(&self, h: &str) -> Result<(), String> {
|
||||
self.inner.remove(h)
|
||||
}
|
||||
}
|
||||
|
||||
let racing = Store::at(
|
||||
Some(dir.path().to_path_buf()),
|
||||
DiscardAfterPut {
|
||||
inner: keychain.clone(),
|
||||
dir: dir.path().to_path_buf(),
|
||||
id: first.id.clone(),
|
||||
fired: std::sync::atomic::AtomicBool::new(false),
|
||||
},
|
||||
);
|
||||
let account = racing.sign_in(&new_account(), &Secret::new("session-2"), NOW + 10).unwrap();
|
||||
|
||||
assert_eq!(account.id, first.id, "the same deployment and subject is the same handle");
|
||||
assert!(
|
||||
keychain.has(&account.id),
|
||||
"a discard landed between this sign-in's own token write and its row commit; the row this call reported Ok for must not be left without a token"
|
||||
);
|
||||
match Store::at(Some(dir.path().to_path_buf()), keychain.clone()).shared() {
|
||||
Shared::Session { token, .. } => assert_eq!(token, Secret::new("session-2")),
|
||||
other => panic!("expected a session, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
// ---- generations never wrap ------------------------------------------------
|
||||
|
||||
/// What a crafted accounts file at the limit looks like: one account, holding `generation`.
|
||||
fn account_at(id: &str, generation: u32) -> Account {
|
||||
Account {
|
||||
id: id.to_owned(),
|
||||
service: SERVICE.to_owned(),
|
||||
user: USER.to_owned(),
|
||||
display: "Ada Lovelace".to_owned(),
|
||||
generation,
|
||||
..Account::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remove_with_tombstone_refuses_to_wrap_past_the_maximum_generation() {
|
||||
let mut list = accounts::Accounts::default();
|
||||
let err = list.remove_with_tombstone("x", u32::MAX).unwrap_err();
|
||||
assert_eq!(err, Error::GenerationExhausted("x".to_owned()));
|
||||
assert!(list.tombstones.is_empty(), "a refused bump must leave no tombstone behind");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_refresh_against_an_account_already_at_the_maximum_generation_is_refused() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join(paths::FILE);
|
||||
let id = accounts::handle(SERVICE, USER);
|
||||
let list =
|
||||
accounts::Accounts { format: accounts::FORMAT, accounts: vec![account_at(&id, u32::MAX)], active: Some(id.clone()), tombstones: Vec::new() };
|
||||
accounts::write(&path, &list).unwrap();
|
||||
let keychain = Memory::new();
|
||||
keychain.put(&id, &Secret::new(TOKEN)).unwrap();
|
||||
let store = Store::at(Some(dir.path().to_path_buf()), keychain);
|
||||
|
||||
let err = store.update_token(&id, u32::MAX, &Secret::new("refreshed"), NOW + 1).unwrap_err();
|
||||
assert_eq!(err, Error::GenerationExhausted(id));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn signing_in_over_a_tombstone_at_the_maximum_generation_is_refused() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join(paths::FILE);
|
||||
let id = accounts::handle(SERVICE, USER);
|
||||
let list = accounts::Accounts {
|
||||
format: accounts::FORMAT,
|
||||
accounts: Vec::new(),
|
||||
active: None,
|
||||
tombstones: vec![accounts::Tombstone { id: id.clone(), generation: u32::MAX }],
|
||||
};
|
||||
accounts::write(&path, &list).unwrap();
|
||||
let store = Store::at(Some(dir.path().to_path_buf()), Memory::new());
|
||||
|
||||
let err = store.sign_in(&new_account(), &Secret::new(TOKEN), NOW).unwrap_err();
|
||||
assert_eq!(err, Error::GenerationExhausted(id));
|
||||
}
|
||||
|
||||
// ---- the list never grows past what the next reader can open ---------------
|
||||
|
||||
#[test]
|
||||
fn write_refuses_a_list_too_large_for_read_to_ever_open_again() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join(paths::FILE);
|
||||
let oversized = accounts::Accounts {
|
||||
format: accounts::FORMAT,
|
||||
accounts: vec![Account { display: "x".repeat(2 << 20), ..account_at("huge", 0) }],
|
||||
active: None,
|
||||
tombstones: Vec::new(),
|
||||
};
|
||||
|
||||
assert!(matches!(accounts::write(&path, &oversized), Err(Error::Malformed(_))));
|
||||
assert!(!path.exists(), "a write that cannot be read back must never land on disk");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn write_leaves_a_previously_good_file_untouched_when_the_new_one_is_too_large() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join(paths::FILE);
|
||||
let good =
|
||||
accounts::Accounts { format: accounts::FORMAT, accounts: vec![account_at("a", 0)], active: Some("a".to_owned()), tombstones: Vec::new() };
|
||||
accounts::write(&path, &good).unwrap();
|
||||
|
||||
let oversized = accounts::Accounts {
|
||||
format: accounts::FORMAT,
|
||||
accounts: vec![Account { display: "x".repeat(2 << 20), ..account_at("huge", 0) }],
|
||||
active: None,
|
||||
tombstones: Vec::new(),
|
||||
};
|
||||
assert!(accounts::write(&path, &oversized).is_err());
|
||||
|
||||
assert_eq!(accounts::read(&path).unwrap(), good, "the earlier, readable file must still be exactly what was there before");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_sign_in_with_an_oversized_display_name_fails_without_bricking_the_list() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let keychain = Memory::new();
|
||||
let store = Store::at(Some(dir.path().to_path_buf()), keychain.clone());
|
||||
store.sign_in(&new_account(), &Secret::new(TOKEN), NOW).unwrap();
|
||||
|
||||
let huge = NewAccount { display: "x".repeat(2 << 20), ..NewAccount { service: "https://other.example.com".to_owned(), ..new_account() } };
|
||||
assert!(store.sign_in(&huge, &Secret::new("another-token"), NOW + 1).is_err());
|
||||
|
||||
// The list a moment ago is still exactly readable. The first account is still there.
|
||||
// `shared()` still answers normally. Without the guard, every later call would fail on a
|
||||
// file nothing can parse back.
|
||||
let list = store.accounts().unwrap();
|
||||
assert_eq!(list.accounts.len(), 1);
|
||||
assert!(matches!(store.shared(), Shared::Session { .. }));
|
||||
}
|
||||
|
||||
// ---- nobody is signed in ---------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn an_empty_suite_offers_nothing() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let store = Store::at(Some(dir.path().to_path_buf()), Memory::new());
|
||||
assert!(matches!(store.shared(), Shared::None));
|
||||
assert!(store.accounts().unwrap().accounts.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_isolated_store_offers_nothing_and_signs_nobody_in() {
|
||||
let store: Store<Memory> = Store::at(None, Memory::new());
|
||||
assert!(matches!(store.shared(), Shared::None));
|
||||
assert_eq!(store.usable().unwrap_err(), Error::Isolated);
|
||||
assert_eq!(store.sign_in(&new_account(), &Secret::new(TOKEN), NOW).unwrap_err(), Error::Isolated);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_machine_with_no_keychain_signs_nobody_in() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let store = Store::at(Some(dir.path().to_path_buf()), Memory::missing("no Secret Service on this machine"));
|
||||
assert!(matches!(store.shared(), Shared::None));
|
||||
match store.sign_in(&new_account(), &Secret::new(TOKEN), NOW).unwrap_err() {
|
||||
Error::Keychain(why) => assert!(why.contains("no Secret Service")),
|
||||
other => panic!("expected a keychain failure, got {other:?}"),
|
||||
}
|
||||
assert!(!store.path().unwrap().exists(), "a refused sign-in should write no file");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unreadable_keychain_says_so_rather_than_pretending_nobody_signed_in() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
// Sign in against a working keychain, then read the same folder through a locked one.
|
||||
let store = Store::at(Some(dir.path().to_path_buf()), Memory::new());
|
||||
let account = store.sign_in(&new_account(), &Secret::new(TOKEN), NOW).unwrap();
|
||||
|
||||
let locked = Store::at(Some(dir.path().to_path_buf()), Memory::refusing("the keychain is locked"));
|
||||
match locked.shared() {
|
||||
Shared::Unreadable { account: found, why } => {
|
||||
assert_eq!(found.id, account.id);
|
||||
assert!(why.contains("locked"));
|
||||
}
|
||||
other => panic!("expected an unreadable session, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_account_whose_entry_is_gone_reads_as_nobody_signed_in() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let keychain = Memory::new();
|
||||
let store = Store::at(Some(dir.path().to_path_buf()), keychain.clone());
|
||||
let account = store.sign_in(&new_account(), &Secret::new(TOKEN), NOW).unwrap();
|
||||
// Somebody deleted the credential from the platform's own window.
|
||||
keychain.remove(&account.id).unwrap();
|
||||
assert!(matches!(store.shared(), Shared::None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_active_account_that_is_no_longer_listed_reads_as_nobody_signed_in() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join(paths::FILE);
|
||||
let list = accounts::Accounts { format: accounts::FORMAT, accounts: Vec::new(), active: Some("vanished".to_owned()), tombstones: Vec::new() };
|
||||
accounts::write(&path, &list).unwrap();
|
||||
let store = Store::at(Some(dir.path().to_path_buf()), Memory::new());
|
||||
assert!(matches!(store.shared(), Shared::None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_from_a_later_format_is_refused_rather_than_misread() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join(paths::FILE);
|
||||
std::fs::write(&path, br#"{"format":99,"accounts":[],"active":null}"#).unwrap();
|
||||
let store = Store::at(Some(dir.path().to_path_buf()), Memory::new());
|
||||
assert!(matches!(store.accounts(), Err(Error::Malformed(_))));
|
||||
// An application still starts: the shared answer is that nobody is signed in.
|
||||
assert!(matches!(store.shared(), Shared::None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unreadable_json_does_not_stop_an_application_starting() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
std::fs::write(dir.path().join(paths::FILE), b"this is not JSON").unwrap();
|
||||
let store = Store::at(Some(dir.path().to_path_buf()), Memory::new());
|
||||
assert!(matches!(store.shared(), Shared::None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_format_of_zero_is_refused_rather_than_silently_accepted() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join(paths::FILE);
|
||||
std::fs::write(&path, br#"{"format":0,"accounts":[],"active":null,"tombstones":[]}"#).unwrap();
|
||||
assert!(matches!(accounts::read(&path), Err(Error::Malformed(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_format_marker_is_refused_rather_than_silently_accepted() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join(paths::FILE);
|
||||
// No `format` key at all: `#[serde(default)]` would otherwise read this exactly as it reads
|
||||
// an explicit `"format":0` above. Both would have passed the old `> FORMAT` check.
|
||||
std::fs::write(&path, br#"{"accounts":[],"active":null,"tombstones":[]}"#).unwrap();
|
||||
assert!(matches!(accounts::read(&path), Err(Error::Malformed(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_one_supported_format_still_reads() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join(paths::FILE);
|
||||
let body = format!(r#"{{"format":{},"accounts":[],"active":null,"tombstones":[]}}"#, accounts::FORMAT);
|
||||
std::fs::write(&path, body.as_bytes()).unwrap();
|
||||
assert!(accounts::read(&path).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_read_error_does_not_name_the_profile_folder_it_lives_under() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let home = dir.path().join("Users").join("a-real-persons-name").join(paths::DIR);
|
||||
std::fs::create_dir_all(&home).unwrap();
|
||||
let path = home.join(paths::FILE);
|
||||
std::fs::write(&path, b"this is not JSON").unwrap();
|
||||
|
||||
let message = accounts::read(&path).unwrap_err().to_string();
|
||||
assert!(!message.contains("a-real-persons-name"), "the profile folder leaked into the error: {message}");
|
||||
assert!(message.contains(paths::FILE), "the error should still say which file: {message}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_oversized_file_error_does_not_name_the_profile_folder_either() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let home = dir.path().join("Users").join("another-real-name").join(paths::DIR);
|
||||
std::fs::create_dir_all(&home).unwrap();
|
||||
let path = home.join(paths::FILE);
|
||||
std::fs::write(&path, vec![b'x'; 2 << 20]).unwrap();
|
||||
|
||||
let message = accounts::read(&path).unwrap_err().to_string();
|
||||
assert!(!message.contains("another-real-name"), "the profile folder leaked into the error: {message}");
|
||||
}
|
||||
|
||||
// ---- taking over a per-application session file ----------------------------
|
||||
|
||||
/// What GridCraft's `legacy-session.json` is read as.
|
||||
fn legacy_file(dir: &Path) -> PathBuf {
|
||||
let path = dir.join("legacy-session.json");
|
||||
let body = format!(r#"{{"service":"{SERVICE}","token":"{TOKEN}","user":"{USER}","display":"Ada Lovelace"}}"#);
|
||||
std::fs::write(&path, body.as_bytes()).unwrap();
|
||||
path
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_per_application_session_moves_into_the_suite_store_and_the_file_goes() {
|
||||
let suite = tempfile::tempdir().unwrap();
|
||||
let app = tempfile::tempdir().unwrap();
|
||||
let keychain = Memory::new();
|
||||
let store = Store::at(Some(suite.path().to_path_buf()), keychain.clone());
|
||||
let path = legacy_file(app.path());
|
||||
|
||||
match crate::migrate::adopt(&store, &path, NOW).unwrap() {
|
||||
Adopted::Taken(account) => {
|
||||
assert_eq!(account.service, SERVICE);
|
||||
assert_eq!(account.user, USER);
|
||||
assert!(keychain.has(&account.id), "the token should be in the keychain");
|
||||
}
|
||||
other => panic!("expected the session to be taken over, got {other:?}"),
|
||||
}
|
||||
assert!(!path.exists(), "the session file should be gone");
|
||||
match store.shared() {
|
||||
Shared::Session { token, .. } => assert_eq!(token, Secret::new(TOKEN)),
|
||||
other => panic!("expected a session, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn migration_repairs_an_orphan_keychain_token_with_the_legacy_file() {
|
||||
const LEGACY: &str = "legacy-session-token";
|
||||
let suite = tempfile::tempdir().unwrap();
|
||||
let app = tempfile::tempdir().unwrap();
|
||||
let keychain = Memory::new();
|
||||
let store = Store::at(Some(suite.path().to_path_buf()), keychain.clone());
|
||||
let id = accounts::handle(SERVICE, USER);
|
||||
keychain.put(&id, &Secret::new("orphan-token")).unwrap();
|
||||
let path = legacy_file(app.path());
|
||||
std::fs::write(&path, format!(r#"{{"service":"{SERVICE}","token":"{LEGACY}","user":"{USER}","display":"Ada Lovelace"}}"#).as_bytes()).unwrap();
|
||||
|
||||
match crate::migrate::adopt(&store, &path, NOW).unwrap() {
|
||||
Adopted::Taken(account) => assert_eq!(account.id, id),
|
||||
other => panic!("expected the legacy session to be taken over, got {other:?}"),
|
||||
}
|
||||
assert!(!path.exists());
|
||||
match store.shared() {
|
||||
Shared::Session { token, .. } => assert_eq!(token, Secret::new(LEGACY)),
|
||||
other => panic!("expected a session, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn migration_leaves_a_legacy_file_alone_once_it_changed_after_being_read() {
|
||||
let suite = tempfile::tempdir().unwrap();
|
||||
let app = tempfile::tempdir().unwrap();
|
||||
let path = legacy_file(app.path());
|
||||
|
||||
/// Stands in for another process still running the application's own, now-superseded
|
||||
/// writer: it rewrites the legacy file with a different token the moment the suite store
|
||||
/// writes this account's token, the exact window between `adopt`'s read of the file and its
|
||||
/// removal of it.
|
||||
struct RewriteFileOnPut {
|
||||
inner: Memory,
|
||||
path: PathBuf,
|
||||
}
|
||||
impl TokenStore for RewriteFileOnPut {
|
||||
fn available(&self) -> Result<(), String> {
|
||||
self.inner.available()
|
||||
}
|
||||
fn get(&self, h: &str) -> Result<Option<Secret>, String> {
|
||||
self.inner.get(h)
|
||||
}
|
||||
fn put(&self, h: &str, t: &Secret) -> Result<(), String> {
|
||||
let body = format!(r#"{{"service":"{SERVICE}","token":"refreshed-elsewhere","user":"{USER}","display":"Ada Lovelace"}}"#);
|
||||
std::fs::write(&self.path, body.as_bytes()).unwrap();
|
||||
self.inner.put(h, t)
|
||||
}
|
||||
fn remove(&self, h: &str) -> Result<(), String> {
|
||||
self.inner.remove(h)
|
||||
}
|
||||
}
|
||||
|
||||
let store = Store::at(Some(suite.path().to_path_buf()), RewriteFileOnPut { inner: Memory::new(), path: path.clone() });
|
||||
let account = match crate::migrate::adopt(&store, &path, NOW).unwrap() {
|
||||
Adopted::Taken(account) => account,
|
||||
other => panic!("expected the session to be taken over, got {other:?}"),
|
||||
};
|
||||
assert_eq!(account.service, SERVICE, "the session that was actually read is still the one adopted");
|
||||
|
||||
assert!(
|
||||
path.exists(),
|
||||
"the file changed after it was read; deleting it would discard the rewritten session with nothing left to recover it from"
|
||||
);
|
||||
let left_behind = std::fs::read_to_string(&path).unwrap();
|
||||
assert!(left_behind.contains("refreshed-elsewhere"), "the file on disk must still be the rewritten one: {left_behind}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_second_migration_finds_nothing_to_do() {
|
||||
let suite = tempfile::tempdir().unwrap();
|
||||
let app = tempfile::tempdir().unwrap();
|
||||
let store = Store::at(Some(suite.path().to_path_buf()), Memory::new());
|
||||
let path = legacy_file(app.path());
|
||||
crate::migrate::adopt(&store, &path, NOW).unwrap();
|
||||
assert_eq!(crate::migrate::adopt(&store, &path, NOW).unwrap(), Adopted::Nothing);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn migration_with_no_keychain_leaves_the_file_alone() {
|
||||
let suite = tempfile::tempdir().unwrap();
|
||||
let app = tempfile::tempdir().unwrap();
|
||||
let store = Store::at(Some(suite.path().to_path_buf()), Memory::missing("no keychain here"));
|
||||
let path = legacy_file(app.path());
|
||||
|
||||
match crate::migrate::adopt(&store, &path, NOW).unwrap() {
|
||||
Adopted::Kept { why } => assert!(why.contains("no keychain here")),
|
||||
other => panic!("expected the file to be kept, got {other:?}"),
|
||||
}
|
||||
assert!(path.exists(), "removing it would have signed the user out");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn migration_in_an_isolated_process_leaves_the_file_alone() {
|
||||
let app = tempfile::tempdir().unwrap();
|
||||
let store: Store<Memory> = Store::at(None, Memory::new());
|
||||
let path = legacy_file(app.path());
|
||||
assert!(matches!(crate::migrate::adopt(&store, &path, NOW).unwrap(), Adopted::Kept { .. }));
|
||||
assert!(path.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_session_file_carrying_no_session_is_refused() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("legacy-session.json");
|
||||
std::fs::write(&path, br#"{"service":"https://craft.example.com","token":" "}"#).unwrap();
|
||||
assert!(matches!(crate::migrate::read(&path), Err(Error::Malformed(_))));
|
||||
}
|
||||
|
||||
/// The four keys an application writes today, spelled exactly as it writes them.
|
||||
#[test]
|
||||
fn the_four_keys_an_application_writes_today_adopt_cleanly() {
|
||||
let suite = tempfile::tempdir().unwrap();
|
||||
let app = tempfile::tempdir().unwrap();
|
||||
let keychain = Memory::new();
|
||||
let store = Store::at(Some(suite.path().to_path_buf()), keychain.clone());
|
||||
let path = app.path().join("legacy-session.json");
|
||||
let body = format!(r#"{{"token":"{TOKEN}","service":"{SERVICE}","subject":"{USER}","display":"Ada Lovelace"}}"#);
|
||||
std::fs::write(&path, body.as_bytes()).unwrap();
|
||||
|
||||
match crate::migrate::adopt(&store, &path, NOW).unwrap() {
|
||||
Adopted::Taken(account) => {
|
||||
assert_eq!(account.service, SERVICE);
|
||||
assert_eq!(account.user, USER, "`subject` is the subject the handle is keyed on");
|
||||
assert_eq!(account.display, "Ada Lovelace");
|
||||
assert_eq!(account.id, accounts::handle(SERVICE, USER));
|
||||
assert!(keychain.has(&account.id));
|
||||
}
|
||||
other => panic!("expected the session to be taken over, got {other:?}"),
|
||||
}
|
||||
assert!(!path.exists());
|
||||
}
|
||||
|
||||
/// What is on every machine that signed in before the application recorded anything else.
|
||||
#[test]
|
||||
fn a_token_only_session_file_is_left_alone_until_the_application_records_more() {
|
||||
let suite = tempfile::tempdir().unwrap();
|
||||
let app = tempfile::tempdir().unwrap();
|
||||
let keychain = Memory::new();
|
||||
let store = Store::at(Some(suite.path().to_path_buf()), keychain.clone());
|
||||
let path = app.path().join("legacy-session.json");
|
||||
std::fs::write(&path, format!(r#"{{"token":"{TOKEN}"}}"#).as_bytes()).unwrap();
|
||||
|
||||
// It parses, and it says nothing to key an account on.
|
||||
let legacy = crate::migrate::read(&path).unwrap().unwrap();
|
||||
assert_eq!(legacy.token, Secret::new(TOKEN));
|
||||
assert_eq!(legacy.service, "");
|
||||
assert_eq!(legacy.user, "", "the subject is never stood in for");
|
||||
assert_eq!(legacy.incomplete(), Some("which deployment it belongs to"));
|
||||
|
||||
match crate::migrate::adopt(&store, &path, NOW).unwrap() {
|
||||
Adopted::Kept { why } => assert!(why.contains("does not say"), "{why}"),
|
||||
other => panic!("expected the file to be kept, got {other:?}"),
|
||||
}
|
||||
assert!(path.exists(), "removing it would have signed the user out");
|
||||
assert_eq!(keychain.count(), 0, "nothing should be filed under a made-up handle");
|
||||
assert!(store.accounts().unwrap().accounts.is_empty());
|
||||
assert!(matches!(store.shared(), Shared::None));
|
||||
|
||||
// The application rewrites the file once it knows the rest. The next startup adopts it.
|
||||
let body = format!(r#"{{"token":"{TOKEN}","service":"{SERVICE}","subject":"{USER}","display":"Ada Lovelace"}}"#);
|
||||
std::fs::write(&path, body.as_bytes()).unwrap();
|
||||
assert!(matches!(crate::migrate::adopt(&store, &path, NOW).unwrap(), Adopted::Taken(_)));
|
||||
assert!(!path.exists());
|
||||
match store.shared() {
|
||||
Shared::Session { account, token } => {
|
||||
assert_eq!(account.id, accounts::handle(SERVICE, USER));
|
||||
assert_eq!(token, Secret::new(TOKEN));
|
||||
}
|
||||
other => panic!("expected a session, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The deployment is recorded the moment the device flow completes. The subject only arrives when
|
||||
/// `/api/v1/me` first answers, so a file can hold one without the other.
|
||||
#[test]
|
||||
fn a_session_file_with_no_subject_is_left_alone() {
|
||||
let suite = tempfile::tempdir().unwrap();
|
||||
let app = tempfile::tempdir().unwrap();
|
||||
let keychain = Memory::new();
|
||||
let store = Store::at(Some(suite.path().to_path_buf()), keychain.clone());
|
||||
let path = app.path().join("legacy-session.json");
|
||||
std::fs::write(&path, format!(r#"{{"token":"{TOKEN}","service":"{SERVICE}"}}"#).as_bytes()).unwrap();
|
||||
|
||||
let legacy = crate::migrate::read(&path).unwrap().unwrap();
|
||||
assert_eq!(legacy.service, SERVICE);
|
||||
assert_eq!(legacy.incomplete(), Some("whose account it is"));
|
||||
|
||||
match crate::migrate::adopt(&store, &path, NOW).unwrap() {
|
||||
Adopted::Kept { why } => assert!(why.contains("whose account it is"), "{why}"),
|
||||
other => panic!("expected the file to be kept, got {other:?}"),
|
||||
}
|
||||
assert!(path.exists());
|
||||
assert_eq!(keychain.count(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_session_file_spelled_the_other_way_still_reads() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let path = dir.path().join("legacy-session.json");
|
||||
let body = format!(r#"{{"base_url":"{SERVICE}/","access_token":"{TOKEN}","sub":"{USER}","name":"Ada"}}"#);
|
||||
std::fs::write(&path, body.as_bytes()).unwrap();
|
||||
let legacy = crate::migrate::read(&path).unwrap().unwrap();
|
||||
assert_eq!(legacy.service, SERVICE, "the trailing slash comes off");
|
||||
assert_eq!(legacy.user, USER);
|
||||
assert_eq!(legacy.display, "Ada");
|
||||
assert_eq!(legacy.token, Secret::new(TOKEN));
|
||||
}
|
||||
|
||||
// ---- the secret itself -----------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_secret_never_prints_itself() {
|
||||
let secret = Secret::new(TOKEN);
|
||||
let shown = format!("{secret:?}");
|
||||
assert!(!shown.contains(TOKEN), "Debug printed the token: {shown}");
|
||||
assert_eq!(shown, format!("Secret({} bytes)", TOKEN.len()));
|
||||
assert_eq!(secret.len(), TOKEN.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_account_record_prints_no_secret() {
|
||||
let account = Account { id: "abc".to_owned(), service: SERVICE.to_owned(), ..Account::default() };
|
||||
assert!(!format!("{account:?}").contains(TOKEN));
|
||||
}
|
||||
@@ -0,0 +1,305 @@
|
||||
//! Conformance tests for `craft-suite-account` (PR #665), adapted from the maintainer's review
|
||||
//! reproduction gist for this crate (skylartaylor, rev `2e9c84f`). Each test asserts the behaviour
|
||||
//! the crate's docs and RFC-0025 promise.
|
||||
//!
|
||||
//! The first two tests below once drove their race through a hook on the [`Memory`] keychain's
|
||||
//! `put`, timed to land between [`Store::update_token`]'s keychain write and its second, locked
|
||||
//! check. That write now happens only inside the lock, in the second check's own success arm (see
|
||||
//! the module docs). Nothing sits between the two checks to hook into any more. A hook that tried
|
||||
//! would be asking `update_token` to take a lock it already holds. Real threads racing on a
|
||||
//! [`std::sync::Barrier`] replace it, the same device [`concurrent_sign_ins_from_two_threads_lose_no_rows`]
|
||||
//! already uses below. The lock makes both outcomes this PR promises hold for every interleaving,
|
||||
//! never only the one picked in advance. A race no longer needs to land in one exact window to
|
||||
//! prove it.
|
||||
//!
|
||||
//! Not adapted here: the gist's `review_h2_forget_during_refresh_is_undone`. `forget` is, by
|
||||
//! RFC-0025's "Cross-app lifecycle guarantees" (point 4), a deliberately generation-agnostic,
|
||||
//! keychain-only, local operation. It does not read or write the accounts list at all, so nothing
|
||||
//! in a locked read-change-write over that list can observe it racing a refresh. Fixing that
|
||||
//! interleaving would mean giving `forget` list/generation semantics it does not have today, a
|
||||
//! broader behaviour change than the three gates this PR closes (see the PR comment).
|
||||
|
||||
use std::sync::{Arc, Barrier};
|
||||
|
||||
use craft_suite_account::{Error, Memory, NewAccount, Secret, Store, TokenStore};
|
||||
|
||||
const SERVICE: &str = "https://craft.example.com";
|
||||
const NOW: i64 = 1_760_000_000;
|
||||
|
||||
fn acct(user: &str) -> NewAccount {
|
||||
NewAccount { service: SERVICE.to_owned(), user: user.to_owned(), display: user.to_owned(), email: None, linked: true }
|
||||
}
|
||||
|
||||
fn tok(s: &str) -> Secret {
|
||||
Secret::new(s.to_owned())
|
||||
}
|
||||
|
||||
// ---- gate: locked read-change-write on every list mutation -----------------
|
||||
|
||||
/// H1b: app A refreshes X while app B signs in Y, on real threads racing to start at the same
|
||||
/// moment. A's write must not land a stale copy of the list that was read before B's sign-in, or
|
||||
/// Y's row is lost even though Y's token sits in the keychain. `update_token`'s own lock always
|
||||
/// re-reads the list fresh right before it commits. That holds for either thread landing first.
|
||||
#[test]
|
||||
fn refresh_racing_another_sign_in_does_not_lose_that_row() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let keychain = Memory::new();
|
||||
let app_a = Store::at(Some(dir.path().to_owned()), keychain.clone());
|
||||
let app_b = Store::at(Some(dir.path().to_owned()), keychain.clone());
|
||||
|
||||
let x = app_a.sign_in(&acct("x"), &tok("x1"), NOW).unwrap();
|
||||
|
||||
let start = Arc::new(Barrier::new(2));
|
||||
let (a_start, b_start) = (start.clone(), start.clone());
|
||||
let a_id = x.id.clone();
|
||||
let a = std::thread::spawn(move || {
|
||||
a_start.wait();
|
||||
app_a.update_token(&a_id, x.generation, &tok("x2"), NOW + 1)
|
||||
});
|
||||
let b = std::thread::spawn(move || {
|
||||
b_start.wait();
|
||||
app_b.sign_in(&acct("y"), &tok("y1"), NOW)
|
||||
});
|
||||
a.join().unwrap().unwrap();
|
||||
let y = b.join().unwrap().unwrap();
|
||||
|
||||
let list = Store::at(Some(dir.path().to_owned()), Memory::new()).accounts().unwrap();
|
||||
let ids: Vec<_> = list.accounts.iter().map(|a| a.user.clone()).collect();
|
||||
assert!(
|
||||
list.get(&y.id).is_some(),
|
||||
"Y signed in successfully but its row is gone after X's refresh: accounts on file = {ids:?}, \
|
||||
Y token in keychain = {}",
|
||||
keychain.has(&y.id)
|
||||
);
|
||||
}
|
||||
|
||||
/// H1c: the same lost update with no hook at all: real threads, separate `Store`s over one folder
|
||||
/// (as two applications in one process would be), each signing in its own account. Every sign-in
|
||||
/// that returned Ok must be on the list afterwards, and none should fail.
|
||||
#[test]
|
||||
fn concurrent_sign_ins_from_two_threads_lose_no_rows() {
|
||||
let rounds = 200;
|
||||
let (mut lost, mut failed) = (0, 0);
|
||||
let mut examples = Vec::new();
|
||||
for round in 0..rounds {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let keychain = Memory::new();
|
||||
let start = Arc::new(Barrier::new(2));
|
||||
let handles: Vec<_> = ["a", "b"]
|
||||
.into_iter()
|
||||
.map(|who| {
|
||||
let (path, kc, start) = (dir.path().to_owned(), keychain.clone(), start.clone());
|
||||
std::thread::spawn(move || {
|
||||
let store = Store::at(Some(path), kc);
|
||||
start.wait();
|
||||
store.sign_in(&acct(&format!("{who}-{round}")), &tok(who), NOW)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let results: Vec<_> = handles.into_iter().map(|h| h.join().unwrap()).collect();
|
||||
let list = Store::at(Some(dir.path().to_owned()), Memory::new()).accounts().unwrap();
|
||||
for r in &results {
|
||||
match r {
|
||||
Ok(a) if list.get(&a.id).is_none() => {
|
||||
lost += 1;
|
||||
if examples.len() < 3 {
|
||||
examples.push(format!("round {round}: sign_in Ok but row missing ({} of 2 rows on file)", list.accounts.len()));
|
||||
}
|
||||
}
|
||||
Ok(_) => {}
|
||||
Err(e) => {
|
||||
failed += 1;
|
||||
if examples.len() < 3 {
|
||||
examples.push(format!("round {round}: sign_in Err({e})"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
lost == 0 && failed == 0,
|
||||
"{rounds} rounds x 2 concurrent sign-ins: {lost} Ok sign-ins lost their row, {failed} sign-ins failed; e.g. {examples:#?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// Helper for the two-process case below: when REVIEW_DIR is set, sign in REVIEW_N accounts named
|
||||
/// REVIEW_WHO-i into that folder. Does nothing in a normal run.
|
||||
#[test]
|
||||
fn concurrent_sign_in_helper() {
|
||||
let (Ok(dir), Ok(who)) = (std::env::var("REVIEW_DIR"), std::env::var("REVIEW_WHO")) else { return };
|
||||
let n: usize = std::env::var("REVIEW_N").ok().and_then(|n| n.parse().ok()).unwrap_or(100);
|
||||
let store = Store::at(Some(dir.into()), Memory::new());
|
||||
for i in 0..n {
|
||||
store.sign_in(&acct(&format!("{who}-{i}")), &tok(&who), NOW).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
/// The gate's named case: two OS processes (this test binary re-run as the helper above), each
|
||||
/// signing in 100 distinct accounts into one suite folder. All 200 succeed (Ok), so 200 rows must
|
||||
/// be on file: real processes rather than simulated interleaving, since this crate's own test
|
||||
/// binary can spawn itself and CI here can run child processes.
|
||||
#[test]
|
||||
fn concurrent_sign_ins_from_two_processes_lose_no_rows() {
|
||||
if std::env::var("REVIEW_DIR").is_ok() {
|
||||
return;
|
||||
}
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let exe = std::env::current_exe().unwrap();
|
||||
let children: Vec<_> = ["p", "q"]
|
||||
.into_iter()
|
||||
.map(|who| {
|
||||
std::process::Command::new(&exe)
|
||||
.args(["--exact", "concurrent_sign_in_helper", "--test-threads=1"])
|
||||
.env("REVIEW_DIR", dir.path())
|
||||
.env("REVIEW_WHO", who)
|
||||
.env("REVIEW_N", "100")
|
||||
.spawn()
|
||||
.unwrap()
|
||||
})
|
||||
.collect();
|
||||
for mut c in children {
|
||||
assert!(c.wait().unwrap().success(), "a helper process failed a sign_in");
|
||||
}
|
||||
let list = Store::at(Some(dir.path().to_owned()), Memory::new()).accounts().unwrap();
|
||||
assert_eq!(
|
||||
list.accounts.len(),
|
||||
200,
|
||||
"two processes each completed 100 successful sign_in calls, but only {} rows are on file",
|
||||
list.accounts.len()
|
||||
);
|
||||
}
|
||||
|
||||
// ---- gate: generations monotonic across removal and re-add -----------------
|
||||
|
||||
/// The gate's named case "refresh-racing-discard": app A refreshes X's token while app B signs X
|
||||
/// out (`discard`), on real threads racing to start at the same moment. Removal must win (RFC-0025
|
||||
/// lifecycle guarantee 2) whichever one actually lands first: neither the row nor the keychain
|
||||
/// entry may come back, whether the refresh commits before the discard removes it, or the discard
|
||||
/// lands first and the refresh's own second check then refuses a tombstoned account.
|
||||
#[test]
|
||||
fn refresh_racing_discard_resurrects_nothing() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let keychain = Memory::new();
|
||||
let app_a = Store::at(Some(dir.path().to_owned()), keychain.clone());
|
||||
let app_b = Store::at(Some(dir.path().to_owned()), keychain.clone());
|
||||
|
||||
let x = app_a.sign_in(&acct("x"), &tok("x-session-1"), NOW).unwrap();
|
||||
|
||||
let start = Arc::new(Barrier::new(2));
|
||||
let (a_start, b_start) = (start.clone(), start.clone());
|
||||
let a_id = x.id.clone();
|
||||
let a = std::thread::spawn(move || {
|
||||
a_start.wait();
|
||||
app_a.update_token(&a_id, x.generation, &tok("x-session-1-refreshed"), NOW + 1)
|
||||
});
|
||||
let b_id = x.id.clone();
|
||||
let b = std::thread::spawn(move || {
|
||||
b_start.wait();
|
||||
app_b.discard(&b_id)
|
||||
});
|
||||
let refreshed = a.join().unwrap();
|
||||
b.join().unwrap().unwrap();
|
||||
|
||||
let after = Store::at(Some(dir.path().to_owned()), Memory::new()).accounts().unwrap();
|
||||
let row_back = after.get(&x.id).is_some();
|
||||
let token_back = keychain.has(&x.id);
|
||||
assert!(
|
||||
!row_back && !token_back,
|
||||
"sign-out (discard) must win over an in-flight refresh; instead update_token returned {:?}, \
|
||||
row present after discard = {row_back}, keychain entry present after discard = {token_back}",
|
||||
refreshed.as_ref().map(|a| a.generation)
|
||||
);
|
||||
}
|
||||
|
||||
/// The gate's named case "stale-refresh-after-discard-and-re-add": a refresh that started under
|
||||
/// session 1 lands after the account was discarded and signed in again (session 2). Generations
|
||||
/// monotonic across removal and re-add means the re-added row never restarts at 0, so the stale
|
||||
/// refresh is refused and session 2's token survives.
|
||||
#[test]
|
||||
fn stale_refresh_after_discard_and_re_add_is_refused() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let keychain = Memory::new();
|
||||
let store = Store::at(Some(dir.path().to_owned()), keychain.clone());
|
||||
|
||||
let s1 = store.sign_in(&acct("x"), &tok("session-1"), NOW).unwrap();
|
||||
let seen_generation = s1.generation; // a refresher reads this, then goes to the network
|
||||
store.discard(&s1.id).unwrap(); // the person signs out ...
|
||||
let s2 = store.sign_in(&acct("x"), &tok("session-2"), NOW + 10).unwrap(); // ... and back in
|
||||
|
||||
let stale = store.update_token(&s1.id, seen_generation, &tok("session-1-refreshed"), NOW + 20);
|
||||
let now_token = keychain.get(&s1.id).unwrap().map(|t| t.expose().to_owned());
|
||||
assert_eq!(
|
||||
stale,
|
||||
Err(Error::StaleGeneration { id: s1.id.clone(), expected: seen_generation, current: s2.generation }),
|
||||
"refresh from the discarded session (generation {seen_generation}) must be refused as stale, \
|
||||
never Unknown: re-added session has generation {}; keychain now holds {:?}",
|
||||
s2.generation,
|
||||
now_token
|
||||
);
|
||||
assert_eq!(now_token, Some("session-2".to_owned()), "session 2's token must survive the stale refresh");
|
||||
}
|
||||
|
||||
/// The gate's named case "re-add-continues-generation": removing an account and signing it back in
|
||||
/// must never restart its generation at 0. One bump for the tombstone the removal leaves, one for
|
||||
/// the sign-in that follows it.
|
||||
#[test]
|
||||
fn re_add_continues_generation_past_the_tombstone() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let store = Store::at(Some(dir.path().to_owned()), Memory::new());
|
||||
|
||||
let s1 = store.sign_in(&acct("x"), &tok("session-1"), NOW).unwrap();
|
||||
assert_eq!(s1.generation, 0);
|
||||
store.discard(&s1.id).unwrap();
|
||||
let s2 = store.sign_in(&acct("x"), &tok("session-2"), NOW + 10).unwrap();
|
||||
|
||||
assert_eq!(s2.id, s1.id, "the same deployment and subject is the same handle");
|
||||
assert!(
|
||||
s2.generation > s1.generation,
|
||||
"the re-added session's generation must be ahead of the discarded one, never restarting at 0: {} vs {}",
|
||||
s2.generation,
|
||||
s1.generation
|
||||
);
|
||||
assert_eq!(s2.generation, s1.generation + 2, "one bump for the tombstone, one for the sign-in");
|
||||
|
||||
// A third sign-in should continue on from there rather than from the tombstone again.
|
||||
let s3 = store.sign_in(&acct("x"), &tok("session-3"), NOW + 20).unwrap();
|
||||
assert_eq!(s3.generation, s2.generation + 1);
|
||||
}
|
||||
|
||||
// ---- gate: defined partial-failure recovery ---------------------------------
|
||||
|
||||
/// RFC-0025 guarantee 1: a partial failure leaves a state the next reader detects and repairs,
|
||||
/// never a silent mismatch. Simulates the window `update_token` opens between writing the
|
||||
/// refreshed token to the keychain and committing the matching generation bump to the list (see
|
||||
/// the crate's module docs, "Concurrent mutations and partial-failure recovery"): the token store
|
||||
/// receives the refreshed token directly, standing in for a crash right after that write and
|
||||
/// before the list commit. The list is then one generation behind a keychain token that is already
|
||||
/// the newer one. The next `update_token` against that same, still-current generation must still
|
||||
/// succeed and bring both back into step, rather than getting stuck re-reporting the mismatch.
|
||||
#[test]
|
||||
fn torn_state_between_the_keychain_write_and_the_generation_commit_recovers() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let keychain = Memory::new();
|
||||
let store = Store::at(Some(dir.path().to_owned()), keychain.clone());
|
||||
|
||||
let account = store.sign_in(&acct("x"), &tok("session-1"), NOW).unwrap();
|
||||
|
||||
// Stand in for the crash: the keychain already holds the refreshed token, but the list was
|
||||
// never told, so it still shows the old generation.
|
||||
keychain.put(&account.id, &tok("session-1-refreshed")).unwrap();
|
||||
match store.shared() {
|
||||
craft_suite_account::Shared::Session { token, .. } => {
|
||||
assert_eq!(token, tok("session-1-refreshed"), "the torn state is detectable: the keychain is already ahead of the list");
|
||||
}
|
||||
other => panic!("expected a session, got {other:?}"),
|
||||
}
|
||||
|
||||
// The next legitimate refresh, made against the generation the list still shows, must still
|
||||
// go through and bring both back into step.
|
||||
let recovered = store.update_token(&account.id, account.generation, &tok("session-2"), NOW + 30).unwrap();
|
||||
assert_eq!(recovered.generation, account.generation + 1);
|
||||
match store.shared() {
|
||||
craft_suite_account::Shared::Session { token, .. } => assert_eq!(token, tok("session-2")),
|
||||
other => panic!("expected a session, got {other:?}"),
|
||||
}
|
||||
}
|
||||
@@ -156,19 +156,21 @@ impl<'a> Tokenizer<'a> {
|
||||
Some(v)
|
||||
}
|
||||
|
||||
fn next_tok(&mut self) -> Option<Tok> {
|
||||
fn next_tok(&mut self) -> Result<Option<Tok>> {
|
||||
let mut nums = Numbers { s: self.s, i: self.i };
|
||||
nums.skip_seps();
|
||||
self.i = nums.i;
|
||||
self.tok_start = self.i;
|
||||
let c = self.s.get(self.i).copied()?;
|
||||
let Some(c) = self.s.get(self.i).copied() else { return Ok(None) };
|
||||
if c.is_ascii_alphabetic() {
|
||||
self.i += 1;
|
||||
return Some(Tok::Cmd(c));
|
||||
return Ok(Some(Tok::Cmd(c)));
|
||||
}
|
||||
let tok = nums.next_num().map(Tok::Num);
|
||||
self.i = nums.i;
|
||||
tok
|
||||
// Invalid bytes and malformed/non-finite numbers are not EOF: returning a
|
||||
// successful prefix here would silently discard the rest of the shape.
|
||||
tok.map(Some).ok_or_else(|| Error("SVG: invalid path token".into()))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -193,7 +195,7 @@ pub fn parse_path(d: &str) -> Result<Vec<Subpath>> {
|
||||
*look = Some(other);
|
||||
Err(Error("SVG: path command is missing coordinates".into()))
|
||||
}
|
||||
None => match tk.next_tok() {
|
||||
None => match tk.next_tok()? {
|
||||
Some(Tok::Num(v)) => Ok(v),
|
||||
Some(other @ Tok::Cmd(_)) => {
|
||||
*look = Some(other);
|
||||
@@ -204,7 +206,10 @@ pub fn parse_path(d: &str) -> Result<Vec<Subpath>> {
|
||||
}
|
||||
};
|
||||
|
||||
while let Some(tok) = lookahead.take().or_else(|| tk.next_tok()) {
|
||||
while let Some(tok) = match lookahead.take() {
|
||||
Some(tok) => Some(tok),
|
||||
None => tk.next_tok()?,
|
||||
} {
|
||||
let rel = match tok {
|
||||
Tok::Cmd(c) => {
|
||||
if c.eq_ignore_ascii_case(&b'z') {
|
||||
@@ -459,6 +464,25 @@ mod tests {
|
||||
assert!((sweep - std::f64::consts::PI).abs() < 1e-10);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_invalid_tokens_instead_of_returning_a_partial_path() {
|
||||
for input in ["@", "M0 0 L1 1@ L2 2", "M0 0 L1 1@", "M0 0 Z@", "M0 0 L1 1é", "M0 0 L1 1 +", "M0 0 L1 1 .", "M0 0 L1 1 2e+", "M0 0 L1 1 1e999"]
|
||||
{
|
||||
assert!(parse_path(input).is_err(), "accepted malformed path: {input}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn token_errors_do_not_change_clean_eof_or_compact_numbers() {
|
||||
assert!(parse_path(" \t\r\n,").unwrap().is_empty());
|
||||
let paths = parse_path("M.5-.5 L1e1-2e0 A6 7 30 0110 12 z ,\n").unwrap();
|
||||
assert_eq!(paths.len(), 1);
|
||||
assert!(paths[0].closed);
|
||||
assert_eq!(paths[0].start, Point::new(0.5, -0.5));
|
||||
assert_eq!(paths[0].segs[0], Segment::Line(Point::new(10.0, -2.0)));
|
||||
assert_eq!(paths[0].segs[1], Segment::Arc { rx: 6.0, ry: 7.0, rot: 30.0, large: false, sweep: true, end: Point::new(10.0, 12.0) });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_invalid_flags_and_limits_segments() {
|
||||
assert!(parse_path("M0 0 A1 1 0 5 1 2 2").is_err());
|
||||
|
||||
@@ -1124,7 +1124,7 @@ mod tests {
|
||||
let cases = [
|
||||
(0.3, 0.7, [true, false], [1.473_799_7, -0.072_800_055, 0.645_000_2, 0.733_799_8]),
|
||||
(0.3, 0.7, [false, true], [1.473_799_7, -0.072_800_055, 0.645_000_2, 0.733_799_8]),
|
||||
(1.2, -0.4, [true, false], [-1.722_999_5, 0.127_000_57, 0.089_999_32, 1.939_999_3]),
|
||||
(1.2, -0.4, [true, false], [-1.722_999_5, 0.127_000_57, 0.089_999_32_f32, 1.939_999_3]),
|
||||
(1.2, -0.4, [false, true], [-1.057_000_3, -1.094, 0.756_000_1, 2.606_000_2]),
|
||||
(-0.15, 1.1, [true, false], [2.051, -1.76, 0.090_000_15, 1.311_000_1]),
|
||||
(-0.15, 1.1, [false, true], [-1.834_000_6, 0.015_999_317, 0.608_000_5, 2.458_000_7]),
|
||||
|
||||
@@ -19,9 +19,11 @@ log = "0.4"
|
||||
serde = { version = "1", features = ["derive"], optional = true }
|
||||
# Same version as epaint's, for reading a face's character map.
|
||||
skrifa = { version = "0.44", default-features = false, features = ["std"] }
|
||||
# The vendor-neutral vocabulary the share dialog speaks. No IO and no
|
||||
# vendor, so this stays buildable for the web.
|
||||
# The vendor-neutral vocabulary the share and e-sign dialogs speak. No IO and
|
||||
# no vendor, so this stays buildable for the web.
|
||||
craft-cloud = { workspace = true, optional = true }
|
||||
# The e-sign contract the request-signatures dialog states its work through.
|
||||
craft-esign = { workspace = true, optional = true }
|
||||
# The control channel's report of the cloud state. One serialiser here
|
||||
# rather than one per application. No IO and no vendor.
|
||||
serde_json = { workspace = true, optional = true }
|
||||
@@ -65,6 +67,8 @@ share = ["dep:craft-cloud"]
|
||||
# Open and Save against cloud storage. Needs the share dialog, which a
|
||||
# document's overflow menu and the Share split button both open.
|
||||
cloud = ["share", "dep:serde_json"]
|
||||
# Request-signatures dialog.
|
||||
esign = ["dep:craft-cloud", "dep:craft-esign"]
|
||||
|
||||
[dev-dependencies]
|
||||
# serde: the IME tests read events that only the suite's egui fork has from JSON.
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
//! Where the e-sign dialog's work happens, which is never on the frame.
|
||||
//!
|
||||
//! Same shape as [`crate::share::ShareBackend`]: the dialog states what it
|
||||
//! wants, something behind this trait does the waiting, and answers arrive on
|
||||
//! a channel keyed by sequence number.
|
||||
|
||||
use craft_cloud::Contact;
|
||||
use craft_esign::{CompletedDocument, Envelope, EnvelopeDraft, EsignCapability};
|
||||
|
||||
/// One thing the dialog needs done.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Request {
|
||||
/// What the signing service can actually do, and who is legally responsible.
|
||||
Capabilities,
|
||||
/// People matching what has been typed so far (cloud contacts).
|
||||
Lookup { query: String, limit: usize },
|
||||
/// Create a draft from a document snapshot, then optionally send it.
|
||||
Create { draft: Box<EnvelopeDraft>, document: Vec<u8>, idempotency_key: String, send: bool },
|
||||
/// Current status of one envelope.
|
||||
Status { envelope: String },
|
||||
/// Finished document bytes.
|
||||
Completed { envelope: String },
|
||||
/// Cancel an in-flight envelope.
|
||||
Void { envelope: String, reason: String },
|
||||
/// Nudge one recipient.
|
||||
Remind { envelope: String, recipient: String },
|
||||
}
|
||||
|
||||
/// What came back.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Answer {
|
||||
Capabilities {
|
||||
capabilities: Vec<EsignCapability>,
|
||||
responsible_party: String,
|
||||
/// Whether a cloud account is attached so invitations can leave.
|
||||
linked: bool,
|
||||
},
|
||||
Lookup(Vec<Contact>),
|
||||
Created(Envelope),
|
||||
Status(Envelope),
|
||||
Completed(CompletedDocument),
|
||||
Voided {
|
||||
envelope: String,
|
||||
},
|
||||
Reminded {
|
||||
envelope: String,
|
||||
recipient: String,
|
||||
},
|
||||
}
|
||||
|
||||
/// Where one answer goes.
|
||||
pub struct Replier {
|
||||
seq: u64,
|
||||
tx: std::sync::mpsc::Sender<(u64, Result<Answer, String>)>,
|
||||
}
|
||||
|
||||
impl Replier {
|
||||
pub(crate) fn new(seq: u64, tx: std::sync::mpsc::Sender<(u64, Result<Answer, String>)>) -> Replier {
|
||||
Replier { seq, tx }
|
||||
}
|
||||
|
||||
pub fn seq(&self) -> u64 {
|
||||
self.seq
|
||||
}
|
||||
|
||||
pub fn dup(&self) -> Replier {
|
||||
Replier { seq: self.seq, tx: self.tx.clone() }
|
||||
}
|
||||
|
||||
pub fn answer(self, answer: Answer) {
|
||||
self.deliver(Ok(answer));
|
||||
}
|
||||
|
||||
pub fn refuse(self, reason: impl Into<String>) {
|
||||
self.deliver(Err(reason.into()));
|
||||
}
|
||||
|
||||
fn deliver(self, result: Result<Answer, String>) {
|
||||
let _ = self.tx.send((self.seq, result));
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Replier {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("Replier").field("seq", &self.seq).finish()
|
||||
}
|
||||
}
|
||||
|
||||
/// Somewhere a [`Request`] can run without blocking a frame.
|
||||
pub trait EsignBackend {
|
||||
fn submit(&self, request: Request, reply: Replier);
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
//! Regression tests for the CodeRabbit findings reviewed on PR #661,
|
||||
//! reproduced against ef496161 (storytold/craft-libs#661).
|
||||
//!
|
||||
//! Reuses `review_repro`'s `Hold` backend and helpers: a test chooses when,
|
||||
//! and in what order, a held request is answered.
|
||||
|
||||
use craft_esign::{Envelope, EnvelopeStatus};
|
||||
|
||||
use super::review_repro::{Hold, envelope_for, ready, send, who};
|
||||
use super::*;
|
||||
|
||||
/// Only one capabilities probe is ever outstanding for the current backend.
|
||||
/// `set_backend` clears `caps_seq`, but a reply already in flight from the
|
||||
/// backend being replaced keeps its old sequence number: it must not
|
||||
/// overwrite capabilities, responsible or linked for the new backend when
|
||||
/// it finally arrives.
|
||||
#[test]
|
||||
fn a_capabilities_reply_from_a_replaced_backend_does_not_overwrite_the_new_ones() {
|
||||
let hold_a = Hold::default();
|
||||
let mut dialog = EsignDialog::default();
|
||||
dialog.set_backend(hold_a.clone());
|
||||
dialog.pump(0.0);
|
||||
let (_, caps_a) = hold_a.take(|r| matches!(r, Request::Capabilities));
|
||||
|
||||
// The backend is replaced before A's capabilities probe answers.
|
||||
let hold_b = Hold::default();
|
||||
dialog.set_backend(hold_b.clone());
|
||||
dialog.pump(0.1);
|
||||
let (_, caps_b) = hold_b.take(|r| matches!(r, Request::Capabilities));
|
||||
|
||||
caps_b.answer(Answer::Capabilities { capabilities: vec![EsignCapability::Envelopes], responsible_party: "B".into(), linked: true });
|
||||
dialog.pump(0.2);
|
||||
assert_eq!(dialog.responsible.as_deref(), Some("B"));
|
||||
|
||||
// A's reply, from the replaced backend, arrives after B's already installed.
|
||||
caps_a.answer(Answer::Capabilities { capabilities: vec![EsignCapability::Void], responsible_party: "A".into(), linked: false });
|
||||
dialog.pump(0.3);
|
||||
|
||||
assert_eq!(dialog.responsible.as_deref(), Some("B"), "a stale Capabilities reply from a replaced backend overwrote the new backend's");
|
||||
assert!(dialog.linked, "a stale Capabilities reply from a replaced backend turned linked back off");
|
||||
}
|
||||
|
||||
/// A document's revision changing is itself a context change: a reply for
|
||||
/// the bytes under the old `document_etag` must not install under the new
|
||||
/// one, even though the document id never changed.
|
||||
#[test]
|
||||
fn stale_create_reply_for_old_revision_is_dropped_after_reopen_with_new_etag() {
|
||||
let (mut dialog, hold) = ready();
|
||||
dialog.open("doc-A".into(), "A.pdf".into(), Some("etag-1".into()), who("alice"));
|
||||
send(&mut dialog, b"A bytes etag1");
|
||||
dialog.open("doc-A".into(), "A.pdf".into(), Some("etag-2".into()), who("alice"));
|
||||
|
||||
let (_, create) = hold.take(|r| matches!(r, Request::Create { .. }));
|
||||
create.answer(Answer::Created(envelope_for("doc-A", "alice")));
|
||||
dialog.pump(1.0);
|
||||
|
||||
assert!(
|
||||
dialog.envelope.is_none(),
|
||||
"stale reply for etag-1 installed into the etag-2 opening: {:?}",
|
||||
dialog.envelope.as_ref().map(|e| e.id.clone())
|
||||
);
|
||||
}
|
||||
|
||||
/// `take_send_request` already handed the application doc-A's draft; the
|
||||
/// dialog then reopens for doc-B before the application calls
|
||||
/// `submit_request`. The reply this produces must still be tagged with
|
||||
/// doc-A's context, not doc-B's.
|
||||
#[test]
|
||||
fn create_reply_for_a_request_taken_before_reopening_does_not_install_in_the_new_document() {
|
||||
let (mut dialog, hold) = ready();
|
||||
dialog.open("doc-A".into(), "A.pdf".into(), None, who("alice"));
|
||||
dialog.add_email("bob@example.com".into());
|
||||
dialog.queue_send();
|
||||
let out = dialog.take_send_request().expect("send produced a request");
|
||||
|
||||
// The dialog moves on before the application gets around to submitting
|
||||
// what it already took.
|
||||
dialog.open("doc-B".into(), "B.pdf".into(), None, who("alice"));
|
||||
dialog.submit_request(Request::Create {
|
||||
draft: Box::new(out.draft),
|
||||
document: b"A bytes".to_vec(),
|
||||
idempotency_key: out.idempotency_key,
|
||||
send: true,
|
||||
});
|
||||
|
||||
let (_, create) = hold.take(|r| matches!(r, Request::Create { .. }));
|
||||
create.answer(Answer::Created(envelope_for("doc-A", "alice")));
|
||||
dialog.pump(1.0);
|
||||
|
||||
assert!(
|
||||
dialog.envelope.is_none(),
|
||||
"doc-A's envelope, submitted after reopening doc-B, installed into doc-B's dialog: {:?}",
|
||||
dialog.envelope.as_ref().map(|e| e.id.clone())
|
||||
);
|
||||
}
|
||||
|
||||
/// An untaken `SendRequest` is specific to the context that queued it; it
|
||||
/// must not survive into a reopened dialog for another document.
|
||||
#[test]
|
||||
fn an_untaken_send_request_does_not_survive_reopening_for_another_document() {
|
||||
let (mut dialog, _hold) = ready();
|
||||
dialog.open("doc-A".into(), "A.pdf".into(), None, who("alice"));
|
||||
dialog.add_email("bob@example.com".into());
|
||||
dialog.queue_send();
|
||||
|
||||
dialog.open("doc-B".into(), "B.pdf".into(), None, who("alice"));
|
||||
|
||||
assert!(dialog.take_send_request().is_none(), "doc-B's dialog still held doc-A's untaken send request");
|
||||
}
|
||||
|
||||
/// `note_create_result` is the synchronous twin of `submit_request`: an app
|
||||
/// that handles create itself, rather than through the backend channel,
|
||||
/// reports the outcome here. It must drop a result for a context the dialog
|
||||
/// has already left, exactly as a channel reply would.
|
||||
#[test]
|
||||
fn note_create_result_for_a_previous_document_does_not_install_in_the_reopened_dialog() {
|
||||
let (mut dialog, _hold) = ready();
|
||||
dialog.open("doc-A".into(), "A.pdf".into(), None, who("alice"));
|
||||
dialog.add_email("bob@example.com".into());
|
||||
dialog.queue_send();
|
||||
let _out = dialog.take_send_request().expect("send produced a request");
|
||||
|
||||
dialog.open("doc-B".into(), "B.pdf".into(), None, who("alice"));
|
||||
dialog.note_create_result(Ok(envelope_for("doc-A", "alice")));
|
||||
|
||||
assert!(
|
||||
dialog.envelope.is_none(),
|
||||
"doc-A's result, reported after reopening doc-B, installed into doc-B's dialog: {:?}",
|
||||
dialog.envelope.as_ref().map(|e| e.id.clone())
|
||||
);
|
||||
}
|
||||
|
||||
/// `Replier::dup` is the only way a backend can answer one sequence twice.
|
||||
/// The dialog answers the first reply normally, but a second reply for the
|
||||
/// same (already resolved) sequence must drop unconditionally, not reach
|
||||
/// the match arms with no context left to check against.
|
||||
#[test]
|
||||
fn a_duplicated_answer_for_an_already_resolved_sequence_is_dropped() {
|
||||
let (mut dialog, hold) = ready();
|
||||
dialog.open("doc-A".into(), "A.pdf".into(), None, who("alice"));
|
||||
send(&mut dialog, b"A bytes");
|
||||
|
||||
let (_, create) = hold.take(|r| matches!(r, Request::Create { .. }));
|
||||
let dup = create.dup();
|
||||
create.answer(Answer::Created(envelope_for("doc-A", "alice")));
|
||||
dialog.pump(1.0);
|
||||
assert_eq!(dialog.envelope.as_ref().map(|e| e.id.clone()), Some("env-doc-A".to_owned()), "the first answer should have installed normally");
|
||||
|
||||
// The dialog moves on; a backend still holding `dup` from the first
|
||||
// request answers it again.
|
||||
dialog.open("doc-B".into(), "B.pdf".into(), None, who("alice"));
|
||||
dup.answer(Answer::Created(envelope_for("doc-A", "alice")));
|
||||
dialog.pump(2.0);
|
||||
|
||||
let shown = dialog.envelope.as_ref().and_then(|e| e.document_id.clone());
|
||||
assert!(
|
||||
shown.is_none() || shown.as_deref() == Some("doc-B"),
|
||||
"a duplicate answer for the first request reinstalled doc-A's envelope into doc-B's dialog: {shown:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// `busy` belongs to whichever operation is still pending. A lookup that
|
||||
/// fails while a create is genuinely in flight must not report the create
|
||||
/// as finished.
|
||||
#[test]
|
||||
fn a_failed_lookup_does_not_clear_busy_for_a_pending_create() {
|
||||
let (mut dialog, hold) = ready();
|
||||
dialog.open("doc-A".into(), "A.pdf".into(), None, who("alice"));
|
||||
send(&mut dialog, b"A bytes");
|
||||
assert!(dialog.busy, "queue_send should have left the dialog busy");
|
||||
|
||||
dialog.query = "ca".into();
|
||||
dialog.query_changed_at = 0.0;
|
||||
dialog.maybe_lookup(1.0);
|
||||
let (_, lookup) = hold.take(|r| matches!(r, Request::Lookup { .. }));
|
||||
lookup.refuse("lookup failed");
|
||||
dialog.pump(2.0);
|
||||
|
||||
assert!(dialog.busy, "a failed lookup cleared busy while the create for doc-A was still pending");
|
||||
}
|
||||
|
||||
/// Two "Refresh status" clicks before either reply arrives race two
|
||||
/// `Request::Status` calls. If the older one answers after the newer one
|
||||
/// already installed, it must not overwrite the newer status.
|
||||
#[test]
|
||||
fn an_older_status_reply_does_not_overwrite_a_newer_one() {
|
||||
let (mut dialog, hold) = ready();
|
||||
dialog.open("doc-A".into(), "A.pdf".into(), None, who("alice"));
|
||||
send(&mut dialog, b"A bytes");
|
||||
let (_, create) = hold.take(|r| matches!(r, Request::Create { .. }));
|
||||
create.answer(Answer::Created(envelope_for("doc-A", "alice")));
|
||||
dialog.pump(1.0);
|
||||
let env_id = dialog.envelope.as_ref().expect("created").id.clone();
|
||||
|
||||
dialog.busy = true;
|
||||
let seq1 = dialog.submit_in_context(Request::Status { envelope: env_id.clone() });
|
||||
dialog.pending_op_seq = Some(seq1);
|
||||
dialog.status_seq = seq1;
|
||||
dialog.busy = true;
|
||||
let seq2 = dialog.submit_in_context(Request::Status { envelope: env_id.clone() });
|
||||
dialog.pending_op_seq = Some(seq2);
|
||||
dialog.status_seq = seq2;
|
||||
|
||||
let (_, status1) = hold.take(|r| matches!(r, Request::Status { .. }));
|
||||
let (_, status2) = hold.take(|r| matches!(r, Request::Status { .. }));
|
||||
|
||||
// The newer request (seq2) answers first.
|
||||
status2.answer(Answer::Status(Envelope { status: EnvelopeStatus::Completed, ..envelope_for("doc-A", "alice") }));
|
||||
dialog.pump(2.0);
|
||||
assert_eq!(dialog.envelope.as_ref().map(|e| e.status), Some(EnvelopeStatus::Completed));
|
||||
|
||||
// The older request (seq1), issued first, answers last.
|
||||
status1.answer(Answer::Status(Envelope { status: EnvelopeStatus::Sent, ..envelope_for("doc-A", "alice") }));
|
||||
dialog.pump(3.0);
|
||||
assert_eq!(dialog.envelope.as_ref().map(|e| e.status), Some(EnvelopeStatus::Completed), "an older status reply overwrote a newer one");
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
//! Regression tests for CodeRabbit's second review pass on PR #661,
|
||||
//! reproduced against 1e84947c (storytold/craft-libs#661).
|
||||
//!
|
||||
//! Reuses `review_repro`'s `Hold` backend and helpers, the same as
|
||||
//! `coderabbit_repro`.
|
||||
|
||||
use craft_esign::{Envelope, EnvelopeStatus};
|
||||
|
||||
use super::review_repro::{Hold, envelope_for, ready, send, who};
|
||||
use super::*;
|
||||
|
||||
/// A host can drive `Request::Status` through the public `submit_request`
|
||||
/// path directly, not only through `status_panel`'s own "Refresh status"
|
||||
/// button. That path must register `status_seq` too, or the reply it
|
||||
/// produces fails the supersession guard added for the button's path and is
|
||||
/// dropped.
|
||||
#[test]
|
||||
fn submit_request_for_a_public_status_submission_registers_status_seq() {
|
||||
let (mut dialog, hold) = ready();
|
||||
dialog.open("doc-A".into(), "A.pdf".into(), None, who("alice"));
|
||||
send(&mut dialog, b"A bytes");
|
||||
let (_, create) = hold.take(|r| matches!(r, Request::Create { .. }));
|
||||
create.answer(Answer::Created(envelope_for("doc-A", "alice")));
|
||||
dialog.pump(1.0);
|
||||
let env_id = dialog.envelope.as_ref().expect("created").id.clone();
|
||||
|
||||
dialog.submit_request(Request::Status { envelope: env_id });
|
||||
let (_, status) = hold.take(|r| matches!(r, Request::Status { .. }));
|
||||
status.answer(Answer::Status(Envelope { status: EnvelopeStatus::Completed, ..envelope_for("doc-A", "alice") }));
|
||||
dialog.pump(2.0);
|
||||
|
||||
assert_eq!(
|
||||
dialog.envelope.as_ref().map(|e| e.status),
|
||||
Some(EnvelopeStatus::Completed),
|
||||
"a Status reply submitted through the public submit_request path was dropped by the status_seq guard"
|
||||
);
|
||||
}
|
||||
|
||||
/// `available()` stops asking again once the service has reported
|
||||
/// `Envelopes`, so a backend whose `linked` value changes out of band (the
|
||||
/// user signs in after the dialog already probed) is never re-asked unless
|
||||
/// something clears the cached capabilities. `reset_capabilities` is that
|
||||
/// something, on the same backend instance.
|
||||
#[test]
|
||||
fn reset_capabilities_reprobes_the_same_backend_after_an_out_of_band_sign_in() {
|
||||
let hold = Hold::default();
|
||||
let mut dialog = EsignDialog::default();
|
||||
dialog.set_backend(hold.clone());
|
||||
dialog.pump(0.0);
|
||||
let (_, caps1) = hold.take(|r| matches!(r, Request::Capabilities));
|
||||
caps1.answer(Answer::Capabilities { capabilities: vec![EsignCapability::Envelopes], responsible_party: "Stub Signing".into(), linked: false });
|
||||
dialog.pump(0.1);
|
||||
assert!(dialog.available());
|
||||
assert!(!dialog.linked);
|
||||
|
||||
// Available is already true, so pump's own retry condition
|
||||
// (`!available() && ...`) never fires again on its own, no matter how
|
||||
// much time passes.
|
||||
for t in 0..5 {
|
||||
dialog.pump(0.2 + f64::from(t));
|
||||
}
|
||||
|
||||
// The user signs in; nothing about the backend instance changes, so
|
||||
// only an explicit reset asks again.
|
||||
dialog.reset_capabilities();
|
||||
dialog.pump(1.0);
|
||||
let (_, caps2) = hold.take(|r| matches!(r, Request::Capabilities));
|
||||
caps2.answer(Answer::Capabilities { capabilities: vec![EsignCapability::Envelopes], responsible_party: "Stub Signing".into(), linked: true });
|
||||
dialog.pump(1.1);
|
||||
|
||||
assert!(dialog.linked, "reset_capabilities did not pick up the backend's new linked state");
|
||||
}
|
||||
|
||||
/// The captured send context belongs only to the create submission that
|
||||
/// answers a taken [`SendRequest`]. A status refresh submitted for the
|
||||
/// current document while another document's send is still outstanding must
|
||||
/// carry the current context, or `pump` drops its reply as belonging to the
|
||||
/// abandoned send.
|
||||
#[test]
|
||||
fn status_for_the_current_document_is_not_consumed_by_an_outstanding_send_from_another() {
|
||||
let (mut dialog, hold) = ready();
|
||||
|
||||
// Document A's send is taken by the app but never submitted: its captured
|
||||
// context stays pending. The `send` helper would submit the create and
|
||||
// consume that context, which is exactly what this test must avoid.
|
||||
dialog.open("doc-A".into(), "A.pdf".into(), None, who("alice"));
|
||||
dialog.add_email("bob@example.com".into());
|
||||
dialog.queue_send();
|
||||
let taken = dialog.take_send_request();
|
||||
assert!(taken.is_some(), "A's send request was taken, leaving its context pending");
|
||||
|
||||
// The dialog moves on to document B, which already has an envelope the
|
||||
// host wants a status for.
|
||||
dialog.open("doc-B".into(), "B.pdf".into(), None, who("alice"));
|
||||
dialog.envelope = Some(envelope_for("doc-B", "alice"));
|
||||
let env_id = dialog.envelope.as_ref().map(|e| e.id.clone()).unwrap_or_default();
|
||||
|
||||
dialog.submit_request(Request::Status { envelope: env_id });
|
||||
let (_, status) = hold.take(|r| matches!(r, Request::Status { .. }));
|
||||
status.answer(Answer::Status(Envelope { status: EnvelopeStatus::Completed, ..envelope_for("doc-B", "alice") }));
|
||||
dialog.pump(1.0);
|
||||
|
||||
assert_eq!(
|
||||
dialog.envelope.as_ref().map(|e| e.status),
|
||||
Some(EnvelopeStatus::Completed),
|
||||
"B's status reply was dropped because the status request consumed A's outstanding send context"
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,153 @@
|
||||
//! Regression tests for the three gate items skylartaylor raised on PR #661,
|
||||
//! reproduced against 0a937ef (storytold/craft-libs#661):
|
||||
//! <https://gist.github.com/skylartaylor/c1108ecf20d63c5e3183947408ddab7a>.
|
||||
//!
|
||||
//! `Hold` is a backend that keeps every request and its `Replier` so a test
|
||||
//! chooses when, and in what order, the service answers.
|
||||
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use craft_cloud::Identity;
|
||||
use craft_esign::{Envelope, EnvelopeStatus, EsignCapability};
|
||||
|
||||
use super::*;
|
||||
|
||||
/// Reused by `coderabbit_repro`, the regression tests for the CodeRabbit
|
||||
/// findings reviewed on the same pull request.
|
||||
#[derive(Clone, Default)]
|
||||
pub(super) struct Hold(Arc<Mutex<Vec<(Request, Replier)>>>);
|
||||
|
||||
impl EsignBackend for Hold {
|
||||
fn submit(&self, request: Request, reply: Replier) {
|
||||
self.0.lock().unwrap().push((request, reply));
|
||||
}
|
||||
}
|
||||
|
||||
impl Hold {
|
||||
/// Takes the oldest held request matching `pick`.
|
||||
pub(super) fn take(&self, pick: impl Fn(&Request) -> bool) -> (Request, Replier) {
|
||||
let mut held = self.0.lock().unwrap();
|
||||
let i = held.iter().position(|(r, _)| pick(r)).expect("request was submitted");
|
||||
held.remove(i)
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn who(id: &str) -> Identity {
|
||||
Identity { id: id.into(), display: id.into(), email: Some(format!("{id}@example.com")), avatar: None }
|
||||
}
|
||||
|
||||
pub(super) fn envelope_for(doc: &str, sender: &str) -> Envelope {
|
||||
Envelope {
|
||||
id: format!("env-{doc}"),
|
||||
title: format!("Contract {doc}"),
|
||||
message: None,
|
||||
sender: who(sender),
|
||||
document_id: Some(doc.into()),
|
||||
document_etag: None,
|
||||
content_sha256: String::new(),
|
||||
recipients: Vec::new(),
|
||||
placements: Vec::new(),
|
||||
status: EnvelopeStatus::Sent,
|
||||
expires: None,
|
||||
created: None,
|
||||
completed_at: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// A dialog with a held backend whose capabilities probe has been answered.
|
||||
pub(super) fn ready() -> (EsignDialog, Hold) {
|
||||
let hold = Hold::default();
|
||||
let mut dialog = EsignDialog::default();
|
||||
dialog.set_backend(hold.clone());
|
||||
dialog.pump(0.0); // submits Capabilities
|
||||
let (_, caps) = hold.take(|r| matches!(r, Request::Capabilities));
|
||||
caps.answer(Answer::Capabilities {
|
||||
capabilities: vec![EsignCapability::Envelopes, EsignCapability::Void],
|
||||
responsible_party: "Stub Signing".into(),
|
||||
linked: true,
|
||||
});
|
||||
dialog.pump(0.1);
|
||||
assert!(dialog.available());
|
||||
(dialog, hold)
|
||||
}
|
||||
|
||||
/// The app's Send path: queue_send -> take_send_request -> submit Create.
|
||||
pub(super) fn send(dialog: &mut EsignDialog, doc_bytes: &[u8]) {
|
||||
dialog.add_email("bob@example.com".into());
|
||||
dialog.queue_send();
|
||||
let out = dialog.take_send_request().expect("Send produced a request");
|
||||
dialog.submit_request(Request::Create {
|
||||
draft: Box::new(out.draft),
|
||||
document: doc_bytes.to_vec(),
|
||||
idempotency_key: out.idempotency_key,
|
||||
send: true,
|
||||
});
|
||||
}
|
||||
|
||||
/// Gate item 1 (document variant): the dialog is reopened for document B
|
||||
/// while document A's create is in flight. A's late reply carries document
|
||||
/// A's context and must not be installed as document B's envelope.
|
||||
#[test]
|
||||
fn review_h5_reply_for_previous_document_is_installed_after_reopen() {
|
||||
let (mut dialog, hold) = ready();
|
||||
dialog.open("doc-A".into(), "A.pdf".into(), None, who("alice"));
|
||||
send(&mut dialog, b"A bytes");
|
||||
dialog.open("doc-B".into(), "B.pdf".into(), None, who("alice"));
|
||||
|
||||
let (_, create_a) = hold.take(|r| matches!(r, Request::Create { .. }));
|
||||
create_a.answer(Answer::Created(envelope_for("doc-A", "alice")));
|
||||
dialog.pump(1.0);
|
||||
|
||||
let shown = dialog.envelope.as_ref().and_then(|e| e.document_id.clone());
|
||||
assert!(
|
||||
shown.is_none() || shown.as_deref() == Some("doc-B"),
|
||||
"dialog is open for doc-B but shows the envelope for {shown:?} (status panel: Void/Remind act on it); busy={}",
|
||||
dialog.busy
|
||||
);
|
||||
}
|
||||
|
||||
/// Gate item 1 (account variant): reopened for the same document under
|
||||
/// another signed-in account. Alice's envelope must never render for
|
||||
/// mallory.
|
||||
#[test]
|
||||
fn review_h5_reply_for_previous_account_is_installed_after_account_switch() {
|
||||
let (mut dialog, hold) = ready();
|
||||
dialog.open("doc-A".into(), "A.pdf".into(), None, who("alice"));
|
||||
send(&mut dialog, b"A bytes");
|
||||
dialog.open("doc-A".into(), "A.pdf".into(), None, who("mallory"));
|
||||
|
||||
let (_, create) = hold.take(|r| matches!(r, Request::Create { .. }));
|
||||
create.answer(Answer::Created(envelope_for("doc-A", "alice")));
|
||||
dialog.pump(1.0);
|
||||
|
||||
let shown = dialog.envelope.as_ref().map(|e| e.sender.id.clone());
|
||||
assert!(shown.is_none() || shown.as_deref() == Some("mallory"), "dialog now belongs to mallory but shows alice's envelope: sender={shown:?}");
|
||||
}
|
||||
|
||||
/// Gate item 2: Send is in flight; the user types in the signer search box
|
||||
/// (a lookup is submitted, which used to bump the old staleness counter).
|
||||
/// The create reply then arrives for the same context and must still
|
||||
/// install: typing in a search box is not a context change.
|
||||
#[test]
|
||||
fn review_n1_create_reply_dropped_after_a_lookup_leaves_dialog_busy() {
|
||||
let (mut dialog, hold) = ready();
|
||||
dialog.open("doc-A".into(), "A.pdf".into(), None, who("alice"));
|
||||
send(&mut dialog, b"A bytes");
|
||||
assert!(dialog.busy);
|
||||
|
||||
dialog.query = "ca".into(); // typed after pressing Send
|
||||
dialog.query_changed_at = 1.0;
|
||||
dialog.maybe_lookup(2.0);
|
||||
|
||||
let (_, create) = hold.take(|r| matches!(r, Request::Create { .. }));
|
||||
create.answer(Answer::Created(envelope_for("doc-A", "alice")));
|
||||
for t in 0..10 {
|
||||
dialog.pump(3.0 + f64::from(t));
|
||||
}
|
||||
assert!(
|
||||
!dialog.busy && dialog.envelope.is_some(),
|
||||
"provider created env-doc-A but dialog busy={} envelope={:?} (reply dropped as stale)",
|
||||
dialog.busy,
|
||||
dialog.envelope.as_ref().map(|e| e.id.clone())
|
||||
);
|
||||
}
|
||||
@@ -15,6 +15,8 @@ pub mod cloud;
|
||||
pub mod combo;
|
||||
pub mod direction;
|
||||
pub mod docking;
|
||||
#[cfg(feature = "esign")]
|
||||
pub mod esign;
|
||||
mod focus;
|
||||
pub mod fonts;
|
||||
pub mod icons;
|
||||
|
||||
+23
-1
@@ -279,6 +279,7 @@ fn find_end(data: &[u8]) -> Result<(u64, u64, u64, usize), ZipError> {
|
||||
// it from an empty EOCD-shaped record inside the preceding archive's comment. Keep it as a
|
||||
// last resort while searching for an older, structurally stronger candidate.
|
||||
let mut empty_sfx = None;
|
||||
let mut measured_directory = None;
|
||||
let mut fallback = None;
|
||||
// Fake EOCD records in a comment can all describe the same large directory. Cache binary
|
||||
// directory jumps so checking each candidate does not rescan every entry.
|
||||
@@ -318,6 +319,21 @@ fn find_end(data: &[u8]) -> Result<(u64, u64, u64, usize), ZipError> {
|
||||
let Some((_, shift)) = locate_directory(data, count.into(), size.into(), offset.into(), candidate)
|
||||
.filter(|&(dir, _)| directory_is_exact(data, dir, size.into(), count.into(), &mut directory_jumps))
|
||||
else {
|
||||
// An overstated size is safe to ignore only when the recorded entries fill
|
||||
// the byte range from the declared offset to this single-disk end record.
|
||||
// The classic entry count is below MAX_ENTRIES, so the walk checks every entry.
|
||||
if count != 0
|
||||
&& u32_at(data, candidate + 4) == Some(0)
|
||||
&& u16_at(data, candidate + 8) == Some(count)
|
||||
&& let Ok(start) = usize::try_from(offset)
|
||||
&& let Some(measured) = candidate.checked_sub(start).and_then(|n| u32::try_from(n).ok())
|
||||
&& measured < size
|
||||
&& directory_is_exact(data, start, measured.into(), count.into(), &mut directory_jumps)
|
||||
{
|
||||
// Keep scanning for a valid declared size. Among measured candidates,
|
||||
// prefer the earliest record so a copy in its comment cannot hide it.
|
||||
measured_directory = Some((count.into(), measured.into(), offset.into(), candidate));
|
||||
}
|
||||
continue;
|
||||
};
|
||||
if count == 0 && shift > 0 {
|
||||
@@ -328,7 +344,13 @@ fn find_end(data: &[u8]) -> Result<(u64, u64, u64, usize), ZipError> {
|
||||
eocd = Some(candidate);
|
||||
break;
|
||||
}
|
||||
let eocd = eocd.or(empty_sfx).or(fallback).ok_or(ZipError::NotZip)?;
|
||||
let eocd = eocd.or(empty_sfx);
|
||||
if eocd.is_none()
|
||||
&& let Some(directory) = measured_directory
|
||||
{
|
||||
return Ok(directory);
|
||||
}
|
||||
let eocd = eocd.or(fallback).ok_or(ZipError::NotZip)?;
|
||||
let field16 = |o: usize| u16_at(data, eocd + o).ok_or(ZipError::Damaged("the end record is cut short"));
|
||||
let field32 = |o: usize| u32_at(data, eocd + o).ok_or(ZipError::Damaged("the end record is cut short"));
|
||||
let (disk, dir_disk, on_disk, count) = (field16(4)?, field16(6)?, field16(8)?, field16(10)?);
|
||||
|
||||
@@ -108,6 +108,23 @@ fn damaged_archives_are_errors() {
|
||||
assert!(Archive::open(&z).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_a_directory_with_an_overstated_size() {
|
||||
let mut z = zip(&[("DOMDocument.xml", b"<DOMDocument/>", true), ("LIBRARY/ball.xml", b"<DOMSymbolItem/>", false)]);
|
||||
let end = z.len() - 22;
|
||||
let size = u32_at(&z, end + 12).unwrap();
|
||||
z[end + 12..end + 16].copy_from_slice(&(size + 13).to_le_bytes());
|
||||
|
||||
let archive = Archive::open(&z).unwrap();
|
||||
assert_eq!(archive.counts().0, 2);
|
||||
assert_eq!(archive.read("DOMDocument.xml").unwrap().unwrap(), b"<DOMDocument/>");
|
||||
assert_eq!(archive.read("LIBRARY/ball.xml").unwrap().unwrap(), b"<DOMSymbolItem/>");
|
||||
|
||||
// Keep the overstated end record but remove the last byte of the final entry's name.
|
||||
z.remove(end - 1);
|
||||
assert_eq!(Archive::open(&z).err(), Some(ZipError::Damaged("the central directory is outside the archive")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_truncated_central_directory_is_damaged() {
|
||||
let z = zip(&[("DOMDocument.xml", b"<DOMDocument/>", true), ("b.xml", b"<b/>", true), ("c.xml", b"<c/>", false)]);
|
||||
@@ -306,6 +323,32 @@ fn nonempty_comment_eocd_candidate_does_not_mask_valid_archive() {
|
||||
assert_eq!(archive.read("a.xml").unwrap().unwrap(), b"x");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overstated_comment_eocd_does_not_mask_valid_archive() {
|
||||
let mut bytes = zip(&[("a.xml", b"x", false)]);
|
||||
let end = bytes.len() - 22;
|
||||
let size = u32_at(&bytes, end + 12).unwrap();
|
||||
let start = u32_at(&bytes, end + 16).unwrap() as usize;
|
||||
let fake_start = bytes.len();
|
||||
|
||||
// Copy the directory and end record into the real comment, then corrupt the copies.
|
||||
bytes.extend_from_within(start..);
|
||||
let comment_len = u16::try_from(bytes.len() - fake_start).unwrap();
|
||||
bytes[end + 20..end + 22].copy_from_slice(&comment_len.to_le_bytes());
|
||||
bytes[fake_start + 42..fake_start + 46].copy_from_slice(&1u32.to_le_bytes());
|
||||
let fake_end = bytes.len() - 22;
|
||||
bytes[fake_end + 12..fake_end + 16].copy_from_slice(&(size + 1).to_le_bytes());
|
||||
bytes[fake_end + 16..fake_end + 20].copy_from_slice(&u32::try_from(fake_start).unwrap().to_le_bytes());
|
||||
|
||||
let archive = Archive::open(&bytes).unwrap();
|
||||
assert_eq!(archive.read("a.xml").unwrap().unwrap(), b"x");
|
||||
|
||||
// If both candidates need recovery, the record before the comment still wins.
|
||||
bytes[end + 12..end + 16].copy_from_slice(&(size + 1).to_le_bytes());
|
||||
let archive = Archive::open(&bytes).unwrap();
|
||||
assert_eq!(archive.read("a.xml").unwrap().unwrap(), b"x");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeated_eocd_directory_candidates_reuse_entry_validation() {
|
||||
let entries = (0..1024).map(|index| Raw::new(&format!("entry-{index:04}.xml"), b"", false)).collect::<Vec<_>>();
|
||||
|
||||
@@ -108,6 +108,15 @@ impl<'a> Archive<'a> {
|
||||
Ok(Some(file.is_dir()))
|
||||
}
|
||||
|
||||
/// Declared decoded and compressed sizes at `index`, without name lookup.
|
||||
pub fn entry_sizes(&mut self, index: usize) -> Result<Option<(u64, u64)>, Error> {
|
||||
if index >= self.zip.len() {
|
||||
return Ok(None);
|
||||
}
|
||||
let file = self.zip.by_index_raw(index).map_err(|e| Error::NotZip(e.to_string()))?;
|
||||
Ok(Some((file.size(), file.compressed_size())))
|
||||
}
|
||||
|
||||
/// Do two entries share a name? `zip` then keeps one of them, and which one a writer meant
|
||||
/// is not known: a format that must not guess refuses the archive.
|
||||
pub fn has_duplicate_names(&self) -> bool {
|
||||
@@ -178,6 +187,20 @@ impl<'a> Archive<'a> {
|
||||
/// Only the bytes of a read that succeeds are charged to the total.
|
||||
pub fn read(&mut self, name: &str, max: u64) -> Result<Option<Vec<u8>>, Error> {
|
||||
let Some(index) = self.zip.index_for_name(name) else { return Ok(None) };
|
||||
self.read_index_named(index, name, max)
|
||||
}
|
||||
|
||||
/// Read the entry at `index` under the same size, checksum and aggregate budget
|
||||
/// rules as [`Self::read`], without repeating a decoded-name lookup.
|
||||
pub fn read_index(&mut self, index: usize, max: u64) -> Result<Option<Vec<u8>>, Error> {
|
||||
if index >= self.zip.len() {
|
||||
return Ok(None);
|
||||
}
|
||||
let name = self.entry_name(index)?.unwrap_or_default();
|
||||
self.read_index_named(index, &name, max)
|
||||
}
|
||||
|
||||
fn read_index_named(&mut self, index: usize, name: &str, max: u64) -> Result<Option<Vec<u8>>, Error> {
|
||||
let entry = |msg: String| Error::Entry { name: name.to_string(), msg };
|
||||
let f = self.zip.by_index(index).map_err(|e| entry(e.to_string()))?;
|
||||
let declared = f.size();
|
||||
@@ -213,6 +236,32 @@ impl Archive<'static> {
|
||||
mod ownership_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn named_read_preserves_entry_error_for_a_corrupt_local_header() {
|
||||
let mut writer = crate::Writer::new();
|
||||
writer.add("a", b"abc", crate::Compression::Stored).unwrap();
|
||||
let mut bytes = writer.finish().unwrap();
|
||||
bytes[0] = 0; // The central directory remains valid; the local signature does not.
|
||||
let mut archive = Archive::open(&bytes, Limits { max_entries: 1, max_total_bytes: 3 }).unwrap();
|
||||
assert!(matches!(archive.read("a", 3), Err(Error::Entry { name, .. }) if name == "a"));
|
||||
assert_eq!(archive.budget().remaining(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn indexed_reads_charge_the_same_budget_and_enforce_entry_limits() {
|
||||
let mut writer = crate::Writer::new();
|
||||
writer.add("a", b"abc", crate::Compression::Stored).unwrap();
|
||||
writer.add("b", b"def", crate::Compression::Deflated).unwrap();
|
||||
let bytes = writer.finish().unwrap();
|
||||
let mut archive = Archive::open(&bytes, Limits { max_entries: 2, max_total_bytes: 5 }).unwrap();
|
||||
assert!(archive.read_index(0, 2).is_err());
|
||||
assert_eq!(archive.read_index(0, 3).unwrap().unwrap(), b"abc");
|
||||
assert!(archive.read_index(1, 3).is_err());
|
||||
assert_eq!(archive.read_index(2, 3).unwrap(), None);
|
||||
assert_eq!(archive.entry_sizes(0).unwrap(), Some((3, 3)));
|
||||
assert_eq!(archive.entry_sizes(2).unwrap(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn owned_storage_lives_until_last_archive_clone_is_dropped() {
|
||||
let bytes = crate::Writer::new().finish().unwrap();
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
# Full validation
|
||||
|
||||
The fast Workspace workflow intentionally samples hostile-input/proptest cases and primarily
|
||||
runs all features. It is not evidence of full default-feature runtime or doctest coverage.
|
||||
|
||||
Add the `full-validation` label to a pull request to start the separate Full validation workflow.
|
||||
Keep it on the pull request so each new push receives full checks. The workflow checks the PR
|
||||
merge ref using `pull_request`, never `pull_request_target`, and does not inherit secrets.
|
||||
A workflow dispatch validates the selected repository ref; it is not evidence for another PR SHA.
|
||||
|
||||
Before treating a candidate as fully validated, verify on its current head/merge ref:
|
||||
|
||||
- All three `Full native / gate` checks actually ran and succeeded (Linux, Windows, macOS).
|
||||
- Both workspace test configurations ran with `cargo test`: default and all features, including
|
||||
their doctests and Cargo's ordinary example compilation/linking. Both clippy configurations
|
||||
and formatting checks also pass. No hostile divisor or proptest case override is set.
|
||||
- All three `Full PDF contracts / gate` checks ran and succeeded, including the Unicode fixture
|
||||
cfg and the separate read-only-contract manifest. Linux-only generic tests do not replace them.
|
||||
- The normal MSRV, WASM and applicable specialized workflow checks pass too. This optional
|
||||
workflow does not replace those checks, Sonar analysis, independent review, or branch rules.
|
||||
|
||||
An unlabelled PR's skipped Full validation jobs are not a full-validation pass. The label is an
|
||||
opt-in mechanism, not a branch-protection change or a merge authorization. A new base/head may
|
||||
need a fresh full run. Do not dispatch another copy when the matching run is already active.
|
||||
|
||||
The existing fast path and nightly workflow are left unchanged. This workflow is separate from
|
||||
platform-selection and lint/cache optimization work in #2113. Its native commands deliberately
|
||||
retain the repository's `cargo test --workspace` pre-merge requirement.
|
||||
@@ -0,0 +1,13 @@
|
||||
#!/usr/bin/env bash
|
||||
# Restore both runtime feature configurations, docs and ordinary example linking, without fuzz caps.
|
||||
set -euo pipefail
|
||||
unset CRAFT_HOSTILE_DIVISOR PROPTEST_CASES
|
||||
if [ "${RUNNER_OS:-}" = Windows ]; then
|
||||
powershell.exe -NoProfile -Command '$ErrorActionPreference = "Stop"; Start-Service Spooler; Add-PrinterDriver -Name "Generic / Text Only"'
|
||||
fi
|
||||
cargo fmt --check
|
||||
cargo clippy --workspace --all-targets --locked -- -D warnings
|
||||
cargo clippy --workspace --all-targets --all-features --locked -- -D warnings
|
||||
# cargo test includes docs and ordinary example linking, as required by AGENTS.md.
|
||||
cargo test --workspace --locked
|
||||
cargo test --workspace --all-features --locked
|
||||
@@ -0,0 +1,124 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Exercise the full gate's command sequence without building Rust locally."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SCRIPT = ROOT / "scripts/ci-full-validation.sh"
|
||||
# Actions uses Git Bash on Windows; Python's PATH search can instead select the WSL launcher.
|
||||
BASH = (str(Path(os.environ.get("ProgramFiles", r"C:\Program Files")) / "Git/bin/bash.exe")
|
||||
if sys.platform == "win32" else "bash")
|
||||
COMMANDS = [
|
||||
"fmt --check",
|
||||
"clippy --workspace --all-targets --locked -- -D warnings",
|
||||
"clippy --workspace --all-targets --all-features --locked -- -D warnings",
|
||||
"test --workspace --locked",
|
||||
"test --workspace --all-features --locked",
|
||||
]
|
||||
|
||||
|
||||
# Validate the real script, but execute only this fixed, reviewed command sequence.
|
||||
# Repository-file bytes must never become bash -c source in a mock-only harness.
|
||||
SOURCE = r"""
|
||||
set -euo pipefail
|
||||
unset CRAFT_HOSTILE_DIVISOR PROPTEST_CASES
|
||||
if [ "${RUNNER_OS:-}" = Windows ]; then
|
||||
powershell.exe -NoProfile -Command '$ErrorActionPreference = "Stop"; Start-Service Spooler; Add-PrinterDriver -Name "Generic / Text Only"'
|
||||
fi
|
||||
cargo fmt --check
|
||||
cargo clippy --workspace --all-targets --locked -- -D warnings
|
||||
cargo clippy --workspace --all-targets --all-features --locked -- -D warnings
|
||||
cargo test --workspace --locked
|
||||
cargo test --workspace --all-features --locked
|
||||
"""
|
||||
|
||||
|
||||
def source_lines(text):
|
||||
return [line.strip() for line in text.splitlines()
|
||||
if line.strip() and not line.lstrip().startswith("#")]
|
||||
|
||||
|
||||
def run(os_name, fail=""):
|
||||
if source_lines(SCRIPT.read_text()) != source_lines(SOURCE):
|
||||
raise AssertionError("full validation command sequence changed")
|
||||
env = dict(os.environ, RUNNER_OS=os_name, FAIL=fail,
|
||||
CRAFT_HOSTILE_DIVISOR="8", PROPTEST_CASES="64")
|
||||
mock = r"""
|
||||
cargo() {
|
||||
test -z "${CRAFT_HOSTILE_DIVISOR+x}" && test -z "${PROPTEST_CASES+x}" || return 29
|
||||
printf '%s\n' "$*"
|
||||
if [ "$*" = "$FAIL" ]; then return 17; fi
|
||||
}
|
||||
powershell.exe() { printf 'print-queue\n'; }
|
||||
"""
|
||||
return subprocess.run([BASH, "-c", mock + SOURCE], env=env,
|
||||
capture_output=True, text=True, check=False)
|
||||
|
||||
|
||||
class FullValidation(unittest.TestCase):
|
||||
def test_changed_source_is_rejected_without_execution(self):
|
||||
for source in [
|
||||
SOURCE + "\necho injected",
|
||||
SOURCE.replace("cargo fmt --check", "cargo fmt --check; echo injected"),
|
||||
SOURCE.replace("cargo fmt --check", "cargo fmt $(echo injected) --check"),
|
||||
SOURCE.replace("cargo test --workspace --locked", ""),
|
||||
SOURCE + "\ncargo test --workspace --locked",
|
||||
]:
|
||||
with self.subTest(source=source):
|
||||
with patch.object(Path, "read_text", return_value=source), patch.object(subprocess, "run") as execute:
|
||||
with self.assertRaises(AssertionError):
|
||||
run("Linux")
|
||||
execute.assert_not_called()
|
||||
|
||||
def test_comments_and_blank_lines_do_not_change_commands(self):
|
||||
with patch.object(Path, "read_text", return_value="# harmless comment\n\n" + SOURCE):
|
||||
result = run("Linux")
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
self.assertEqual(result.stdout.splitlines(), COMMANDS)
|
||||
|
||||
def test_every_os_runs_both_full_configurations(self):
|
||||
for name in ["Linux", "macOS", "Windows"]:
|
||||
with self.subTest(os=name):
|
||||
p = run(name)
|
||||
self.assertEqual(p.returncode, 0, p.stdout + p.stderr)
|
||||
self.assertEqual(p.stdout.splitlines(),
|
||||
(["print-queue"] if name == "Windows" else []) + COMMANDS)
|
||||
|
||||
def test_every_failure_stops_the_gate(self):
|
||||
for i, command in enumerate(COMMANDS):
|
||||
with self.subTest(command=command):
|
||||
p = run("Linux", command)
|
||||
self.assertEqual(p.returncode, 17, p.stdout + p.stderr)
|
||||
self.assertEqual(p.stdout.splitlines(), COMMANDS[:i + 1])
|
||||
|
||||
def test_workflow_preserves_fork_and_platform_boundaries(self):
|
||||
text = (ROOT / ".github/workflows/full-validation.yml").read_text()
|
||||
self.assertIn("os: '[\"ubuntu-latest\",\"windows-latest\",\"macos-latest\"]'", text)
|
||||
self.assertIn("select-os: '[]'", text)
|
||||
self.assertIn("contents: read", text)
|
||||
self.assertNotIn("pull_request_target", text)
|
||||
self.assertNotIn("secrets:", text)
|
||||
self.assertIn("bash scripts/ci-full-validation.sh", text)
|
||||
self.assertIn("github.event.label.name != 'full-validation' && github.run_id", text)
|
||||
self.assertIn("github.event.action != 'labeled' || github.event.label.name == 'full-validation'", text)
|
||||
self.assertNotIn("CRAFT_HOSTILE_DIVISOR=", text)
|
||||
self.assertNotIn("PROPTEST_CASES=", text)
|
||||
|
||||
def test_pdf_contracts_are_separate_and_uncapped(self):
|
||||
text = (ROOT / ".github/workflows/full-validation.yml").read_text()
|
||||
pdf = text.split(" pdf-contracts:", 1)[1]
|
||||
self.assertIn("RUSTFLAGS=--cfg craft_pdf_unicode_fixtures", pdf)
|
||||
self.assertIn("unset CRAFT_HOSTILE_DIVISOR PROPTEST_CASES", pdf)
|
||||
self.assertIn("cargo test -p craft-pdf --all-features --locked", pdf)
|
||||
self.assertIn("cargo test --manifest-path crates/pdf/read-only-contract/Cargo.toml --locked", pdf)
|
||||
self.assertIn("select-os: '[]'", pdf)
|
||||
self.assertIn("windows-latest", pdf)
|
||||
self.assertIn("macos-latest", pdf)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -5,6 +5,7 @@ import re
|
||||
import subprocess
|
||||
import tomllib
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
@@ -18,19 +19,67 @@ def block(text, name):
|
||||
return "\n".join(line[8:] for line in match[1].splitlines())
|
||||
|
||||
|
||||
def commands(os_name, fail="", name="command"):
|
||||
# Functions avoid executing any caller-supplied cargo command or changing the workspace.
|
||||
# The real bash -euo pipefail semantics still apply, including failures inside a branch.
|
||||
stub = """
|
||||
# Only these literal programs may be exercised. Workflow text is compared, never executed.
|
||||
LINT_SOURCE = """
|
||||
if [ "$RUNNER_OS" = Linux ]; then
|
||||
python3 scripts/test-workspace-concurrency.py
|
||||
python3 scripts/test-workspace-tests.py
|
||||
fi
|
||||
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
|
||||
"""
|
||||
TEST_SOURCE = """
|
||||
cargo nextest run --workspace --all-features --locked --profile ci
|
||||
cargo test --workspace --doc --all-features --locked
|
||||
cargo nextest run -p craft-image-codecs -p craft-text --locked --profile ci
|
||||
"""
|
||||
WINDOWS_SETUP = """powershell.exe -NoProfile -Command '$ErrorActionPreference = "Stop"; Start-Service Spooler; Add-PrinterDriver -Name "Generic / Text Only"'"""
|
||||
EXPECTED_SOURCE = {
|
||||
"lint-command": LINT_SOURCE,
|
||||
"command": TEST_SOURCE,
|
||||
"windows-command": WINDOWS_SETUP + "\n" + TEST_SOURCE,
|
||||
}
|
||||
|
||||
|
||||
def source_lines(source):
|
||||
return [line.strip() for line in source.splitlines()
|
||||
if line.strip() and not line.lstrip().startswith("#")]
|
||||
|
||||
|
||||
def validate_source(text, name):
|
||||
if name not in EXPECTED_SOURCE:
|
||||
raise AssertionError(f"unsupported command block: {name}")
|
||||
if source_lines(block(text, name)) != source_lines(EXPECTED_SOURCE[name]):
|
||||
raise AssertionError(f"unexpected command source: {name}")
|
||||
|
||||
|
||||
# The child shell only receives this checked-in literal, never bytes read from the workflow.
|
||||
HARNESS = """
|
||||
cargo() {
|
||||
printf '%s\\n' "$*"
|
||||
if [ -n "$FAIL" ] && [ "$*" = "$FAIL" ]; then return 17; fi
|
||||
}
|
||||
python3() { :; }
|
||||
case "$BLOCK" in
|
||||
lint-command)
|
||||
""" + LINT_SOURCE + """
|
||||
;;
|
||||
command)
|
||||
""" + TEST_SOURCE + """
|
||||
;;
|
||||
*) exit 29 ;;
|
||||
esac
|
||||
"""
|
||||
|
||||
|
||||
def commands(os_name, fail="", name="command", source=None):
|
||||
validate_source(WORKFLOW.read_text() if source is None else source, name)
|
||||
return subprocess.run(
|
||||
["bash", "-euo", "pipefail", "-c", stub + block(WORKFLOW.read_text(), name)],
|
||||
env={**os.environ, "RUNNER_OS": os_name, "FAIL": fail},
|
||||
["bash", "-euo", "pipefail", "-c", HARNESS],
|
||||
env={**os.environ, "RUNNER_OS": os_name, "FAIL": fail, "BLOCK": name},
|
||||
text=True, capture_output=True, check=False,
|
||||
)
|
||||
|
||||
@@ -49,11 +98,14 @@ TESTS = [
|
||||
|
||||
class WorkspaceTests(unittest.TestCase):
|
||||
def test_every_leg_lints_with_both_feature_sets(self):
|
||||
for os_name in ("Linux", "macOS", "Windows"):
|
||||
# Windows skips only rustfmt: one call with every source root of the workspace is longer
|
||||
# than a Windows command line may be (os error 206), and Linux and macOS check the same
|
||||
# formatting.
|
||||
for os_name, expected in (("Linux", COMMON), ("macOS", COMMON), ("Windows", COMMON[1:])):
|
||||
with self.subTest(os=os_name):
|
||||
result = commands(os_name, name="lint-command")
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertEqual(result.stdout.splitlines(), COMMON)
|
||||
self.assertEqual(result.stdout.splitlines(), expected)
|
||||
|
||||
def test_linux_and_macos_run_one_feature_set_with_doctests(self):
|
||||
for os_name in ("Linux", "macOS"):
|
||||
@@ -71,10 +123,31 @@ class WorkspaceTests(unittest.TestCase):
|
||||
self.assertEqual(result.stdout.splitlines(), stages[:index + 1])
|
||||
|
||||
def test_windows_runs_the_same_tests(self):
|
||||
validate_source(WORKFLOW.read_text(), "windows-command")
|
||||
source = block(WORKFLOW.read_text(), "windows-command")
|
||||
cargo = [line.strip() for line in source.splitlines() if line.strip().startswith("cargo ")]
|
||||
self.assertEqual(cargo, ["cargo " + command for command in TESTS])
|
||||
|
||||
def test_workflow_source_is_rejected_before_starting_any_process(self):
|
||||
source = WORKFLOW.read_text()
|
||||
for payload in ("cargo fmt --check; echo injected", "cargo fmt $(echo injected)",
|
||||
"cargo fmt --check | cat", "cargo fmt --check > injected",
|
||||
"echo injected", "cargo fmt --check\n touch injected"):
|
||||
with self.subTest(payload=payload), patch("subprocess.run") as child:
|
||||
changed = source.replace("cargo fmt --check", payload, 1)
|
||||
with self.assertRaisesRegex(AssertionError, "unexpected command source"):
|
||||
commands("Linux", name="lint-command", source=changed)
|
||||
child.assert_not_called()
|
||||
|
||||
def test_added_or_missing_stage_is_rejected_before_execution(self):
|
||||
source = WORKFLOW.read_text()
|
||||
for replacement in ("", "cargo fmt --check\n cargo fmt --check"):
|
||||
with self.subTest(replacement=replacement), patch("subprocess.run") as child:
|
||||
with self.assertRaisesRegex(AssertionError, "unexpected command source"):
|
||||
commands("Linux", name="lint-command",
|
||||
source=source.replace("cargo fmt --check", replacement, 1))
|
||||
child.assert_not_called()
|
||||
|
||||
def test_ci_profile_keeps_its_failure_policy_without_retries_or_filtering(self):
|
||||
config = tomllib.loads((ROOT / ".config/nextest.toml").read_text())
|
||||
self.assertIs(config["profile"]["ci"]["fail-fast"], False)
|
||||
|
||||
Reference in new issue
Block a user