Merge current main into develop inpaint, retaining both lock entries

This commit is contained in:
Dylan M. Taylor
2026-11-18 13:27:53 -05:00
292 changed files with 42128 additions and 1353 deletions
+20 -3
View File
@@ -1,7 +1,6 @@
# cargo-nextest (https://nexte.st) runs every test in its own process, in parallel across test
# binaries. The Windows leg of the Workspace gate uses it (.github/workflows/workspace.yml); every
# other leg, and local runs, keep `cargo test`. Nextest does not run doctests, so the Windows leg
# also runs `cargo test --doc`.
# binaries. Every leg of the Workspace gate uses it (.github/workflows/workspace.yml); local runs may
# keep `cargo test`. Nextest does not run doctests, so the gate also runs `cargo test --doc`.
#
# cargo nextest run --workspace --profile ci
# cargo test --workspace --doc
@@ -22,6 +21,9 @@ video-fixtures = { max-threads = 1 }
# craft-print: `PRINT_TICKET_PROVIDER` serializes the Windows PrintTicket provider, and the tests
# share the one test print queue the gate installs.
print = { max-threads = 1 }
# craft-video integration tests on Linux and macOS: the binaries generate and read the same fixture
# directories (see the `ci` overrides below).
video-integration = { max-threads = 1 }
[[profile.default.overrides]]
filter = 'package(craft-ui) & (binary(visual_regression) | test(/^combo::tests::|selected_tab_erases_a_baseline_centered_on_its_bottom_edge/))'
@@ -42,3 +44,18 @@ test-group = 'print'
fail-fast = false
slow-timeout = { period = "60s" }
failure-output = "immediate-final"
# Linux and macOS (the resource audit in craft-libs#2058): every GPU consumer shares the one `gpu`
# slot, and the craft-video integration binaries share their fixture directories. Conservative on
# purpose: the in-process mutexes these tests rely on do not reach across nextest's processes.
# Windows keeps the default groups above, which its leg has passed with since it moved to nextest.
[[profile.ci.overrides]]
platform = 'cfg(unix)'
filter = 'package(craft-ui) | package(craft-keymap) | package(craft-update)'
test-group = 'gpu'
[[profile.ci.overrides]]
platform = 'cfg(unix)'
filter = 'package(craft-video) & kind(test)'
test-group = 'video-integration'
+2 -38
View File
@@ -18,7 +18,6 @@ workflows:
- 'actions/checkout@v7.0.1'
- 'step-security/dtolnay-rust-toolchain@v1.0.0'
- 'step-security/harden-runner@v2.22.4'
- 'step-security/rust-cache@v2.9.2'
'.github/workflows/cms.yml':
- 'actions/checkout@v4.4.0'
- 'dtolnay/rust-toolchain@stable'
@@ -27,7 +26,6 @@ workflows:
- 'actions/checkout@v7.0.1'
- 'step-security/dtolnay-rust-toolchain@v1.0.0'
- 'step-security/harden-runner@v2.22.4'
- 'step-security/rust-cache@v2.9.2'
'.github/workflows/dialogs.yml':
- 'actions/checkout@v7.0.1'
- 'step-security/dtolnay-rust-toolchain@v1.0.0'
@@ -36,10 +34,6 @@ workflows:
- 'actions/checkout@v7.0.1'
- 'step-security/dtolnay-rust-toolchain@v1.0.0'
- 'step-security/harden-runner@v2.22.4'
'.github/workflows/docpath.yml':
- 'actions/checkout@v7.0.1'
- 'step-security/dtolnay-rust-toolchain@v1.0.0'
- 'step-security/harden-runner@v2.22.4'
'.github/workflows/ecproj-format.yml':
- 'actions/checkout@v7.0.1'
- 'step-security/dtolnay-rust-toolchain@v1.0.0'
@@ -52,22 +46,16 @@ workflows:
- 'actions/checkout@v7.0.1'
- 'dtolnay/rust-toolchain@stable'
- 'step-security/harden-runner@v2.22.4'
- 'swatinem/rust-cache@v2.9.3'
'.github/workflows/full-validation.yml': []
'.github/workflows/house-rules.yml': []
'.github/workflows/i18n.yml':
- 'actions/checkout@v7.0.1'
- 'step-security/dtolnay-rust-toolchain@v1.0.0'
- 'step-security/harden-runner@v2.22.4'
'.github/workflows/jpeg.yml':
- 'actions/checkout@v7.0.1'
- 'step-security/dtolnay-rust-toolchain@v1.0.0'
- 'step-security/harden-runner@v2.22.4'
- 'step-security/rust-cache@v2.9.2'
'.github/workflows/keymap.yml':
- 'actions/checkout@v7.0.1'
- 'step-security/dtolnay-rust-toolchain@v1.0.0'
- 'step-security/harden-runner@v2.22.4'
- 'step-security/rust-cache@v2.9.2'
'.github/workflows/lockfile.yml':
- 'actions/checkout@v7.0.1'
- 'step-security/harden-runner@v2.22.4'
@@ -75,11 +63,10 @@ workflows:
- 'actions/checkout@v7.0.1'
- 'step-security/dtolnay-rust-toolchain@v1.0.0'
- 'step-security/harden-runner@v2.22.4'
- 'step-security/rust-cache@v2.9.2'
'.github/workflows/menu.yml':
- 'actions/checkout@v7.0.1'
- 'dtolnay/rust-toolchain@stable'
- 'swatinem/rust-cache@v2.9.3'
'.github/workflows/nightly.yml': []
'.github/workflows/pcraft-format.yml':
- 'actions/checkout@v7.0.1'
- 'step-security/dtolnay-rust-toolchain@v1.0.0'
@@ -89,23 +76,12 @@ workflows:
- 'actions/setup-python@v7.1.0'
- 'step-security/dtolnay-rust-toolchain@v1.0.0'
- 'step-security/harden-runner@v2.22.4'
- 'step-security/rust-cache@v2.9.2'
- 'step-security/taiki-e-install-action@v2.87.32'
'.github/workflows/print.yml':
- 'actions/checkout@v7.0.1'
- 'step-security/dtolnay-rust-toolchain@v1.0.0'
- 'step-security/harden-runner@v2.22.4'
'.github/workflows/proof.yml':
- 'actions/checkout@v7.0.1'
- 'step-security/dtolnay-rust-toolchain@v1.0.0'
- 'step-security/harden-runner@v2.22.4'
- 'step-security/rust-cache@v2.9.2'
'.github/workflows/sonarcloud.yml': []
'.github/workflows/ui.yml':
- 'actions/checkout@v7.0.1'
- 'step-security/dtolnay-rust-toolchain@v1.0.0'
- 'step-security/harden-runner@v2.22.4'
- 'step-security/rust-cache@v2.9.2'
'.github/workflows/update.yml':
- 'actions/checkout@v7.0.1'
- 'step-security/dtolnay-rust-toolchain@v1.0.0'
@@ -118,7 +94,6 @@ workflows:
- 'actions/checkout@v7.0.1'
- 'step-security/dtolnay-rust-toolchain@v1.0.0'
- 'step-security/harden-runner@v2.22.4'
- 'step-security/rust-cache@v2.9.2'
'.github/workflows/web-api.yml':
- 'actions/checkout@v7.0.1'
- 'step-security/dtolnay-rust-toolchain@v1.0.0'
@@ -128,7 +103,6 @@ workflows:
- 'actions/checkout@v7.0.1'
- 'step-security/dtolnay-rust-toolchain@v1.0.0'
- 'step-security/harden-runner@v2.22.4'
- 'step-security/rust-cache@v2.9.2'
- 'step-security/taiki-e-install-action@v2.87.32'
'.github/workflows/window.yml':
- 'actions/checkout@v7.0.1'
@@ -171,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
+7 -14
View File
@@ -12,20 +12,17 @@ permissions:
contents: read
concurrency:
# Pull requests share one group per branch, so a newer push cancels the older run. Every other
# run (main, manual) gets a group of its own, so it is neither cancelled nor replaced while queued.
group: ai-core-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
# One group per pull request and per branch: a newer push cancels the run it supersedes, on main
# too, since the newest run checks everything before it.
group: ai-core-${{ github.ref }}
cancel-in-progress: true
# fmt, clippy and the tests run in the Workspace gate on every OS; this checks what it does not.
jobs:
ai-core:
name: AI model WASM
timeout-minutes: 15
strategy:
fail-fast: false
matrix:
# macOS runners are kept for releases: macOS runs only when started by hand.
os: ${{ github.event_name == 'workflow_dispatch' && fromJSON('["ubuntu-latest","windows-latest","macos-latest"]') || fromJSON('["ubuntu-latest","windows-latest"]') }}
runs-on: ${{ matrix.os }}
runs-on: ubuntu-latest
steps:
- name: Harden runner
uses: step-security/harden-runner@v2.22.4
@@ -35,10 +32,6 @@ jobs:
- uses: step-security/dtolnay-rust-toolchain@v1.0.0
with:
toolchain: stable
components: rustfmt, clippy
targets: wasm32-unknown-unknown
- run: cargo fmt --check
- run: cargo clippy -p craft-ai-core --all-targets --locked -- -D warnings
- run: cargo test -p craft-ai-core --locked
# The model promises to compile for the web.
- run: cargo check -p craft-ai-core --target wasm32-unknown-unknown --locked
+7 -16
View File
@@ -12,20 +12,17 @@ permissions:
contents: read
concurrency:
# Pull requests share one group per branch, so a newer push cancels the older run. Every other
# run (main, manual) gets a group of its own, so it is neither cancelled nor replaced while queued.
group: atomic-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
# One group per pull request and per branch: a newer push cancels the run it supersedes, on main
# too, since the newest run checks everything before it.
group: atomic-${{ github.ref }}
cancel-in-progress: true
# fmt, clippy and the tests run in the Workspace gate on every OS; this runs what it does not.
jobs:
atomic:
name: Atomic inherited Linux ACLs
timeout-minutes: 15
strategy:
fail-fast: false
matrix:
# macOS runners are kept for releases: macOS runs only when started by hand.
os: ${{ github.event_name == 'workflow_dispatch' && fromJSON('["ubuntu-latest","windows-latest","macos-latest"]') || fromJSON('["ubuntu-latest","windows-latest"]') }}
runs-on: ${{ matrix.os }}
runs-on: ubuntu-latest
steps:
- name: Harden runner
uses: step-security/harden-runner@v2.22.4
@@ -35,15 +32,9 @@ jobs:
- uses: step-security/dtolnay-rust-toolchain@v1.0.0
with:
toolchain: stable
components: rustfmt, clippy
- name: Install ACL tools
if: runner.os == 'Linux'
run: sudo apt-get update && sudo apt-get install -y acl
- run: cargo fmt --check
- run: cargo clippy -p craft-atomic -p craft-settings --all-targets --locked -- -D warnings
- run: cargo test -p craft-atomic -p craft-settings --locked -- --nocapture
- name: Check inherited Linux ACLs
if: runner.os == 'Linux'
run: cargo test -p craft-atomic --locked -- --ignored --nocapture
wasm:
+12 -40
View File
@@ -11,17 +11,22 @@ on:
permissions:
contents: read
# A fraction of the fuzz-style cases, as in the Workspace gate; nightly.yml runs them in full.
env:
CRAFT_HOSTILE_DIVISOR: "8"
PROPTEST_CASES: "64"
concurrency:
# Pull requests share one group per branch, so a newer push cancels the older run. Every other
# run (main, manual) gets its own group: it is never cancelled or replaced while queued, so it
# always gets to save the cache.
group: shared-audio-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
# One group per pull request and per branch: a newer push cancels the run it supersedes, on main
# too, since the newest run checks everything before it.
group: shared-audio-${{ github.ref }}
cancel-in-progress: true
jobs:
lint:
timeout-minutes: 15
name: Audio lint, feature sets, docs, WASM
# fmt, clippy with all features and the minimum Rust version run in the Workspace gate.
name: Audio feature sets, docs, WASM
runs-on: ubuntu-latest
steps:
- name: Harden runner
@@ -34,13 +39,8 @@ jobs:
- uses: step-security/dtolnay-rust-toolchain@v1.0.0
with:
toolchain: stable
components: rustfmt, clippy
components: clippy
targets: wasm32-unknown-unknown
- uses: step-security/rust-cache@v2.9.2
with:
key: craft-audio-lint
save-if: ${{ github.ref == 'refs/heads/main' }}
- run: cargo fmt -p craft-audio --check
# Each feature on its own, so code that needs another feature fails here.
- name: Clippy, each feature alone
run: |
@@ -49,7 +49,6 @@ jobs:
cargo clippy -p craft-audio --all-targets --locked --no-default-features ${f:+--features "$f"} -- -D warnings
echo "::endgroup::"
done
- run: cargo clippy -p craft-audio --all-targets --locked --all-features -- -D warnings
# missing_docs is a warning in the crate; -D warnings makes it (and broken links) fail here.
- run: cargo doc -p craft-audio --all-features --no-deps --locked
env:
@@ -63,25 +62,6 @@ jobs:
RUSTDOCFLAGS: "-D warnings"
- run: cargo check -p craft-audio --all-features --locked --target wasm32-unknown-unknown
- run: cargo check -p craft-audio --no-default-features --features lossless-encode --locked --target wasm32-unknown-unknown
msrv:
timeout-minutes: 10
name: Audio on the minimum Rust version
runs-on: ubuntu-latest
steps:
- name: Harden runner
uses: step-security/harden-runner@v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@v7.0.1
with:
persist-credentials: false
# The workspace's rust-version.
- run: rustup toolchain install 1.95.0 --profile minimal
- uses: step-security/rust-cache@v2.9.2
with:
key: craft-audio-msrv
save-if: ${{ github.ref == 'refs/heads/main' }}
- run: cargo +1.95.0 check -p craft-audio -p craft-media --all-features --locked
features:
timeout-minutes: 10
name: Audio tests without symphonia and lossless-encode only
@@ -97,10 +77,6 @@ jobs:
- uses: step-security/dtolnay-rust-toolchain@v1.0.0
with:
toolchain: stable
- uses: step-security/rust-cache@v2.9.2
with:
key: craft-audio-features
save-if: ${{ github.ref == 'refs/heads/main' }}
- run: cargo test -p craft-audio --no-default-features --features lossless-encode --locked
- run: cargo test -p craft-audio --no-default-features --features pcm-encode --locked --lib
- run: cargo test -p craft-audio --no-default-features --features flac-encode --locked --lib
@@ -122,10 +98,6 @@ jobs:
- uses: step-security/dtolnay-rust-toolchain@v1.0.0
with:
toolchain: stable
- uses: step-security/rust-cache@v2.9.2
with:
key: craft-audio-test
save-if: ${{ github.ref == 'refs/heads/main' }}
- uses: actions/cache@v6.1.0
with:
path: ${{ runner.temp }}/media-fixtures/opus/vectors
+7 -3
View File
@@ -11,6 +11,13 @@ on:
permissions:
contents: read
concurrency:
# One group per pull request and per branch: a newer push cancels the run it supersedes, on main
# too, since the newest run checks everything before it.
group: cms-${{ github.ref }}
cancel-in-progress: true
# clippy and the debug tests run in the Workspace gate; this runs the release build of the tests.
jobs:
cms:
timeout-minutes: 20
@@ -18,9 +25,6 @@ jobs:
steps:
- uses: actions/checkout@v4.4.0
- uses: dtolnay/rust-toolchain@stable
with:
components: clippy
- run: cargo clippy -p craft-cms --all-targets --all-features --locked -- -D warnings
# Release: the FOGRA39 fit and ink-limit tests take about 35 s in debug and 4 s here. Tests that need
# installed system profiles print "skipped:" when none are present.
- run: cargo test -p craft-cms --all-features --release --locked -- --nocapture
+5 -41
View File
@@ -12,41 +12,13 @@ permissions:
contents: read
concurrency:
# Pull requests share one group per branch, so a newer push cancels the older run. Every other
# run (main, manual) gets its own group: it is never cancelled or replaced while queued, so it
# always gets to save the cache.
group: shared-crw-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
# One group per pull request and per branch: a newer push cancels the run it supersedes, on main
# too, since the newest run checks everything before it.
group: shared-crw-${{ github.ref }}
cancel-in-progress: true
# fmt, clippy and the tests run in the Workspace gate on every OS; this checks what it does not.
jobs:
native:
timeout-minutes: 20
name: CRW lint and tests (${{ matrix.os }})
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, windows-latest]
runs-on: ${{ matrix.os }}
steps:
- name: Harden runner
uses: step-security/harden-runner@v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@v7.0.1
with:
persist-credentials: false
- uses: step-security/dtolnay-rust-toolchain@v1.0.0
with:
toolchain: stable
components: rustfmt, clippy
- uses: step-security/rust-cache@v2.9.2
with:
key: craft-crw-${{ matrix.os }}
save-if: ${{ github.ref == 'refs/heads/main' }}
- run: cargo fmt -p craft-crw --check
- run: cargo clippy -p craft-crw --all-targets --locked -- -D warnings
- run: cargo test -p craft-crw --locked
wasm:
timeout-minutes: 10
name: CRW WASM
@@ -63,10 +35,6 @@ jobs:
with:
toolchain: stable
targets: wasm32-unknown-unknown
- uses: step-security/rust-cache@v2.9.2
with:
key: craft-crw-wasm
save-if: ${{ github.ref == 'refs/heads/main' }}
- run: cargo check -p craft-crw --locked --target wasm32-unknown-unknown
samples:
@@ -84,10 +52,6 @@ jobs:
- uses: step-security/dtolnay-rust-toolchain@v1.0.0
with:
toolchain: stable
- uses: step-security/rust-cache@v2.9.2
with:
key: craft-crw-samples
save-if: ${{ github.ref == 'refs/heads/main' }}
- name: Cache the CC0 sample files
uses: actions/cache@v6.1.0
with:
+5 -6
View File
@@ -12,10 +12,10 @@ permissions:
contents: read
concurrency:
# Pull requests share one group per branch, so a newer push cancels the older run. Every other
# run (main, manual) gets a group of its own, so it is neither cancelled nor replaced while queued.
group: dialogs-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
# One group per pull request and per branch: a newer push cancels the run it supersedes, on main
# too, since the newest run checks everything before it.
group: dialogs-${{ github.ref }}
cancel-in-progress: true
jobs:
dialogs:
@@ -37,6 +37,5 @@ jobs:
components: clippy
# The macOS code is linted on Linux: it compiles for the target without the SDK.
targets: aarch64-apple-darwin
- run: cargo clippy -p craft-dialogs --all-targets --locked -- -D warnings
# Native clippy and the tests run in the Workspace gate.
- run: cargo clippy -p craft-dialogs --target aarch64-apple-darwin --locked -- -D warnings
- run: cargo test -p craft-dialogs --locked
+7 -16
View File
@@ -12,20 +12,17 @@ permissions:
contents: read
concurrency:
# Pull requests share one group per branch, so a newer push cancels the older run. Every other
# run (main, manual) gets a group of its own, so it is neither cancelled nor replaced while queued.
group: doc-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
# One group per pull request and per branch: a newer push cancels the run it supersedes, on main
# too, since the newest run checks everything before it.
group: doc-${{ github.ref }}
cancel-in-progress: true
# fmt, clippy and the tests run in the Workspace gate on every OS; this checks what it does not.
jobs:
doc:
name: Craft documents WASM
timeout-minutes: 15
strategy:
fail-fast: false
matrix:
# macOS runners are kept for releases: macOS runs only when started by hand.
os: ${{ github.event_name == 'workflow_dispatch' && fromJSON('["ubuntu-latest","windows-latest","macos-latest"]') || fromJSON('["ubuntu-latest","windows-latest"]') }}
runs-on: ${{ matrix.os }}
runs-on: ubuntu-latest
steps:
- name: Harden runner
uses: step-security/harden-runner@v2.22.4
@@ -37,11 +34,5 @@ jobs:
- uses: step-security/dtolnay-rust-toolchain@v1.0.0
with:
toolchain: stable
components: rustfmt, clippy
targets: wasm32-unknown-unknown
- run: cargo fmt --check
- run: cargo clippy -p craft-doc --all-targets --locked -- -D warnings
- run: cargo clippy -p craft-doc --all-targets --all-features --locked -- -D warnings
- run: cargo test -p craft-doc --locked -- --nocapture
- run: cargo test -p craft-doc --all-features --locked -- --nocapture
- run: cargo check -p craft-doc --all-features --locked --target wasm32-unknown-unknown
-41
View File
@@ -1,41 +0,0 @@
name: Document paths
on:
workflow_dispatch:
push:
branches: [main]
paths: ['crates/docpath/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/docpath.yml']
pull_request:
paths: ['crates/docpath/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/docpath.yml']
permissions:
contents: read
concurrency:
# Pull requests share one group per branch, so a newer push cancels the older run. Every other
# run (main, manual) gets a group of its own, so it is neither cancelled nor replaced while queued.
group: docpath-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
docpath:
timeout-minutes: 15
strategy:
fail-fast: false
matrix:
# macOS runners are kept for releases: macOS runs only when started by hand.
os: ${{ github.event_name == 'workflow_dispatch' && fromJSON('["ubuntu-latest","windows-latest","macos-latest"]') || fromJSON('["ubuntu-latest","windows-latest"]') }}
runs-on: ${{ matrix.os }}
steps:
- name: Harden runner
uses: step-security/harden-runner@v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@v7.0.1
- uses: step-security/dtolnay-rust-toolchain@v1.0.0
with:
toolchain: stable
components: rustfmt, clippy
- run: cargo fmt --check
- run: cargo clippy -p craft-docpath --all-targets --locked -- -D warnings
- run: cargo test -p craft-docpath --locked -- --nocapture
+7 -14
View File
@@ -12,20 +12,17 @@ permissions:
contents: read
concurrency:
# Pull requests share one group per branch, so a newer push cancels the older run. Every other
# run (main, manual) gets a group of its own, so it is neither cancelled nor replaced while queued.
group: ecproj-format-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
# One group per pull request and per branch: a newer push cancels the run it supersedes, on main
# too, since the newest run checks everything before it.
group: ecproj-format-${{ github.ref }}
cancel-in-progress: true
# fmt, clippy and the tests run in the Workspace gate on every OS; this checks what it does not.
jobs:
ecproj-format:
name: EffectCraft project format WASM
timeout-minutes: 15
strategy:
fail-fast: false
matrix:
# macOS runners are kept for releases: macOS runs only when started by hand.
os: ${{ github.event_name == 'workflow_dispatch' && fromJSON('["ubuntu-latest","windows-latest","macos-latest"]') || fromJSON('["ubuntu-latest","windows-latest"]') }}
runs-on: ${{ matrix.os }}
runs-on: ubuntu-latest
steps:
- name: Harden runner
uses: step-security/harden-runner@v2.22.4
@@ -37,9 +34,5 @@ jobs:
- uses: step-security/dtolnay-rust-toolchain@v1.0.0
with:
toolchain: stable
components: rustfmt, clippy
targets: wasm32-unknown-unknown
- run: cargo fmt --check
- run: cargo clippy -p craft-ecproj-format --all-targets --locked -- -D warnings
- run: cargo test -p craft-ecproj-format --locked -- --nocapture
- run: cargo check -p craft-ecproj-format --locked --target wasm32-unknown-unknown
+7 -17
View File
@@ -12,20 +12,17 @@ permissions:
contents: read
concurrency:
# Pull requests share one group per branch, so a newer push cancels the older run. Every other
# run (main, manual) gets a group of its own, so it is neither cancelled nor replaced while queued.
group: font-store-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
# One group per pull request and per branch: a newer push cancels the run it supersedes, on main
# too, since the newest run checks everything before it.
group: font-store-${{ github.ref }}
cancel-in-progress: true
# fmt, clippy and the tests run in the Workspace gate on every OS; this checks what it does not.
jobs:
font-store:
name: Font store WASM
timeout-minutes: 20
strategy:
fail-fast: false
matrix:
# macOS runners are kept for releases: macOS runs only when started by hand.
os: ${{ github.event_name == 'workflow_dispatch' && fromJSON('["ubuntu-latest","windows-latest","macos-latest"]') || fromJSON('["ubuntu-latest","windows-latest"]') }}
runs-on: ${{ matrix.os }}
runs-on: ubuntu-latest
steps:
- name: Harden runner
uses: step-security/harden-runner@v2.22.4
@@ -35,13 +32,6 @@ jobs:
- uses: step-security/dtolnay-rust-toolchain@v1.0.0
with:
toolchain: stable
components: rustfmt, clippy
targets: wasm32-unknown-unknown
- run: cargo fmt --check
- run: cargo clippy -p craft-font-store --all-targets --locked -- -D warnings
- run: cargo test -p craft-font-store --locked
- run: cargo clippy -p craft-font-catalog --all-targets --locked -- -D warnings
- run: cargo test -p craft-font-catalog --locked
- name: Check the web build
if: runner.os == 'Linux'
run: cargo check -p craft-font-store --target wasm32-unknown-unknown --locked
+10 -22
View File
@@ -42,11 +42,10 @@ permissions:
contents: read
concurrency:
# Pull requests share one group per branch, so a newer push cancels the older run. Every other
# run (main, manual) gets its own group: it is never cancelled or replaced while queued, so it
# always gets to save the cache.
group: shared-formats-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
# One group per pull request and per branch: a newer push cancels the run it supersedes, on main
# too, since the newest run checks everything before it.
group: shared-formats-${{ github.ref }}
cancel-in-progress: true
jobs:
check:
@@ -68,7 +67,9 @@ jobs:
- { crate: craft-tiff, features: "" }
- { crate: craft-heif, features: "testdata" }
- { crate: craft-cms, features: "" }
name: ${{ matrix.crate }} lint, tests, WASM
# fmt, clippy with default and with all features, and the tests run in the Workspace gate on
# every OS; this lints each feature alone and checks the web build.
name: ${{ matrix.crate }} feature sets, WASM
runs-on: ubuntu-latest
steps:
- name: Harden runner
@@ -80,32 +81,19 @@ jobs:
persist-credentials: false
- uses: dtolnay/rust-toolchain@stable
with:
components: rustfmt, clippy
components: clippy
targets: wasm32-unknown-unknown
- uses: Swatinem/rust-cache@v2.9.3
with:
key: ${{ matrix.crate }}
save-if: ${{ github.ref == 'refs/heads/main' }}
- run: cargo fmt -p "$CRATE" --check
env:
CRATE: ${{ matrix.crate }}
- name: Clippy, default features and each feature alone
- name: Clippy, each feature alone
if: matrix.features != ''
env:
CRATE: ${{ matrix.crate }}
FEATURES: ${{ matrix.features }}
run: |
cargo clippy -p "$CRATE" --all-targets --locked -- -D warnings
for f in $FEATURES; do
echo "::group::feature: $f"
cargo clippy -p "$CRATE" --all-targets --locked --no-default-features --features "$f" -- -D warnings
echo "::endgroup::"
done
- run: cargo clippy -p "$CRATE" --all-targets --locked --all-features -- -D warnings
env:
CRATE: ${{ matrix.crate }}
- run: cargo test -p "$CRATE" --all-features --locked
env:
CRATE: ${{ matrix.crate }}
- run: cargo check -p "$CRATE" --all-features --locked --target wasm32-unknown-unknown
env:
CRATE: ${{ matrix.crate }}
+64
View File
@@ -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
-41
View File
@@ -1,41 +0,0 @@
name: Translations
on:
workflow_dispatch:
push:
branches: [main]
paths: ['crates/i18n/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/i18n.yml']
pull_request:
paths: ['crates/i18n/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/i18n.yml']
permissions:
contents: read
concurrency:
# Pull requests share one group per branch, so a newer push cancels the older run. Every other
# run (main, manual) gets a group of its own, so it is neither cancelled nor replaced while queued.
group: i18n-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
i18n:
timeout-minutes: 15
strategy:
fail-fast: false
matrix:
# macOS runners are kept for releases: macOS runs only when started by hand.
os: ${{ github.event_name == 'workflow_dispatch' && fromJSON('["ubuntu-latest","windows-latest","macos-latest"]') || fromJSON('["ubuntu-latest","windows-latest"]') }}
runs-on: ${{ matrix.os }}
steps:
- name: Harden runner
uses: step-security/harden-runner@v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@v7.0.1
- uses: step-security/dtolnay-rust-toolchain@v1.0.0
with:
toolchain: stable
components: rustfmt, clippy
- run: cargo fmt --check
- run: cargo clippy -p craft-i18n --all-targets --features collate --locked -- -D warnings
- run: cargo test -p craft-i18n --features collate --locked -- --nocapture
+8 -15
View File
@@ -12,16 +12,17 @@ permissions:
contents: read
concurrency:
# Pull requests share one group per branch, so a newer push cancels the older run. Every other
# run (main, manual) gets its own group: it is never cancelled or replaced while queued, so it
# always gets to save the cache.
group: shared-jpeg-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
# One group per pull request and per branch: a newer push cancels the run it supersedes, on main
# too, since the newest run checks everything before it.
group: shared-jpeg-${{ github.ref }}
cancel-in-progress: true
jobs:
check:
timeout-minutes: 10
name: JPEG lint, tests, WASM
# Uncached: the wasm check builds its dependencies on every run (about 10 minutes with setup).
timeout-minutes: 20
# fmt, clippy and the tests run in the Workspace gate on every OS.
name: JPEG WASM
runs-on: ubuntu-latest
steps:
- name: Harden runner
@@ -34,13 +35,5 @@ jobs:
- uses: step-security/dtolnay-rust-toolchain@v1.0.0
with:
toolchain: stable
components: rustfmt, clippy
targets: wasm32-unknown-unknown
- uses: step-security/rust-cache@v2.9.2
with:
key: craft-jpeg
save-if: ${{ github.ref == 'refs/heads/main' }}
- run: cargo fmt -p craft-jpeg --check
- run: cargo clippy -p craft-jpeg --all-targets --locked -- -D warnings
- run: cargo test -p craft-jpeg --locked
- run: cargo check -p craft-jpeg --locked --target wasm32-unknown-unknown
+8 -50
View File
@@ -12,16 +12,17 @@ permissions:
contents: read
concurrency:
# Pull requests share one group per branch, so a newer push cancels the older run. Every other
# run (main, manual) gets its own group: it is never cancelled or replaced while queued, so it
# always gets to save the cache.
group: keymap-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
# One group per pull request and per branch: a newer push cancels the run it supersedes, on main
# too, since the newest run checks everything before it.
group: keymap-${{ github.ref }}
cancel-in-progress: true
jobs:
linux:
timeout-minutes: 15
name: Keymap (Linux)
# fmt, and clippy and the tests with default and with all features, run in the Workspace gate
# on every OS; this runs the feature subsets.
name: Keymap feature sets
runs-on: ubuntu-latest
env:
CRAFT_FONTS_DIR: ${{ github.workspace }}/.test-inputs/craft-fonts
@@ -43,12 +44,7 @@ jobs:
- uses: step-security/dtolnay-rust-toolchain@v1.0.0
with:
toolchain: stable
components: rustfmt, clippy
- uses: step-security/rust-cache@v2.9.2
with:
key: craft-keymap-linux
save-if: ${{ github.ref == 'refs/heads/main' }}
- run: cargo fmt -p craft-keymap --check
components: clippy
- run: cargo clippy -p craft-keymap --all-targets --no-default-features --locked -- -D warnings
# `snapshot` covers `ui` and `egui` and compiles the dialog screenshots, which need a GPU
# to run, so the test steps leave them out.
@@ -58,40 +54,6 @@ jobs:
run: cargo test -p craft-keymap --no-default-features --lib --tests --locked
- name: Test egui dispatch and the shortcuts dialog
run: cargo test -p craft-keymap --features ui --locked
native:
timeout-minutes: 15
name: Keymap (${{ matrix.os }})
strategy:
fail-fast: false
matrix:
# macOS runners are kept for releases: macOS runs only when started by hand.
os: ${{ github.event_name == 'workflow_dispatch' && fromJSON('["macos-latest","windows-latest"]') || fromJSON('["windows-latest"]') }}
runs-on: ${{ matrix.os }}
env:
CRAFT_FONTS_DIR: ${{ github.workspace }}/.test-inputs/craft-fonts
steps:
- name: Harden runner
uses: step-security/harden-runner@v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@v7.0.1
with:
persist-credentials: false
- name: Checkout test fonts
uses: actions/checkout@v7.0.1
with:
repository: storytold/craft-fonts
ref: b076417b5880bd4154bd22f00695b1d28c6bea83
path: .test-inputs/craft-fonts
persist-credentials: false
- uses: step-security/dtolnay-rust-toolchain@v1.0.0
with:
toolchain: stable
- uses: step-security/rust-cache@v2.9.2
with:
key: craft-keymap-${{ matrix.os }}
save-if: ${{ github.ref == 'refs/heads/main' }}
- run: cargo test -p craft-keymap --features ui --locked
wasm:
timeout-minutes: 10
name: Keymap WASM
@@ -108,8 +70,4 @@ jobs:
with:
toolchain: stable
targets: wasm32-unknown-unknown
- uses: step-security/rust-cache@v2.9.2
with:
key: craft-keymap-wasm
save-if: ${{ github.ref == 'refs/heads/main' }}
- run: cargo check -p craft-keymap --features ui --locked --target wasm32-unknown-unknown
+12 -19
View File
@@ -11,17 +11,22 @@ on:
permissions:
contents: read
# A fraction of the fuzz-style cases, as in the Workspace gate; nightly.yml runs them in full.
env:
CRAFT_HOSTILE_DIVISOR: "8"
PROPTEST_CASES: "64"
concurrency:
# Pull requests share one group per branch, so a newer push cancels the older run. Every other
# run (main, manual) gets its own group: it is never cancelled or replaced while queued, so it
# always gets to save the cache.
group: shared-media-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
# One group per pull request and per branch: a newer push cancels the run it supersedes, on main
# too, since the newest run checks everything before it.
group: shared-media-${{ github.ref }}
cancel-in-progress: true
jobs:
lint:
timeout-minutes: 10
name: Media lint, feature sets, WASM
# fmt, and clippy with default and with all features, run in the Workspace gate on every OS.
name: Media feature sets, WASM
runs-on: ubuntu-latest
steps:
- name: Harden runner
@@ -34,20 +39,12 @@ jobs:
- uses: step-security/dtolnay-rust-toolchain@v1.0.0
with:
toolchain: stable
components: rustfmt, clippy
components: clippy
targets: wasm32-unknown-unknown
- uses: step-security/rust-cache@v2.9.2
with:
key: craft-media-lint
save-if: ${{ github.ref == 'refs/heads/main' }}
- run: cargo fmt -p craft-media --check
- run: cargo clippy -p craft-media --all-targets --locked --no-default-features -- -D warnings
- run: cargo clippy -p craft-media --all-targets --locked --no-default-features --features bitstream -- -D warnings
- run: cargo clippy -p craft-media --all-targets --locked -- -D warnings
- run: cargo clippy -p craft-media --all-targets --locked --no-default-features --features matroska -- -D warnings
- run: cargo clippy -p craft-media --all-targets --locked --no-default-features --features ogg -- -D warnings
- run: cargo clippy -p craft-media --all-targets --locked --all-features -- -D warnings
- run: cargo clippy -p craft-media-testkit --all-targets --locked -- -D warnings
- run: cargo clippy -p craft-media --all-targets --locked --no-default-features --features serde -- -D warnings
- run: cargo check -p craft-media --all-features --locked --target wasm32-unknown-unknown
test:
@@ -65,10 +62,6 @@ jobs:
- uses: step-security/dtolnay-rust-toolchain@v1.0.0
with:
toolchain: stable
- uses: step-security/rust-cache@v2.9.2
with:
key: craft-media-test
save-if: ${{ github.ref == 'refs/heads/main' }}
- name: Build tests while installing ffmpeg
run: |
# The man-db index rebuild after dpkg is slow on hosted runners.
+3 -8
View File
@@ -18,7 +18,8 @@ concurrency:
jobs:
linux:
timeout-minutes: 15
name: Menu (Linux)
# fmt, native clippy and the tests run in the Workspace gate on every OS.
name: Menu macOS and WASM lint
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7.0.1
@@ -26,14 +27,8 @@ jobs:
persist-credentials: false
- uses: dtolnay/rust-toolchain@stable
with:
components: rustfmt, clippy
components: clippy
targets: aarch64-apple-darwin, wasm32-unknown-unknown
- uses: Swatinem/rust-cache@v2.9.3
with:
key: craft-menu-linux
- run: cargo fmt -p craft-menu --check
- run: cargo clippy -p craft-menu --all-targets --locked -- -D warnings
# The macOS backend type-checks from Linux; it needs no linker or SDK.
- run: cargo clippy -p craft-menu --lib --locked --target aarch64-apple-darwin -- -D warnings
- run: cargo clippy -p craft-menu --lib --locked --target wasm32-unknown-unknown -- -D warnings
- run: cargo test -p craft-menu --locked
+34
View File
@@ -0,0 +1,34 @@
name: Nightly full tests
# The tests the Workspace gate shortens, in full, once a day: every hostile-input hammer and sweep
# without CRAFT_HOSTILE_DIVISOR, and every proptest at its own case count (no PROPTEST_CASES). The
# rest of the workspace's tests run with them, on Linux, with the gate's setup.
on:
schedule:
- cron: "37 2 * * *"
workflow_dispatch:
permissions:
contents: read
concurrency:
group: nightly-${{ github.ref }}
cancel-in-progress: false
jobs:
full:
name: Full tests
uses: storytold/craft-common-actions/.github/workflows/gate.yml@main
with:
os: '["ubuntu-latest"]'
timeout-minutes: 120
tools: cargo-nextest@0.9.150
packages: mesa-vulkan-drivers libvulkan1
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
linux-env: WGPU_BACKEND=vulkan
env: CRAFT_PRINT_REQUIRE_QUEUE=0
setup-command: bash scripts/ci-test-inputs.sh
cache-paths: .test-inputs/photocraft/corpus
cache-key: photocraft-corpus
cache-key-files: scripts/ci-test-inputs.sh
command: cargo nextest run --workspace --all-features --locked --profile ci
+8 -14
View File
@@ -12,20 +12,18 @@ permissions:
contents: read
concurrency:
# Pull requests share one group per branch, so a newer push cancels the older run. Every other
# run (main, manual) gets a group of its own, so it is neither cancelled nor replaced while queued.
group: pcraft-format-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
# One group per pull request and per branch: a newer push cancels the run it supersedes, on main
# too, since the newest run checks everything before it.
group: pcraft-format-${{ github.ref }}
cancel-in-progress: true
# fmt, clippy and the tests run in the Workspace gate on every OS, and its msrv job checks the
# workspace on 1.95; this checks the web build on 1.95.
jobs:
pcraft-format:
name: PhotoCraft format WASM
timeout-minutes: 15
strategy:
fail-fast: false
matrix:
# macOS runners are kept for releases: macOS runs only when started by hand.
os: ${{ github.event_name == 'workflow_dispatch' && fromJSON('["ubuntu-latest","windows-latest","macos-latest"]') || fromJSON('["ubuntu-latest","windows-latest"]') }}
runs-on: ${{ matrix.os }}
runs-on: ubuntu-latest
steps:
- name: Harden runner
uses: step-security/harden-runner@v2.22.4
@@ -37,9 +35,5 @@ jobs:
- uses: step-security/dtolnay-rust-toolchain@v1.0.0
with:
toolchain: "1.95"
components: rustfmt, clippy
targets: wasm32-unknown-unknown
- run: cargo fmt --check
- run: cargo clippy -p craft-pcraft-format --all-targets --locked -- -D warnings
- run: cargo test -p craft-pcraft-format --locked -- --nocapture
- run: cargo check -p craft-pcraft-format --locked --target wasm32-unknown-unknown
+14 -56
View File
@@ -11,22 +11,23 @@ on:
permissions:
contents: read
# A fraction of the proptest cases, as in the Workspace gate; nightly.yml runs them in full.
env:
PROPTEST_CASES: "64"
concurrency:
# Pull requests share one group per branch, so a newer push cancels the older run. Every other
# run (main, manual) gets its own group: it is never cancelled or replaced while queued, so it
# always gets to save the cache.
group: shared-pdf-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
# One group per pull request and per branch: a newer push cancels the run it supersedes, on main
# too, since the newest run checks everything before it.
group: shared-pdf-${{ github.ref }}
cancel-in-progress: true
jobs:
native:
name: PDF (${{ matrix.os }})
strategy:
fail-fast: false
matrix:
# macOS runners are kept for releases: macOS runs only when started by hand.
os: ${{ github.event_name == 'workflow_dispatch' && fromJSON('["ubuntu-latest","windows-latest","macos-latest"]') || fromJSON('["ubuntu-latest","windows-latest"]') }}
runs-on: ${{ matrix.os }}
# fmt, clippy and the tests run in the Workspace gate on every OS, with the licensed fonts and
# the plate tests; this runs the tests behind craft_pdf_unicode_fixtures and the read-only
# contract, which is its own workspace.
name: PDF Unicode fixtures and read-only contract
runs-on: ubuntu-latest
env:
RUSTFLAGS: --cfg craft_pdf_unicode_fixtures
steps:
@@ -38,11 +39,6 @@ jobs:
- uses: step-security/dtolnay-rust-toolchain@v1.0.0
with:
toolchain: stable
components: rustfmt, clippy
- uses: step-security/rust-cache@v2.9.2
with:
key: craft-pdf
save-if: ${{ github.ref == 'refs/heads/main' }}
- uses: actions/setup-python@v7.1.0
with:
python-version: "3.12"
@@ -52,9 +48,7 @@ jobs:
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"
- run: cargo fmt --check
- run: cargo clippy -p craft-pdf --all-targets --all-features --locked -- -D warnings
- run: cargo test -p craft-pdf --all-features --locked
- run: cargo test -p craft-pdf --all-features --locked --test unicode_writing --test upstream_compatibility --test upstream_reading
- run: cargo test --manifest-path crates/pdf/read-only-contract/Cargo.toml --locked
backends:
name: PDF vendored contracts
@@ -68,10 +62,6 @@ jobs:
- uses: step-security/dtolnay-rust-toolchain@v1.0.0
with:
toolchain: stable
- uses: step-security/rust-cache@v2.9.2
with:
key: craft-pdf-backends
save-if: ${{ github.ref == 'refs/heads/main' }}
- run: bash scripts/test-pdf-backends.sh
wasm:
name: PDF WASM runtime
@@ -89,10 +79,6 @@ jobs:
with:
toolchain: stable
targets: wasm32-unknown-unknown
- uses: step-security/rust-cache@v2.9.2
with:
key: craft-pdf-wasm
save-if: ${{ github.ref == 'refs/heads/main' }}
- uses: actions/setup-python@v7.1.0
with:
python-version: "3.12"
@@ -117,31 +103,3 @@ jobs:
fallback: cargo-install
- run: cargo test -p craft-pdf --all-features --locked --target wasm32-unknown-unknown
- run: cargo test --manifest-path crates/pdf/read-only-contract/Cargo.toml --locked --target wasm32-unknown-unknown
plate-test:
name: Plate tests and craft-prepress
runs-on: ubuntu-latest
steps:
- name: Harden runner
uses: step-security/harden-runner@v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@v7.0.1
- uses: step-security/dtolnay-rust-toolchain@v1.0.0
with:
toolchain: stable
components: clippy
- uses: step-security/rust-cache@v2.9.2
with:
key: craft-plate-test
save-if: ${{ github.ref == 'refs/heads/main' }}
- uses: actions/setup-python@v7.1.0
with:
python-version: "3.12"
- name: Provision licensed PDF test fonts
shell: bash
run: |
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"
- run: cargo clippy -p craft-plate-test -p craft-prepress --all-targets --all-features --locked -- -D warnings
- run: cargo test -p craft-plate-test -p craft-prepress --all-features --locked
-46
View File
@@ -1,46 +0,0 @@
name: Print spooler
on:
workflow_dispatch:
push:
branches: [main]
paths: ['crates/print/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/print.yml']
pull_request:
paths: ['crates/print/**', 'Cargo.toml', 'Cargo.lock', '.github/workflows/print.yml']
permissions:
contents: read
concurrency:
# Pull requests share one group per branch, so a newer push cancels the older run. Every other
# run (main, manual) gets a group of its own, so it is neither cancelled nor replaced while queued.
group: print-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
print:
timeout-minutes: 30
strategy:
fail-fast: false
matrix:
# macOS runners are kept for releases: macOS runs only when started by hand.
os: ${{ github.event_name == 'workflow_dispatch' && fromJSON('["ubuntu-latest","windows-latest","macos-latest"]') || fromJSON('["ubuntu-latest","windows-latest"]') }}
runs-on: ${{ matrix.os }}
steps:
- name: Harden runner
uses: step-security/harden-runner@v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@v7.0.1
- uses: step-security/dtolnay-rust-toolchain@v1.0.0
with:
toolchain: stable
components: rustfmt, clippy
- run: cargo fmt --check
- run: cargo clippy -p craft-print --all-targets -- -D warnings
- name: Prepare the Windows test driver
if: runner.os == 'Windows'
shell: powershell
run: |
Start-Service Spooler
Add-PrinterDriver -Name 'Generic / Text Only'
- run: cargo test -p craft-print --locked -- --nocapture
timeout-minutes: 10
env:
CRAFT_PRINT_REQUIRE_QUEUE: ${{ runner.os == 'Windows' && '1' || '0' }}
+9 -17
View File
@@ -12,16 +12,16 @@ permissions:
contents: read
concurrency:
# Pull requests share one group per branch, so a newer push cancels the older run. Every other
# run (main, manual) gets its own group: it is never cancelled or replaced while queued, so it
# always gets to save the cache.
group: craft-proof-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
# One group per pull request and per branch: a newer push cancels the run it supersedes, on main
# too, since the newest run checks everything before it.
group: craft-proof-${{ github.ref }}
cancel-in-progress: true
jobs:
check:
timeout-minutes: 20
name: Proofing lint, tests with and without Language data, WASM
# fmt, and clippy and the tests without Language data, run in the Workspace gate on every OS.
name: Proofing with Language data, WASM
runs-on: ubuntu-latest
steps:
- name: Harden runner
@@ -43,18 +43,10 @@ jobs:
- uses: step-security/dtolnay-rust-toolchain@v1.0.0
with:
toolchain: stable
components: rustfmt, clippy
components: clippy
targets: wasm32-unknown-unknown
- uses: step-security/rust-cache@v2.9.2
with:
key: craft-proof
save-if: ${{ github.ref == 'refs/heads/main' }}
- run: cargo fmt -p craft-proof --check
- name: Without Language data (a fork, docs.rs, offline)
run: |
cargo clippy -p craft-proof --all-targets --locked -- -D warnings
cargo test -p craft-proof --locked
cargo check -p craft-proof --locked --target wasm32-unknown-unknown
- name: The web build without Language data (a fork, docs.rs, offline)
run: cargo check -p craft-proof --locked --target wasm32-unknown-unknown
- name: A release without Language data fails
run: |
if CRAFT_I18N_REQUIRED=1 cargo check -p craft-proof --locked 2>build.log; then
-74
View File
@@ -1,74 +0,0 @@
name: Shared UI
on:
push:
branches: [main]
paths: ["crates/ui/**", "crates/i18n/**", "Cargo.toml", "Cargo.lock", ".github/workflows/ui.yml"]
pull_request:
paths: ["crates/ui/**", "crates/i18n/**", "Cargo.toml", "Cargo.lock", ".github/workflows/ui.yml"]
workflow_dispatch:
permissions:
contents: read
concurrency:
# Pull requests share one group per branch, so a newer push cancels the older run. Every other
# run (main, manual) gets its own group: it is never cancelled or replaced while queued, so it
# always gets to save the cache.
group: shared-ui-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
native:
timeout-minutes: 30
name: UI (${{ matrix.os }})
strategy:
fail-fast: false
matrix:
# macOS runners are kept for releases: macOS runs only when started by hand.
os: ${{ github.event_name == 'workflow_dispatch' && fromJSON('["ubuntu-latest","windows-latest","macos-latest"]') || fromJSON('["ubuntu-latest","windows-latest"]') }}
runs-on: ${{ matrix.os }}
steps:
- name: Harden runner
uses: step-security/harden-runner@v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@v7.0.1
- name: Install software Vulkan renderer
if: runner.os == 'Linux'
run: |
sudo apt-get update
sudo apt-get install -y mesa-vulkan-drivers libvulkan1
echo 'WGPU_BACKEND=vulkan' >> "$GITHUB_ENV"
- uses: step-security/dtolnay-rust-toolchain@v1.0.0
with:
toolchain: stable
components: rustfmt, clippy
- uses: step-security/rust-cache@v2.9.2
with:
key: craft-ui
save-if: ${{ github.ref == 'refs/heads/main' }}
- run: cargo fmt --check
- run: cargo clippy -p craft-ui --all-targets --locked -- -D warnings
- run: cargo clippy -p craft-ui --all-targets --all-features --locked -- -D warnings
- run: cargo test -p craft-ui --locked
- run: cargo test -p craft-ui --all-features --locked
wasm:
timeout-minutes: 15
name: UI WASM
runs-on: ubuntu-latest
steps:
- name: Harden runner
uses: step-security/harden-runner@v2.22.4
with:
egress-policy: audit
- uses: actions/checkout@v7.0.1
- uses: step-security/dtolnay-rust-toolchain@v1.0.0
with:
toolchain: stable
targets: wasm32-unknown-unknown
- uses: step-security/rust-cache@v2.9.2
with:
key: craft-ui-wasm
save-if: ${{ github.ref == 'refs/heads/main' }}
- run: cargo check -p craft-ui --all-features --locked --target wasm32-unknown-unknown
+9 -15
View File
@@ -12,20 +12,18 @@ permissions:
contents: read
concurrency:
# Pull requests share one group per branch, so a newer push cancels the older run. Every other
# run (main, manual) gets a group of its own, so it is neither cancelled nor replaced while queued.
group: update-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
# One group per pull request and per branch: a newer push cancels the run it supersedes, on main
# too, since the newest run checks everything before it.
group: update-${{ github.ref }}
cancel-in-progress: true
# fmt, clippy and the tests with default and with all features run in the Workspace gate on every
# OS; this runs the egui feature alone.
jobs:
update:
name: Update with egui alone
timeout-minutes: 15
strategy:
fail-fast: false
matrix:
# macOS runners are kept for releases: macOS runs only when started by hand.
os: ${{ github.event_name == 'workflow_dispatch' && fromJSON('["ubuntu-latest","windows-latest","macos-latest"]') || fromJSON('["ubuntu-latest","windows-latest"]') }}
runs-on: ${{ matrix.os }}
runs-on: ubuntu-latest
steps:
- name: Harden runner
uses: step-security/harden-runner@v2.22.4
@@ -39,10 +37,6 @@ jobs:
- uses: step-security/dtolnay-rust-toolchain@v1.0.0
with:
toolchain: stable
components: rustfmt, clippy
- run: cargo fmt --check
# Default (no egui) and the egui feature both build and lint cleanly.
- run: cargo clippy -p craft-update --all-targets --locked -- -D warnings
components: clippy
- run: cargo clippy -p craft-update --all-targets --locked --features egui -- -D warnings
- run: cargo test -p craft-update --locked -- --nocapture
- run: cargo test -p craft-update --locked --features egui -- --nocapture
+8 -14
View File
@@ -12,20 +12,18 @@ permissions:
contents: read
concurrency:
# Pull requests share one group per branch, so a newer push cancels the older run. Every other
# run (main, manual) gets a group of its own, so it is neither cancelled nor replaced while queued.
group: vectorcraft-format-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
# One group per pull request and per branch: a newer push cancels the run it supersedes, on main
# too, since the newest run checks everything before it.
group: vectorcraft-format-${{ github.ref }}
cancel-in-progress: true
# fmt, clippy and the tests run in the Workspace gate on every OS, and its msrv job checks the
# workspace on 1.95; this checks the web build on 1.95.
jobs:
vectorcraft-format:
name: VectorCraft format WASM
timeout-minutes: 15
strategy:
fail-fast: false
matrix:
# macOS runners are kept for releases: macOS runs only when started by hand.
os: ${{ github.event_name == 'workflow_dispatch' && fromJSON('["ubuntu-latest","windows-latest","macos-latest"]') || fromJSON('["ubuntu-latest","windows-latest"]') }}
runs-on: ${{ matrix.os }}
runs-on: ubuntu-latest
steps:
- name: Harden runner
uses: step-security/harden-runner@v2.22.4
@@ -37,9 +35,5 @@ jobs:
- uses: step-security/dtolnay-rust-toolchain@v1.0.0
with:
toolchain: "1.95"
components: rustfmt, clippy
targets: wasm32-unknown-unknown
- run: cargo fmt --check
- run: cargo clippy -p craft-vectorcraft-format --all-targets --locked -- -D warnings
- run: cargo test -p craft-vectorcraft-format --locked -- --nocapture
- run: cargo check -p craft-vectorcraft-format --locked --target wasm32-unknown-unknown
+12 -18
View File
@@ -11,6 +11,11 @@ on:
permissions:
contents: read
# A fraction of the fuzz-style cases, as in the Workspace gate; nightly.yml runs them in full.
env:
CRAFT_HOSTILE_DIVISOR: "8"
PROPTEST_CASES: "64"
concurrency:
group: shared-video-${{ github.ref }}
cancel-in-progress: true
@@ -18,7 +23,8 @@ concurrency:
jobs:
lint:
timeout-minutes: 20
name: Video lint, feature sets, docs, WASM
# fmt and clippy with all features run in the Workspace gate on every OS.
name: Video feature sets, docs, WASM
runs-on: ubuntu-latest
steps:
- name: Harden runner
@@ -31,12 +37,8 @@ jobs:
- uses: step-security/dtolnay-rust-toolchain@v1.0.0
with:
toolchain: "1.95"
components: rustfmt, clippy
components: clippy
targets: wasm32-unknown-unknown
- uses: step-security/rust-cache@v2.9.2
with:
key: craft-video-lint
- run: cargo fmt -p craft-video --check
# Each feature on its own, so code that needs another feature fails here.
- name: Clippy, each feature alone
run: |
@@ -45,19 +47,15 @@ jobs:
cargo clippy -p craft-video --all-targets --locked --no-default-features ${f:+--features "$f"} -- -D warnings
echo "::endgroup::"
done
- run: cargo clippy -p craft-video --all-targets --locked --all-features -- -D warnings
- run: cargo doc -p craft-video --all-features --no-deps --locked
env:
RUSTDOCFLAGS: "-D warnings"
- run: cargo check -p craft-video --all-features --locked --target wasm32-unknown-unknown
test:
timeout-minutes: 30
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, windows-latest]
runs-on: ${{ matrix.os }}
name: Video tests (${{ matrix.os }})
# The Workspace gate runs these tests on every OS without ffmpeg; this runs them with it.
runs-on: ubuntu-latest
name: Video tests with ffmpeg
steps:
- name: Harden runner
uses: step-security/harden-runner@v2.22.4
@@ -69,11 +67,7 @@ jobs:
- uses: step-security/dtolnay-rust-toolchain@v1.0.0
with:
toolchain: "1.95"
- uses: step-security/rust-cache@v2.9.2
with:
key: craft-video-${{ matrix.os }}
- name: Install ffmpeg (Linux)
if: runner.os == 'Linux'
- name: Install ffmpeg
run: |
sudo rm -f /var/lib/man-db/auto-update
sudo apt-get update -qq && sudo apt-get install -y -qq --no-install-recommends ffmpeg
+6 -8
View File
@@ -12,10 +12,10 @@ permissions:
contents: read
concurrency:
# Pull requests share one group per branch, so a newer push cancels the older run. Every other
# run (main, manual) gets a group of its own, so it is neither cancelled nor replaced while queued.
group: web-api-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
# One group per pull request and per branch: a newer push cancels the run it supersedes, on main
# too, since the newest run checks everything before it.
group: web-api-${{ github.ref }}
cancel-in-progress: true
jobs:
web-api:
@@ -35,7 +35,7 @@ jobs:
- uses: step-security/dtolnay-rust-toolchain@v1.0.0
with:
toolchain: stable
components: rustfmt, clippy
components: clippy
targets: wasm32-unknown-unknown
- name: Read the wasm-bindgen version from Cargo.lock
id: wasm-bindgen
@@ -50,8 +50,6 @@ jobs:
with:
tool: wasm-bindgen@${{ steps.wasm-bindgen.outputs.version }}
fallback: cargo-install
- run: cargo fmt --check
- run: cargo clippy -p craft-web-api --all-targets --locked -- -D warnings
# fmt, native clippy and the native tests run in the Workspace gate.
- run: cargo clippy -p craft-web-api --all-targets --locked --target wasm32-unknown-unknown -- -D warnings
- run: cargo test -p craft-web-api --locked
- run: cargo test -p craft-web-api --locked --target wasm32-unknown-unknown
+7 -14
View File
@@ -12,16 +12,16 @@ permissions:
contents: read
concurrency:
# Pull requests share one group per branch, so a newer push cancels the older run. Every other
# run (main, manual) gets its own group: it is never cancelled or replaced while queued, so it
# always gets to save the cache.
group: shared-web-host-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
# One group per pull request and per branch: a newer push cancels the run it supersedes, on main
# too, since the newest run checks everything before it.
group: shared-web-host-${{ github.ref }}
cancel-in-progress: true
jobs:
check:
timeout-minutes: 20
name: Web host lint, tests, WASM tests
# fmt, native clippy and the native tests run in the Workspace gate.
name: Web host WASM lint and tests
runs-on: ubuntu-latest
env:
CARGO_TARGET_WASM32_UNKNOWN_UNKNOWN_RUNNER: wasm-bindgen-test-runner
@@ -36,16 +36,9 @@ jobs:
- uses: step-security/dtolnay-rust-toolchain@v1.0.0
with:
toolchain: stable
components: rustfmt, clippy
components: clippy
targets: wasm32-unknown-unknown
- uses: step-security/rust-cache@v2.9.2
with:
key: craft-web-host
save-if: ${{ github.ref == 'refs/heads/main' }}
- run: cargo fmt -p craft-web-host --check
- run: cargo clippy -p craft-web-host --all-targets --locked -- -D warnings
- run: cargo clippy -p craft-web-host --all-targets --locked --target wasm32-unknown-unknown -- -D warnings
- run: cargo test -p craft-web-host --locked
- name: Read the wasm-bindgen version from Cargo.lock
id: wasm-bindgen
shell: bash
+10 -16
View File
@@ -12,20 +12,18 @@ permissions:
contents: read
concurrency:
# Pull requests share one group per branch, so a newer push cancels the older run. Every other
# run (main, manual) gets a group of its own, so it is neither cancelled nor replaced while queued.
group: window-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
# One group per pull request and per branch: a newer push cancels the run it supersedes, on main
# too, since the newest run checks everything before it.
group: window-${{ github.ref }}
cancel-in-progress: true
# fmt, clippy and the tests with default and with all features (egui and restore together) run in
# the Workspace gate on every OS; this runs each feature alone.
jobs:
window:
name: Window with each feature alone
timeout-minutes: 15
strategy:
fail-fast: false
matrix:
# macOS runners are kept for releases: macOS runs only when started by hand.
os: ${{ github.event_name == 'workflow_dispatch' && fromJSON('["ubuntu-latest","windows-latest","macos-latest"]') || fromJSON('["ubuntu-latest","windows-latest"]') }}
runs-on: ${{ matrix.os }}
runs-on: ubuntu-latest
steps:
- name: Harden runner
uses: step-security/harden-runner@v2.22.4
@@ -39,12 +37,8 @@ jobs:
- uses: step-security/dtolnay-rust-toolchain@v1.0.0
with:
toolchain: stable
components: rustfmt, clippy
- run: cargo fmt --check
# Default (no egui) and the egui feature both build and lint cleanly.
- run: cargo clippy -p craft-window --all-targets --locked -- -D warnings
components: clippy
- run: cargo clippy -p craft-window --all-targets --locked --features egui -- -D warnings
- run: cargo test -p craft-window --locked -- --nocapture
- run: cargo test -p craft-window --locked --features egui -- --nocapture
- run: cargo clippy -p craft-window --all-targets --locked --features restore -- -D warnings
- run: cargo test -p craft-window --locked --features restore,egui -- --nocapture
- run: cargo test -p craft-window --locked --features restore -- --nocapture
+59 -39
View File
@@ -6,17 +6,21 @@ on:
tags: ["v*"]
pull_request:
workflow_dispatch:
# A full run on main every 6 hours that is never cancelled, so the caches are saved while pushes
# to main cancel each other.
schedule:
- cron: "17 */6 * * *"
permissions:
contents: read
concurrency:
# Pull requests share one group per branch, so a newer push cancels the older run. Every other
# run (push to main, a release tag, a manual run) gets a group of its own: it is neither
# cancelled nor replaced while queued, so a main run always finishes and saves the dependency
# cache, and a release run is never cancelled.
group: workspace-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
# A pull request, and main, each have one group, so a newer push cancels the run it supersedes;
# the newest push's run still tests everything before it. Every other run (a release tag, a
# manual run, the scheduled run) gets a group of its own and is neither cancelled nor replaced
# while queued: a release run always finishes, and the scheduled run saves the caches.
group: workspace-${{ (github.event_name == 'pull_request' || github.event_name == 'push' && github.ref == 'refs/heads/main') && github.ref || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' || github.event_name == 'push' && github.ref == 'refs/heads/main' }}
jobs:
native:
@@ -24,47 +28,63 @@ jobs:
uses: storytold/craft-common-actions/.github/workflows/gate.yml@main
with:
os: '["ubuntu-latest","windows-latest","macos-latest"]'
# On a pull request, macOS and Windows run only when it can change platform behaviour: a
# crate with platform cfg code or one that depends on it, the build setup, or a file outside
# the crates (craft-common-actions' select-platforms). The full-ci label runs them anyway
# from the next push or manual run; pushes to main always run every leg.
select-os: '["windows-latest","macos-latest"]'
timeout-minutes: 120
# The Windows leg runs its tests with nextest (.config/nextest.toml).
# Every leg runs its tests with nextest, and its doctests with cargo test (.config/nextest.toml).
tools: cargo-nextest@0.9.150
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: |
set -euo pipefail
corpus_fetcher=.test-inputs/photocraft
mkdir -p "$corpus_fetcher"
git -C "$corpus_fetcher" init
git -C "$corpus_fetcher" remote add origin https://github.com/storytold/PhotoCraft.git
git -C "$corpus_fetcher" fetch --quiet --depth=1 origin 74330157cb601573ae4523a95bb9132822fc3918
git -C "$corpus_fetcher" checkout --quiet --detach FETCH_HEAD
(cd "$corpus_fetcher" && cargo xtask corpus --psd --psd-tools --atn --exr --heif --pngsuite)
mkdir -p corpus
cp -a "$corpus_fetcher/corpus/." corpus/
python scripts/test-fetch-pdf-test-fonts.py
python scripts/fetch-pdf-test-fonts.py "$RUNNER_TEMP/craft-pdf-test-fonts"
printf 'CRAFT_PSD_CORPUS=%s\n' "$GITHUB_WORKSPACE/$corpus_fetcher/corpus" >> "$GITHUB_ENV"
printf 'CRAFT_PDF_TEST_FONT_DIR=%s\n' "$RUNNER_TEMP/craft-pdf-test-fonts" >> "$GITHUB_ENV"
# No debuginfo on Windows: writing PDBs for every test binary is a large part of its link
# time. A panic still names its file and line; only backtrace frames lose theirs, and the
# Linux and macOS legs keep line tables.
windows-env: |
CRAFT_PRINT_REQUIRE_QUEUE=1
CARGO_PROFILE_DEV_DEBUG=0
# The fuzz-style tests run a fraction of their cases here: every hostile-input hammer and
# sweep 1/8 (craft-testkit's CRAFT_HOSTILE_DIVISOR), every proptest without its own case
# count 64 cases instead of 256. nightly.yml runs them all in full.
env: |
CRAFT_PRINT_REQUIRE_QUEUE=0
CRAFT_HOSTILE_DIVISOR=8
PROPTEST_CASES=64
setup-command: bash scripts/ci-test-inputs.sh
# The PhotoCraft corpora, keyed on the script that pins them: a hit skips the PhotoCraft
# checkout and its xtask build (1:51 on Windows).
cache-paths: .test-inputs/photocraft/corpus
cache-key: photocraft-corpus
cache-key-files: scripts/ci-test-inputs.sh
# A `lint (<os>)` leg beside each `gate (<os>)` leg, so clippy is off the tests' critical path.
lint-command: |
if [ "$RUNNER_OS" = Linux ]; then
python3 scripts/test-workspace-concurrency.py
python3 scripts/test-workspace-tests.py
fi
# 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: |
python3 scripts/test-workspace-concurrency.py
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
windows-command: |
powershell.exe -NoProfile -Command '$ErrorActionPreference = "Stop"; Start-Service Spooler; Add-PrinterDriver -Name "Generic / Text Only"'
cargo fmt --check
cargo clippy --workspace --all-targets --locked -- -D warnings
cargo clippy --workspace --all-targets --all-features --locked -- -D warnings
# The same tests as `cargo test`, run in parallel across test binaries instead of one
# binary at a time; nextest skips doctests, so `cargo test --doc` runs them.
cargo nextest run --workspace --locked --profile ci
cargo test --workspace --doc --locked
# The tests run once, with every feature, in parallel across test binaries; nextest skips
# doctests, so `cargo test --doc` runs them. The default-feature compile is the lint leg's
# first clippy run; the last command runs the crates whose tests check behaviour with a
# feature off, which an all-features build cannot reach.
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-command: |
powershell.exe -NoProfile -Command '$ErrorActionPreference = "Stop"; Start-Service Spooler; Add-PrinterDriver -Name "Generic / Text Only"'
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
msrv:
name: Rust 1.95
+34
View File
@@ -119,6 +119,7 @@ The XML reader in `crates/plist/src/xml.rs` and its base64 compatibility helper
`crates/palette` extracts the GPL text parser from AniCraft `crates/doc/src/swatch.rs` at `d875a7feb250e6ab06aa28a37fb78a0699e88330` (MIT OR Apache-2.0), introduced by Tanish Manku in `a64130a9da9bdde545463b852d95d6a6774b1dfd` (AniCraft #270). The import preserves Tanish as primary author. Neutral RGB/name adaptation separates application display-name sanitization and the `Untitled` policy; validation tests and integration are subsequent Dylan M. Taylor changes.
The legacy ZIP Zstandard method-20 mapping and bounded-read regression in `crates/zip/src/lenient` are ported from RRFZ's Craft Anything commit `29badae7c9280fdf4c24795927bf3a91f51694c6` (MIT OR Apache-2.0). RRFZ remains the primary Git author. Firmware scanner detection remains app-owned and is not part of this port.
## TAR/CPIO compatibility updates
The old GNU sparse-extension traversal, GNU CRC-symlink compatibility and PAX-size precedence fixes and their regression tests in `crates/tar` are ported from RRFZ's Craft Anything PRs #1973 (`8ea2ec66a1bc80f0420f3695baac877a0cb9b9a5`), #1984 (`b226a475f7dce9710e3af7a069386fe7a9720df7`) and #2007 (`d29465c20b0d570ea4973be512a0cb4e212bb60f`). Source is MIT OR Apache-2.0; RRFZ remains the primary Git author of each port. The PAX update adapts to the shared parser's existing `PaxOverrides` structure without changing the source policy.
@@ -130,14 +131,47 @@ The USDZ alignment requirement and compatibility fixture for `Writer::add_stored
The raw gradient wire ordering in `craft-lottie::Gradient::flat_values` follows
AniCraft's Lottie exporter by Tanish Manku (`63b39355`, `b9258b7b`), MIT OR Apache-2.0.
Sanitization, animation fitting and numeric output policy remain caller-owned.
## Screen Video key frames
`crates/video/src/screen_video.rs` extracts AniCraft `crates/xfl/src/video.rs` codec-3 decoding and its synthetic partial-block fixture, introduced by Tanish Manku in `1f3e603b7ff53a3da364e41ec4da8d43dc83aab0` with pixel-loop cleanup `2b7571363b4b647266df758f95b6e397021cfd4d` (MIT OR Apache-2.0). Import commits preserve Tanish as primary author. Caller-owned bounds and neutral RGBA output separate codec work from the consuming app's FLV first-frame/report policy. Boundary tests and integration are subsequent Dylan M. Taylor changes.
## Source Map v3 parser and lookup
`crates/sourcemap` extracts the bounded parser, source inventory and generated-position lookup from Craft Anything `crates/formats/src/sourcemap.rs` at `e5c9c94106747ed44b9a3fb0decce867c2285f93` (MIT OR Apache-2.0). Core-history ports preserve Brandon Thomas, BFlat, Afloat, RRFZ, Nicolas Bohn and Alex Joaquim Pereira as primary authors, with exact source revisions in each commit. Six regression files preserve their source authors; nine core unit tests retain the original tests. App annotation scanning, data URLs, base64 and file I/O are intentionally not imported. Workspace wiring is a subsequent change; existing limits and errors are unchanged.
## JSONC span-preserving editing
`crates/jsonc` is extracted from Craft Anything `crates/formats/src/jsonc.rs` at `e5c9c94106747ed44b9a3fb0decce867c2285f93` (MIT OR Apache-2.0). The original implementation and hardening by BFlat, newline preservation by NetterSilver, and subsequent RRFZ/Afloat correctness fixes retain separate primary-author port commits with immutable source revisions. Shared API wiring and optional input-byte admission are subsequent changes. Compatibility parsing and all existing formatting/editing tests are retained; application file I/O and policy are not imported.
## XFA XML DOM
`crates/xfa/src/xml.rs` is extracted from PDFCraft at `271e479c53723b1b294c866d5cb2f27604601b29`, originally by Dylan M. Taylor (`eead4541`, `7d44e654`), MIT OR Apache-2.0. The initial extraction changes visibility and module boundaries; subsequent namespace-retention budget hardening intentionally tightens resource admission. PDF/layout/form policy remains in the app.
## Java class inspection
`crates/java-class` extracts Craft Anything `java_class.rs` and `java_ops.rs` at `5979f9b13f16dcf1df3c7ae7f8e7735f452866f2` (MIT OR Apache-2.0), preserving separate primary-author source-history ports by Brandon Thomas, BFlat, Afloat and RRFZ. The checked byte-reader, modified UTF-8 unit decoder, descriptor display helper and synthetic class fixtures come from the same source snapshot. Seven regression files retain their source authors. Neutral error wiring and shared crate integration are subsequent changes. No JAR archive, application I/O or bytecode execution is imported.
## WebAssembly inspection
`crates/wasm` extracts Craft Anything `crates/formats/src/wasm.rs` at `5979f9b13f16dcf1df3c7ae7f8e7735f452866f2`, with its checked byte-reader subset and original synthetic WASM/testkit fixtures (MIT OR Apache-2.0). Eight core-history ports preserve Brandon Thomas, Afloat and RRFZ as primary authors; component, repeated-custom-section and referenced-string regression imports retain source authors and commit references. Fixtures come from `crates/testkit/src/formats.rs` and deterministic mutation helpers from `crates/testkit/src/lib.rs`; no third-party binaries. Shared error naming and workspace wiring are subsequent changes. Existing inspection limits and report behavior are unchanged; this crate validates/inspects/renders, never executes modules.
## Packet capture and protocol inspection
`crates/pcap` extracts Craft Anything `crates/formats/src/pcap.rs`, its checked byte reader primitives and synthetic packet fixtures/regressions at `5979f9b13f16dcf1df3c7ae7f8e7735f452866f2` (MIT OR Apache-2.0). Brandon Thomas introduced the implementation, byte reader and fixtures in `f64ae3bf3c8863a982af1304e06de20653803968`. Subsequent fixes by phatloi0010, GGWA, BFlat, Afloat, NetterSilver, Max Mittelstädt and RRFZ retain separate primary-author source-history commits with immutable source revisions. Shared error/API wiring and chrono-based timestamp formatting with exhaustive day-boundary parity tests are subsequent Dylan M. Taylor changes. No packet reassembly, decryption, live capture or app analysis policy is imported.
## HTTP Archive reader
`crates/har` preserves Craft Anything `crates/formats/src/har.rs` from `5979f9b13f16dcf1df3c7ae7f8e7735f452866f2` (MIT OR Apache-2.0). Brandon Thomas introduced the typed reader in `f64ae3bf3c8863a982af1304e06de20653803968`; BFlat added UTF-8 BOM compatibility in `cb0bb9d8fa4536ba44ef2c86f5ed759b879cc2d3`. Both source snapshots retain primary author attribution. Shared wiring, explicit byte admission and its tests are subsequent Dylan M. Taylor changes. Redaction and analysis remain app-owned.
## Dalvik DEX inspection
`crates/dex` extracts Craft Anything `crates/formats/src/dex.rs` and `dex_ops.rs` at `5979f9b13f16dcf1df3c7ae7f8e7735f452866f2` (MIT OR Apache-2.0). Five source-history ports preserve Brandon Thomas, BFlat and Afloat as primary authors. Five regression imports retain BFlat/Afloat authors and exact source revisions. The checked byte-reader/MUTF-8 subset and synthetic DEX fixture come from that app's `bytes.rs` and `testkit/src/android.rs`; deterministic noise/mutations come from its testkit. No application file I/O, APK logic or execution is imported. Shared neutral errors and workspace wiring are subsequent changes; existing per-file strings, member/handler and bytecode payload budgets are retained.
## EVM bytecode inspection
`crates/evm` extracts Craft Anything `crates/formats/src/evm.rs` at `a31e995858f4312e0f1d59a007112da191ef2d26` (MIT OR Apache-2.0). Eight separate source-history ports preserve Brandon Thomas, Afloat, RRFZ and NetterSilver as primary authors with immutable source references. Synthetic EVM fixtures and deterministic mutation helpers come from the same app source; regression files retain their source provenance. Neutral errors and workspace integration are subsequent changes. No code execution or transaction behavior is imported.
## XFDF field reader
`crates/xfdf` extracts PDFCraft field reading from #5937 refresh `cb564fd827f572818e9ddb0ea5989a432b1f39fd` (MIT OR Apache-2.0). App-side annotation and form policy remains local; source history is retained in the original repository.
Retained XFDF source contributors (move-aware blame): Brandon Thomas, Marco Arnulfo, pkibiego and storybored379; module split by aiongg. Subsequent budget/integration work by Dylan M. Taylor.
Generated
+281 -3
View File
@@ -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"
@@ -1074,6 +1085,18 @@ dependencies = [
"winx",
]
[[package]]
name = "cap-std"
version = "4.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c1ec78e242cfa2cfe276807ac2ecc00315a6c97786977414bcd1c3963b6c91b8"
dependencies = [
"cap-primitives",
"io-extras",
"io-lifetimes 3.0.1",
"rustix 1.1.5",
]
[[package]]
name = "cast"
version = "0.3.0"
@@ -1545,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"
@@ -1616,6 +1649,25 @@ dependencies = [
"craft-media-testkit",
]
[[package]]
name = "craft-cloud"
version = "0.1.0"
dependencies = [
"serde",
"thiserror 2.0.21",
]
[[package]]
name = "craft-cloud-local"
version = "0.1.0"
dependencies = [
"cap-std",
"craft-cloud",
"craft-ui",
"egui",
"tempfile",
]
[[package]]
name = "craft-cms"
version = "0.1.0"
@@ -1644,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]]
@@ -1730,6 +1787,15 @@ dependencies = [
"rayon",
]
[[package]]
name = "craft-dex"
version = "0.1.0"
dependencies = [
"craft-testkit",
"serde",
"thiserror 2.0.21",
]
[[package]]
name = "craft-dialogs"
version = "0.1.0"
@@ -1769,6 +1835,7 @@ dependencies = [
"craft-wordmodel",
"image",
"log",
"md4",
"miniz_oxide 0.9.1",
"proptest",
"serde_json",
@@ -1889,6 +1956,26 @@ 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"
dependencies = [
"craft-testkit",
"serde",
"serde_json",
"thiserror 2.0.21",
]
[[package]]
name = "craft-ews"
version = "0.1.0"
@@ -2269,6 +2356,15 @@ dependencies = [
"widestring",
]
[[package]]
name = "craft-java-class"
version = "0.1.0"
dependencies = [
"craft-testkit",
"serde",
"thiserror 2.0.21",
]
[[package]]
name = "craft-jmap"
version = "0.1.0"
@@ -2619,6 +2715,16 @@ dependencies = [
name = "craft-palette"
version = "0.1.0"
[[package]]
name = "craft-pcap"
version = "0.1.0"
dependencies = [
"chrono",
"serde",
"serde_json",
"thiserror 2.0.21",
]
[[package]]
name = "craft-pcraft-bundle"
version = "0.1.0"
@@ -3070,6 +3176,15 @@ dependencies = [
name = "craft-sniff"
version = "0.1.0"
[[package]]
name = "craft-sourcemap"
version = "0.1.0"
dependencies = [
"serde",
"serde_json",
"thiserror 2.0.21",
]
[[package]]
name = "craft-ssip"
version = "0.1.0"
@@ -3108,6 +3223,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"
@@ -3116,11 +3246,14 @@ dependencies = [
"craft-xml",
"data-url",
"flate2",
"gif",
"image-webp",
"kurbo 0.13.1",
"quick-xml 0.41.0",
"resvg 0.48.1",
"roxmltree 0.21.2",
"thiserror 2.0.21",
"toml",
"usvg 0.48.1",
"vectorcraft-geom",
"vectorcraft-pathops",
@@ -3138,6 +3271,7 @@ dependencies = [
name = "craft-tar"
version = "0.1.0"
dependencies = [
"craft-testkit",
"serde",
]
@@ -3222,6 +3356,8 @@ dependencies = [
name = "craft-ui"
version = "0.1.0"
dependencies = [
"craft-cloud",
"craft-esign",
"craft-fonts-build",
"craft-i18n",
"eframe",
@@ -3323,6 +3459,17 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-wasm"
version = "0.1.0"
dependencies = [
"craft-testkit",
"serde",
"thiserror 2.0.21",
"wasmparser 0.261.0",
"wasmprinter",
]
[[package]]
name = "craft-web-api"
version = "0.1.0"
@@ -3397,6 +3544,21 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-xfa"
version = "0.1.0"
dependencies = [
"craft-xml",
]
[[package]]
name = "craft-xfdf"
version = "0.1.0"
dependencies = [
"craft-xml",
"thiserror 2.0.21",
]
[[package]]
name = "craft-xfl"
version = "0.1.0"
@@ -4352,7 +4514,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",
@@ -5001,6 +5163,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"
@@ -5021,6 +5194,7 @@ checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc"
dependencies = [
"futures-core",
"futures-io",
"futures-macro",
"futures-sink",
"futures-task",
"memchr",
@@ -5630,6 +5804,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"
@@ -6611,6 +6794,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"
@@ -6906,6 +7110,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"
@@ -8085,7 +8298,7 @@ dependencies = [
"generic-array",
"getrandom 0.2.17",
"hex",
"hkdf",
"hkdf 0.12.4",
"idea",
"k256",
"log",
@@ -9650,6 +9863,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"
@@ -12006,7 +12238,7 @@ dependencies = [
"wasmi_collections",
"wasmi_core",
"wasmi_ir",
"wasmparser",
"wasmparser 0.228.0",
]
[[package]]
@@ -12046,6 +12278,28 @@ dependencies = [
"indexmap",
]
[[package]]
name = "wasmparser"
version = "0.261.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4f20f20e44f7e8aeb6744823ea9d869ede51e51be4fdaedede2852282e54d2d8"
dependencies = [
"bitflags 2.13.2",
"indexmap",
"semver",
]
[[package]]
name = "wasmprinter"
version = "0.261.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "86a21c9e3325655ba02de3e645bc8357a8b3651a2e3ada25b6dbc37560deb9b7"
dependencies = [
"anyhow",
"termcolor",
"wasmparser 0.261.0",
]
[[package]]
name = "wayland-backend"
version = "0.3.17"
@@ -12437,6 +12691,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"
@@ -12980,6 +13247,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"
+14
View File
@@ -11,7 +11,13 @@ rust-version = "1.95"
repository = "https://github.com/storytold/craft-libs"
[workspace.dependencies]
craft-xfa = { path = "crates/xfa" }
craft-evm = { path = "crates/evm" }
craft-java-class = { path = "crates/java-class" }
craft-sourcemap = { path = "crates/sourcemap" }
craft-pcap = { path = "crates/pcap" }
craft-har = { path = "crates/har" }
craft-xfdf = { path = "crates/xfdf" }
craft-jsonc = { path = "crates/jsonc" }
craft-palette = { path = "crates/palette" }
craft-score = { path = "crates/score" }
@@ -28,6 +34,7 @@ acadrust = "=0.6.6"
log = "0.4"
# internal: add each crate here as `craft-<name> = { path = "crates/<name>" }`
craft-plist = { path = "crates/plist" }
craft-wasm = { path = "crates/wasm" }
craft-platform = { path = "crates/platform" }
craft-aep = { path = "crates/aep" }
craft-affinity = { path = "crates/affinity" }
@@ -54,11 +61,16 @@ 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" }
craft-cfb = { path = "crates/cfb" }
craft-codepage = { path = "crates/codepage" }
craft-cms = { path = "crates/cms" }
craft-cloud = { path = "crates/cloud" }
craft-cloud-local = { path = "crates/cloud-local" }
craft-color = { path = "crates/color" }
craft-frame = { path = "crates/frame" }
craft-crs = { path = "crates/crs" }
@@ -88,6 +100,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" }
@@ -166,6 +179,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" }
+25
View File
@@ -0,0 +1,25 @@
[package]
name = "craft-cloud-local"
version.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
rust-version.workspace = true
description = "A reference CloudBackend over a local folder, proving the contract needs no specific provider"
[lints]
workspace = true
[dependencies]
# Resolution-time confinement: every path this crate resolves goes through a `Dir` capability
# opened on the configured root, never through an absolute OS path this crate builds itself.
# `craft-font-store` already depends on the lower-level `cap-primitives` for the same family of
# guarantee; this crate uses the ergonomic `cap-std` built on top of it instead of hand-rolling
# the equivalent `Dir`-style API again.
cap-std = "4"
craft-cloud = { workspace = true }
craft-ui = { workspace = true, features = ["cloud"] }
[dev-dependencies]
tempfile = "3"
egui = { workspace = true }
+39
View File
@@ -0,0 +1,39 @@
# craft-cloud-local
A reference `CloudBackend` over one folder on disk, proving that `craft-cloud`'s contract needs
no specific provider behind it.
## No-escape policy
Every path this crate is handed, a `Job::List`/`Read`/`Write` path or a `Job::Create` name, is
confined to the configured root before anything touches a filesystem, in two layers.
A path's segments are accepted only when each one parses as a single `Component::Normal`: no
`..`, no `.`, no empty segment, and no absolute form. A `Create` name goes through a stricter
check of its own, since it is one chosen name and not a path: it additionally refuses a
backslash, a colon, or a Windows reserved device name (`CON`, `COM1`, `CONIN$`, and so on), on
every platform this crate builds for, not only on Windows, because a chosen name reaches this
backend from whatever platform the UI runs on. An existing name that already has one of those
characters, discovered through `list`, stays reachable: `:` and `\` are not path separators on
any platform's filesystem, so refusing to read a real file back because of a byte in its name
(macOS stores a `/` typed in Finder as `:` on disk) would be a usability bug with no matching
security benefit.
The second layer is the one that actually keeps resolution inside the root: every already
segment-checked relative path is handed to a [`cap-std`](https://docs.rs/cap-std) `Dir`
capability opened on the root, never joined onto the root as an absolute OS path this crate
builds itself. `cap-std` resolves one path component at a time against real, already-open
directory handles, so a symlink or (on Windows) a directory junction anywhere under the root,
dangling or already pointing outside, cannot walk resolution above the root. There is no separate
"does this still look like it is inside the root" check with a window for the directory tree to
change underneath it between the check and the actual read or write; the one resolution is the
open.
## Hard links
A hard link is not a symlink, and this backend does not refuse one: from inside the sandbox the
inode it names is an ordinary file. What it protects instead is the shared inode's content: a
write never truncates its target in place. It writes a new sibling file and renames that sibling
over the target, so the target's directory entry is replaced rather than its bytes being
overwritten. A rename only ever changes one name; it does not reach through to any other name,
inside the root or out, that happens to point at the same inode.
+510
View File
@@ -0,0 +1,510 @@
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
//! A reference [`CloudBackend`] that treats one folder on disk as the cloud.
//!
//! [`craft_ui::cloud::CloudBackend`] names a contract and nothing about who
//! answers it. This crate is the proof: a working implementation that reaches
//! no service, a vendor, or a personal repo anybody else has to trust. An app
//! wires [`LocalBackend`] the same way it would wire a provider's own client,
//! by calling [`craft_ui::cloud::CloudFiles::connect`]. Swapping one for the
//! other is the whole point; nothing above the [`CloudBackend`] seam can tell
//! the difference.
//!
//! What this is not: a sync engine, a sharing service, or a place to keep a
//! credential. A folder has no concept of another account, so
//! [`Job::SharedWithMe`] answers empty and [`Job::Conversation`] answers with
//! a [`Fault`], and [`Account::capabilities`] claims neither. Reporting a
//! capability this backend cannot honour would be the broken window the
//! contract's own docs warn about.
//!
//! Every job answers on its own [`std::thread`]. [`CloudBackend::submit`]
//! must return before the file is opened, let alone read, or a twenty
//! megabyte document would freeze the window that called it.
//!
//! # The no-escape policy
//!
//! `Entry::id` and `Entry::path` are the same slash-separated path relative to
//! `root`, always starting with `/` below the root itself (the root's own
//! path is the empty string, matching [`Job::List`]'s contract), and a
//! [`Job::Create`] name is one plain file name, not a path at all. Neither is
//! an OS path string handed to `std::fs`. Confinement happens in two layers:
//!
//! 1. [`confine_segment`] (every path segment) and [`confine_name`] (a
//! `Create` name, stricter) reject `..`, `.`, an empty segment, an
//! absolute form, and anything that is not exactly one
//! [`std::path::Component::Normal`]. `confine_name` additionally refuses a
//! backslash, a colon, and a Windows reserved device name
//! (`CON`, `COM1`, `CONIN$`, ...) on every platform this crate builds for,
//! because a chosen name reaches this backend from whatever platform the
//! UI runs on. Browsing an *existing* name is more lenient: a literal `:`
//! or `\` already on disk (macOS stores a `/` typed in Finder as `:`) is
//! not itself a path separator on any platform's filesystem, so
//! `confine_segment` lets `list`, `read` and `write` keep such a name
//! reachable instead of discovering it and then refusing to open it.
//! 2. [`open_root`] opens `root` as a [`cap_std::fs::Dir`] capability once per
//! job. Every [`list`], [`read`], [`write`] and [`create`] routes its
//! already-segment-checked relative path through that one `Dir`, never
//! through an absolute OS path built by this crate. `cap_std` resolves one
//! component at a time against real, already-open directory handles, so a
//! symlink or a Windows junction anywhere under `root`, dangling or not,
//! cannot walk resolution above `root`: there is no separate "is this
//! still inside the root" check with a window for the directory tree to
//! change underneath it, because the one resolution *is* the open.
//!
//! A hard link is not a symlink and `cap_std` does not refuse one; the inode
//! it names is an ordinary file from inside the sandbox. [`write`] protects
//! it a different way: it always writes a sibling temporary file and renames
//! it over the target, rather than truncating the target in place. A rename
//! replaces one name's directory entry; it never reaches through to another
//! name that happens to point at the same inode outside `root`.
use std::ffi::OsStr;
use std::fs;
use std::io::{Read as _, Write as _};
use std::path::{Component, Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use cap_std::fs::{Dir, OpenOptions};
use craft_cloud::{Capability, Entry, EntryKind};
use craft_ui::cloud::{Account, CloudBackend, Event, Fault, Job, Post};
/// Where "the cloud" lives for this backend: one directory on disk.
pub struct LocalBackend {
root: PathBuf,
/// Shown in the account badge. Nothing else reads it.
display: String,
}
impl LocalBackend {
/// Treat `root` as the cloud. The directory is not created here; a
/// listing of a root that does not exist yet answers with a [`Fault`]
/// the same way a real provider's missing folder would. [`Job::Create`]
/// is the one exception, and always has been: it brings a fresh root
/// into existence itself, the same way a first Save As does not require
/// the destination folder to already be there.
pub fn new(root: PathBuf) -> LocalBackend {
LocalBackend { root, display: "Local disk".to_owned() }
}
/// Name shown in the account badge, in place of the default "Local disk".
pub fn named(mut self, display: impl Into<String>) -> LocalBackend {
self.display = display.into();
self
}
}
impl CloudBackend for LocalBackend {
fn submit(&self, job: Job, post: Post) {
let root = self.root.clone();
match job {
// Nothing is saved between runs and nothing was ever signed into,
// so there is nothing to forget. The trait states no answer for
// this job; CloudFiles::sign_out clears its own state regardless
// of whether anything ever arrives.
Job::SignOut => {}
Job::Account | Job::SignIn => {
let display = self.display.clone();
std::thread::spawn(move || post.send(Event::Account(Ok(account(display)))));
}
// There is no browser round trip: a local folder is already
// "linked" the moment it exists. Reporting that immediately,
// rather than inventing a URL nobody needs to visit, is what the
// contract calls honest.
Job::LinkStart | Job::LinkPoll(_) => {
std::thread::spawn(move || post.send(Event::Linked(Ok(true))));
}
Job::List(path) => {
std::thread::spawn(move || post.send(Event::Listed { entries: list(&root, &path), path }));
}
Job::SharedWithMe => {
std::thread::spawn(move || post.send(Event::Shared(Ok(Vec::new()))));
}
Job::Read { entry, into } => {
std::thread::spawn(move || match read(&root, &entry) {
Ok((entry, bytes)) => post.send(Event::Read { entry, into, bytes: Ok(bytes) }),
Err(fault) => post.send(Event::Read { entry, into, bytes: Err(fault) }),
});
}
Job::Write { uid, entry, bytes } => {
std::thread::spawn(move || post.send(Event::Saved { uid, entry: write(&root, &entry, &bytes) }));
}
Job::Create { uid, folder, name, bytes } => {
std::thread::spawn(move || post.send(Event::Saved { uid, entry: create(&root, &folder, &name, &bytes) }));
}
// No sharing, no accounts beyond this one, and so nowhere for a
// conversation to live. A reference backend that invented one
// would be lying about what a folder on disk can do.
Job::Conversation(_) => {
std::thread::spawn(move || {
post.send(Event::Conversation(Err(Fault::Refused("this reference backend has no shared workspace to converse in".to_owned()))))
});
}
}
}
}
fn account(display: String) -> Account {
Account { display, capabilities: vec![Capability::Files, Capability::Etags], provider_linked: true }
}
/// Turns a [`Job`]'s slash-separated path into a path relative to `root`,
/// refusing anything that is not a run of ordinary names. The result is
/// never joined onto `root` as an OS path; every caller hands it to a
/// [`cap_std::fs::Dir`] opened on `root` instead, which is the layer that
/// actually keeps resolution from leaving `root`.
///
/// `.` and repeated or leading slashes are just an empty segment and are
/// skipped, the same way a browser's address bar collapses them. Every other
/// segment goes through [`confine_segment`].
fn relative(path: &str) -> Result<PathBuf, Fault> {
let mut rel = PathBuf::new();
for segment in path.split('/') {
if segment.is_empty() || segment == "." {
continue;
}
rel.push(confine_segment(segment)?);
}
Ok(rel)
}
/// Confines one path segment to a single ordinary file or folder name.
///
/// Accepted only when `segment` parses as exactly one [`Component::Normal`]
/// equal to `segment` itself: no empty name, no `.` or `..`, no absolute
/// form, and nothing left over for a second component to hide in.
///
/// This is deliberately lenient about an ordinary character such as `:` or
/// `\` that is not, on its own, a path separator on any platform's
/// filesystem: `list` discovers real names from disk, and a name containing
/// one of those (macOS stores a `/` typed in Finder as `:` on disk) must stay
/// reachable by a later `read` or `write`, not become visible-but-unopenable.
/// [`confine_name`] is the stricter check for a name being chosen new, where
/// refusing those characters costs nothing and closes a real escape.
fn confine_segment(segment: &str) -> Result<&str, Fault> {
let mut components = Path::new(segment).components();
match (components.next(), components.next()) {
(Some(Component::Normal(name)), None) if name == OsStr::new(segment) => Ok(segment),
_ => Err(Fault::Refused(format!("{segment} is not a plain file name"))),
}
}
/// Windows device names that name a device rather than a file, with or
/// without a trailing extension (`CON`, `con.txt`, ...). Checked on every
/// platform: a name chosen here can end up read on a Windows client too.
const WINDOWS_RESERVED_NAMES: &[&str] = &[
"CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "LPT1", "LPT2", "LPT3",
"LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9",
];
fn is_windows_reserved_name(name: &str) -> bool {
let stem = name.split('.').next().unwrap_or(name);
WINDOWS_RESERVED_NAMES.iter().any(|reserved| stem.eq_ignore_ascii_case(reserved))
}
/// Confines a [`Job::Create`] `name` to a single ordinary file name that is
/// safe to choose on any platform, not only the one this crate is built for.
///
/// Stricter than [`confine_segment`]: a backslash or colon is refused
/// outright first, because a Unix build's [`Component`] parser does not
/// treat either as a separator and would wave a Windows drive letter or UNC
/// prefix (`C:`, `\\server\share`) straight through as one ordinary name. A
/// Windows reserved device name is refused the same way. None of this costs
/// anything here, unlike applying it to a name `list` merely discovered.
fn confine_name(name: &str) -> Result<&str, Fault> {
if name.contains('\\') || name.contains(':') {
return Err(Fault::Refused(format!("{name} is not a plain file name")));
}
if is_windows_reserved_name(name) {
return Err(Fault::Refused(format!("{name} is a reserved device name on Windows")));
}
confine_segment(name)
}
/// Opens `root` as the one ambient-authority capability this crate holds.
/// Every other path in this crate is resolved relative to the [`Dir`] this
/// returns, never as an absolute OS path built by string concatenation.
fn open_root(root: &Path) -> Result<Dir, Fault> {
Dir::open_ambient_dir(root, cap_std::ambient_authority()).map_err(|error| io_fault(&error))
}
/// The path a listed child gets, given the folder it was found in.
fn child_path(folder: &str, name: &str) -> String {
format!("{}/{name}", folder.trim_end_matches('/'))
}
/// An opaque version token for a file's current bytes.
///
/// Not a timestamp for a person to read (that would go through `chrono`, per
/// this workspace's rule); just enough to tell "the file I read" from "the
/// file as it is now" apart, which is all a conditional write needs.
fn etag_of(meta: &cap_std::fs::Metadata) -> String {
let stamp =
meta.modified().ok().and_then(|time| time.duration_since(cap_std::time::SystemClock::UNIX_EPOCH).ok()).map(|d| d.as_nanos()).unwrap_or(0);
format!("{}-{stamp}", meta.len())
}
fn io_fault(error: &std::io::Error) -> Fault {
use std::io::ErrorKind;
match error.kind() {
ErrorKind::NotFound => Fault::Refused("no such file or folder".to_owned()),
ErrorKind::PermissionDenied => Fault::Refused("permission denied".to_owned()),
_ => Fault::Unreachable(error.to_string()),
}
}
fn list(root: &Path, path: &str) -> Result<Vec<Entry>, Fault> {
let rel = relative(path)?;
let dir = open_root(root)?;
let read = if rel.as_os_str().is_empty() { dir.entries() } else { dir.read_dir(&rel) };
let read = read.map_err(|error| io_fault(&error))?;
let mut entries = Vec::new();
for item in read {
let item = item.map_err(|error| io_fault(&error))?;
let meta = item.metadata().map_err(|error| io_fault(&error))?;
let name = item.file_name().to_string_lossy().into_owned();
let id = child_path(path, &name);
entries.push(Entry {
room: format!("local:{id}"),
name,
kind: if meta.is_dir() { EntryKind::Folder } else { EntryKind::File },
size: if meta.is_dir() { None } else { Some(meta.len()) },
modified: None,
mime: None,
etag: if meta.is_dir() { None } else { Some(etag_of(&meta)) },
writable: true,
shared_by: None,
path: id.clone(),
id,
});
}
entries.sort_by(|a, b| (a.kind != EntryKind::Folder, &a.name).cmp(&(b.kind != EntryKind::Folder, &b.name)));
Ok(entries)
}
/// Reads a file's bytes together with the entry for the version just read.
///
/// The entry is built from a fresh metadata call here, not handed back
/// unchanged from what the caller already believed. A reload after a conflict
/// hands in the stale entry it is trying to get past; echoing that back would
/// carry the old etag into the reloaded document, so the very next save would
/// conflict again on a copy that is actually current.
///
/// Refuses outright if `entry.id` names a symlink, the same policy `write`
/// uses: this backend never reports the bytes of whatever a link happens to
/// point at, inside `root` or out.
fn read(root: &Path, entry: &Entry) -> Result<(Entry, Vec<u8>), Fault> {
let rel = relative(&entry.id)?;
let dir = open_root(root)?;
// Stats without following only the last component; every component
// before it is still resolved, and sandboxed, normally, so a link
// earlier in `rel` is refused by `open_root`'s `Dir` itself when `open`
// below walks it, never silently followed here either way.
match dir.symlink_metadata(&rel) {
Ok(meta) if meta.is_symlink() => return Err(Fault::Refused("that path is a link, not a plain file".to_owned())),
Ok(_) => {}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => return Err(io_fault(&error)),
}
let mut file = dir.open(&rel).map_err(|error| io_fault(&error))?;
let mut bytes = Vec::new();
file.read_to_end(&mut bytes).map_err(|error| io_fault(&error))?;
let meta = file.metadata().map_err(|error| io_fault(&error))?;
let fresh = Entry { size: Some(meta.len()), etag: Some(etag_of(&meta)), ..entry.clone() };
Ok((fresh, bytes))
}
/// Saves back over `entry`, refusing the write when the file moved on since
/// `entry.etag` was read. A file that no longer exists has nothing to
/// conflict with, the same way a provider treats a deleted document.
///
/// Never truncates `entry.id`'s current bytes in place. [`write_replacing`]
/// writes a sibling temporary file and renames it over the target instead,
/// so a hard link sharing the target's inode keeps its own, unmodified copy:
/// the rename replaces `entry.id`'s directory entry, and never reaches
/// through to any other name pointing at the same inode.
fn write(root: &Path, entry: &Entry, bytes: &[u8]) -> Result<Entry, Fault> {
let rel = relative(&entry.id)?;
let dir = open_root(root)?;
match dir.symlink_metadata(&rel) {
Ok(meta) if meta.is_symlink() => return Err(Fault::Refused("that path is a link, not a plain file".to_owned())),
Ok(meta) => {
if Some(etag_of(&meta)) != entry.etag {
return Err(Fault::Conflict);
}
}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => return Err(io_fault(&error)),
}
if let Some(parent) = rel.parent() {
dir.create_dir_all(parent).map_err(|error| io_fault(&error))?;
}
write_replacing(&dir, &rel, bytes)?;
let meta = dir.metadata(&rel).map_err(|error| io_fault(&error))?;
Ok(Entry { size: Some(meta.len()), etag: Some(etag_of(&meta)), ..entry.clone() })
}
/// The next in a run of sibling temporary names, unique within this process.
/// Not meant to resist a second process picking the same name; the create
/// this writes with is exclusive (`create_new`), so a collision there is
/// just retried under a new counter value rather than silently overwritten.
static TEMP_SEQUENCE: AtomicU64 = AtomicU64::new(0);
/// Writes `bytes` to a new sibling of `rel` inside `dir`, then renames that
/// sibling over `rel`. See the module docs for why: a direct write would
/// truncate whatever `rel` currently names in place, and if that happens to
/// be a hard link to a file outside `root`, the outside copy would be
/// corrupted along with it. A rename only ever replaces `rel`'s own
/// directory entry.
fn write_replacing(dir: &Dir, rel: &Path, bytes: &[u8]) -> Result<(), Fault> {
let name = rel.file_name().ok_or_else(|| Fault::Refused("that path names no file".to_owned()))?;
let mut temp_name = OsStr::new(".").to_os_string();
temp_name.push(name);
temp_name.push(format!(".tmp-{}-{}", std::process::id(), TEMP_SEQUENCE.fetch_add(1, Ordering::Relaxed)));
let temp_rel = match rel.parent() {
Some(parent) if !parent.as_os_str().is_empty() => parent.join(&temp_name),
_ => PathBuf::from(&temp_name),
};
let mut options = OpenOptions::new();
options.write(true).create_new(true);
let written = (|| -> Result<(), Fault> {
let mut handle = dir.open_with(&temp_rel, &options).map_err(|error| io_fault(&error))?;
handle.write_all(bytes).map_err(|error| io_fault(&error))?;
handle.sync_all().map_err(|error| io_fault(&error))
})();
if let Err(fault) = written {
let _ = dir.remove_file(&temp_rel);
return Err(fault);
}
if let Err(error) = dir.rename(&temp_rel, dir, rel) {
let _ = dir.remove_file(&temp_rel);
return Err(io_fault(&error));
}
Ok(())
}
fn create(root: &Path, folder: &str, name: &str, bytes: &[u8]) -> Result<Entry, Fault> {
// `name` is never a path: it is one `Job::Create` field that names the
// new file, so it goes through `confine_name` directly rather than
// through `relative`, which only ever splits and confines a slash path.
let name = confine_name(name)?;
// `root` is the operator-configured boundary, never attacker input, so
// creating it directly with `std::fs` is safe; this is also the one
// place that has always brought a fresh root into existence (see
// `LocalBackend::new`'s docs), and `Dir::open_ambient_dir` below needs it
// to already exist.
fs::create_dir_all(root).map_err(|error| io_fault(&error))?;
let dir = open_root(root)?;
let rel_folder = relative(folder)?;
dir.create_dir_all(&rel_folder).map_err(|error| io_fault(&error))?;
let rel = rel_folder.join(name);
// Exclusive creation, not an `exists` check ahead of a separate write: two
// creates of the same name racing both see "not there yet" otherwise, and
// the second write silently replaces the first with neither ever refused.
// `create_new` asks the filesystem to open and create in one step, so the
// loser gets an error instead of a chance to overwrite the winner. It also
// refuses outright when `name` already exists as a symlink, dangling or
// not: `O_EXCL` never follows one to decide whether it is "in the way".
let mut create_options = OpenOptions::new();
create_options.write(true).create_new(true);
let mut handle = match dir.open_with(&rel, &create_options) {
Ok(handle) => handle,
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
return Err(Fault::Refused(format!("{name} already exists")));
}
Err(error) => return Err(io_fault(&error)),
};
handle.write_all(bytes).map_err(|error| io_fault(&error))?;
drop(handle);
let meta = dir.metadata(&rel).map_err(|error| io_fault(&error))?;
let id = child_path(folder, name);
Ok(Entry {
room: format!("local:{id}"),
name: name.to_owned(),
kind: EntryKind::File,
size: Some(meta.len()),
modified: None,
mime: None,
etag: Some(etag_of(&meta)),
writable: true,
shared_by: None,
path: id.clone(),
id,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_parent_segment_cannot_walk_out_of_root() {
assert!(relative("../secrets").is_err());
assert!(relative("Archive/../../../etc/passwd").is_err());
}
#[test]
fn repeated_and_trailing_slashes_collapse_like_a_browser_address_bar() {
assert_eq!(relative("//Archive//2026/").unwrap(), Path::new("Archive").join("2026"));
assert_eq!(relative("").unwrap(), PathBuf::new());
}
#[test]
fn confine_segment_accepts_only_a_single_ordinary_name() {
for ordinary in ["Minutes.txt", "Archive", "2026", "a name with spaces.docx"] {
assert!(confine_segment(ordinary).is_ok(), "{ordinary} is an ordinary name");
}
}
#[test]
fn confine_segment_refuses_empty_dot_and_dot_dot() {
for bad in ["", ".", ".."] {
assert!(confine_segment(bad).is_err(), "{bad:?} is not a single ordinary name");
}
}
#[test]
fn confine_segment_refuses_a_slash_hidden_inside_a_create_name() {
assert!(confine_segment("folder/evil").is_err());
assert!(confine_segment("../outside.txt").is_err());
assert!(confine_segment("/outside.txt").is_err());
}
/// The fix for the non-blocking finding that `list` made a real macOS
/// name (a literal `/`, stored on disk as `:`) visible but unreadable: an
/// existing name with an ordinary `:` byte is not refused by the lenient
/// per-segment check, only by `confine_name` for a chosen one. A literal
/// `\` is not tested the same way here: on a Windows build it really is
/// a second path component (`std::path::Component` already splits on
/// it), so there is no existing-name case for `confine_segment` to stay
/// lenient about cross-platform the way there is for `:`.
#[test]
fn confine_segment_tolerates_a_colon_already_on_disk() {
assert!(confine_segment("weird:name.txt").is_ok());
assert!(relative("weird:name.txt").is_ok());
}
#[test]
fn confine_name_refuses_backslash_and_colon_on_every_platform() {
for bad in ["..\\outside.txt", "C:\\x", "C:evil", "\\\\server\\share\\x"] {
assert!(confine_name(bad).is_err(), "{bad:?} must be refused on every platform, not only on Windows");
}
}
#[test]
fn confine_name_refuses_windows_reserved_device_names() {
for bad in ["CON", "con", "con.txt", "NUL", "COM1", "lpt9.log", "CONIN$"] {
assert!(confine_name(bad).is_err(), "{bad:?} names a Windows device, not a file");
}
for ordinary in ["console.txt", "NULLABLE.md", "COM10"] {
assert!(confine_name(ordinary).is_ok(), "{ordinary} only resembles a reserved name");
}
}
#[test]
fn a_folder_announces_no_capability_this_backend_cannot_honour() {
let reported = account("Local disk".to_owned()).capabilities;
for absent in [Capability::SharedWithMe, Capability::Sharing, Capability::Conversation, Capability::Contacts] {
assert!(!reported.contains(&absent), "a folder has no {absent:?}");
}
}
}
+244
View File
@@ -0,0 +1,244 @@
//! Drives [`craft_cloud_local::LocalBackend`] the way an app does: through
//! `craft_ui::cloud`'s own public functions, never by calling the backend
//! directly. That is the seam this crate exists to prove, so the tests stay
//! on the application's side of it.
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use craft_cloud::{Entry, EntryKind};
use craft_cloud_local::LocalBackend;
use craft_ui::cloud::{self, Account, CloudApp, CloudFiles, Destination, DocumentKind, Job};
const NOTE: DocumentKind = DocumentKind { extensions: &["txt"], mimes: &["text/plain"], noun: "note", default_extension: "txt" };
/// A document the harness was told to open: its name and its bytes.
type OpenedDocs = Arc<Mutex<Vec<(String, Vec<u8>)>>>;
/// The least a [`CloudApp`] can be. What it was told to open is recorded, so a
/// round trip can be checked by content and not only by the entry metadata
/// `craft_ui` itself remembers.
struct Harness {
cloud: CloudFiles,
share: craft_ui::share::ShareDialog,
presence: craft_ui::presence::PresenceBar,
opened: OpenedDocs,
said: Arc<Mutex<Vec<String>>>,
}
impl Harness {
fn new() -> Harness {
Harness {
cloud: CloudFiles::new(),
share: craft_ui::share::ShareDialog::new(),
presence: craft_ui::presence::PresenceBar::new(),
opened: Arc::new(Mutex::new(Vec::new())),
said: Arc::new(Mutex::new(Vec::new())),
}
}
}
impl CloudApp for Harness {
fn cloud(&self) -> &CloudFiles {
&self.cloud
}
fn cloud_mut(&mut self) -> &mut CloudFiles {
&mut self.cloud
}
fn kind(&self) -> DocumentKind {
NOTE
}
fn active(&self) -> Option<u64> {
None
}
fn title(&self, _uid: u64) -> String {
String::new()
}
fn open_bytes(&mut self, name: &str, bytes: Vec<u8>) -> Result<Option<u64>, String> {
self.opened.lock().unwrap().push((name.to_owned(), bytes));
Ok(Some(1))
}
fn encode(&mut self, _uid: u64, _into: Destination<'_>) -> Result<Vec<u8>, String> {
Ok(Vec::new())
}
fn close(&mut self, _uid: u64) {}
fn sharing(&mut self) -> &mut craft_ui::share::ShareDialog {
&mut self.share
}
fn presence(&mut self) -> &mut craft_ui::presence::PresenceBar {
&mut self.presence
}
fn paint_icon(&self, _painter: &egui::Painter, _rect: egui::Rect, _kind: EntryKind, _colour: egui::Color32) {}
fn open_url(&self, _url: &str) {}
fn say(&mut self, text: String) {
self.said.lock().unwrap().push(text);
}
fn app_name(&self) -> &str {
"Harness"
}
}
fn wired(root: std::path::PathBuf) -> (Harness, egui::Context) {
let mut app = Harness::new();
app.cloud.connect(LocalBackend::new(root));
(app, egui::Context::default())
}
/// Drains whatever the backend's worker threads have sent so far, until
/// `done` says the state the test is waiting for arrived or five seconds pass.
/// Five seconds is far more than a thread doing local file IO ever needs; it
/// only guards against a real bug leaving the test to hang forever.
fn settle(app: &mut Harness, ctx: &egui::Context, mut done: impl FnMut(&Harness) -> bool) {
let start = Instant::now();
loop {
ctx.begin_pass(Default::default());
cloud::pump(app, ctx);
ctx.end_pass().textures_delta.clear();
if done(app) {
return;
}
assert!(start.elapsed() < Duration::from_secs(5), "timed out waiting for the backend's worker thread");
std::thread::sleep(Duration::from_millis(5));
}
}
#[test]
fn account_and_sign_in_report_the_same_fixed_identity_with_no_browser_round_trip() {
let dir = tempfile::tempdir().unwrap();
let (mut app, ctx) = wired(dir.path().to_path_buf());
cloud::start(&mut app);
settle(&mut app, &ctx, |app| app.cloud().account.is_some());
assert_eq!(
app.cloud().account,
Some(Account {
display: "Local disk".to_owned(),
capabilities: vec![craft_cloud::Capability::Files, craft_cloud::Capability::Etags],
provider_linked: true
})
);
// There was never an account to link, so nothing was ever offered.
assert!(app.cloud().link.is_none());
}
#[test]
fn creating_a_document_writes_real_bytes_a_read_gets_back() {
let dir = tempfile::tempdir().unwrap();
let (mut app, ctx) = wired(dir.path().to_path_buf());
cloud::submit(&app, Job::Create { uid: 1, folder: String::new(), name: "Minutes.txt".to_owned(), bytes: b"first draft".to_vec() });
settle(&mut app, &ctx, |app| app.cloud().origins.contains_key(&1));
let entry = app.cloud().origins.get(&1).unwrap().entry.clone();
assert_eq!(entry.name, "Minutes.txt");
assert_eq!(entry.id, "/Minutes.txt");
assert_eq!(fs_read(dir.path(), "Minutes.txt"), b"first draft");
cloud::submit(&app, Job::Read { entry, into: None });
settle(&mut app, &ctx, |app| !app.opened.lock().unwrap().is_empty());
let opened = app.opened.lock().unwrap().clone();
assert_eq!(opened, vec![("Minutes.txt".to_owned(), b"first draft".to_vec())], "the read got back exactly what the create wrote");
}
#[test]
fn a_write_under_a_stale_version_is_refused_and_never_overwrites_the_newer_file() {
let dir = tempfile::tempdir().unwrap();
let (mut app, ctx) = wired(dir.path().to_path_buf());
cloud::submit(&app, Job::Create { uid: 1, folder: String::new(), name: "Minutes.txt".to_owned(), bytes: b"v1".to_vec() });
settle(&mut app, &ctx, |app| app.cloud().origins.contains_key(&1));
let stale = app.cloud().origins.get(&1).unwrap().entry.clone();
// Somebody else saves first, changing the file's etag without going
// through this window at all.
std::fs::write(dir.path().join("Minutes.txt"), b"somebody else's edit").unwrap();
cloud::submit(&app, Job::Write { uid: 1, entry: stale, bytes: b"this window's edit".to_vec() });
settle(&mut app, &ctx, |app| app.cloud().conflict.is_some());
assert_eq!(app.cloud().conflict.as_ref().unwrap().uid, 1);
assert_eq!(fs_read(dir.path(), "Minutes.txt"), b"somebody else's edit", "the refused write never touched the file");
}
#[test]
fn listing_the_root_reflects_a_file_nobody_went_through_this_backend_to_write() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("Agenda.txt"), b"1. roll call").unwrap();
std::fs::create_dir(dir.path().join("Archive")).unwrap();
let (mut app, ctx) = wired(dir.path().to_path_buf());
cloud::browse(&mut app, "");
settle(&mut app, &ctx, |app| app.cloud().mine.loaded);
let names: Vec<_> = app.cloud().mine.entries.iter().map(|entry| entry.name.clone()).collect();
assert_eq!(names, vec!["Archive".to_owned(), "Agenda.txt".to_owned()], "folders first, then files, each alphabetised");
let folder = app.cloud().mine.entries.iter().find(|entry| entry.name == "Archive").unwrap();
assert_eq!(folder.kind, EntryKind::Folder);
assert!(folder.size.is_none());
}
#[test]
fn nobody_has_shared_anything_with_a_folder() {
let dir = tempfile::tempdir().unwrap();
let (mut app, ctx) = wired(dir.path().to_path_buf());
cloud::load_shared(&mut app);
settle(&mut app, &ctx, |app| app.cloud().shared.loaded);
assert_eq!(app.cloud().shared.entries, Vec::new());
assert!(app.cloud().shared.error.is_none(), "an empty share list is not a failure");
}
#[test]
fn a_conversation_is_a_fault_this_backend_is_honest_about() {
let dir = tempfile::tempdir().unwrap();
let (mut app, ctx) = wired(dir.path().to_path_buf());
cloud::submit(&app, Job::Conversation("/Minutes.txt".to_owned()));
settle(&mut app, &ctx, |app| app.cloud().status.is_some());
assert_eq!(app.cloud().status, Some("this reference backend has no shared workspace to converse in".to_owned()));
}
#[test]
fn a_read_of_a_document_that_is_not_there_is_put_to_the_user_not_silently_dropped() {
let dir = tempfile::tempdir().unwrap();
let (mut app, ctx) = wired(dir.path().to_path_buf());
let ghost = Entry {
id: "/ghost.txt".to_owned(),
room: "local:/ghost.txt".to_owned(),
name: "ghost.txt".to_owned(),
path: "/ghost.txt".to_owned(),
kind: EntryKind::File,
size: None,
modified: None,
mime: None,
etag: None,
writable: true,
shared_by: None,
};
cloud::submit(&app, Job::Read { entry: ghost, into: None });
settle(&mut app, &ctx, |app| !app.said.lock().unwrap().is_empty());
assert!(app.said.lock().unwrap()[0].contains("ghost.txt"), "the message names the document, not just that something failed");
}
fn fs_read(root: &std::path::Path, name: &str) -> Vec<u8> {
std::fs::read(root.join(name)).unwrap()
}
@@ -0,0 +1,431 @@
//! Confinement regressions for `crates/cloud-local`. The first round (FredApps' re-review) found
//! that `resolve` only split on `/` and rejected a segment equal to `..`, with no constraint on a
//! Windows backslash, a drive letter or UNC prefix, or a filesystem link, and that `create`
//! joined `name` onto the resolved folder with no validation of `name` at all. The second round
//! (benandez's re-review) reproduced three escapes the first fix still left open: a dangling
//! symlink, a check-then-use race on a swapped link, and a hard link sharing a file's inode.
//! Driven through `craft_ui::cloud`'s public functions the way an application does, with a
//! sentinel file and directory kept as a sibling of the configured root: every test here must
//! leave both untouched and unread.
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use craft_cloud::{Entry, EntryKind};
use craft_cloud_local::LocalBackend;
use craft_ui::cloud::{self, CloudApp, CloudFiles, Destination, DocumentKind, Job};
const NOTE: DocumentKind = DocumentKind { extensions: &["txt"], mimes: &["text/plain"], noun: "note", default_extension: "txt" };
/// A document the harness was told to open: its name and its bytes.
type OpenedDocs = Arc<Mutex<Vec<(String, Vec<u8>)>>>;
struct Harness {
cloud: CloudFiles,
share: craft_ui::share::ShareDialog,
presence: craft_ui::presence::PresenceBar,
opened: OpenedDocs,
said: Arc<Mutex<Vec<String>>>,
}
impl Harness {
fn new() -> Harness {
Harness {
cloud: CloudFiles::new(),
share: craft_ui::share::ShareDialog::new(),
presence: craft_ui::presence::PresenceBar::new(),
opened: Arc::new(Mutex::new(Vec::new())),
said: Arc::new(Mutex::new(Vec::new())),
}
}
}
impl CloudApp for Harness {
fn cloud(&self) -> &CloudFiles {
&self.cloud
}
fn cloud_mut(&mut self) -> &mut CloudFiles {
&mut self.cloud
}
fn kind(&self) -> DocumentKind {
NOTE
}
fn active(&self) -> Option<u64> {
None
}
fn title(&self, _uid: u64) -> String {
String::new()
}
fn open_bytes(&mut self, name: &str, bytes: Vec<u8>) -> Result<Option<u64>, String> {
self.opened.lock().unwrap().push((name.to_owned(), bytes));
Ok(Some(1))
}
fn encode(&mut self, _uid: u64, _into: Destination<'_>) -> Result<Vec<u8>, String> {
Ok(Vec::new())
}
fn close(&mut self, _uid: u64) {}
fn sharing(&mut self) -> &mut craft_ui::share::ShareDialog {
&mut self.share
}
fn presence(&mut self) -> &mut craft_ui::presence::PresenceBar {
&mut self.presence
}
fn paint_icon(&self, _painter: &egui::Painter, _rect: egui::Rect, _kind: EntryKind, _colour: egui::Color32) {}
fn open_url(&self, _url: &str) {}
fn say(&mut self, text: String) {
self.said.lock().unwrap().push(text);
}
fn app_name(&self) -> &str {
"Harness"
}
}
fn wired(root: PathBuf) -> (Harness, egui::Context) {
let mut app = Harness::new();
app.cloud.connect(LocalBackend::new(root));
(app, egui::Context::default())
}
/// Drains whatever the backend's worker threads have sent so far, until `done` says the state
/// the test is waiting for arrived or five seconds pass. Five seconds is far more than a thread
/// doing local file IO ever needs; it only guards against a real bug leaving the test to hang.
fn settle(app: &mut Harness, ctx: &egui::Context, mut done: impl FnMut(&Harness) -> bool) {
let start = Instant::now();
loop {
ctx.begin_pass(Default::default());
cloud::pump(app, ctx);
ctx.end_pass().textures_delta.clear();
if done(app) {
return;
}
assert!(start.elapsed() < Duration::from_secs(5), "timed out waiting for the backend's worker thread");
std::thread::sleep(Duration::from_millis(5));
}
}
/// Clears both event sinks, then waits for the next job to land in either one. Clearing first
/// matters for a test that submits several jobs in a loop: without it, a stale `said` from two
/// iterations ago would satisfy `settle` immediately, before the new job had actually answered.
fn said(app: &mut Harness, ctx: &egui::Context) -> Vec<String> {
app.opened.lock().unwrap().clear();
app.said.lock().unwrap().clear();
settle(app, ctx, |app| !app.said.lock().unwrap().is_empty() || !app.opened.lock().unwrap().is_empty());
app.said.lock().unwrap().clone()
}
/// A tempdir holding the cloud root, plus a sentinel file and a sentinel directory that sit
/// beside it rather than inside it. Every test below must leave both exactly as they start.
struct Sentinels {
// Kept only so the tempdir outlives every test that borrows the paths below; nothing reads
// it back once the paths it was built from are in hand.
_arena: tempfile::TempDir,
root: PathBuf,
sentinel_file: PathBuf,
sentinel_dir: PathBuf,
}
const SENTINEL_FILE_BYTES: &[u8] = b"a sibling file this backend must never read or write";
const SENTINEL_DIR_FILE_BYTES: &[u8] = b"a sibling directory this backend must never list";
fn sentinels() -> Sentinels {
let arena = tempfile::tempdir().unwrap();
let root = arena.path().join("root");
std::fs::create_dir(&root).unwrap();
let sentinel_file = arena.path().join("sentinel.txt");
std::fs::write(&sentinel_file, SENTINEL_FILE_BYTES).unwrap();
let sentinel_dir = arena.path().join("sentinel-dir");
std::fs::create_dir(&sentinel_dir).unwrap();
std::fs::write(sentinel_dir.join("secret.txt"), SENTINEL_DIR_FILE_BYTES).unwrap();
Sentinels { _arena: arena, root, sentinel_file, sentinel_dir }
}
fn assert_sentinels_untouched(sentinels: &Sentinels) {
assert_eq!(std::fs::read(&sentinels.sentinel_file).unwrap(), SENTINEL_FILE_BYTES, "the sentinel file outside the root was changed");
assert_eq!(
std::fs::read(sentinels.sentinel_dir.join("secret.txt")).unwrap(),
SENTINEL_DIR_FILE_BYTES,
"the sentinel directory's file outside the root was changed"
);
}
/// Every one of these is a [`Job::Create`] `name` that must be refused before any byte reaches
/// disk: the review's own examples (a parent segment, an absolute path, and the three
/// Windows-shaped forms), none of which a Unix build's native parser alone would catch, and a
/// name that already is nothing but a Windows separator or drive prefix on top of that.
fn malicious_create_names() -> Vec<&'static str> {
vec!["../sentinel.txt", "/sentinel.txt", "..\\sentinel.txt", "C:\\x", "C:evil", "\\\\server\\share\\x"]
}
#[test]
fn create_refuses_every_escaping_name_and_the_sentinels_stay_untouched() {
for name in malicious_create_names() {
let sentinels = sentinels();
let (mut app, ctx) = wired(sentinels.root.clone());
cloud::submit(&app, Job::Create { uid: 1, folder: String::new(), name: name.to_owned(), bytes: b"pwned".to_vec() });
let messages = said(&mut app, &ctx);
assert!(cloud::origin(&app).is_none(), "{name:?} must not be reported as created");
assert!(!messages.is_empty(), "{name:?} must be refused, not silently dropped");
assert_sentinels_untouched(&sentinels);
}
}
// ------------------------------------------------------------------- link-based escapes
//
// `escape(&sentinels)` places one link named `escape` inside the cloud root, pointing out to
// `sentinels.sentinel_dir`: a symlink on Unix, a directory junction on Windows, which needs no
// elevated privilege, unlike a Windows symlink. The Linux gate runs the symlink half of every
// test below; CI's windows-latest lanes run the junction half. Either way `root/escape/...`
// reaches into the sentinel directory through the link.
/// Nothing to clean up on Unix: `tempfile`'s own recursive removal of the arena directory
/// removes a plain symlink entry without following it. This exists only so `escape` returns the
/// same shape of RAII handle on every platform, rather than a bare `()` some lint would flag.
#[cfg(unix)]
struct Linked;
#[cfg(unix)]
fn escape(sentinels: &Sentinels) -> Linked {
std::os::unix::fs::symlink(&sentinels.sentinel_dir, sentinels.root.join("escape")).unwrap();
Linked
}
/// A directory junction, removed on drop before the tempdir it sits beside is cleaned up.
#[cfg(windows)]
struct Junction(PathBuf);
#[cfg(windows)]
impl Drop for Junction {
fn drop(&mut self) {
let _ = std::fs::remove_dir(&self.0);
}
}
#[cfg(windows)]
fn escape(sentinels: &Sentinels) -> Junction {
use std::os::windows::process::CommandExt as _;
let link = sentinels.root.join("escape");
let target = &sentinels.sentinel_dir;
assert!(link.is_absolute() && target.is_absolute());
let output = std::process::Command::new("cmd")
.args(["/C", "mklink", "/J"])
.arg(&link)
.arg(target)
.creation_flags(0x0800_0000) // CREATE_NO_WINDOW
.output()
.unwrap();
assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr));
Junction(link)
}
/// An [`Entry`] stub naming `id`, for a [`Job::Read`] or [`Job::Write`] this file submits
/// directly rather than through an entry the backend itself handed back.
fn leaked_entry(id: &str, name: &str) -> Entry {
Entry {
id: id.to_owned(),
room: format!("local:{id}"),
name: name.to_owned(),
path: id.to_owned(),
kind: EntryKind::File,
size: None,
modified: None,
mime: None,
etag: None,
writable: true,
shared_by: None,
}
}
#[cfg(any(unix, windows))]
#[test]
fn listing_a_linked_folder_cannot_see_outside_the_root() {
let sentinels = sentinels();
let (mut app, ctx) = wired(sentinels.root.clone());
let _escape = escape(&sentinels);
cloud::browse(&mut app, "escape");
settle(&mut app, &ctx, |app| app.cloud().mine.loaded);
assert!(app.cloud().mine.error.is_some(), "listing through a symlink or junction out of the root must be refused");
assert!(app.cloud().mine.entries.is_empty());
assert_sentinels_untouched(&sentinels);
}
#[cfg(any(unix, windows))]
#[test]
fn reading_through_a_linked_folder_cannot_return_bytes_from_outside_the_root() {
let sentinels = sentinels();
let (mut app, ctx) = wired(sentinels.root.clone());
let _escape = escape(&sentinels);
cloud::submit(&app, Job::Read { entry: leaked_entry("/escape/secret.txt", "secret.txt"), into: None });
said(&mut app, &ctx);
assert!(app.opened.lock().unwrap().is_empty(), "a read through a symlink or junction out of the root must not deliver bytes");
assert_sentinels_untouched(&sentinels);
}
/// benandez's finding 4: the original version of this test targeted the pre-existing
/// `secret.txt`, with `etag: None`. `write` refused that for an unrelated reason, a version
/// mismatch, before confinement ever ran, so the test passed whether or not confinement worked.
/// Targeting a name that does not exist yet under the link reaches the code that actually
/// matters, and the oracle (the file must never be created) is one confinement failing would
/// actually flip.
#[cfg(any(unix, windows))]
#[test]
fn writing_through_a_linked_folder_cannot_create_a_file_outside_the_root() {
let sentinels = sentinels();
let (mut app, ctx) = wired(sentinels.root.clone());
let _escape = escape(&sentinels);
cloud::submit(&app, Job::Write { uid: 1, entry: leaked_entry("/escape/not-yet-created.txt", "not-yet-created.txt"), bytes: b"pwned".to_vec() });
said(&mut app, &ctx);
assert!(!sentinels.sentinel_dir.join("not-yet-created.txt").exists(), "a write through a link must not create a file outside the root");
assert_sentinels_untouched(&sentinels);
}
/// benandez's finding 5: nothing previously exercised a link in the `folder` a `Create` targets.
#[cfg(any(unix, windows))]
#[test]
fn creating_through_a_linked_folder_cannot_create_a_file_outside_the_root() {
let sentinels = sentinels();
let (mut app, ctx) = wired(sentinels.root.clone());
let _escape = escape(&sentinels);
cloud::submit(&app, Job::Create { uid: 1, folder: "escape".to_owned(), name: "new.txt".to_owned(), bytes: b"pwned".to_vec() });
let messages = said(&mut app, &ctx);
assert!(cloud::origin(&app).is_none(), "a create into a linked folder must not be reported as created");
assert!(!messages.is_empty(), "a create into a linked folder must be refused, not silently dropped");
assert!(!sentinels.sentinel_dir.join("new.txt").exists(), "a create through a link must not create a file outside the root");
assert_sentinels_untouched(&sentinels);
}
// ------------------------------------------------------------------- Unix-only reproductions
//
// Directory junctions cannot be dangling (`mklink /J` requires the target to exist) and the
// race and hard-link reproductions below are exactly benandez's own repros, run on Linux only,
// as stated in that review. The structural fix (resolving through a `cap_std::fs::Dir`, and
// writing through a temporary file and rename) is the same code on every platform; these three
// just do not have a Windows-shaped equivalent worth a separate repro.
/// benandez's finding 1, reproduced exactly: `root/doc.txt` is a symlink to a file that does not
/// exist yet, outside the root. The old code's `confine_to_root` canonicalised the dangling link
/// to `NotFound`, walked up to `root`, accepted it, found no file to conflict with, and `write`
/// created the target for real, outside the root.
#[cfg(unix)]
#[test]
fn writing_through_a_dangling_symlink_cannot_create_a_file_outside_the_root() {
let sentinels = sentinels();
let outside_target = sentinels._arena.path().join("outside-planted.txt");
std::os::unix::fs::symlink(&outside_target, sentinels.root.join("doc.txt")).unwrap();
let (mut app, ctx) = wired(sentinels.root.clone());
cloud::submit(&app, Job::Write { uid: 1, entry: leaked_entry("/doc.txt", "doc.txt"), bytes: b"pwned".to_vec() });
said(&mut app, &ctx);
assert!(!outside_target.exists(), "a write through a dangling symlink must not create its target outside the root");
assert_sentinels_untouched(&sentinels);
}
/// benandez's finding 3, reproduced exactly: `root/hl` is a hard link sharing an inode with a
/// file outside the root. Reading it through the backend is legitimate (it is, from inside the
/// sandbox, an ordinary file), which is also how this test gets a real, matching etag to write
/// with, the same way a real caller would after opening the document. The old code's `write`
/// truncated the shared inode in place; `write_replacing` must instead replace `hl`'s own
/// directory entry, leaving the sentinel file's inode, and its other name, untouched.
#[cfg(unix)]
#[test]
fn writing_through_a_hard_link_replaces_the_entry_without_touching_the_shared_file() {
let sentinels = sentinels();
std::fs::hard_link(&sentinels.sentinel_file, sentinels.root.join("hl")).unwrap();
let (mut app, ctx) = wired(sentinels.root.clone());
cloud::submit(&app, Job::Read { entry: leaked_entry("/hl", "hl"), into: None });
settle(&mut app, &ctx, |app| !app.opened.lock().unwrap().is_empty());
let real_entry = app.cloud().origins.get(&1).expect("the read registered an origin for uid 1").entry.clone();
// A successful write answers through `cloud.status`, not through `said` or `opened`, so it
// needs its own wait condition rather than the `said` helper used everywhere else in this
// file for a refusal. The read above already set `status` once (`Opened hl from the
// cloud.`), so that has to be cleared first or this would observe the read's own status and
// never actually wait for the write to finish.
app.cloud_mut().status = None;
cloud::submit(&app, Job::Write { uid: 1, entry: real_entry, bytes: b"replaced via rename, not truncated in place".to_vec() });
settle(&mut app, &ctx, |app| app.cloud().status.is_some() || app.cloud().conflict.is_some() || !app.said.lock().unwrap().is_empty());
assert!(app.cloud().conflict.is_none(), "the write through the hard-linked name should succeed, not conflict");
assert!(
app.said.lock().unwrap().is_empty(),
"the write through the hard-linked name should succeed, not be refused: {:?}",
app.said.lock().unwrap()
);
assert_eq!(
std::fs::read(sentinels.root.join("hl")).unwrap(),
b"replaced via rename, not truncated in place",
"the write through the hard-linked name should still succeed"
);
assert_sentinels_untouched(&sentinels);
}
/// benandez's finding 2, reproduced at a smaller scale: a background thread swaps `root/d`
/// between a symlink into an inside folder and a symlink to the sentinel directory, as fast as
/// it can, with no coordination with the reads below. The old code's `confine_to_root` checked
/// one path string and then `fs::read` resolved that path again, a second, later lookup a swap
/// could land in between; out of 3000 such reads benandez's own run returned the outside file's
/// bytes 347 times. `cap_std::fs::Dir::open` resolves and opens `d` as one operation with no
/// such second lookup, so this must come back empty every time, not merely most of the time.
#[cfg(unix)]
#[test]
fn reading_through_a_link_being_swapped_never_observes_the_outside_target() {
use std::sync::atomic::{AtomicBool, Ordering};
let sentinels = sentinels();
let inside = sentinels.root.join("inside");
std::fs::create_dir(&inside).unwrap();
std::fs::write(inside.join("secret.txt"), b"inside bytes, always safe to read").unwrap();
let link = sentinels.root.join("d");
std::os::unix::fs::symlink(&inside, &link).unwrap();
let stop = Arc::new(AtomicBool::new(false));
let swapper = {
let stop = stop.clone();
let link = link.clone();
let outside = sentinels.sentinel_dir.clone();
std::thread::spawn(move || {
let temp = link.with_extension("swap");
let mut toward_outside = false;
while !stop.load(Ordering::Relaxed) {
let target = if toward_outside { &outside } else { &inside };
// A stale `temp` from a rename that did not happen (should not occur, but a
// leftover `temp` would otherwise wedge every later iteration's `symlink` call,
// silently stopping the swap rather than failing the test loudly) is cleared
// first so this loop cannot get stuck.
let _ = std::fs::remove_file(&temp);
if std::os::unix::fs::symlink(target, &temp).is_ok() {
let _ = std::fs::rename(&temp, &link);
}
toward_outside = !toward_outside;
}
})
};
let (mut app, ctx) = wired(sentinels.root.clone());
let mut leaked = false;
for _ in 0..200 {
cloud::submit(&app, Job::Read { entry: leaked_entry("/d/secret.txt", "secret.txt"), into: None });
said(&mut app, &ctx);
if let Some((_, bytes)) = app.opened.lock().unwrap().first() {
leaked |= bytes.as_slice() == SENTINEL_DIR_FILE_BYTES;
}
}
stop.store(true, Ordering::Relaxed);
swapper.join().unwrap();
assert!(!leaked, "a read observed the outside target's bytes while the link was being swapped underneath it");
assert_sentinels_untouched(&sentinels);
}
@@ -0,0 +1,160 @@
//! Two save-path defects that need a real backend to show: a reload after a conflict carrying a
//! stale etag into the next save, and two creates of the same name racing past an exists check.
//! Driven through craft_ui::cloud's public functions the way an application does.
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use craft_cloud::{Entry, EntryKind};
use craft_cloud_local::LocalBackend;
use craft_ui::cloud::{self, CloudApp, CloudFiles, Destination, DocumentKind};
const NOTE: DocumentKind = DocumentKind { extensions: &["txt"], mimes: &["text/plain"], noun: "note", default_extension: "txt" };
struct Window {
cloud: CloudFiles,
share: craft_ui::share::ShareDialog,
presence: craft_ui::presence::PresenceBar,
body: Vec<u8>,
said: Arc<Mutex<Vec<String>>>,
}
impl Window {
fn new(root: std::path::PathBuf, body: &[u8]) -> Window {
let mut w = Window {
cloud: CloudFiles::new(),
share: craft_ui::share::ShareDialog::new(),
presence: craft_ui::presence::PresenceBar::new(),
body: body.to_vec(),
said: Arc::default(),
};
w.cloud.connect(LocalBackend::new(root));
w
}
}
impl CloudApp for Window {
fn cloud(&self) -> &CloudFiles {
&self.cloud
}
fn cloud_mut(&mut self) -> &mut CloudFiles {
&mut self.cloud
}
fn kind(&self) -> DocumentKind {
NOTE
}
fn active(&self) -> Option<u64> {
Some(1)
}
fn title(&self, _uid: u64) -> String {
String::new()
}
fn open_bytes(&mut self, _name: &str, bytes: Vec<u8>) -> Result<Option<u64>, String> {
self.body = bytes;
Ok(Some(1))
}
fn encode(&mut self, _uid: u64, _into: Destination<'_>) -> Result<Vec<u8>, String> {
Ok(self.body.clone())
}
fn close(&mut self, _uid: u64) {}
fn sharing(&mut self) -> &mut craft_ui::share::ShareDialog {
&mut self.share
}
fn presence(&mut self) -> &mut craft_ui::presence::PresenceBar {
&mut self.presence
}
fn paint_icon(&self, _p: &egui::Painter, _r: egui::Rect, _k: EntryKind, _c: egui::Color32) {}
fn open_url(&self, _url: &str) {}
fn say(&mut self, text: String) {
self.said.lock().unwrap().push(text);
}
fn app_name(&self) -> &str {
"Review"
}
}
fn settle(app: &mut Window, ctx: &egui::Context, mut done: impl FnMut(&Window) -> bool) {
let start = Instant::now();
loop {
ctx.begin_pass(Default::default());
cloud::pump(app, ctx);
ctx.end_pass().textures_delta.clear();
if done(app) {
return;
}
assert!(start.elapsed() < Duration::from_secs(5), "timed out");
std::thread::sleep(Duration::from_millis(2));
}
}
fn listed(app: &mut Window, ctx: &egui::Context, name: &str) -> Entry {
cloud::browse(app, "");
settle(app, ctx, |a| a.cloud.mine.loaded);
app.cloud.mine.entries.iter().find(|e| e.name == name).cloned().expect("listed")
}
/// Open v1, another writer stores v2, Save conflicts, the user picks "Reload from the cloud"
/// (`reload_active`, what the modal calls). The window now shows v2's bytes, so the next Save
/// must go through rather than conflict again on the etag the reloaded copy was read at.
#[test]
fn reload_after_a_conflict_carries_the_freshly_read_etag_so_the_next_save_succeeds() {
let root = tempfile::tempdir().unwrap();
std::fs::write(root.path().join("note.txt"), b"v1").unwrap();
let ctx = egui::Context::default();
let mut app = Window::new(root.path().to_owned(), b"");
let v1 = listed(&mut app, &ctx, "note.txt");
cloud::open_entry(&mut app, v1.clone(), None);
settle(&mut app, &ctx, |a| a.cloud.busy.is_none() && a.body == b"v1");
std::thread::sleep(Duration::from_millis(20));
std::fs::write(root.path().join("note.txt"), b"v2 by someone else").unwrap();
app.body = b"my edit".to_vec();
cloud::save(&mut app).unwrap();
settle(&mut app, &ctx, |a| a.cloud.busy.is_none());
assert!(app.cloud.conflict.is_some(), "the first save is refused (correct)");
cloud::reload_active(&mut app).unwrap();
settle(&mut app, &ctx, |a| a.cloud.busy.is_none());
assert_eq!(app.body, b"v2 by someone else", "reload shows the stored bytes");
let origin_etag = cloud::report(&app)["origin"]["etag"].clone();
cloud::save(&mut app).unwrap();
settle(&mut app, &ctx, |a| a.cloud.busy.is_none());
let on_disk = std::fs::read(root.path().join("note.txt")).unwrap();
assert!(
app.cloud.conflict.is_none(),
"after reloading v2 the save conflicted again: origin etag after reload = {origin_etag} \
(listing etag was {:?}); file on disk = {:?}",
v1.etag,
String::from_utf8_lossy(&on_disk)
);
}
/// Two windows Save As the same new name at once. At most one create may succeed; the other
/// must be refused ("already exists") rather than both reporting success while one silently
/// replaces the other on disk.
#[test]
fn concurrent_create_of_one_name_refuses_the_loser() {
let rounds = 300;
let (mut both_ok, mut example) = (0, String::new());
for round in 0..rounds {
let root = tempfile::tempdir().unwrap();
let ctx = egui::Context::default();
let mut a = Window::new(root.path().to_owned(), format!("window A round {round}").as_bytes());
let mut b = Window::new(root.path().to_owned(), format!("window B round {round}").as_bytes());
cloud::save_as(&mut a, "", "Report.txt").unwrap();
cloud::save_as(&mut b, "", "Report.txt").unwrap();
settle(&mut a, &ctx, |w| w.cloud.busy.is_none());
settle(&mut b, &ctx, |w| w.cloud.busy.is_none());
let (a_ok, b_ok) = (cloud::origin(&a).is_some(), cloud::origin(&b).is_some());
if a_ok && b_ok {
both_ok += 1;
if example.is_empty() {
let disk = std::fs::read_to_string(root.path().join("Report.txt")).unwrap();
example = format!("round {round}: A status {:?}, B status {:?}, file holds {disk:?}", a.cloud.status, b.cloud.status);
}
}
}
assert_eq!(both_ok, 0, "{both_ok}/{rounds} rounds: both windows were told the new file was created; e.g. {example}");
}
+15
View File
@@ -0,0 +1,15 @@
[package]
name = "craft-cloud"
version.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
rust-version.workspace = true
description = "What a cloud provider offers the Craft apps: files, sharing, contacts, notifications and mail as contracts, with no vendor and no IO"
[lints]
workspace = true
[dependencies]
serde = { workspace = true }
thiserror = { workspace = true }
+68
View File
@@ -0,0 +1,68 @@
//! One error type for every contract.
//!
//! The cases are the ones a caller acts on differently. A UI shows a different
//! thing for "you may not" than for "the server is unreachable", and a save
//! retries on a conflict where it would not on a refusal.
use thiserror::Error;
#[derive(Debug, Error)]
pub enum Error {
/// The provider could not be reached. Worth retrying.
#[error("the provider could not be reached: {0}")]
Unreachable(String),
/// The credential was rejected. The user has to sign in again.
#[error("the provider rejected the credential")]
Unauthenticated,
/// Authenticated, and not allowed to do this. Signing in again will not
/// help, so a UI must not offer it.
#[error("not permitted: {0}")]
Forbidden(String),
/// No such document, folder or share.
#[error("{what} not found: {id}")]
NotFound { what: &'static str, id: String },
/// The document changed since the caller last read it. A save that would
/// have overwritten somebody else's work lands here.
#[error("{0} changed since you opened it")]
Conflict(String),
/// The provider does not offer this at all.
///
/// Distinct from [`Error::Forbidden`]: there is nothing to grant. A UI
/// hides the feature rather than explaining it.
#[error("this provider 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 name or path could not be used safely. Carried, never panicked.
#[error("invalid {what}: {detail}")]
Invalid { what: &'static str, detail: String },
}
impl Error {
pub fn not_found(what: &'static str, id: impl Into<String>) -> Error {
Error::NotFound { what, id: id.into() }
}
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::Unreachable(_))
}
}
pub type Result<T> = std::result::Result<T, Error>;
+189
View File
@@ -0,0 +1,189 @@
//! What a cloud provider has to offer the Craft apps, and nothing about who
//! provides it.
//!
//! Every capability here is an RFC or an ordinary HTTP API that many systems
//! implement. Files are WebDAV. Contacts are CardDAV. Calendars are CalDAV.
//! Sharing and notification are the only genuinely vendor-shaped parts, and
//! they are small. So there is no reason for an app to know which server it is
//! talking to, and no reason to write the same logic again for the next one.
//!
//! Nothing in this crate opens a socket. Each trait is implemented by a
//! provider crate that brings its own transport, which keeps this testable
//! with no server and keeps the contracts honest about what they need.
//!
//! No type here names a vendor. If a field only makes sense for one product,
//! it belongs in that provider's crate.
//!
//! Nothing here says where an implementation runs. A local adapter may
//! implement these traits against a provider directly, and an application may
//! consume them that way. The contracts do not care.
//!
//! CollabCraft chooses otherwise for its own apps. They reach one service, and
//! that service is the single place a provider is configured, a credential is
//! held and a permission is decided. A desktop binary carrying a provider
//! credential leaks one the moment somebody copies the file, which is what
//! that arrangement exists to prevent. It is a deployment policy, and this
//! crate imposes it on nobody.
#![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::{
Capability, Contact, Conversation, Entry, EntryKind, Identity, MailMessage, Notification, Permission, Share, ShareOptions, ShareTarget,
};
/// Reading and writing documents.
///
/// `list` and `shared_with_me` are separate because they answer different
/// questions. One is a folder's contents, the other is everything another
/// person has given this user access to, which has no single parent folder.
pub trait Files {
/// One folder's contents. An empty path means the user's root.
fn list(&self, path: &str) -> Result<Vec<Entry>>;
/// Everything shared with this user, wherever it lives.
///
/// A provider with no concept of this returns an empty list rather than an
/// error, because "nobody has shared anything with you" and "this server
/// cannot tell you" look the same to a file picker.
fn shared_with_me(&self) -> Result<Vec<Entry>>;
/// One document's bytes.
fn read(&self, id: &str) -> Result<Vec<u8>>;
/// A byte range of one document.
///
/// Defaulted to a full [`read`] and a slice, so providers that have no
/// ranged GET still satisfy the trait. A provider with real range support
/// overrides this.
fn read_range(&self, id: &str, offset: u64, length: u64) -> Result<Vec<u8>> {
let bytes = self.read(id)?;
let start = usize::try_from(offset).unwrap_or(usize::MAX);
if start >= bytes.len() {
return Ok(Vec::new());
}
let take = usize::try_from(length).unwrap_or(usize::MAX);
let end = start.saturating_add(take).min(bytes.len());
Ok(bytes[start..end].to_vec())
}
/// Replace one document's bytes.
///
/// `if_match` carries the etag the caller last saw. A provider that
/// supports conditional writes uses it to refuse a save that would
/// overwrite somebody else's, returning [`Error::Conflict`]. Passing
/// `None` means "write regardless", which is what a Save As does.
fn write(&self, id: &str, bytes: &[u8], if_match: Option<&str>) -> Result<Entry>;
/// Create a document and return it.
fn create(&self, folder: &str, name: &str, bytes: &[u8]) -> Result<Entry>;
/// One document's metadata, without its bytes.
fn stat(&self, id: &str) -> Result<Entry>;
}
/// Giving other people access to a document.
///
/// Persisting a share through the provider matters more than it looks. A share
/// recorded only by the caller would be invisible in the provider's own file
/// manager, so the two would disagree about who can open what. The provider
/// stays the authority.
pub trait Sharing {
/// Share a document.
///
/// A link share has no recipient, so [`ShareTarget::Link`] is how a caller
/// asks for one. The returned [`Share::url`] is what to hand out.
fn share(&self, id: &str, with: &ShareTarget, permission: Permission, options: &ShareOptions) -> Result<Share>;
/// Who currently has access.
fn shares(&self, id: &str) -> Result<Vec<Share>>;
/// Withdraw one share.
fn unshare(&self, share_id: &str) -> Result<()>;
}
/// Looking people up, for a share dialog's autocomplete.
///
/// This is the only thing the share dialog needs, so it is the only thing the
/// contract exposes. A full address book API would be a bigger surface for no
/// gain.
pub trait Contacts {
/// People matching a partial name or address.
///
/// `limit` exists because this runs on every keystroke. A provider is free
/// to return fewer.
fn search(&self, query: &str, limit: usize) -> Result<Vec<Contact>>;
}
/// Telling somebody something happened.
///
/// Separate from [`Mail`] on purpose. An in-app notification is cheap, arrives
/// instantly and is read in context. An email is none of those and is the
/// right choice for somebody who is not currently in the app. A share usually
/// wants both.
pub trait Notifications {
fn notify(&self, user: &str, notification: &Notification) -> Result<()>;
}
/// Sending mail as the provider.
pub trait Mail {
fn send(&self, message: &MailMessage) -> Result<()>;
}
/// Who the caller is, according to the provider.
pub trait Accounts {
/// Resolve the signed-in user.
fn me(&self) -> Result<Identity>;
}
/// Working together on a document, through whatever the provider calls it.
///
/// Defaulted throughout. A provider without the feature writes an empty
/// `impl` and reports [`Capability::Conversation`] as absent. The caller
/// then draws no control at all.
pub trait Conversations {
/// What this provider calls the feature. `None` where it has none.
///
/// Separate from the capability on purpose. The name is a property of
/// the provider. Whether it is available is a property of the
/// instance, and an administrator decides that one.
fn conversation_name(&self) -> Option<String> {
None
}
/// Start a conversation about a document, or join the one already there.
///
/// Two people pressing the same control have to arrive in the same
/// place, so this is expected to be idempotent for a given document.
///
/// `id` is the provider's own handle and means nothing outside the
/// account it came from. A conversation is therefore keyed on the
/// provider, the account and the document together, and `self` carries
/// the first two. A document copied into another account is a different
/// document to its provider, so it gets a conversation of its own.
/// Nothing here can attach one account's thread to another's.
fn conversation(&self, _id: &str, _title: &str) -> Result<Conversation> {
Err(Error::Unsupported("conversations"))
}
}
/// Everything one provider can do.
///
/// A provider implements the capabilities it has and reports the rest as
/// absent, so a caller can hide a share button on a server with no sharing
/// rather than offering a feature that will fail.
pub trait Provider: Files + Sharing + Contacts + Notifications + Mail + Accounts + Conversations {
/// A stable identifier, such as `nextcloud`. Used in configuration and
/// logs, never shown to a user.
fn id(&self) -> &str;
/// What this provider actually supports.
fn capabilities(&self) -> Vec<Capability>;
fn supports(&self, capability: Capability) -> bool {
self.capabilities().contains(&capability)
}
}
+216
View File
@@ -0,0 +1,216 @@
//! The data the 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.
use serde::{Deserialize, Serialize};
/// What a provider can do.
///
/// Reported rather than assumed, so a caller hides a share button on a
/// server without sharing instead of offering a feature that fails on use.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Capability {
Files,
SharedWithMe,
Sharing,
Contacts,
Notifications,
Mail,
/// Conditional writes, so a save can refuse to clobber a newer version.
Etags,
/// Public links. Absent on a server that forbids them, and the dialog then
/// offers no Copy link rather than a button that fails.
LinkShares,
/// A key on a public link. This is what most places mean when they talk
/// about sharing with somebody who has no account.
LinkPassword,
/// The server requires that key, so a link cannot be made without one.
LinkPasswordRequired,
/// An expiry date on a share.
ShareExpiry,
/// The provider can tell a recipient that something was shared with them.
///
/// Distinct from [`Capability::Mail`], which is about sending arbitrary
/// mail. A provider commonly has this and not that: it will notify the
/// person a share names without offering any way to send mail in general.
ShareNotify,
/// A conversation about a document, such as a call or a chat room.
///
/// Every provider that has this calls it something else, so the name
/// comes from [`crate::Conversations::conversation_name`]. Reported
/// separately from that name: a provider knows what it would call the
/// feature whether or not an administrator installed it.
Conversation,
}
/// A file or folder.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Entry {
/// An opaque handle for reading, writing and sharing this entry.
///
/// Only the provider that issued it may interpret it. A caller passes it
/// back and never parses it.
pub id: String,
/// The stable identity used for a collaboration room.
///
/// Separate from `id` on purpose. A provider's read and write handle is
/// often a path, and a path changes when somebody renames or moves the
/// file. A room keyed on that would silently split in two mid-session,
/// with each half seeing only its own edits. This one survives a rename.
pub room: String,
/// What to show the user.
pub name: String,
/// Where it sits, for a breadcrumb. Never a handle.
pub path: String,
pub kind: EntryKind,
/// Bytes, absent for a folder.
pub size: Option<u64>,
/// RFC 3339. Absent when the provider does not say.
pub modified: Option<String>,
/// For matching a document to the app that opens it.
pub mime: Option<String>,
/// The version the caller last saw, for a conditional write.
pub etag: Option<String>,
/// Whether this user may change it. A read-only share still lists.
pub writable: bool,
/// Who shared it, when it came from somebody else.
pub shared_by: Option<String>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EntryKind {
File,
Folder,
}
/// A person, as a share dialog needs them.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Contact {
/// What the provider wants back when sharing with this person.
pub id: String,
/// How to share with them, decided by the provider and never guessed.
///
/// The distinction is not cosmetic. A contact with an account is a user
/// share. One known only by address is an email share. Sharing an address
/// as though it were a user id fails with "not found", because no such
/// user exists, and nothing in `id` alone says which case this is.
pub target: ShareTarget,
/// What to show. A display name where there is one.
pub name: String,
pub email: Option<String>,
/// An avatar, as a URL the client may fetch. Never image bytes: a search
/// returning ten people would otherwise carry ten pictures nobody asked
/// for yet.
pub avatar: Option<String>,
/// A group rather than a person. Shown differently and shared differently.
pub is_group: bool,
}
/// Who to share with.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "kind", content = "id")]
pub enum ShareTarget {
User(String),
Group(String),
/// Somebody with no account, reached by address.
Email(String),
/// Anybody holding the link.
Link,
}
/// What a share allows.
///
/// Deliberately coarse. Providers disagree on the fine detail, and a dialog
/// offering a distinction the server cannot keep is worse than one that does
/// not.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Permission {
/// Open and read. No edits reach the document.
View,
/// Open and edit.
Edit,
}
/// Everything optional about a share.
///
/// A struct rather than more positional arguments. The list grew past the
/// point where a call site reads correctly, and a provider that cannot honour
/// one of these needs to see which it was given.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ShareOptions {
/// Shown to the recipient.
pub note: Option<String>,
/// Send mail where the provider can.
pub notify: bool,
/// A key the recipient must present. Only meaningful for a link, and
/// refused by a server that does not allow one.
pub password: Option<String>,
/// `YYYY-MM-DD`. After this the share stops working.
pub expires: Option<String>,
}
/// Where to go to work together on a document.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Conversation {
/// Where to join. Handed to a browser, or to the provider's own app.
pub url: String,
/// What the provider calls the feature, for the control's wording. A
/// menu item reading "Work together in Talk" is built from this.
pub name: String,
}
/// A share that exists.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Share {
pub id: String,
pub target: ShareTarget,
/// What to call the recipient, where the provider says.
///
/// A share carries the handle the server wants back, which for a user is
/// an account id. People are not known to each other by account id. A
/// provider that knows the difference says so here.
pub display: Option<String>,
pub permission: Permission,
/// Present for a link share, absent otherwise.
pub url: Option<String>,
pub note: Option<String>,
/// RFC 3339.
pub created: Option<String>,
}
/// Something worth telling a user about, in the app.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Notification {
/// A short machine-readable kind, such as `document_shared`. Lets a client
/// decide how to render without parsing prose.
pub kind: String,
pub subject: String,
pub body: Option<String>,
/// Where to go when it is clicked.
pub link: Option<String>,
}
/// An email to send.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct MailMessage {
pub to: Vec<String>,
pub subject: String,
pub body: String,
/// Whether `body` is HTML. Plain text otherwise.
pub html: bool,
}
/// The signed-in user, as the provider sees them.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Identity {
/// The provider's identifier for this account.
pub id: String,
/// What to show. Never an identity: two people can share a display name.
pub display: String,
pub email: Option<String>,
pub avatar: Option<String>,
}
+6
View File
@@ -81,6 +81,12 @@ Buffers are checked once per call, before any pixel is written.
the exact and float paths compare each pixel with white; all other colours are left as the
profiles give them. With a profile whose white falls between its nodes (`coated-cmyk`: 0.4 %
C), the last step to white is that much larger than its neighbours.
* Black preservation (opt-in, `BlackPreserving`): for CMYK → CMYK, a colour with exactly zero
C, M and Y comes out as exactly `(0, 0, 0, K')`, where `K'` is the destination black whose
K-only L* equals the source's (both K ramps sampled at 1024 points when the transform is
built, with its intent and BPC). The test is exact zero, so an input with any chromatic ink
takes the ordinary path. Absolute colorimetric, non-CMYK profiles and K ramps that reverse at
one of the 1024 samples are refused (a reversal between samples is not detected).
## Built-in profiles (all CC0-1.0, generated by this crate)
Binary file not shown.
+205
View File
@@ -0,0 +1,205 @@
//! K-only black preservation for CMYK → CMYK transforms.
//!
//! A CMYK → CMYK transform goes through the three-component PCS, so black alone (C = M = Y = 0)
//! comes out as a four-ink mix. ISO 32000-2 §8.6.5.7 notes that this loses fidelity in the black
//! component. ICC defines no black preservation; this is a named policy the caller opts into.
//!
//! [`BlackPreserving`] converts like its [`Transform`], except that a colour with exactly zero
//! cyan, magenta and yellow becomes exactly `(0, 0, 0, K')`. `K'` is the destination black whose
//! K-only L* equals the source's, both measured to Lab with the transform's own intent and BPC
//! setting: both ramps are sampled once, at construction, and the destination ramp is inverted.
//! A source black darker than the destination's maximum black maps to K = 1. The test is exact zero, so the transform is discontinuous at C = M = Y = 0: an input
//! with any chromatic ink takes the ordinary path.
use crate::transform::{Transform, TransformOptions};
use crate::{Builtin, CmsError, ColorSpace, Intent, Profile, invalid_arg};
/// Samples along each K-only ramp. Linear interpolation between samples of a smooth ramp is far
/// below the 16-bit quantum.
const K_SAMPLES: usize = 1024;
/// Slack for the monotonicity checks (L* units, K units).
const MONOTONIC_EPS: f64 = 1e-6;
/// A CMYK → CMYK transform that keeps black-only colours black-only.
#[derive(Debug)]
pub struct BlackPreserving {
transform: Transform,
/// Destination K for source K at `i / (K_SAMPLES - 1)`; `K_SAMPLES` values in `[0, 1]`.
curve: Vec<f32>,
/// Source K from which the source black is at least as dark as the destination's darkest:
/// mapped to exactly 1. Infinite when the destination's black is the darker.
saturate: f32,
/// The mapping at the 256 8-bit source codes, already quantised.
curve8: [u8; 256],
}
impl BlackPreserving {
/// Transform from `src` to `dst` with black preservation.
///
/// Errors with [`CmsError::InvalidArgument`] when either profile is not CMYK or the intent is
/// absolute colorimetric (which reproduces the source's paper and black, so there is no
/// black to map), and with [`CmsError::Unsupported`] when a profile's K-only ramp is not
/// monotonic at its 1024 samples (black that gets lighter as K rises has no equal-lightness
/// inverse; a reversal between samples is not detected). Other errors
/// are those of [`Transform::with_options`].
pub fn new(src: &Profile, dst: &Profile, opts: TransformOptions) -> Result<BlackPreserving, CmsError> {
if src.color_space != ColorSpace::Cmyk || dst.color_space != ColorSpace::Cmyk {
return Err(invalid_arg("black preservation needs CMYK source and destination profiles"));
}
if opts.intent == Intent::AbsoluteColorimetric {
return Err(invalid_arg("black preservation does not apply to absolute colorimetric"));
}
let transform = Transform::with_options(src, dst, opts)?;
let src_l = k_ramp_lightness(src, opts)?;
let dst_l = k_ramp_lightness(dst, opts)?;
let (curve, saturate) = k_curve(&src_l, &dst_l)?;
let mut curve8 = [0u8; 256];
for (code, slot) in curve8.iter_mut().enumerate() {
*slot = quantise(map(&curve, saturate, code as f32 / 255.0), 255.0) as u8;
}
Ok(BlackPreserving { transform, curve, saturate, curve8 })
}
/// The ordinary transform, which every colour with chromatic ink goes through. Converting with
/// it directly does not preserve black.
pub fn transform(&self) -> &Transform {
&self.transform
}
/// Destination K for a black-only source colour of `k` (clamped to `[0, 1]`).
pub fn map_k(&self, k: f32) -> f32 {
map(&self.curve, self.saturate, k)
}
/// Exact evaluation of one colour; slices as in [`Transform::eval`].
pub fn eval(&self, input: &[f32], out: &mut [f32]) -> Result<(), CmsError> {
self.transform.eval(input, out)?;
self.patch_one(input, out);
Ok(())
}
/// Lookup-table evaluation of one colour; slices as in [`Transform::eval`].
pub fn eval_fast(&self, input: &[f32], out: &mut [f32]) -> Result<(), CmsError> {
self.transform.eval_fast(input, out)?;
self.patch_one(input, out);
Ok(())
}
/// Converts float pixels; layout and errors as in [`Transform::convert_f32`].
pub fn convert_f32(&self, src: &[f32], src_stride: usize, dst: &mut [f32], dst_stride: usize, copy_extra: bool) -> Result<(), CmsError> {
self.transform.convert_f32(src, src_stride, dst, dst_stride, copy_extra)?;
for (s, d) in src.chunks_exact(src_stride).zip(dst.chunks_exact_mut(dst_stride)) {
self.patch_one(s, d);
}
Ok(())
}
/// Converts 8-bit pixels; layout and errors as in [`Transform::convert_u8`].
pub fn convert_u8(&self, src: &[u8], src_stride: usize, dst: &mut [u8], dst_stride: usize, copy_extra: bool) -> Result<(), CmsError> {
self.transform.convert_u8(src, src_stride, dst, dst_stride, copy_extra)?;
for (s, d) in src.chunks_exact(src_stride).zip(dst.chunks_exact_mut(dst_stride)) {
if let ([0, 0, 0, k, ..], [c, m, y, kd, ..]) = (s, d) {
(*c, *m, *y) = (0, 0, 0);
*kd = self.curve8[usize::from(*k)];
}
}
Ok(())
}
/// Converts 16-bit pixels; layout and errors as in [`Transform::convert_u16`].
pub fn convert_u16(&self, src: &[u16], src_stride: usize, dst: &mut [u16], dst_stride: usize, copy_extra: bool) -> Result<(), CmsError> {
self.transform.convert_u16(src, src_stride, dst, dst_stride, copy_extra)?;
for (s, d) in src.chunks_exact(src_stride).zip(dst.chunks_exact_mut(dst_stride)) {
if let ([0, 0, 0, k, ..], [c, m, y, kd, ..]) = (s, d) {
(*c, *m, *y) = (0, 0, 0);
*kd = quantise(self.map_k(f32::from(*k) / 65535.0), 65535.0) as u16;
}
}
Ok(())
}
fn patch_one(&self, input: &[f32], out: &mut [f32]) {
if let ([0.0, 0.0, 0.0, k, ..], [c, m, y, kd, ..]) = (input, out) {
(*c, *m, *y) = (0.0, 0.0, 0.0);
*kd = self.map_k(*k);
}
}
}
/// The sampled mapping from the source to the destination K-only ramp, and the source K at
/// which the destination's darkest black is reached (the `saturate` field).
fn k_curve(src_l: &[f64], dst_l: &[f64]) -> Result<(Vec<f32>, f32), CmsError> {
let curve: Vec<f32> = src_l.iter().map(|&l| invert(dst_l, l) as f32).collect();
if !curve.windows(2).all(|w| f64::from(w[0]) - f64::from(w[1]) <= MONOTONIC_EPS) {
return Err(CmsError::Unsupported("black preservation: the K mapping is not monotonic".into()));
}
let saturate = match (src_l.last(), dst_l.last()) {
(Some(&s), Some(&d)) if s < d => invert(src_l, d) as f32,
_ => f32::INFINITY,
};
Ok((curve, saturate))
}
/// L* of `p`'s K-only ramp at `K_SAMPLES` points, light to dark; refused when it is not
/// non-increasing.
fn k_ramp_lightness(p: &Profile, opts: TransformOptions) -> Result<Vec<f64>, CmsError> {
let to_lab = Transform::with_options(p, Builtin::LabD50.profile(), TransformOptions { precise_float: true, ..opts })?;
let mut ramp = Vec::with_capacity(K_SAMPLES);
let mut lab = [0.0f32; 3];
for i in 0..K_SAMPLES {
let k = i as f32 / (K_SAMPLES - 1) as f32;
to_lab.eval(&[0.0, 0.0, 0.0, k], &mut lab)?;
ramp.push(f64::from(lab[0]) * 100.0);
}
if !ramp.iter().all(|l| l.is_finite()) || !ramp.windows(2).all(|w| w[1] - w[0] <= MONOTONIC_EPS) {
return Err(CmsError::Unsupported("black preservation: a K-only ramp is not monotonic".into()));
}
Ok(ramp)
}
/// The K in `[0, 1]` at which the non-increasing `ramp` reaches `target`, clamped to its ends.
fn invert(ramp: &[f64], target: f64) -> f64 {
let (Some(&first), Some(&last)) = (ramp.first(), ramp.last()) else { return 0.0 };
if ramp.len() < 2 || target >= first {
return 0.0;
}
if target <= last {
return 1.0;
}
// ramp[lo] > target >= ramp[hi]
let (mut lo, mut hi) = (0usize, ramp.len() - 1);
while hi - lo > 1 {
let mid = lo + (hi - lo) / 2;
if ramp.get(mid).is_some_and(|&v| v > target) {
lo = mid;
} else {
hi = mid;
}
}
let (a, b) = (ramp.get(lo).copied().unwrap_or(first), ramp.get(hi).copied().unwrap_or(last));
let t = if a - b > MONOTONIC_EPS { (a - target) / (a - b) } else { 0.0 };
(lo as f64 + t) / (ramp.len() - 1) as f64
}
/// Linear interpolation in `curve` (samples over `[0, 1]`) at `k`, clamped; 1 from `saturate`.
fn map(curve: &[f32], saturate: f32, k: f32) -> f32 {
let Some(&last) = curve.last() else { return 0.0 };
let k = if k.is_nan() { 0.0 } else { k.clamp(0.0, 1.0) };
if k >= saturate {
return 1.0;
}
let x = k * (curve.len() - 1) as f32;
let i = x.floor() as usize;
match (curve.get(i), curve.get(i + 1)) {
(Some(&a), Some(&b)) => a + (b - a) * (x - i as f32),
_ => last,
}
}
fn quantise(v: f32, max: f32) -> f32 {
(v.clamp(0.0, 1.0) * max + 0.5).floor()
}
#[cfg(test)]
#[path = "black_tests.rs"]
mod tests;
+149
View File
@@ -0,0 +1,149 @@
use super::*;
fn coated() -> &'static Profile {
Builtin::CoatedCmyk.profile()
}
fn fogra() -> &'static Profile {
Builtin::CoatedFogra39.profile()
}
fn opts() -> TransformOptions {
TransformOptions::default()
}
/// L* of a CMYK colour under `p`, measured as the transform with `o` measures it.
fn lightness(p: &Profile, o: TransformOptions, cmyk: [f32; 4]) -> f32 {
let t = Transform::with_options(p, Builtin::LabD50.profile(), o).unwrap();
let mut lab = [0.0f32; 3];
t.eval(&cmyk, &mut lab).unwrap();
lab[0] * 100.0
}
#[test]
fn the_plain_transform_turns_black_into_four_inks() {
// What the policy is for: without it, black alone gains chromatic ink across presses.
let t = Transform::with_options(coated(), fogra(), opts()).unwrap();
let mut out = [0.0f32; 4];
t.eval(&[0.0, 0.0, 0.0, 0.5], &mut out).unwrap();
assert!(out[..3].iter().any(|v| *v > 0.01), "{out:?}");
}
#[test]
fn black_only_stays_black_only_on_every_path() {
for (src, dst) in [(coated(), fogra()), (fogra(), coated()), (fogra(), fogra())] {
let bp = BlackPreserving::new(src, dst, opts()).unwrap();
for k in [0.0f32, 0.1, 0.5, 0.9, 1.0] {
for fast in [false, true] {
let mut out = [1.0f32; 4];
if fast { bp.eval_fast(&[0.0, 0.0, 0.0, k], &mut out) } else { bp.eval(&[0.0, 0.0, 0.0, k], &mut out) }.unwrap();
assert_eq!(out[..3], [0.0; 3], "k {k} fast {fast}");
assert_eq!(out[3], bp.map_k(k));
}
}
let src8: Vec<u8> = (0..=255u8).flat_map(|k| [0, 0, 0, k, 7]).collect();
let mut dst8 = vec![0u8; src8.len()];
bp.convert_u8(&src8, 5, &mut dst8, 5, true).unwrap();
for (k, px) in dst8.as_chunks::<5>().0.iter().enumerate() {
assert_eq!(px[..3], [0; 3], "u8 k {k}");
assert!((f32::from(px[3]) - bp.map_k(k as f32 / 255.0) * 255.0).abs() <= 0.5, "u8 k {k}: {}", px[3]);
assert_eq!(px[4], 7, "extra channel copied");
}
let src16: Vec<u16> = (0..=64u16).flat_map(|k| [0, 0, 0, k * 1023]).collect();
let mut dst16 = vec![0u16; src16.len()];
bp.convert_u16(&src16, 4, &mut dst16, 4, false).unwrap();
for (px, k) in dst16.as_chunks::<4>().0.iter().zip(src16.as_chunks::<4>().0) {
assert_eq!(px[..3], [0; 3], "u16 {k:?}");
assert!((f32::from(px[3]) - bp.map_k(f32::from(k[3]) / 65535.0) * 65535.0).abs() <= 0.5, "u16 {k:?}: {}", px[3]);
}
let srcf: Vec<f32> = (0..=10).flat_map(|k| [0.0, 0.0, 0.0, k as f32 / 10.0]).collect();
let mut dstf = vec![0.0f32; srcf.len()];
bp.convert_f32(&srcf, 4, &mut dstf, 4, false).unwrap();
for (px, k) in dstf.as_chunks::<4>().0.iter().zip(srcf.as_chunks::<4>().0) {
assert_eq!(*px, [0.0, 0.0, 0.0, bp.map_k(k[3])], "f32 {k:?}");
}
}
}
#[test]
fn the_destination_black_matches_the_source_lightness() {
// Measured worst error over 201 K steps, both directions, both intents, BPC on and off:
// 0.007 L*.
for intent in [Intent::RelativeColorimetric, Intent::Perceptual] {
for bpc in [true, false] {
let o = TransformOptions { intent, bpc, ..opts() };
for (src, dst) in [(coated(), fogra()), (fogra(), coated())] {
let bp = BlackPreserving::new(src, dst, o).unwrap();
let dst_black = lightness(dst, o, [0.0, 0.0, 0.0, 1.0]);
for k in [0.1f32, 0.3, 0.5, 0.7, 0.9, 1.0] {
let want = lightness(src, o, [0.0, 0.0, 0.0, k]);
if want <= dst_black {
assert_eq!(bp.map_k(k), 1.0, "darker than the destination's black clamps to K = 1");
continue;
}
let got = lightness(dst, o, [0.0, 0.0, 0.0, bp.map_k(k)]);
assert!((got - want).abs() < 0.02, "{intent:?} bpc {bpc} k {k}: L* {got} for {want}");
}
assert_eq!(bp.map_k(0.0), 0.0, "paper stays paper");
assert!(bp.map_k(1.0) > 0.95, "full black stays near full black: {}", bp.map_k(1.0));
assert!(bp.map_k(0.25) < bp.map_k(0.75));
}
}
}
let same = BlackPreserving::new(fogra(), fogra(), opts()).unwrap();
for k in [0.0f32, 0.2, 0.6, 1.0] {
assert!((same.map_k(k) - k).abs() < 1e-3, "{k} -> {}", same.map_k(k));
}
}
#[test]
fn colours_with_any_chromatic_ink_take_the_ordinary_path() {
let bp = BlackPreserving::new(coated(), fogra(), opts()).unwrap();
for input in [[1e-6f32, 0.0, 0.0, 0.5], [0.0, 0.2, 0.0, 0.5], [0.3, 0.3, 0.3, 0.0], [0.0, 0.0, 1.0, 1.0]] {
let (mut a, mut b) = ([0.0f32; 4], [0.0f32; 4]);
bp.eval(&input, &mut a).unwrap();
bp.transform().eval(&input, &mut b).unwrap();
assert_eq!(a, b, "{input:?}");
}
let src = [1u8, 0, 0, 128, 0, 1, 0, 128];
let (mut a, mut b) = ([0u8; 8], [0u8; 8]);
bp.convert_u8(&src, 4, &mut a, 4, false).unwrap();
bp.transform().convert_u8(&src, 4, &mut b, 4, false).unwrap();
assert_eq!(a, b);
}
#[test]
fn refusals_and_hostile_values() {
let srgb = Builtin::Srgb.profile();
assert!(matches!(BlackPreserving::new(srgb, fogra(), opts()), Err(CmsError::InvalidArgument(_))));
assert!(matches!(BlackPreserving::new(fogra(), srgb, opts()), Err(CmsError::InvalidArgument(_))));
let abs = TransformOptions { intent: Intent::AbsoluteColorimetric, ..opts() };
assert!(matches!(BlackPreserving::new(fogra(), coated(), abs), Err(CmsError::InvalidArgument(_))));
let bp = BlackPreserving::new(coated(), fogra(), opts()).unwrap();
for k in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, -1.0, 2.0] {
assert!((0.0..=1.0).contains(&bp.map_k(k)), "{k}");
}
let mut out = [0.0f32; 4];
assert!(bp.eval(&[0.0; 3], &mut out).is_err(), "short input");
assert!(bp.convert_u8(&[0, 0, 0, 9, 0], 4, &mut [0u8; 4], 4, false).is_err(), "partial pixel");
assert_eq!(invert(&[], 50.0), 0.0);
assert_eq!(invert(&[100.0], 50.0), 0.0);
assert_eq!(invert(&[100.0, 0.0], 150.0), 0.0);
assert_eq!(invert(&[100.0, 0.0], -5.0), 1.0);
assert!((invert(&[100.0, 50.0, 0.0], 25.0) - 0.75).abs() < 1e-12);
assert_eq!(map(&[], f32::INFINITY, 0.5), 0.0);
}
#[test]
fn black_beyond_the_destination_maximum_maps_to_full_black_between_samples() {
// Source L* = 100 (1 - K), destination L* = 100 - 50 K: from K = 0.5 the source is darker
// than any destination black, and 0.5 falls between the 1024 samples.
let ramp = |f: fn(f64) -> f64| (0..K_SAMPLES).map(|i| f(i as f64 / (K_SAMPLES - 1) as f64)).collect::<Vec<_>>();
let (src, dst) = (ramp(|k| 100.0 * (1.0 - k)), ramp(|k| 100.0 - 50.0 * k));
let (curve, saturate) = k_curve(&src, &dst).unwrap();
assert!((saturate - 0.5).abs() < 1e-6, "{saturate}");
for k in [0.5001f32, 0.6, 1.0] {
assert_eq!(map(&curve, saturate, k), 1.0, "{k}");
}
assert!((map(&curve, saturate, 0.25) - 0.5).abs() < 1e-4);
let (_, never) = k_curve(&dst, &src).unwrap();
assert_eq!(never, f32::INFINITY, "a lighter source never saturates");
}
+2
View File
@@ -19,6 +19,7 @@
//! CIE 15, and Adobe's published black point compensation paper.
#![forbid(unsafe_code)]
pub mod black;
pub mod builtin;
mod builtin_v2;
pub mod clut;
@@ -39,6 +40,7 @@ pub mod transform;
mod write;
pub mod write_v2;
pub use black::BlackPreserving;
pub use builtin::Builtin;
pub use clut::Clut;
pub use curve::Curve;
+322 -15
View File
@@ -19,6 +19,9 @@
//! L* is scaled onto the device black, chroma is softly compressed against a gamut boundary
//! descriptor sampled from the forward model — then solved as above.
//!
//! That is [`GamutMapping::Legacy`]. [`GamutMapping::Oklab`] maps out-of-gamut colours in Oklab
//! instead and gives saturation its own table; the Coated FOGRA39 built-in uses it.
//!
//! The model is plausible for coated offset, not a measured characterisation: use a real
//! profile from your print provider for production print.
//!
@@ -49,6 +52,11 @@ pub struct CmykParams {
pub k_max: f64,
/// Exponent of the black generation curve above `gcr_start`.
pub gcr_gamma: f64,
/// Black generation as a curve of `[gray component, black]` points with increasing gray
/// components in `[0, 1]`, interpolated linearly and held flat beyond the ends. Empty by
/// default: black is then `k_max` times the ramp of `gcr_start` and `gcr_gamma` (the curve
/// of the shipped Photocraft profile).
pub gcr_curve: Vec<[f64; 2]>,
/// Tone value increase at 50 % for C, M, Y, K.
pub tvi: [f64; 4],
/// Grid points of the AToB (4D) and BToA (3D) tables.
@@ -60,6 +68,32 @@ pub struct CmykParams {
/// encoding and separates to a trace of ink. Off by default, which keeps the bytes of the
/// shipped Photocraft profile.
pub white_on_node: bool,
/// How the BToA tables bring colours into the gamut. [`GamutMapping::Legacy`] by default,
/// which keeps the bytes of the shipped Photocraft profile.
pub mapping: GamutMapping,
}
/// How the BToA tables map colours the printer cannot reach.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum GamutMapping {
/// The shipped Photocraft profile: out-of-gamut colours land on the closest reachable
/// colour (ΔE76); perceptual scales L* onto the device black and compresses Lab chroma;
/// saturation shares the perceptual table.
Legacy,
/// Gamut mapping in Oklab, whose hue lines stay perceptually constant (a CIELAB hue line
/// from a saturated blue toward grey drifts toward purple; an Oklab one does not):
///
/// * **Colorimetric**: in-gamut colours separate exactly. An out-of-gamut colour takes the
/// closest colour the printer reaches in Oklab, lightness and hue weighted above chroma,
/// and more so the further outside it is; black is generated from the clipped colour, so
/// inks the clip drives to 100 % stay there.
/// * **Perceptual** and **saturation**: the ICC v4 perceptual reference black is mapped
/// onto the device black linearly in XYZ (as black point compensation does) for neutrals,
/// fading out with Oklab chroma, so greys separate as with colorimetric + BPC and colourful
/// colours keep their lightness. Perceptual then compresses Oklab chroma above `knee` ×
/// the gamut boundary into the boundary; saturation scales Oklab chroma by `saturation`
/// and clips as colorimetric does.
Oklab { knee: f64, saturation: f64 },
}
impl Default for CmykParams {
@@ -71,10 +105,12 @@ impl Default for CmykParams {
gcr_start: 0.2,
k_max: 0.95,
gcr_gamma: 1.1,
gcr_curve: Vec::new(),
tvi: [0.14, 0.14, 0.14, 0.17],
grid_a2b: 11,
grid_b2a: 21,
white_on_node: false,
mapping: GamutMapping::Legacy,
}
}
}
@@ -183,6 +219,11 @@ impl Forward for TableForward {
/// Bounded least-squares solve for C, M, Y given K, minimising ΔE76 to `target`, subject to
/// `C + M + Y ≤ limit` (projected Levenberg–Marquardt with a numerical Jacobian).
fn solve_cmy<F: Forward + ?Sized>(model: &F, target: [f64; 3], k: f64, limit: f64, seeds: &[[f64; 3]]) -> ([f64; 3], f64) {
solve_cmy_by(model, k, limit, seeds, |l| [l[0] - target[0], l[1] - target[1], l[2] - target[2]])
}
/// [`solve_cmy`] minimising the norm of `residual(lab)` instead of ΔE76.
fn solve_cmy_by<F: Forward + ?Sized>(model: &F, k: f64, limit: f64, seeds: &[[f64; 3]], residual: impl Fn([f64; 3]) -> [f64; 3]) -> ([f64; 3], f64) {
let project = |mut x: [f64; 3]| {
for _ in 0..4 {
for v in &mut x {
@@ -202,10 +243,7 @@ fn solve_cmy<F: Forward + ?Sized>(model: &F, target: [f64; 3], k: f64, limit: f6
}
x
};
let err = |x: [f64; 3]| {
let l = model.lab([x[0], x[1], x[2], k]);
[l[0] - target[0], l[1] - target[1], l[2] - target[2]]
};
let err = |x: [f64; 3]| residual(model.lab([x[0], x[1], x[2], k]));
let norm2 = |e: [f64; 3]| e[0] * e[0] + e[1] * e[1] + e[2] * e[2];
let mut best = ([0.0; 3], f64::INFINITY);
for seed in seeds {
@@ -275,13 +313,32 @@ fn solve_cmy<F: Forward + ?Sized>(model: &F, target: [f64; 3], k: f64, limit: f6
const SEEDS: [[f64; 3]; 5] = [[0.3, 0.3, 0.3], [0.05, 0.05, 0.05], [0.8, 0.8, 0.8], [0.9, 0.2, 0.2], [0.2, 0.9, 0.9]];
/// Black for a gray component `g` (the smallest of C, M, Y without black).
fn gcr(p: &CmykParams, g: f64) -> f64 {
let Some(first) = p.gcr_curve.first() else {
// The Photocraft profile's curve.
return if g <= p.gcr_start { 0.0 } else { p.k_max * ((g - p.gcr_start) / (1.0 - p.gcr_start)).powf(p.gcr_gamma) };
};
let mut k = first[1];
for w in p.gcr_curve.windows(2) {
let ([g0, k0], [g1, k1]) = (w[0], w[1]);
if g >= g1 {
k = k1;
} else if g > g0 {
k = k0 + (k1 - k0) * (g - g0) / (g1 - g0);
break;
}
}
k.clamp(0.0, 1.0)
}
/// Colorimetric separation of a relative Lab target: GCR black generation then a CMY solve.
pub fn separate<F: Forward + ?Sized>(model: &F, p: &CmykParams, target: [f64; 3], warm: Option<[f64; 4]>) -> ([f64; 4], f64) {
let mut seeds: Vec<[f64; 3]> = warm.map(|w| vec![[w[0], w[1], w[2]]]).unwrap_or_default();
seeds.extend_from_slice(&SEEDS);
let (cmy0, _) = solve_cmy(model, target, 0.0, 3.0, &seeds);
let g = cmy0[0].min(cmy0[1]).min(cmy0[2]);
let k = if g <= p.gcr_start { 0.0 } else { p.k_max * ((g - p.gcr_start) / (1.0 - p.gcr_start)).powf(p.gcr_gamma) };
let k = gcr(p, g);
let mut seeds2 = vec![[(cmy0[0] - k).max(0.0), (cmy0[1] - k).max(0.0), (cmy0[2] - k).max(0.0)], cmy0];
seeds2.extend_from_slice(&seeds);
let (cmy, de) = solve_cmy(model, target, k, (p.tac - k).max(0.0), &seeds2);
@@ -383,6 +440,187 @@ impl Gbd {
}
}
/// ΔE76 under which a separation counts as reaching its target.
const REACH: f64 = 1.5;
/// Oklab chroma beyond any printable colour: the top of the boundary search.
const OKLAB_CHROMA_MAX: f64 = 0.5;
/// Oklab chroma above which the perceptual and saturation tables no longer lift black: they lift
/// neutrals fully, and less the more colourful a colour is.
const LIFT_CHROMA: f64 = 0.1;
/// Weight of lightness and hue against chroma when a colour just outside the gamut is clipped.
const CLIP_WEIGHT: f64 = 1.5;
/// Growth of that weight with the squared share of chroma the clip loses.
const CLIP_WEIGHT_GROWTH: f64 = 200.0;
// Oklab (Björn Ottosson, 2020): XYZ (D65) → cone response → cube root → Lab-like axes.
const OKLAB_M1: math::Mat3 =
[[0.8189330101, 0.3618667424, -0.1288597137], [0.0329845436, 0.9293118715, 0.0361456387], [0.0482003018, 0.2643662691, 0.6338517070]];
const OKLAB_M2: math::Mat3 =
[[0.2104542553, 0.7936177850, -0.0040720468], [1.9779984951, -2.4285922050, 0.4505937099], [0.0259040371, 0.7827717662, -0.8086757660]];
const OKLAB_M1_INV: math::Mat3 =
[[1.2270138511, -0.5577999807, 0.2812561490], [-0.0405801784, 1.1122568696, -0.0716766787], [-0.0763812845, -0.4214819784, 1.5861632204]];
const OKLAB_M2_INV: math::Mat3 = [[1.0, 0.3963377774, 0.2158037573], [1.0, -0.1055613458, -0.0638541728], [1.0, -0.0894841775, -1.2914855480]];
/// The [`GamutMapping::Oklab`] separations of one forward model.
struct OklabMapper<'a, F: Forward + ?Sized> {
model: &'a F,
p: &'a CmykParams,
knee: f64,
saturation: f64,
/// XYZ scale that maps the v4 perceptual reference black onto the device black (the white
/// stays fixed): `v' = a·v + w·(1 − a)`.
black_scale: f64,
to_d65: math::Mat3,
to_d50: math::Mat3,
}
impl<'a, F: Forward + ?Sized> OklabMapper<'a, F> {
fn new(model: &'a F, p: &'a CmykParams, knee: f64, saturation: f64) -> Self {
let d65 = math::xy_to_xyz(math::D65_XY);
// The darkest neutral the printer reaches.
let (black, _) = separate(model, p, [0.0, 0.0, 0.0], None);
let device = math::lab_to_xyz([model.lab(black)[0], 0.0, 0.0], math::D50)[1];
let reference = crate::transform::PERCEPTUAL_BLACK[1];
OklabMapper {
model,
p,
knee,
saturation,
black_scale: (1.0 - device) / (1.0 - reference),
to_d65: math::bradford(math::D50, d65),
to_d50: math::bradford(d65, math::D50),
}
}
fn oklab(&self, lab: [f64; 3]) -> [f64; 3] {
let xyz = math::apply(&self.to_d65, math::lab_to_xyz(lab, math::D50));
math::apply(&OKLAB_M2, math::apply(&OKLAB_M1, xyz).map(f64::cbrt))
}
fn lab(&self, ok: [f64; 3]) -> [f64; 3] {
let lms = math::apply(&OKLAB_M2_INV, ok).map(|v| v * v * v);
math::xyz_to_lab(math::apply(&self.to_d50, math::apply(&OKLAB_M1_INV, lms)), math::D50)
}
/// The most chroma (scale of `ok`'s chroma in `[0, top]`) the printer reaches at `ok`'s
/// lightness and hue, and its separation; `None` when even the neutral is out of reach.
fn boundary(&self, ok: [f64; 3], top: f64, warm: Option<[f64; 4]>) -> Option<(f64, [f64; 4])> {
let (grey, d) = separate(self.model, self.p, self.lab([ok[0], 0.0, 0.0]), warm);
if d > REACH {
return None;
}
let (mut lo, mut hi, mut best) = (0.0, top, grey);
for _ in 0..14 {
let mid = 0.5 * (lo + hi);
let (c, d) = separate(self.model, self.p, self.lab([ok[0], ok[1] * mid, ok[2] * mid]), Some(best));
if d <= REACH {
lo = mid;
best = c;
} else {
hi = mid;
}
}
Some((lo, best))
}
/// Colorimetric: exact in gamut; outside, the closest colour the printer reaches in Oklab,
/// lightness and hue weighted above chroma, and more so the further outside the colour is.
fn clip(&self, lab: [f64; 3], warm: Option<[f64; 4]>) -> [f64; 4] {
let (cmyk, de) = separate(self.model, self.p, lab, warm);
if de <= REACH {
return cmyk;
}
let ok = self.oklab(lab);
let c0 = ok[1].hypot(ok[2]);
// Unit vectors along the colour's chroma and hue directions.
let (u, v) = if c0 > 1e-9 { ([ok[1] / c0, ok[2] / c0], [-ok[2] / c0, ok[1] / c0]) } else { ([1.0, 0.0], [0.0, 1.0]) };
// Lightness and hue errors weighted by `w`, chroma error by 1; scaled by 100 so the
// solver's step tolerances suit it as they suit ΔE76.
let residual = |w: f64| {
move |l: [f64; 3]| {
let o = self.oklab(l);
let (da, db) = (o[1] - ok[1], o[2] - ok[2]);
[100.0 * w * (o[0] - ok[0]), 100.0 * (da * u[0] + db * u[1]), 100.0 * w * (da * v[0] + db * v[1])]
}
};
let solve = |w: f64, k: f64, from: [f64; 3]| {
let mut seeds = vec![from];
seeds.extend_from_slice(&SEEDS);
solve_cmy_by(self.model, k, (self.p.tac - k).max(0.0), &seeds, residual(w)).0
};
// A first clip without black measures how far outside the colour is. A colour just
// outside may give up a little lightness and hue to keep its chroma (a red reaches the
// full magenta and yellow edge); one far outside keeps its lightness and hue and loses
// chroma (a saturated blue does not slide along the gamut surface).
let first = solve(CLIP_WEIGHT, 0.0, [cmyk[0], cmyk[1], cmyk[2]]);
let o = self.oklab(self.model.lab([first[0], first[1], first[2], 0.0]));
let loss = if c0 > 1e-9 { (1.0 - o[1].hypot(o[2]) / c0).clamp(0.0, 1.0) } else { 0.0 };
let w = CLIP_WEIGHT * (1.0 + CLIP_WEIGHT_GROWTH * loss * loss);
let free = solve(w, 0.0, first);
let norm = |c: [f64; 4]| residual(w)(self.model.lab(c)).iter().map(|v| v * v).sum::<f64>();
// Candidates, the closest kept: the separation itself (a colour it nearly reaches stays
// continuous with its in-gamut neighbours), the clip with the separation's black, and
// the clip with black generated from the black-free clip's gray component (inks the
// clip drives to 100 % stay there and black replaces the rest).
let mut best = (norm(cmyk), cmyk);
for k in [cmyk[3], gcr(self.p, free[0].min(free[1]).min(free[2]))] {
for from in [[cmyk[0], cmyk[1], cmyk[2]], free] {
let cmy = solve(w, k, from);
let c = [cmy[0], cmy[1], cmy[2], k];
let n = norm(c);
if n < best.0 {
best = (n, c);
}
}
}
// Near paper white the gamut narrows to a point: the separation's closest colour keeps
// light tints' chroma where holding lightness would drop them toward bare paper, and
// the table nodes there carry the in-gamut tints between them. The inks blend from the
// clip at L* 85 to the separation at L* 95.
let clip_share = ((95.0 - lab[0]) / 10.0).clamp(0.0, 1.0);
std::array::from_fn(|i| clip_share * best.1[i] + (1.0 - clip_share) * cmyk[i])
}
/// Maps the v4 perceptual reference black onto the device black, linearly in XYZ, for
/// neutrals; colourful colours keep their lightness.
fn lift_black(&self, lab: [f64; 3]) -> [f64; 3] {
let ok = self.oklab(lab);
let neutral = (1.0 - ok[1].hypot(ok[2]) / LIFT_CHROMA).clamp(0.0, 1.0);
let a = 1.0 - neutral * (1.0 - self.black_scale);
let xyz = math::lab_to_xyz(lab, math::D50);
math::xyz_to_lab(std::array::from_fn(|i| a * xyz[i] + math::D50[i] * (1.0 - a)), math::D50)
}
fn perceptual(&self, lab: [f64; 3], warm: Option<[f64; 4]>) -> [f64; 4] {
let lab = self.lift_black(lab);
let ok = self.oklab(lab);
let c = ok[1].hypot(ok[2]);
if c < 1e-9 {
return self.clip(lab, warm);
}
let Some((s, edge)) = self.boundary(ok, OKLAB_CHROMA_MAX / c, warm) else {
return self.clip(lab, warm);
};
// Chroma above the knee is compressed smoothly into the boundary chroma `cb`.
let cb = s * c;
let knee = self.knee * cb;
if c <= knee {
return self.clip(lab, warm);
}
let c2 = knee + (cb - knee) * ((c - knee) / (cb - knee).max(1e-9)).tanh();
let f = c2 / c;
if f >= s {
return edge;
}
self.clip(self.lab([ok[0], ok[1] * f, ok[2] * f]), Some(edge))
}
fn saturation(&self, lab: [f64; 3], warm: Option<[f64; 4]>) -> [f64; 4] {
let ok = self.oklab(self.lift_black(lab));
self.clip(self.lab([ok[0], ok[1] * self.saturation, ok[2] * self.saturation]), warm)
}
}
fn lab_node_legacy(i: usize, n: usize) -> f64 {
i as f64 / (n - 1) as f64
}
@@ -419,6 +657,18 @@ fn white_node_curve(l_axis: bool, x: f64) -> f64 {
}
fn b2a_table<F: Forward + ?Sized>(model: &F, p: &CmykParams, gbd: Option<&Gbd>) -> Result<Clut, CmsError> {
b2a_table_with(p, |lab, warm| {
let target = match gbd {
Some(g) => g.compress(lab),
None => lab,
};
separate(model, p, target, warm).0
})
}
/// Samples a BToA table: `node` separates each relative Lab node, warm-started from the
/// previous node along b.
fn b2a_table_with(p: &CmykParams, node: impl Fn([f64; 3], Option<[f64; 4]>) -> [f64; 4] + Sync) -> Result<Clut, CmsError> {
let n = p.grid_b2a.max(2);
let nodes = n * n * n;
let step = (n - 1) as f64;
@@ -434,11 +684,7 @@ fn b2a_table<F: Forward + ?Sized>(model: &F, p: &CmykParams, gbd: Option<&Gbd>)
} else {
decode_v2([lab_node_legacy(li, n), lab_node_legacy(ai, n), lab_node_legacy(bi, n)])
};
let target = match gbd {
Some(g) => g.compress(lab),
None => lab,
};
let (cmyk, _) = if p.white_on_node && lab == [100.0, 0.0, 0.0] { ([0.0; 4], 0.0) } else { separate(model, p, target, warm) };
let cmyk = if p.white_on_node && lab == [100.0, 0.0, 0.0] { [0.0; 4] } else { node(lab, warm) };
warm = Some(cmyk);
out.extend(cmyk.map(|v| v as f32));
}
@@ -460,6 +706,15 @@ fn check_grids(p: &CmykParams) -> Result<(), CmsError> {
if p.white_on_node && p.grid_b2a.is_multiple_of(2) {
return Err(invalid_arg(format!("white on a node needs an odd BToA grid, not {}", p.grid_b2a)));
}
let valid = |v: &[f64; 2]| v.iter().all(|x| (0.0..=1.0).contains(x));
if !p.gcr_curve.iter().all(valid) || p.gcr_curve.windows(2).any(|w| w[1][0] <= w[0][0]) {
return Err(invalid_arg(format!("black generation curve {:?} needs points in [0, 1] with increasing gray components", p.gcr_curve)));
}
if let GamutMapping::Oklab { knee, saturation } = p.mapping
&& !((0.0..1.0).contains(&knee) && saturation.is_finite() && saturation > 0.0)
{
return Err(invalid_arg(format!("Oklab gamut mapping needs a knee in [0, 1) and a positive saturation, not {knee} and {saturation}")));
}
Ok(())
}
@@ -518,11 +773,23 @@ pub fn cmyk_profile_from_model<F: Forward + ?Sized>(model: &F, paper: [f64; 3],
}
fn lut_profile<F: Forward + ?Sized>(model: &F, a2b: Clut, paper: [f64; 3], p: &CmykParams) -> Result<Profile, CmsError> {
let gbd = Gbd::new(model, p);
let colorimetric = b2a_table(model, p, None)?;
let perceptual = b2a_table(model, p, Some(&gbd))?;
let (perceptual, colorimetric, saturation) = match p.mapping {
GamutMapping::Legacy => {
let gbd = Gbd::new(model, p);
let colorimetric = b2a_table(model, p, None)?;
let perceptual = b2a_table(model, p, Some(&gbd))?;
(perceptual.clone(), colorimetric, perceptual)
}
GamutMapping::Oklab { knee, saturation } => {
let m = OklabMapper::new(model, p, knee, saturation);
let colorimetric = b2a_table_with(p, |lab, warm| m.clip(lab, warm))?;
let perceptual = b2a_table_with(p, |lab, warm| m.perceptual(lab, warm))?;
let saturation = b2a_table_with(p, |lab, warm| m.saturation(lab, warm))?;
(perceptual, colorimetric, saturation)
}
};
let a2b = lut16(a2b, false);
let (b0, b1) = (lut16(perceptual, p.white_on_node), lut16(colorimetric, p.white_on_node));
let (b0, b1, b2) = (lut16(perceptual, p.white_on_node), lut16(colorimetric, p.white_on_node), lut16(saturation, p.white_on_node));
Ok(Profile {
version: (4, 0x30),
class: ProfileClass::Output,
@@ -538,7 +805,7 @@ fn lut_profile<F: Forward + ?Sized>(model: &F, a2b: Clut, paper: [f64; 3], p: &C
trc: None,
gray_trc: None,
a2b: [Some(a2b.clone()), Some(a2b.clone()), Some(a2b)],
b2a: [Some(b0.clone()), Some(b1), Some(b0)],
b2a: [Some(b0), Some(b1), Some(b2)],
bytes: None,
hash: Default::default(),
}
@@ -576,6 +843,46 @@ mod tests {
}
}
#[test]
fn oklab_mapping_refuses_bad_parameters() {
for (knee, saturation) in [(1.0, 1.0), (-0.1, 1.0), (f64::NAN, 1.0), (0.5, 0.0), (0.5, f64::INFINITY), (0.5, f64::NAN)] {
let p = CmykParams { grid_a2b: 2, grid_b2a: 2, mapping: GamutMapping::Oklab { knee, saturation }, ..CmykParams::default() };
assert!(cmyk_profile(&p).is_err(), "knee {knee}, saturation {saturation}");
}
}
#[test]
fn black_generation_curve() {
let p = CmykParams { gcr_curve: vec![[0.0, 0.0], [0.5, 0.2], [1.0, 0.9]], ..CmykParams::default() };
for (g, k) in [(-1.0, 0.0), (0.0, 0.0), (0.25, 0.1), (0.5, 0.2), (0.75, 0.55), (1.0, 0.9), (2.0, 0.9)] {
assert!((gcr(&p, g) - k).abs() < 1e-12, "g {g}: {} != {k}", gcr(&p, g));
}
for curve in [vec![[0.5, 0.2], [0.5, 0.3]], vec![[0.5, 0.2], [0.2, 0.3]], vec![[0.0, 1.5]], vec![[f64::NAN, 0.0]]] {
let p = CmykParams { grid_a2b: 2, grid_b2a: 2, gcr_curve: curve.clone(), ..CmykParams::default() };
assert!(cmyk_profile(&p).is_err(), "{curve:?}");
}
}
#[test]
fn oklab_round_trips() {
let m = CmykModel::coated(CmykParams::default().tvi);
let p = CmykParams::default();
let mapper = OklabMapper::new(&m, &p, 0.65, 1.05);
for lab in [[50.0, 0.0, 0.0], [44.0, 63.7, 47.0], [31.9, 32.9, -76.8], [90.0, -5.0, 80.0]] {
let back = mapper.lab(mapper.oklab(lab));
// The published matrices carry 10 digits, so the inverses are exact to about 1e-5 ΔE.
assert!(math::delta_e76(lab, back) < 1e-3, "{lab:?} -> {back:?}");
}
}
#[test]
fn oklab_profile_has_three_tables() {
let p = CmykParams { grid_a2b: 5, grid_b2a: 5, mapping: GamutMapping::Oklab { knee: 0.65, saturation: 1.05 }, ..CmykParams::default() };
let profile = cmyk_profile(&p).unwrap();
let [Some(b0), Some(b1), Some(b2)] = &profile.b2a else { panic!("missing BToA tables") };
assert!(b0 != b1 && b0 != b2, "perceptual shares a table");
}
#[test]
fn separation_hits_in_gamut_targets() {
let m = CmykModel::coated(CmykParams::default().tvi);
+1 -1
View File
@@ -46,7 +46,7 @@ const OUT_TABLE: usize = GpuMatrixShaper::OUTPUT_ENTRIES;
const _: () = assert!(OUT_TABLE.is_power_of_two());
/// ICC v4 perceptual reference medium black (ICC.1:2010 §6.3.4.4), XYZ.
const PERCEPTUAL_BLACK: [f64; 3] = [0.00336, 0.0034731, 0.00287];
pub(crate) const PERCEPTUAL_BLACK: [f64; 3] = [0.00336, 0.0034731, 0.00287];
/// Accelerated representation of a transform.
#[derive(Debug)]
+60 -1
View File
@@ -12,7 +12,7 @@
//! ([`synth::cmyk_profile_from_model`]).
use craft_cms::math::{self, delta_e2000};
use craft_cms::synth::{self, CmykParams, Forward};
use craft_cms::synth::{self, CmykParams, Forward, GamutMapping};
use craft_cms::{Builtin, Intent, Profile, Transform};
const DATA: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/data/FOGRA39.txt");
@@ -346,8 +346,10 @@ fn regen_coated_fogra39() {
description: Builtin::CoatedFogra39.description().into(),
copyright: craft_cms::builtin::COATED_FOGRA39_COPYRIGHT.into(),
tac: 3.3,
gcr_curve: vec![[0.0, 0.0], [0.2, 0.05], [0.5, 0.205], [0.67, 0.5], [1.0, 0.95]],
grid_b2a: 33,
white_on_node: true,
mapping: GamutMapping::Oklab { knee: 0.65, saturation: 1.05 },
..CmykParams::default()
};
let profile = synth::cmyk_profile_from_model(&f, paper(&p), &params).unwrap();
@@ -564,3 +566,60 @@ fn stand_in_separations_respect_the_ink_limit() {
}
}
}
/// sRGB patches and their separations by the reference application (Convert to Profile to
/// Coated FOGRA39, dither on), CMYK % per intent: relative + BPC, relative, perceptual,
/// saturation, absolute. Measured for storytold/photocraft#14267.
const REFERENCE_SEPARATIONS: [([u8; 3], [[f32; 4]; 5]); 3] = [
(
[200, 30, 30],
[[14.5, 97.7, 95.3, 4.3], [13.3, 100.0, 100.0, 5.5], [18.0, 96.9, 92.9, 8.6], [14.9, 100.0, 100.0, 5.9], [8.6, 100.0, 100.0, 2.4]],
),
([30, 60, 200], [[91.8, 75.3, 0.0, 0.0], [94.5, 76.5, 0.0, 0.0], [94.5, 77.7, 0.0, 0.0], [93.7, 76.9, 0.0, 0.0], [92.6, 74.9, 0.0, 0.0]]),
(
[128, 128, 128],
[[49.0, 38.4, 38.4, 20.0], [49.8, 39.2, 38.8, 21.2], [49.0, 38.4, 38.4, 20.0], [49.0, 38.4, 38.4, 20.0], [46.7, 36.9, 38.4, 18.4]],
),
];
const SEPARATION_INTENTS: [(Intent, bool); 5] = [
(Intent::RelativeColorimetric, true),
(Intent::RelativeColorimetric, false),
(Intent::Perceptual, true),
(Intent::Saturation, true),
(Intent::AbsoluteColorimetric, false),
];
fn separation(intent: Intent, bpc: bool, rgb: [u8; 3]) -> [f32; 4] {
let t = Transform::new(Builtin::Srgb.profile(), fogra39(), intent, bpc).unwrap();
let mut o = [0.0f32; 4];
t.eval(&rgb.map(|v| v as f32 / 255.0), &mut o).unwrap();
o.map(|v| v * 100.0)
}
/// sRGB → Coated FOGRA39 matches the reference application's inks on a red, a saturated blue
/// and a mid grey for every intent. Most land within 2 % per ink; red at the magenta–yellow
/// edge lands between table nodes that are and are not clipped, which costs up to 2.2 % with
/// the 33³ BToA tables.
#[test]
fn separates_like_the_reference_application() {
let mut worst = 0.0f32;
for (rgb, want) in REFERENCE_SEPARATIONS {
for ((intent, bpc), want) in SEPARATION_INTENTS.into_iter().zip(want) {
let got = separation(intent, bpc, rgb);
let diff = (0..4).map(|i| (got[i] - want[i]).abs()).fold(0.0f32, f32::max);
eprintln!("{rgb:?} {intent:?} bpc {bpc}: {got:.1?} reference {want:?} (max {diff:.1})");
worst = worst.max(diff);
}
}
assert!(worst <= 2.5, "worst ink difference {worst} %");
}
/// Saturation has its own table: a red separates with more magenta and yellow than
/// perceptual, whose chroma compression takes some back.
#[test]
fn saturation_and_perceptual_separate_differently() {
let red = [200, 30, 30];
let (perceptual, saturation) = (separation(Intent::Perceptual, true, red), separation(Intent::Saturation, true, red));
assert!(saturation[1] > perceptual[1] + 1.0 && saturation[2] > perceptual[2] + 1.0, "perceptual {perceptual:?}, saturation {saturation:?}");
}
+16
View File
@@ -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"]
+115
View File
@@ -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()
}
+601
View File
@@ -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");
}
}
+78
View File
@@ -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};
+124
View File
@@ -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));
}
}
+94
View File
@@ -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)
}
}
+4 -1
View File
@@ -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"))]
+572
View File
@@ -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());
}
+1 -1
View File
@@ -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
View File
@@ -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);
+3 -2
View File
@@ -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 {
+34
View File
@@ -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(())
}
+16
View File
@@ -0,0 +1,16 @@
[package]
name="craft-dex"
description="Dalvik DEX reader and bytecode decoder with retained input bounds and partial-report semantics"
version.workspace=true
edition.workspace=true
license.workspace=true
rust-version.workspace=true
repository.workspace=true
[lints]
workspace=true
[dependencies]
serde={workspace=true}
thiserror={workspace=true}
[dev-dependencies]
craft-testkit = { workspace = true }
+85
View File
@@ -0,0 +1,85 @@
//! Checked little/big-endian reads over untrusted bytes. Every read returns `None` when out of range.
#[derive(Debug, Clone, Copy)]
pub struct Reader<'a> {
data: &'a [u8],
}
impl<'a> Reader<'a> {
pub fn new(data: &'a [u8]) -> Self {
Reader { data }
}
pub fn len(&self) -> usize {
self.data.len()
}
pub fn is_empty(&self) -> bool {
self.data.is_empty()
}
pub fn data(&self) -> &'a [u8] {
self.data
}
pub fn slice(&self, off: usize, len: usize) -> Option<&'a [u8]> {
let end = off.checked_add(len)?;
self.data.get(off..end)
}
pub fn u8(&self, off: usize) -> Option<u8> {
self.data.get(off).copied()
}
fn arr<const N: usize>(&self, off: usize) -> Option<[u8; N]> {
self.slice(off, N)?.try_into().ok()
}
pub fn u16_le(&self, off: usize) -> Option<u16> {
self.arr(off).map(u16::from_le_bytes)
}
pub fn u32_le(&self, off: usize) -> Option<u32> {
self.arr(off).map(u32::from_le_bytes)
}
/// A NUL-terminated string starting at `off`, at most `max` bytes, lossily decoded.
pub fn cstr(&self, off: usize, max: usize) -> Option<String> {
let rest = self.data.get(off..)?;
let rest = rest.get(..max.min(rest.len()))?;
let end = rest.iter().position(|&b| b == 0).unwrap_or(rest.len());
Some(String::from_utf8_lossy(rest.get(..end)?).into_owned())
}
/// Unsigned LEB128 at `off`: (value, bytes consumed). At most 10 bytes.
pub fn uleb128(&self, off: usize) -> Option<(u64, usize)> {
let mut result = 0u64;
for i in 0..10usize {
let b = self.u8(off.checked_add(i)?)?;
let payload = u64::from(b & 0x7f);
let shift = 7 * i as u32;
if shift > 0 && payload.checked_shl(shift)? >> shift != payload {
return None;
}
result |= payload << shift;
if b & 0x80 == 0 {
return Some((result, i + 1));
}
}
None
}
}
/// Decode one modified UTF-8 code unit. Invalid bytes consume only themselves,
/// so a damaged sequence cannot hide valid text or borrow missing bytes.
pub(crate) fn mutf8_unit(bytes: &[u8]) -> (u16, usize) {
match bytes {
[a @ 0x00..=0x7f, ..] => (u16::from(*a), 1),
[0xc0, 0x80, ..] => (0, 2),
[a @ 0xc2..=0xdf, b @ 0x80..=0xbf, ..] => ((u16::from(*a & 0x1f) << 6) | u16::from(*b & 0x3f), 2),
[a @ 0xe0..=0xef, b @ 0x80..=0xbf, c @ 0x80..=0xbf, ..] if *a != 0xe0 || *b >= 0xa0 => {
((u16::from(*a & 0x0f) << 12) | (u16::from(*b & 0x3f) << 6) | u16::from(*c & 0x3f), 3)
}
_ => (0xfffd, 1),
}
}
File diff suppressed because it is too large Load Diff
+696
View File
@@ -0,0 +1,696 @@
//! Dalvik bytecode: the opcode table (all 256 slots and three payload pseudo-instructions) and a
//! decoder for every instruction format. Pure decoding; index operands are resolved by the caller.
use serde::Serialize;
/// What an index operand refers to.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum IndexKind {
None,
String,
Type,
Field,
Method,
CallSite,
MethodHandle,
Proto,
}
/// Instruction formats from the Dalvik specification (`10x`, `35c`, …).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub enum Fmt {
F10x,
F12x,
F11n,
F11x,
F10t,
F20t,
F22x,
F21t,
F21s,
F21h,
F21c,
F23x,
F22b,
F22t,
F22s,
F22c,
F30t,
F32x,
F31i,
F31t,
F31c,
F35c,
F3rc,
F45cc,
F4rcc,
F51l,
}
impl Fmt {
/// Length in 16-bit code units.
pub fn units(self) -> usize {
use Fmt::*;
match self {
F10x | F12x | F11n | F11x | F10t => 1,
F20t | F22x | F21t | F21s | F21h | F21c | F23x | F22b | F22t | F22s | F22c => 2,
F30t | F32x | F31i | F31t | F31c | F35c | F3rc => 3,
F45cc | F4rcc => 4,
F51l => 5,
}
}
}
/// One opcode slot.
#[derive(Debug, Clone, Copy)]
pub struct Op {
pub name: &'static str,
pub fmt: Fmt,
pub index: IndexKind,
}
const fn op(name: &'static str, fmt: Fmt, index: IndexKind) -> Op {
Op { name, fmt, index }
}
const UNUSED: Op = op("unused", Fmt::F10x, IndexKind::None);
const UNOPS: [&str; 21] = [
"neg-int",
"not-int",
"neg-long",
"not-long",
"neg-float",
"neg-double",
"int-to-long",
"int-to-float",
"int-to-double",
"long-to-int",
"long-to-float",
"long-to-double",
"float-to-int",
"float-to-long",
"float-to-double",
"double-to-int",
"double-to-long",
"double-to-float",
"int-to-byte",
"int-to-char",
"int-to-short",
];
const BINOPS: [&str; 32] = [
"add-int",
"sub-int",
"mul-int",
"div-int",
"rem-int",
"and-int",
"or-int",
"xor-int",
"shl-int",
"shr-int",
"ushr-int",
"add-long",
"sub-long",
"mul-long",
"div-long",
"rem-long",
"and-long",
"or-long",
"xor-long",
"shl-long",
"shr-long",
"ushr-long",
"add-float",
"sub-float",
"mul-float",
"div-float",
"rem-float",
"add-double",
"sub-double",
"mul-double",
"div-double",
"rem-double",
];
const BINOPS_2ADDR: [&str; 32] = [
"add-int/2addr",
"sub-int/2addr",
"mul-int/2addr",
"div-int/2addr",
"rem-int/2addr",
"and-int/2addr",
"or-int/2addr",
"xor-int/2addr",
"shl-int/2addr",
"shr-int/2addr",
"ushr-int/2addr",
"add-long/2addr",
"sub-long/2addr",
"mul-long/2addr",
"div-long/2addr",
"rem-long/2addr",
"and-long/2addr",
"or-long/2addr",
"xor-long/2addr",
"shl-long/2addr",
"shr-long/2addr",
"ushr-long/2addr",
"add-float/2addr",
"sub-float/2addr",
"mul-float/2addr",
"div-float/2addr",
"rem-float/2addr",
"add-double/2addr",
"sub-double/2addr",
"mul-double/2addr",
"div-double/2addr",
"rem-double/2addr",
];
const LIT16: [&str; 8] =
["add-int/lit16", "rsub-int", "mul-int/lit16", "div-int/lit16", "rem-int/lit16", "and-int/lit16", "or-int/lit16", "xor-int/lit16"];
const LIT8: [&str; 11] = [
"add-int/lit8",
"rsub-int/lit8",
"mul-int/lit8",
"div-int/lit8",
"rem-int/lit8",
"and-int/lit8",
"or-int/lit8",
"xor-int/lit8",
"shl-int/lit8",
"shr-int/lit8",
"ushr-int/lit8",
];
const CMP: [&str; 5] = ["cmpl-float", "cmpg-float", "cmpl-double", "cmpg-double", "cmp-long"];
const IF2: [&str; 6] = ["if-eq", "if-ne", "if-lt", "if-ge", "if-gt", "if-le"];
const IFZ: [&str; 6] = ["if-eqz", "if-nez", "if-ltz", "if-gez", "if-gtz", "if-lez"];
const ARR: [&str; 14] = [
"aget",
"aget-wide",
"aget-object",
"aget-boolean",
"aget-byte",
"aget-char",
"aget-short",
"aput",
"aput-wide",
"aput-object",
"aput-boolean",
"aput-byte",
"aput-char",
"aput-short",
];
const IFIELD: [&str; 14] = [
"iget",
"iget-wide",
"iget-object",
"iget-boolean",
"iget-byte",
"iget-char",
"iget-short",
"iput",
"iput-wide",
"iput-object",
"iput-boolean",
"iput-byte",
"iput-char",
"iput-short",
];
const SFIELD: [&str; 14] = [
"sget",
"sget-wide",
"sget-object",
"sget-boolean",
"sget-byte",
"sget-char",
"sget-short",
"sput",
"sput-wide",
"sput-object",
"sput-boolean",
"sput-byte",
"sput-char",
"sput-short",
];
const INVOKE: [&str; 5] = ["invoke-virtual", "invoke-super", "invoke-direct", "invoke-static", "invoke-interface"];
const INVOKE_RANGE: [&str; 5] =
["invoke-virtual/range", "invoke-super/range", "invoke-direct/range", "invoke-static/range", "invoke-interface/range"];
fn pick(list: &[&'static str], i: u8, base: u8) -> &'static str {
list.get(usize::from(i.wrapping_sub(base))).copied().unwrap_or("unused")
}
/// The opcode table entry for `b`.
pub fn opcode(b: u8) -> Op {
use Fmt::*;
use IndexKind as K;
match b {
0x00 => op("nop", F10x, K::None),
0x01 => op("move", F12x, K::None),
0x02 => op("move/from16", F22x, K::None),
0x03 => op("move/16", F32x, K::None),
0x04 => op("move-wide", F12x, K::None),
0x05 => op("move-wide/from16", F22x, K::None),
0x06 => op("move-wide/16", F32x, K::None),
0x07 => op("move-object", F12x, K::None),
0x08 => op("move-object/from16", F22x, K::None),
0x09 => op("move-object/16", F32x, K::None),
0x0a => op("move-result", F11x, K::None),
0x0b => op("move-result-wide", F11x, K::None),
0x0c => op("move-result-object", F11x, K::None),
0x0d => op("move-exception", F11x, K::None),
0x0e => op("return-void", F10x, K::None),
0x0f => op("return", F11x, K::None),
0x10 => op("return-wide", F11x, K::None),
0x11 => op("return-object", F11x, K::None),
0x12 => op("const/4", F11n, K::None),
0x13 => op("const/16", F21s, K::None),
0x14 => op("const", F31i, K::None),
0x15 => op("const/high16", F21h, K::None),
0x16 => op("const-wide/16", F21s, K::None),
0x17 => op("const-wide/32", F31i, K::None),
0x18 => op("const-wide", F51l, K::None),
0x19 => op("const-wide/high16", F21h, K::None),
0x1a => op("const-string", F21c, K::String),
0x1b => op("const-string/jumbo", F31c, K::String),
0x1c => op("const-class", F21c, K::Type),
0x1d => op("monitor-enter", F11x, K::None),
0x1e => op("monitor-exit", F11x, K::None),
0x1f => op("check-cast", F21c, K::Type),
0x20 => op("instance-of", F22c, K::Type),
0x21 => op("array-length", F12x, K::None),
0x22 => op("new-instance", F21c, K::Type),
0x23 => op("new-array", F22c, K::Type),
0x24 => op("filled-new-array", F35c, K::Type),
0x25 => op("filled-new-array/range", F3rc, K::Type),
0x26 => op("fill-array-data", F31t, K::None),
0x27 => op("throw", F11x, K::None),
0x28 => op("goto", F10t, K::None),
0x29 => op("goto/16", F20t, K::None),
0x2a => op("goto/32", F30t, K::None),
0x2b => op("packed-switch", F31t, K::None),
0x2c => op("sparse-switch", F31t, K::None),
0x2d..=0x31 => op(pick(&CMP, b, 0x2d), F23x, K::None),
0x32..=0x37 => op(pick(&IF2, b, 0x32), F22t, K::None),
0x38..=0x3d => op(pick(&IFZ, b, 0x38), F21t, K::None),
0x44..=0x51 => op(pick(&ARR, b, 0x44), F23x, K::None),
0x52..=0x5f => op(pick(&IFIELD, b, 0x52), F22c, K::Field),
0x60..=0x6d => op(pick(&SFIELD, b, 0x60), F21c, K::Field),
0x6e..=0x72 => op(pick(&INVOKE, b, 0x6e), F35c, K::Method),
0x74..=0x78 => op(pick(&INVOKE_RANGE, b, 0x74), F3rc, K::Method),
0x7b..=0x8f => op(pick(&UNOPS, b, 0x7b), F12x, K::None),
0x90..=0xaf => op(pick(&BINOPS, b, 0x90), F23x, K::None),
0xb0..=0xcf => op(pick(&BINOPS_2ADDR, b, 0xb0), F12x, K::None),
0xd0..=0xd7 => op(pick(&LIT16, b, 0xd0), F22s, K::None),
0xd8..=0xe2 => op(pick(&LIT8, b, 0xd8), F22b, K::None),
0xfa => op("invoke-polymorphic", F45cc, K::Method),
0xfb => op("invoke-polymorphic/range", F4rcc, K::Method),
0xfc => op("invoke-custom", F35c, K::CallSite),
0xfd => op("invoke-custom/range", F3rc, K::CallSite),
0xfe => op("const-method-handle", F21c, K::MethodHandle),
0xff => op("const-method-type", F21c, K::Proto),
_ => UNUSED,
}
}
/// Switch and array payloads.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(tag = "kind", rename_all = "kebab-case")]
pub enum Payload {
PackedSwitch { first_key: i32, targets: Vec<i32> },
SparseSwitch { keys: Vec<i32>, targets: Vec<i32> },
FillArrayData { element_width: u16, count: u32, data: Vec<u8> },
}
/// One decoded instruction.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Insn {
/// Offset in 16-bit code units from the start of the method's code.
pub offset: u32,
pub opcode: u8,
pub name: &'static str,
/// Length in code units.
pub units: u32,
/// Registers in operand order (for ranges: every register in the range).
pub regs: Vec<u32>,
/// True for `/range` forms.
pub range: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub literal: Option<i64>,
/// Absolute branch or payload target, in code units.
#[serde(skip_serializing_if = "Option::is_none")]
pub target: Option<i64>,
pub index_kind: IndexKind,
#[serde(skip_serializing_if = "Option::is_none")]
pub index: Option<u32>,
/// Second index (the proto of `invoke-polymorphic`).
#[serde(skip_serializing_if = "Option::is_none")]
pub index2: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub payload: Option<Payload>,
}
/// Most entries decoded from one payload.
const MAX_PAYLOAD: usize = 65_536;
/// Maximum payload bytes retained by one decoded method, including copies attached to users.
pub const DEFAULT_MAX_PAYLOAD_BYTES: usize = 64 << 20;
impl Payload {
fn retained_bytes(&self) -> usize {
match self {
Self::PackedSwitch { targets, .. } => targets.len().saturating_mul(4),
Self::SparseSwitch { keys, targets } => keys.len().saturating_add(targets.len()).saturating_mul(4),
Self::FillArrayData { data, .. } => data.len(),
}
}
fn complete(&self) -> bool {
match self {
Self::FillArrayData { element_width, count, data } => u64::from(*element_width) * u64::from(*count) == data.len() as u64,
_ => true,
}
}
}
fn u32_at(code: &[u16], i: usize) -> Option<u32> {
Some(u32::from(*code.get(i)?) | (u32::from(*code.get(i + 1)?) << 16))
}
/// Decode a payload pseudo-instruction at `pc`; returns it and its length in units.
fn payload(code: &[u16], pc: usize) -> Option<(Payload, usize)> {
let ident = *code.get(pc)?;
match ident {
0x0100 => {
let size = usize::from(*code.get(pc + 1)?);
let first_key = u32_at(code, pc + 2)? as i32;
let mut targets = Vec::with_capacity(size.min(MAX_PAYLOAD));
for i in 0..size.min(MAX_PAYLOAD) {
targets.push(u32_at(code, pc + 4 + i * 2)? as i32);
}
Some((Payload::PackedSwitch { first_key, targets }, size * 2 + 4))
}
0x0200 => {
let size = usize::from(*code.get(pc + 1)?);
let mut keys = Vec::with_capacity(size.min(MAX_PAYLOAD));
let mut targets = Vec::with_capacity(size.min(MAX_PAYLOAD));
for i in 0..size.min(MAX_PAYLOAD) {
keys.push(u32_at(code, pc + 2 + i * 2)? as i32);
targets.push(u32_at(code, pc + 2 + size * 2 + i * 2)? as i32);
}
Some((Payload::SparseSwitch { keys, targets }, size * 4 + 2))
}
0x0300 => {
let width = *code.get(pc + 1)?;
if !matches!(width, 1 | 2 | 4 | 8) {
return None;
}
let count = u32_at(code, pc + 2)?;
let bytes = usize::from(width).checked_mul(count as usize)?;
let units = bytes.checked_add(1)? / 2 + 4;
if pc.checked_add(units)? > code.len() {
return None;
}
let mut data = Vec::with_capacity(bytes.min(MAX_PAYLOAD));
for i in 0..bytes.min(MAX_PAYLOAD) {
let u = *code.get(pc + 4 + i / 2)?;
data.push(if i % 2 == 0 { u as u8 } else { (u >> 8) as u8 });
}
Some((Payload::FillArrayData { element_width: width, count, data }, units))
}
_ => None,
}
}
/// Decode one instruction at `pc`, or `None` when it runs past the end.
pub fn decode_one(code: &[u16], pc: usize) -> Option<Insn> {
use Fmt::*;
let u0 = *code.get(pc)?;
let b = (u0 & 0xff) as u8;
let hi = (u0 >> 8) as u8;
if b == 0 && hi != 0 {
let (p, units) = payload(code, pc)?;
let name = match p {
Payload::PackedSwitch { .. } => "packed-switch-payload",
Payload::SparseSwitch { .. } => "sparse-switch-payload",
Payload::FillArrayData { .. } => "array-data-payload",
};
return Some(Insn {
offset: pc as u32,
opcode: 0,
name,
units: units as u32,
regs: vec![],
range: false,
literal: None,
target: None,
index_kind: IndexKind::None,
index: None,
index2: None,
payload: Some(p),
});
}
let o = opcode(b);
let n = o.fmt.units();
if pc.checked_add(n)? > code.len() {
return None;
}
let u = |i: usize| code.get(pc + i).copied().unwrap_or(0);
let a4 = u32::from(hi & 0x0f);
let b4 = u32::from(hi >> 4);
let aa = u32::from(hi);
let rel = |d: i64| pc as i64 + d;
let mut insn = Insn {
offset: pc as u32,
opcode: b,
name: o.name,
units: n as u32,
regs: vec![],
range: false,
literal: None,
target: None,
index_kind: o.index,
index: None,
index2: None,
payload: None,
};
match o.fmt {
F10x => {}
F12x => insn.regs = vec![a4, b4],
F11n => {
insn.regs = vec![a4];
insn.literal = Some(i64::from((hi as i8) >> 4));
}
F11x => insn.regs = vec![aa],
F10t => insn.target = Some(rel(i64::from(hi as i8))),
F20t => insn.target = Some(rel(i64::from(u(1) as i16))),
F22x => insn.regs = vec![aa, u32::from(u(1))],
F21t => {
insn.regs = vec![aa];
insn.target = Some(rel(i64::from(u(1) as i16)));
}
F21s => {
insn.regs = vec![aa];
insn.literal = Some(i64::from(u(1) as i16));
}
F21h => {
insn.regs = vec![aa];
let v = i64::from(u(1) as i16);
insn.literal = Some(if b == 0x19 { v << 48 } else { v << 16 });
}
F21c => {
insn.regs = vec![aa];
insn.index = Some(u32::from(u(1)));
}
F23x => insn.regs = vec![aa, u32::from(u(1) & 0xff), u32::from(u(1) >> 8)],
F22b => {
insn.regs = vec![aa, u32::from(u(1) & 0xff)];
insn.literal = Some(i64::from((u(1) >> 8) as u8 as i8));
}
F22t => {
insn.regs = vec![a4, b4];
insn.target = Some(rel(i64::from(u(1) as i16)));
}
F22s => {
insn.regs = vec![a4, b4];
insn.literal = Some(i64::from(u(1) as i16));
}
F22c => {
insn.regs = vec![a4, b4];
insn.index = Some(u32::from(u(1)));
}
F30t => insn.target = Some(rel(i64::from((u32::from(u(1)) | (u32::from(u(2)) << 16)) as i32))),
F32x => insn.regs = vec![u32::from(u(1)), u32::from(u(2))],
F31i => {
insn.regs = vec![aa];
insn.literal = Some(i64::from((u32::from(u(1)) | (u32::from(u(2)) << 16)) as i32));
}
F31t => {
insn.regs = vec![aa];
insn.target = Some(rel(i64::from((u32::from(u(1)) | (u32::from(u(2)) << 16)) as i32)));
}
F31c => {
insn.regs = vec![aa];
insn.index = Some(u32::from(u(1)) | (u32::from(u(2)) << 16));
}
F35c | F45cc => {
if b4 > 5 {
return None;
}
let count = b4 as usize;
let g = a4;
let w = u(2);
let all = [u32::from(w & 0xf), u32::from((w >> 4) & 0xf), u32::from((w >> 8) & 0xf), u32::from(w >> 12), g];
insn.regs = all.iter().take(count).copied().collect();
insn.index = Some(u32::from(u(1)));
if o.fmt == F45cc {
insn.index2 = Some(u32::from(u(3)));
}
}
F3rc | F4rcc => {
let first = u32::from(u(2));
let end = first.checked_add(aa)?;
if end > u32::from(u16::MAX) + 1 {
return None;
}
insn.regs = (first..end).collect();
insn.range = true;
insn.index = Some(u32::from(u(1)));
if o.fmt == F4rcc {
insn.index2 = Some(u32::from(u(3)));
}
}
F51l => {
insn.regs = vec![aa];
let v = u64::from(u(1)) | (u64::from(u(2)) << 16) | (u64::from(u(3)) << 32) | (u64::from(u(4)) << 48);
insn.literal = Some(v as i64);
}
}
Some(insn)
}
/// Decode a whole method body, attaching each switch/array payload to the instruction that
/// references it. Stops at `max` instructions and caps all retained payload copies together.
pub fn decode(code: &[u16], max: usize) -> (Vec<Insn>, bool) {
decode_with_payload_limit(code, max, DEFAULT_MAX_PAYLOAD_BYTES)
}
/// Decode with an explicit aggregate payload byte budget. Payloads that do not fit are omitted;
/// their instruction metadata remains and the returned completeness flag is false. A source
/// payload and every attached copy consume the same budget, before the copy is allocated.
pub fn decode_with_payload_limit(code: &[u16], max: usize, max_payload_bytes: usize) -> (Vec<Insn>, bool) {
let mut out = Vec::new();
let mut pc = 0usize;
let mut complete = true;
let mut bytes_left = max_payload_bytes;
while pc < code.len() {
if out.len() >= max {
complete = false;
break;
}
match decode_one(code, pc) {
Some(mut i) => {
pc += (i.units as usize).max(1);
if let Some(p) = &i.payload {
complete &= p.complete();
if let Some(left) = bytes_left.checked_sub(p.retained_bytes()) {
bytes_left = left;
} else {
i.payload = None;
complete = false;
}
}
out.push(i);
}
None => {
complete = false;
break;
}
}
}
// Attach payloads to their users (31t formats).
// The decoder visits offsets in order. Index their positions without copying any payload.
let payloads: Vec<(i64, usize)> = out.iter().enumerate().filter(|(_, i)| i.payload.is_some()).map(|(n, i)| (i64::from(i.offset), n)).collect();
for n in 0..out.len() {
let Some(target) = out.get(n).filter(|i| matches!(i.opcode, 0x26 | 0x2b | 0x2c)).and_then(|i| i.target) else { continue };
let Ok(position) = payloads.binary_search_by_key(&target, |(offset, _)| *offset) else { continue };
let Some(payload) = payloads.get(position).and_then(|(_, index)| out.get(*index)).and_then(|i| i.payload.as_ref()) else { continue };
let Some(left) = bytes_left.checked_sub(payload.retained_bytes()) else {
complete = false;
continue;
};
bytes_left = left;
let copy = payload.clone();
if let Some(instruction) = out.get_mut(n) {
instruction.payload = Some(copy);
}
}
(out, complete)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn table_is_complete() {
let mut named = 0;
for b in 0..=255u8 {
let o = opcode(b);
if o.name != "unused" {
named += 1;
}
}
// 256 slots minus the 0x3e-0x43, 0x73, 0x79-0x7a and 0xe3-0xf9 holes.
assert_eq!(named, 256 - 6 - 1 - 2 - 23);
assert_eq!(opcode(0x6e).name, "invoke-virtual");
assert_eq!(opcode(0x8f).name, "int-to-short");
assert_eq!(opcode(0xaf).name, "rem-double");
assert_eq!(opcode(0xcf).name, "rem-double/2addr");
assert_eq!(opcode(0xe2).name, "ushr-int/lit8");
}
#[test]
fn decodes_formats() {
// const/4 v1, #-1 ; invoke-static {v0, v1}, meth@5 ; packed-switch v0, +4 ; return-void
// payload: packed, size 2, first 10, targets 1, 2
let code: Vec<u16> = vec![0xf112, 0x2071, 5, 0x0010, 0x002b, 4, 0, 0x000e, 0x0100, 2, 10, 0, 1, 0, 2, 0];
let (ins, complete) = decode(&code, 100);
assert!(complete);
assert_eq!(ins[0].name, "const/4");
assert_eq!(ins[0].literal, Some(-1));
assert_eq!(ins[0].regs, vec![1]);
assert_eq!(ins[1].name, "invoke-static");
assert_eq!(ins[1].regs, vec![0, 1]);
assert_eq!(ins[1].index, Some(5));
assert_eq!(ins[2].name, "packed-switch");
assert_eq!(ins[2].target, Some(8));
assert_eq!(ins[2].payload, Some(Payload::PackedSwitch { first_key: 10, targets: vec![1, 2] }));
assert_eq!(ins[4].name, "packed-switch-payload");
// const-wide v0, 0x1122334455667788
let (w, _) = decode(&[0x0018, 0x7788, 0x5566, 0x3344, 0x1122], 10);
assert_eq!(w[0].literal, Some(0x1122_3344_5566_7788));
// fill-array-data payload width 1 count 3
let (f, _) = decode(&[0x0300, 1, 3, 0, 0x0201, 0x0003], 10);
assert_eq!(f[0].payload, Some(Payload::FillArrayData { element_width: 1, count: 3, data: vec![1, 2, 3] }));
// invoke-virtual/range {v4..v6}
let (r, _) = decode(&[0x0374, 9, 4], 10);
assert_eq!(r[0].regs, vec![4, 5, 6]);
assert!(r[0].range);
}
#[test]
fn hostile() {
for seed in 0..200 {
let n = crate::test_support::noise(seed, 256);
let code: Vec<u16> = n.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).collect();
let _ = decode(&code, 1000);
}
let _ = decode(&[0x0300, 0xffff, 0xffff, 0xffff], 10);
let _ = decode(&[0x0200, 0xffff], 10);
let _ = decode(&[0x0018], 10);
}
}
+42
View File
@@ -0,0 +1,42 @@
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#![forbid(unsafe_code)]
//! Dalvik DEX inspection and bytecode decoding. Never executes bytecode.
mod bytes;
/// Checked byte reader accepted by the signed-LEB compatibility helper.
pub use bytes::Reader;
pub mod dex;
pub mod dex_ops;
pub use dex::*;
#[cfg(test)]
mod test_support;
/// Parser admission failures; damaged substructures retain the original partial-report behavior.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum DexError {
#[error("the file ends early ({0})")]
Truncated(String),
#[error("the file is malformed ({0})")]
Malformed(String),
#[error("not supported: {0}")]
Unsupported(String),
}
use DexError as FormatError;
#[cfg(test)]
#[path = "regressions/array_widths.rs"]
mod array_widths;
#[cfg(test)]
#[path = "regressions/capped_table_boundaries.rs"]
mod capped_table_boundaries;
#[cfg(test)]
#[path = "regressions/invoke_registers.rs"]
mod invoke_registers;
#[cfg(test)]
#[path = "regressions/payload_budgets.rs"]
mod payload_budgets;
#[cfg(test)]
#[path = "regressions/signed_leb128.rs"]
mod signed_leb128;
@@ -0,0 +1,39 @@
use crate::dex_ops::{Payload, decode, decode_one};
#[test]
fn zero_width_does_not_describe_a_huge_complete_array() {
let code = [0x0300, 0, 0xffff, 0xffff];
assert!(decode_one(&code, 0).is_none());
assert!(!decode(&code, 16).1);
}
#[test]
fn unsupported_element_widths_are_refused_even_for_empty_arrays() {
for width in [0, 3, 5, 6, 7, 9, 16, u16::MAX] {
assert!(decode_one(&[0x0300, width, 0, 0], 0).is_none(), "width {width}");
}
}
#[test]
fn all_primitive_widths_and_odd_byte_padding_still_decode() {
for width in [1u16, 2, 4, 8] {
let count = 3u32;
let bytes = usize::from(width) * count as usize;
let mut code = vec![0x0300, width, count as u16, 0];
code.resize(4 + bytes.div_ceil(2), 0x2211);
let instruction = decode_one(&code, 0).unwrap();
assert_eq!(instruction.units as usize, code.len());
match instruction.payload.unwrap() {
Payload::FillArrayData { element_width, count: decoded, data } => {
assert_eq!(element_width, width);
assert_eq!(decoded, count);
assert_eq!(data.len(), bytes);
assert_eq!(data[0], 0x11);
}
other => panic!("unexpected payload {other:?}"),
}
assert!(decode_one(&[0x0300, width, 0, 0], 0).is_some());
code.pop();
assert!(decode_one(&code, 0).is_none());
}
}
@@ -0,0 +1,114 @@
use crate::dex::{self, ClassDef, Code};
const MEMBER_CAP: usize = 65_536;
const HANDLER_CAP: usize = 256;
fn uleb(mut value: u32, bytes: &mut Vec<u8>) {
loop {
let byte = (value & 0x7f) as u8;
value >>= 7;
bytes.push(byte | if value == 0 { 0 } else { 0x80 });
if value == 0 {
break;
}
}
}
fn sleb(mut value: i32, bytes: &mut Vec<u8>) {
loop {
let byte = value as u8 & 0x7f;
value >>= 7;
let done = (value == 0 && byte & 0x40 == 0) || (value == -1 && byte & 0x40 != 0);
bytes.push(byte | if done { 0 } else { 0x80 });
if done {
break;
}
}
}
fn header() -> Vec<u8> {
let mut bytes = vec![0; 0x70];
bytes[..8].copy_from_slice(b"dex\n035\0");
bytes[36..40].copy_from_slice(&0x70u32.to_le_bytes());
bytes[40..44].copy_from_slice(&0x1234_5678u32.to_le_bytes());
bytes
}
fn class_data(count: usize) -> dex::ClassData {
let mut bytes = header();
for n in [count as u32, 0, 1, 0] {
uleb(n, &mut bytes);
}
bytes.extend_from_slice(&[0, 1].repeat(count));
bytes.extend_from_slice(&[3, 9, 7]);
let len = bytes.len() as u32;
bytes[32..36].copy_from_slice(&len.to_le_bytes());
let class = ClassDef {
class_idx: 0,
access: 0,
superclass_idx: 0,
interfaces_off: 0,
source_file_idx: 0,
annotations_off: 0,
class_data_off: 0x70,
static_values_off: 0,
};
dex::parse(&bytes).unwrap().class_data(&class)
}
fn code(size: i32, payload: &[u8]) -> Code {
let mut bytes = header();
bytes.extend_from_slice(&[1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 8, 0, 0, 0]);
bytes.extend_from_slice(&[0; 16]);
bytes.extend_from_slice(&[0, 0, 0, 0, 1, 0, 1, 0]);
bytes.push(1);
sleb(size, &mut bytes);
bytes.extend_from_slice(payload);
let len = bytes.len() as u32;
bytes[32..36].copy_from_slice(&len.to_le_bytes());
dex::parse(&bytes).unwrap().code(0x70).unwrap()
}
#[test]
fn capped_class_members_do_not_become_the_next_group() {
let data = class_data(MEMBER_CAP + 1);
assert_eq!(data.static_fields.len(), MEMBER_CAP);
assert!(data.direct_methods.is_empty());
assert!(!data.complete);
}
#[test]
fn an_exact_member_limit_keeps_the_following_group() {
let data = class_data(MEMBER_CAP);
assert_eq!(data.static_fields.len(), MEMBER_CAP);
assert!(data.complete);
assert_eq!(data.direct_methods, [dex::EncodedMethod { method_idx: 3, access: 9, code_off: 7 }]);
}
#[test]
fn an_unread_typed_handler_is_not_a_catch_all() {
let mut payload = [0, 1].repeat(HANDLER_CAP + 1);
payload.push(7);
let parsed = code(-((HANDLER_CAP + 1) as i32), &payload);
assert_eq!(parsed.tries[0].handlers.len(), HANDLER_CAP);
assert!(parsed.tries[0].handlers.iter().all(|handler| handler.exception.is_some() && handler.address == 1));
}
#[test]
fn an_incomplete_typed_handler_cannot_supply_a_catch_all_address() {
let parsed = code(-2, &[0, 1, 0]);
assert_eq!(parsed.tries[0].handlers.len(), 1);
assert!(parsed.tries[0].handlers[0].exception.is_some());
assert_eq!(parsed.tries[0].handlers[0].address, 1);
}
#[test]
fn complete_typed_lists_keep_their_real_catch_all() {
for count in [0, 1, HANDLER_CAP] {
let mut payload = [0, 1].repeat(count);
payload.push(7);
let parsed = code(-(count as i32), &payload);
assert_eq!(parsed.tries[0].handlers.len(), count + 1);
assert_eq!(parsed.tries[0].handlers.last(), Some(&dex::Handler { exception: None, address: 7 }));
}
}
@@ -0,0 +1,33 @@
use crate::dex_ops::{decode, decode_one};
#[test]
fn fixed_register_lists_cannot_claim_more_than_five_arguments() {
for op in [0x24u16, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0xfa, 0xfc] {
for count in 6..=15 {
let code = [(count << 12) | op, 1, 0x4321, 2];
assert!(decode_one(&code, 0).is_none(), "opcode {op:#x}, count {count}");
assert!(!decode(&code, 16).1);
}
}
}
#[test]
fn range_arguments_cannot_leave_the_encoded_register_space() {
for op in [0x25u16, 0x74, 0x75, 0x76, 0x77, 0x78, 0xfb, 0xfd] {
assert!(decode_one(&[0x0200 | op, 1, u16::MAX, 2], 0).is_none(), "{op:#x}");
assert!(decode_one(&[0xff00 | op, 1, u16::MAX - 1, 2], 0).is_none(), "{op:#x}");
}
}
#[test]
fn zero_and_boundary_register_lists_remain_valid() {
let fixed = decode_one(&[0x5571, 1, 0x4321], 0).unwrap();
assert_eq!(fixed.regs, vec![1, 2, 3, 4, 5]);
assert!(decode_one(&[0x0071, 1, 0], 0).unwrap().regs.is_empty());
let range = decode_one(&[0x0277, 1, u16::MAX - 1], 0).unwrap();
assert_eq!(range.regs, vec![65534, 65535]);
assert!(decode_one(&[0x0077, 1, u16::MAX], 0).unwrap().regs.is_empty());
let polymorphic = decode_one(&[0x01fb, 1, u16::MAX, 2], 0).unwrap();
assert_eq!(polymorphic.regs, vec![65535]);
assert_eq!(polymorphic.index2, Some(2));
}
@@ -0,0 +1,88 @@
use crate::dex_ops::{self, Payload};
fn arrays(references: usize, bytes: usize) -> Vec<u16> {
let mut code = Vec::new();
let offset = (references * 3).next_multiple_of(2);
for n in 0..references {
let relative = u32::try_from(offset - n * 3).unwrap();
code.extend([0x0026, relative as u16, (relative >> 16) as u16]);
}
code.resize(offset, 0);
let count = u32::try_from(bytes).unwrap();
code.extend([0x0300, 1, count as u16, (count >> 16) as u16]);
code.resize(code.len() + bytes.div_ceil(2), 0x5a5a);
code
}
fn bytes(rows: &[dex_ops::Insn]) -> usize {
rows.iter()
.map(|i| match i.payload.as_ref() {
Some(Payload::FillArrayData { data, .. }) => data.len(),
Some(Payload::PackedSwitch { targets, .. }) => targets.len() * 4,
Some(Payload::SparseSwitch { keys, targets }) => (keys.len() + targets.len()) * 4,
None => 0,
})
.sum()
}
#[test]
fn shared_arrays_charge_the_source_and_each_attached_copy() {
let code = arrays(4, 8);
let (rows, complete) = dex_ops::decode_with_payload_limit(&code, 100, 24);
assert!(!complete);
assert_eq!(bytes(&rows), 24);
assert!(rows[0].payload.is_some() && rows[1].payload.is_some());
assert!(rows[2].payload.is_none() && rows[3].payload.is_none());
assert!(rows.last().unwrap().payload.is_some());
let (full, complete) = dex_ops::decode_with_payload_limit(&code, 100, 40);
assert!(complete);
assert_eq!(bytes(&full), 40);
}
#[test]
fn zero_budget_keeps_offsets_and_payload_instruction_metadata() {
let code = arrays(2, 8);
let (rows, complete) = dex_ops::decode_with_payload_limit(&code, 100, 0);
assert!(!complete);
assert_eq!(rows.iter().map(|i| i.offset).collect::<Vec<_>>(), [0, 3, 6]);
assert_eq!(rows[2].name, "array-data-payload");
assert_eq!(rows[2].units, 8);
assert!(rows.iter().all(|i| i.payload.is_none()));
assert!(dex_ops::decode_with_payload_limit(&[0x000e], 100, 0).1);
}
#[test]
fn both_switch_tables_are_accounted_and_backward_references_work() {
// packed table: one target; sparse table: one key and one target; users follow the tables.
let code = [0x0100, 1, 7, 0, 1, 0, 0x0200, 1, 9, 0, 2, 0, 0x002b, 0xfff4, 0xffff, 0x002c, 0xfff7, 0xffff];
let (rows, complete) = dex_ops::decode_with_payload_limit(&code, 100, 24);
assert!(complete);
assert_eq!(rows[2].payload, Some(Payload::PackedSwitch { first_key: 7, targets: vec![1] }));
assert_eq!(rows[3].payload, Some(Payload::SparseSwitch { keys: vec![9], targets: vec![2] }));
let (rows, complete) = dex_ops::decode_with_payload_limit(&code, 100, 16);
assert!(!complete);
assert!(rows[2].payload.is_some());
assert!(rows[3].payload.is_none());
assert_eq!(bytes(&rows), 16);
}
#[test]
fn the_existing_per_array_cap_is_reported_as_partial() {
let (rows, complete) = dex_ops::decode(&arrays(1, 65_537), 100);
assert!(!complete);
assert_eq!(bytes(&rows), 2 * 65_536);
let (rows, complete) = dex_ops::decode(&arrays(1, 8), 1);
assert!(!complete);
assert_eq!(rows.len(), 1);
assert!(rows[0].payload.is_none());
}
#[test]
#[ignore = "memory regression: run separately with a 128 MiB address-space limit"]
fn repeated_array_references_stay_under_the_default_byte_budget() {
let code = arrays(2048, 65_536);
let (rows, complete) = dex_ops::decode(&code, 200_000);
assert!(!complete);
assert_eq!(rows.len(), 2049);
assert_eq!(bytes(&rows), dex_ops::DEFAULT_MAX_PAYLOAD_BYTES);
}
@@ -0,0 +1,94 @@
use crate::bytes::Reader;
use crate::dex::{self, Code, Handler, sleb128};
#[test]
fn rejects_invalid_fifth_byte_sign_extensions() {
for prefix in [0x80, 0xff] {
for last in 0x08..=0x77 {
let mut encoded = vec![prefix; 4];
encoded.push(last);
assert_eq!(sleb128(&Reader::new(&encoded), 0), None, "last byte {last:#x}");
}
}
}
#[test]
fn retains_signed_32_bit_limits_and_ordinary_values() {
assert_eq!(sleb128(&Reader::new(&[0xff, 0xff, 0xff, 0xff, 0x07]), 0), Some((i64::from(i32::MAX), 5)));
assert_eq!(sleb128(&Reader::new(&[0x80, 0x80, 0x80, 0x80, 0x78]), 0), Some((i64::from(i32::MIN), 5)));
assert_eq!(sleb128(&Reader::new(&[0x9b, 0xf1, 0x59]), 0), Some((-624485, 3)));
assert_eq!(sleb128(&Reader::new(&[0xe5, 0x8e, 0x26]), 0), Some((624485, 3)));
assert_eq!(sleb128(&Reader::new(&[0xff, 0x7f]), 0), Some((-1, 2)));
assert_eq!(sleb128(&Reader::new(&[0x80, 0]), 0), Some((0, 2)));
assert_eq!(sleb128(&Reader::new(&[0x55, 0x7f, 0x55]), 1), Some((-1, 1)));
}
#[test]
fn retains_valid_five_byte_sign_extensions() {
assert_eq!(sleb128(&Reader::new(&[0x80, 0x80, 0x80, 0x80, 0]), 0), Some((0, 5)));
assert_eq!(sleb128(&Reader::new(&[0x81, 0x80, 0x80, 0x80, 0]), 0), Some((1, 5)));
assert_eq!(sleb128(&Reader::new(&[0xff, 0xff, 0xff, 0xff, 0x7f]), 0), Some((-1, 5)));
}
#[test]
fn rejects_values_longer_than_five_bytes() {
for (prefix, last) in [(0x80, 0), (0xff, 0x7f)] {
for length in [6, 10] {
let mut encoded = vec![prefix; length - 1];
encoded.push(last);
assert_eq!(sleb128(&Reader::new(&encoded), 0), None, "{encoded:x?}");
}
}
}
#[test]
fn rejects_truncated_values_and_out_of_range_offsets() {
assert_eq!(sleb128(&Reader::new(&[0x80; 5]), 0), None);
assert_eq!(sleb128(&Reader::new(&[0x80]), 0), None);
assert_eq!(sleb128(&Reader::new(&[]), 0), None);
assert_eq!(sleb128(&Reader::new(&[0]), usize::MAX), None);
}
fn code_with_handler(size: &[u8], payload: &[u8]) -> Code {
let mut bytes = vec![0; 0x70];
bytes[..8].copy_from_slice(b"dex\n035\0");
bytes[36..40].copy_from_slice(&0x70u32.to_le_bytes());
bytes[40..44].copy_from_slice(&0x1234_5678u32.to_le_bytes());
// Eight nop instructions and one try entry pointing to the first encoded handler.
bytes.extend_from_slice(&[1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 8, 0, 0, 0]);
bytes.extend_from_slice(&[0; 16]);
bytes.extend_from_slice(&[0, 0, 0, 0, 1, 0, 1, 0]);
bytes.push(1);
bytes.extend_from_slice(size);
bytes.extend_from_slice(payload);
let len = bytes.len() as u32;
bytes[32..36].copy_from_slice(&len.to_le_bytes());
dex::parse(&bytes).unwrap().code(0x70).unwrap()
}
#[test]
fn invalid_sizes_do_not_create_handlers() {
let sizes: &[&[u8]] = &[
&[0x80, 0x80, 0x80, 0x80, 0x08],
&[0x80, 0x80, 0x80, 0x80, 0x77],
&[0x80, 0x80, 0x80, 0x80, 0x80, 0],
&[0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0],
];
for size in sizes {
// These bytes could be a type/address pair or a catch-all address if size is accepted.
let code = code_with_handler(size, &[0, 7]);
assert_eq!(code.tries.len(), 1);
assert!(code.tries[0].handlers.is_empty(), "invalid size {size:x?}");
}
}
#[test]
fn valid_catch_all_handlers_are_retained() {
for size in [&[0][..], &[0x80, 0x80, 0x80, 0x80, 0][..]] {
let code = code_with_handler(size, &[7]);
assert_eq!(code.tries.len(), 1);
assert_eq!(code.tries[0].start, 0);
assert_eq!(code.tries[0].end, 1);
assert_eq!(code.tries[0].handlers, vec![Handler { exception: None, address: 7 }]);
}
}
+430
View File
@@ -0,0 +1,430 @@
// Synthetic DEX fixture and deterministic mutations retained from Craft Anything.
pub use craft_testkit::sample_damage::{mutations, noise};
pub mod android {
pub const HELLO: &str = "Hello, Craft!";
fn u16le(v: &mut Vec<u8>, x: u16) {
v.extend_from_slice(&x.to_le_bytes());
}
fn u32le(v: &mut Vec<u8>, x: u32) {
v.extend_from_slice(&x.to_le_bytes());
}
fn uleb(v: &mut Vec<u8>, mut x: u32) {
loop {
let b = (x & 0x7f) as u8;
x >>= 7;
if x == 0 {
v.push(b);
break;
}
v.push(b | 0x80);
}
}
fn sleb(v: &mut Vec<u8>, mut x: i32) {
loop {
let b = (x & 0x7f) as u8;
x >>= 7;
let done = (x == 0 && b & 0x40 == 0) || (x == -1 && b & 0x40 != 0);
v.push(if done { b } else { b | 0x80 });
if done {
break;
}
}
}
fn align4(v: &mut Vec<u8>) {
while !v.len().is_multiple_of(4) {
v.push(0);
}
}
#[derive(Debug, Clone, Default)]
pub struct TrySpec {
pub start: u32,
pub count: u16,
/// (type idx, handler address)
pub handlers: Vec<(u32, u32)>,
pub catch_all: Option<u32>,
}
#[derive(Debug, Clone, Default)]
pub struct CodeSpec {
pub registers: u16,
pub ins: u16,
pub outs: u16,
pub insns: Vec<u16>,
pub tries: Vec<TrySpec>,
}
#[derive(Debug, Clone)]
pub struct MethodSpec {
pub method: u32,
pub access: u32,
pub code: Option<CodeSpec>,
}
#[derive(Debug, Clone, Default)]
pub struct ClassSpec {
pub class: u32,
pub access: u32,
pub superclass: u32,
pub interfaces: Vec<u32>,
pub source_file: u32,
pub annotations: Vec<u32>,
pub static_fields: Vec<(u32, u32)>,
pub instance_fields: Vec<(u32, u32)>,
pub direct: Vec<MethodSpec>,
pub virtuals: Vec<MethodSpec>,
}
#[derive(Debug, Clone, Default)]
pub struct DexBuilder {
strings: Vec<String>,
types: Vec<u32>,
protos: Vec<(u32, u32, Vec<u32>)>,
fields: Vec<(u32, u32, u32)>,
methods: Vec<(u32, u32, u32)>,
pub classes: Vec<ClassSpec>,
}
impl DexBuilder {
pub fn string(&mut self, s: &str) -> u32 {
if let Some(i) = self.strings.iter().position(|x| x == s) {
return i as u32;
}
self.strings.push(s.to_string());
(self.strings.len() - 1) as u32
}
pub fn ty(&mut self, desc: &str) -> u32 {
let s = self.string(desc);
if let Some(i) = self.types.iter().position(|&x| x == s) {
return i as u32;
}
self.types.push(s);
(self.types.len() - 1) as u32
}
pub fn proto(&mut self, ret: &str, params: &[&str]) -> u32 {
let short = |d: &str| if d.starts_with('L') || d.starts_with('[') { 'L' } else { d.chars().next().unwrap() };
let shorty: String = std::iter::once(short(ret)).chain(params.iter().map(|p| short(p))).collect();
let s = self.string(&shorty);
let r = self.ty(ret);
let ps: Vec<u32> = params.iter().map(|p| self.ty(p)).collect();
if let Some(i) = self.protos.iter().position(|p| p.1 == r && p.2 == ps) {
return i as u32;
}
self.protos.push((s, r, ps));
(self.protos.len() - 1) as u32
}
pub fn field(&mut self, cls: &str, ty: &str, name: &str) -> u32 {
let c = self.ty(cls);
let t = self.ty(ty);
let n = self.string(name);
if let Some(i) = self.fields.iter().position(|&f| f == (c, t, n)) {
return i as u32;
}
self.fields.push((c, t, n));
(self.fields.len() - 1) as u32
}
pub fn method(&mut self, cls: &str, name: &str, ret: &str, params: &[&str]) -> u32 {
let c = self.ty(cls);
let p = self.proto(ret, params);
let n = self.string(name);
if let Some(i) = self.methods.iter().position(|&m| m == (c, p, n)) {
return i as u32;
}
self.methods.push((c, p, n));
(self.methods.len() - 1) as u32
}
pub fn build(self) -> Vec<u8> {
let ns = self.strings.len();
let nt = self.types.len();
let np = self.protos.len();
let nf = self.fields.len();
let nm = self.methods.len();
let nc = self.classes.len();
let string_ids = 0x70;
let type_ids = string_ids + ns * 4;
let proto_ids = type_ids + nt * 4;
let field_ids = proto_ids + np * 12;
let method_ids = field_ids + nf * 8;
let class_defs = method_ids + nm * 8;
let mut data_start = class_defs + nc * 32;
data_start = (data_start + 3) & !3;
let mut d: Vec<u8> = Vec::new();
let at = |d: &Vec<u8>| (data_start + d.len()) as u32;
// type lists
let tl = |d: &mut Vec<u8>, list: &[u32]| -> u32 {
if list.is_empty() {
return 0;
}
align4(d);
let o = at(d);
u32le(d, list.len() as u32);
for &t in list {
u16le(d, t as u16);
}
o
};
let proto_params: Vec<u32> = self.protos.iter().map(|p| tl(&mut d, &p.2)).collect();
let class_ifaces: Vec<u32> = self.classes.iter().map(|c| tl(&mut d, &c.interfaces)).collect();
// string data
let mut string_offs = Vec::new();
for s in &self.strings {
string_offs.push(at(&d));
uleb(&mut d, s.encode_utf16().count() as u32);
for c in s.encode_utf16() {
if c == 0 {
d.extend_from_slice(&[0xc0, 0x80]);
} else if c < 0x80 {
d.push(c as u8);
} else if c < 0x800 {
d.extend_from_slice(&[0xc0 | (c >> 6) as u8, 0x80 | (c & 0x3f) as u8]);
} else {
d.extend_from_slice(&[0xe0 | (c >> 12) as u8, 0x80 | ((c >> 6) & 0x3f) as u8, 0x80 | (c & 0x3f) as u8]);
}
}
d.push(0);
}
// code items, class data, annotations
let mut class_data_offs = Vec::new();
let mut annot_offs = Vec::new();
for c in &self.classes {
let code_off = |d: &mut Vec<u8>, m: &MethodSpec| -> u32 {
let Some(code) = &m.code else { return 0 };
align4(d);
let o = at(d);
u16le(d, code.registers);
u16le(d, code.ins);
u16le(d, code.outs);
u16le(d, code.tries.len() as u16);
u32le(d, 0);
u32le(d, code.insns.len() as u32);
for &i in &code.insns {
u16le(d, i);
}
if !code.tries.is_empty() {
if code.insns.len() % 2 == 1 {
u16le(d, 0);
}
let mut list = Vec::new();
uleb(&mut list, code.tries.len() as u32);
let mut offs = Vec::new();
for t in &code.tries {
offs.push(list.len() as u16);
let n = t.handlers.len() as i32;
sleb(&mut list, if t.catch_all.is_some() { -n } else { n });
for &(ty, addr) in &t.handlers {
uleb(&mut list, ty);
uleb(&mut list, addr);
}
if let Some(a) = t.catch_all {
uleb(&mut list, a);
}
}
for (t, off) in code.tries.iter().zip(offs) {
u32le(d, t.start);
u16le(d, t.count);
u16le(d, off);
}
d.extend_from_slice(&list);
}
o
};
let mut direct = c.direct.clone();
direct.sort_by_key(|m| m.method);
let mut virtuals = c.virtuals.clone();
virtuals.sort_by_key(|m| m.method);
let direct_offs: Vec<u32> = direct.iter().map(|m| code_off(&mut d, m)).collect();
let virtual_offs: Vec<u32> = virtuals.iter().map(|m| code_off(&mut d, m)).collect();
let cd = at(&d);
let mut sf = c.static_fields.clone();
sf.sort();
let mut inf = c.instance_fields.clone();
inf.sort();
uleb(&mut d, sf.len() as u32);
uleb(&mut d, inf.len() as u32);
uleb(&mut d, direct.len() as u32);
uleb(&mut d, virtuals.len() as u32);
for list in [&sf, &inf] {
let mut prev = 0;
for &(f, a) in list.iter() {
uleb(&mut d, f - prev);
uleb(&mut d, a);
prev = f;
}
}
for (list, offs) in [(&direct, &direct_offs), (&virtuals, &virtual_offs)] {
let mut prev = 0;
for (m, &o) in list.iter().zip(offs.iter()) {
uleb(&mut d, m.method - prev);
uleb(&mut d, m.access);
uleb(&mut d, o);
prev = m.method;
}
}
class_data_offs.push(cd);
if c.annotations.is_empty() {
annot_offs.push(0);
} else {
let mut items = Vec::new();
for &t in &c.annotations {
items.push(at(&d));
d.push(1); // runtime visibility
uleb(&mut d, t);
uleb(&mut d, 0);
}
align4(&mut d);
let set_off = at(&d);
u32le(&mut d, items.len() as u32);
for i in items {
u32le(&mut d, i);
}
let dir = at(&d);
u32le(&mut d, set_off);
u32le(&mut d, 0);
u32le(&mut d, 0);
u32le(&mut d, 0);
annot_offs.push(dir);
}
}
align4(&mut d);
let file_size = data_start + d.len();
let mut out = vec![0u8; data_start];
out[..8].copy_from_slice(b"dex\n035\0");
let put = |out: &mut Vec<u8>, off: usize, v: u32| out[off..off + 4].copy_from_slice(&v.to_le_bytes());
put(&mut out, 32, file_size as u32);
put(&mut out, 36, 0x70);
put(&mut out, 40, 0x1234_5678);
for (i, (n, o)) in
[(ns, string_ids), (nt, type_ids), (np, proto_ids), (nf, field_ids), (nm, method_ids), (nc, class_defs)].iter().enumerate()
{
put(&mut out, 56 + i * 8, *n as u32);
put(&mut out, 60 + i * 8, if *n == 0 { 0 } else { *o as u32 });
}
put(&mut out, 104, d.len() as u32);
put(&mut out, 108, data_start as u32);
for (i, o) in string_offs.iter().enumerate() {
put(&mut out, string_ids + i * 4, *o);
}
for (i, t) in self.types.iter().enumerate() {
put(&mut out, type_ids + i * 4, *t);
}
for (i, p) in self.protos.iter().enumerate() {
put(&mut out, proto_ids + i * 12, p.0);
put(&mut out, proto_ids + i * 12 + 4, p.1);
put(&mut out, proto_ids + i * 12 + 8, proto_params[i]);
}
for (i, (c, t, n)) in self.fields.iter().enumerate() {
out[field_ids + i * 8..field_ids + i * 8 + 2].copy_from_slice(&(*c as u16).to_le_bytes());
out[field_ids + i * 8 + 2..field_ids + i * 8 + 4].copy_from_slice(&(*t as u16).to_le_bytes());
put(&mut out, field_ids + i * 8 + 4, *n);
}
for (i, (c, p, n)) in self.methods.iter().enumerate() {
out[method_ids + i * 8..method_ids + i * 8 + 2].copy_from_slice(&(*c as u16).to_le_bytes());
out[method_ids + i * 8 + 2..method_ids + i * 8 + 4].copy_from_slice(&(*p as u16).to_le_bytes());
put(&mut out, method_ids + i * 8 + 4, *n);
}
for (i, c) in self.classes.iter().enumerate() {
let o = class_defs + i * 32;
for (k, v) in
[c.class, c.access, c.superclass, class_ifaces[i], c.source_file, annot_offs[i], class_data_offs[i], 0].iter().enumerate()
{
put(&mut out, o + k * 4, *v);
}
}
out.extend_from_slice(&d);
let sum = adler32(&out[12..]);
put(&mut out, 8, sum);
out
}
}
fn adler32(data: &[u8]) -> u32 {
let (mut a, mut b) = (1u32, 0u32);
for &x in data {
a = (a + u32::from(x)) % 65521;
b = (b + a) % 65521;
}
(b << 16) | a
}
const MAIN: &str = "Lcom/example/notes/MainActivity;";
const UTIL: &str = "Lcom/example/notes/Util;";
const STRING: &str = "Ljava/lang/String;";
/// `classes.dex` of the Notes app: `MainActivity` (constructor, `onCreate`, `run`, `pick` with a
/// packed switch inside a try/catch) and `Util` (two `log` overloads printing through
/// `System.out`).
pub fn notes_dex() -> Vec<u8> {
let mut b = DexBuilder::default();
let activity = b.ty("Landroid/app/Activity;");
let main = b.ty(MAIN);
let runnable = b.ty("Ljava/lang/Runnable;");
let deprecated = b.ty("Ljava/lang/Deprecated;");
let rte = b.ty("Ljava/lang/RuntimeException;");
let object = b.ty("Ljava/lang/Object;");
let util = b.ty(UTIL);
let tag = b.field(MAIN, STRING, "TAG");
let count = b.field(MAIN, "I", "count");
let out = b.field("Ljava/lang/System;", "Ljava/io/PrintStream;", "out");
let super_init = b.method("Landroid/app/Activity;", "<init>", "V", &[]);
let super_create = b.method("Landroid/app/Activity;", "onCreate", "V", &["Landroid/os/Bundle;"]);
let init = b.method(MAIN, "<init>", "V", &[]);
let on_create = b.method(MAIN, "onCreate", "V", &["Landroid/os/Bundle;"]);
let run = b.method(MAIN, "run", "V", &[]);
let pick = b.method(MAIN, "pick", "I", &["I"]);
let log_s = b.method(UTIL, "log", "V", &[STRING]);
let log_i = b.method(UTIL, "log", "V", &["I"]);
let println = b.method("Ljava/io/PrintStream;", "println", "V", &[STRING]);
let hello = b.string(HELLO);
let main_src = b.string("MainActivity.java");
let util_src = b.string("Util.java");
let code = |registers, ins, outs, insns: Vec<u16>| Some(CodeSpec { registers, ins, outs, insns, tries: vec![] });
b.classes.push(ClassSpec {
class: main,
access: 0x1,
superclass: activity,
interfaces: vec![runnable],
source_file: main_src,
annotations: vec![deprecated],
static_fields: vec![(tag, 0x1a)],
instance_fields: vec![(count, 0x2)],
direct: vec![MethodSpec { method: init, access: 0x10001, code: code(1, 1, 1, vec![0x1070, super_init as u16, 0x0000, 0x000e]) }],
virtuals: vec![
MethodSpec {
method: on_create,
access: 0x1,
code: code(3, 2, 2, vec![0x001a, hello as u16, 0x1071, log_s as u16, 0x0000, 0x206f, super_create as u16, 0x0021, 0x000e]),
},
MethodSpec { method: run, access: 0x1, code: code(1, 1, 1, vec![0x7012, 0x1071, log_i as u16, 0x0000, 0x000e]) },
MethodSpec {
method: pick,
access: 0x1,
code: Some(CodeSpec {
registers: 3,
ins: 2,
outs: 0,
insns: vec![0x022b, 10, 0, 0x0012, 0x000f, 0x1012, 0x000f, 0x2012, 0x000f, 0x0000, 0x0100, 2, 1, 0, 5, 0, 7, 0],
tries: vec![TrySpec { start: 0, count: 3, handlers: vec![(rte, 3)], catch_all: Some(3) }],
}),
},
],
});
b.classes.push(ClassSpec {
class: util,
access: 0x11,
superclass: object,
source_file: util_src,
direct: vec![
MethodSpec { method: log_s, access: 0x9, code: code(2, 1, 2, vec![0x0062, out as u16, 0x206e, println as u16, 0x0010, 0x000e]) },
MethodSpec { method: log_i, access: 0x9, code: code(1, 1, 0, vec![0x000e]) },
],
..ClassSpec::default()
});
b.build()
}
}
+1
View File
@@ -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 }
+79 -12
View File
@@ -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);
}
}
+79 -1
View File
@@ -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();
+2 -2
View File
@@ -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
View File
@@ -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)]
+7 -5
View File
@@ -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.
+182 -7
View 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
View File
@@ -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 &amp; y</a>
"
",
MAX_ELEMENTS
)
.is_ok()
);
+44
View File
@@ -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");
}
+1
View File
@@ -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;
+19
View File
@@ -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 }
+63
View File
@@ -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>;
+318
View File
@@ -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);
}
}
+186
View File
@@ -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>,
}
+17
View File
@@ -0,0 +1,17 @@
[package]
name = "craft-evm"
description = "Read-only EVM bytecode dispatcher and compiler metadata inspection"
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
repository.workspace = true
[lints]
workspace = true
[dependencies]
serde = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }
[dev-dependencies]
craft-testkit = { workspace = true }
+7
View File
@@ -0,0 +1,7 @@
# craft-evm
Read-only EVM bytecode inspection: strict raw/hex admission, opcode listing, dispatcher selector and jump-pattern facts, and Solidity/Vyper CBOR metadata. No VM execution, RPC, wallet, signing or transaction support.
Preserves Craft Anything's parser behavior and limits: 16 MiB decoded bytecode, 4,096 reported functions and 400 listing entries, plus existing bounded CBOR recursion/collection parsing. These are not a total allocator-byte guarantee. Dispatcher facts are heuristics, not a full control-flow or semantic proof. EOF containers remain unsupported.
Application file I/O, evidence policy and selector naming remain outside this crate.
+895
View File
@@ -0,0 +1,895 @@
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#![forbid(unsafe_code)]
//! EVM bytecode: the public function selectors a contract's dispatcher compares against, where
//! each one jumps, whether it refuses payments, fallback/receive presence, and the compiler
//! metadata (CBOR) appended to the code. Nothing is executed; this is a linear sweep that
//! respects PUSH data plus pattern matching over the instruction stream.
use EvmError as FormatError;
/// Neutral inspection failure; no code is executed.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum EvmError {
#[error("truncated input: {0}")]
Truncated(String),
#[error("malformed input: {0}")]
Malformed(String),
#[error("unsupported: {0}")]
Unsupported(String),
#[error("input too large: {0}")]
TooLarge(String),
}
#[cfg(test)]
mod test_support;
use serde::Serialize;
use serde_json::{Map, Value};
use std::collections::BTreeSet;
/// Largest bytecode we analyse (16 MiB; deployed contracts are at most 24 KiB).
pub const MAX_CODE: usize = 16 << 20;
const MAX_FUNCTIONS: usize = 4096;
const LISTING_CAP: usize = 400;
/// How input bytes are encoded.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Encoding {
/// Hex when the bytes are all hex digits (with an optional 0x), raw otherwise.
Auto,
Raw,
Hex,
}
/// Turn input bytes into bytecode. Hex is strict: optional `0x`, even length, only hex digits;
/// surrounding whitespace is ignored.
pub fn decode_input(input: &[u8], enc: Encoding) -> Result<(Vec<u8>, &'static str), FormatError> {
let trimmed = input.trim_ascii();
let body = trimmed.strip_prefix(b"0x").or_else(|| trimmed.strip_prefix(b"0X")).unwrap_or(trimmed);
let looks_hex = !body.is_empty() && body.iter().all(u8::is_ascii_hexdigit);
let hex = match enc {
Encoding::Hex => true,
Encoding::Raw => false,
Encoding::Auto => looks_hex,
};
if !hex {
if input.len() > MAX_CODE {
return Err(FormatError::TooLarge(format!("{} bytes; the limit is {MAX_CODE}", input.len())));
}
return Ok((input.to_vec(), "raw"));
}
if body.is_empty() {
return Err(FormatError::Malformed("no hex digits".into()));
}
if let Some(p) = body.iter().position(|b| !b.is_ascii_hexdigit()) {
return Err(FormatError::Malformed(format!("not a hex digit at position {p}")));
}
if !body.len().is_multiple_of(2) {
return Err(FormatError::Malformed(format!("odd number of hex digits ({})", body.len())));
}
if body.len() / 2 > MAX_CODE {
return Err(FormatError::TooLarge(format!("{} bytes; the limit is {MAX_CODE}", body.len() / 2)));
}
let nib = |c: u8| -> u8 {
match c {
b'0'..=b'9' => c - b'0',
b'a'..=b'f' => c - b'a' + 10,
_ => c.wrapping_sub(b'A').wrapping_add(10) & 0x0f,
}
};
Ok((body.chunks(2).map(|p| (nib(p.first().copied().unwrap_or(b'0')) << 4) | nib(p.get(1).copied().unwrap_or(b'0'))).collect(), "hex"))
}
#[derive(Debug, Clone, Copy)]
struct Ins {
off: usize,
op: u8,
/// Immediate (PUSH data) start and length.
imm: (usize, usize),
}
fn push_len(op: u8) -> usize {
if (0x60..=0x7f).contains(&op) { usize::from(op - 0x5f) } else { 0 }
}
/// The mnemonic of an opcode (`UNKNOWN_0x…` for unassigned ones).
pub fn mnemonic(op: u8) -> String {
let s = match op {
0x00 => "STOP",
0x01 => "ADD",
0x02 => "MUL",
0x03 => "SUB",
0x04 => "DIV",
0x05 => "SDIV",
0x06 => "MOD",
0x07 => "SMOD",
0x08 => "ADDMOD",
0x09 => "MULMOD",
0x0a => "EXP",
0x0b => "SIGNEXTEND",
0x10 => "LT",
0x11 => "GT",
0x12 => "SLT",
0x13 => "SGT",
0x14 => "EQ",
0x15 => "ISZERO",
0x16 => "AND",
0x17 => "OR",
0x18 => "XOR",
0x19 => "NOT",
0x1a => "BYTE",
0x1b => "SHL",
0x1c => "SHR",
0x1d => "SAR",
0x20 => "KECCAK256",
0x30 => "ADDRESS",
0x31 => "BALANCE",
0x32 => "ORIGIN",
0x33 => "CALLER",
0x34 => "CALLVALUE",
0x35 => "CALLDATALOAD",
0x36 => "CALLDATASIZE",
0x37 => "CALLDATACOPY",
0x38 => "CODESIZE",
0x39 => "CODECOPY",
0x3a => "GASPRICE",
0x3b => "EXTCODESIZE",
0x3c => "EXTCODECOPY",
0x3d => "RETURNDATASIZE",
0x3e => "RETURNDATACOPY",
0x3f => "EXTCODEHASH",
0x40 => "BLOCKHASH",
0x41 => "COINBASE",
0x42 => "TIMESTAMP",
0x43 => "NUMBER",
0x44 => "PREVRANDAO",
0x45 => "GASLIMIT",
0x46 => "CHAINID",
0x47 => "SELFBALANCE",
0x48 => "BASEFEE",
0x49 => "BLOBHASH",
0x4a => "BLOBBASEFEE",
0x50 => "POP",
0x51 => "MLOAD",
0x52 => "MSTORE",
0x53 => "MSTORE8",
0x54 => "SLOAD",
0x55 => "SSTORE",
0x56 => "JUMP",
0x57 => "JUMPI",
0x58 => "PC",
0x59 => "MSIZE",
0x5a => "GAS",
0x5b => "JUMPDEST",
0x5c => "TLOAD",
0x5d => "TSTORE",
0x5e => "MCOPY",
0x5f => "PUSH0",
0x60..=0x7f => return format!("PUSH{}", op - 0x5f),
0x80..=0x8f => return format!("DUP{}", op - 0x7f),
0x90..=0x9f => return format!("SWAP{}", op - 0x8f),
0xa0..=0xa4 => return format!("LOG{}", op - 0xa0),
0xf0 => "CREATE",
0xf1 => "CALL",
0xf2 => "CALLCODE",
0xf3 => "RETURN",
0xf4 => "DELEGATECALL",
0xf5 => "CREATE2",
0xfa => "STATICCALL",
0xfd => "REVERT",
0xfe => "INVALID",
0xff => "SELFDESTRUCT",
_ => return format!("UNKNOWN_{op:#04x}"),
};
s.to_string()
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct EvmFunction {
/// `0x` + 8 hex digits.
pub selector: String,
/// Where the dispatcher sends calls with this selector.
pub bytecode_offset: usize,
/// Offset of the comparison in the dispatcher.
pub compare_offset: usize,
pub dispatch: &'static str,
/// `eq-jumpi` (jump on match) or `eq-iszero-fallthrough` (body follows the check).
pub pattern: &'static str,
/// `nonpayable`, `payable` or `unknown` (view/pure cannot be told from the dispatcher).
pub mutability: &'static str,
/// Why the mutability was chosen.
pub mutability_reason: String,
/// False when the destination is not a JUMPDEST (the match is then doubtful).
pub jumpdest_valid: bool,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct EvmMetadata {
pub offset: usize,
pub length: usize,
pub entries: Value,
pub compiler: Option<String>,
pub ipfs: Option<String>,
pub swarm: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct EvmInterface {
pub code_size: usize,
/// Bytes analysed after removing the metadata tail.
pub analysed_size: usize,
pub metadata: Option<EvmMetadata>,
pub instructions: usize,
pub jumpdests: usize,
/// How the selector is pulled from calldata: `shr-224`, `div-2^224`, `and-mask`, or none.
pub selector_extraction: Option<&'static str>,
pub dispatcher_offset: Option<usize>,
/// `solc-like`, `vyper-like`, `mixed` or `none`.
pub style: &'static str,
pub functions: Vec<EvmFunction>,
/// Comparisons that split the selector range (binary-search dispatchers).
pub binary_search_splits: usize,
/// A CALLVALUE check that runs before any selector comparison (all functions non-payable).
pub callvalue_check_before_dispatch: bool,
pub short_calldata_check: bool,
/// `present`, `absent` or `unknown`.
pub fallback: &'static str,
/// `present` or `not-detected`.
pub receive: &'static str,
/// The dispatcher region as text (first instructions only).
pub dispatcher_listing: Vec<String>,
pub warnings: Vec<String>,
}
fn sweep(code: &[u8]) -> Vec<Ins> {
let mut out = Vec::with_capacity(code.len().min(1 << 20) / 2);
let mut i = 0usize;
while i < code.len() {
let op = code.get(i).copied().unwrap_or(0);
let n = push_len(op);
out.push(Ins { off: i, op, imm: (i + 1, n) });
i = i.saturating_add(1).saturating_add(n);
}
out
}
fn imm<'a>(code: &'a [u8], ins: &Ins) -> &'a [u8] {
// Truncated PUSH data at the end of code reads as zero-padded; we only use what exists.
let (s, n) = ins.imm;
code.get(s..s.saturating_add(n).min(code.len())).unwrap_or(&[])
}
fn imm_u64(code: &[u8], ins: &Ins) -> Option<u64> {
let b = imm(code, ins);
if ins.imm.1 > 8 || b.len() != ins.imm.1 {
return None;
}
Some(b.iter().fold(0u64, |a, &x| (a << 8) | u64::from(x)))
}
fn is_push(op: u8) -> bool {
(0x60..=0x7f).contains(&op)
}
/// Strip and decode a trailing CBOR metadata block.
fn split_metadata(code: &[u8]) -> (usize, Option<EvmMetadata>) {
let n = code.len();
if n < 4 {
return (n, None);
}
let len = usize::from(u16::from_be_bytes([code.get(n - 2).copied().unwrap_or(0), code.get(n - 1).copied().unwrap_or(0)]));
if len == 0 || len.saturating_add(2) > n {
return (n, None);
}
let start = n - 2 - len;
let Some(cbor) = code.get(start..n - 2) else { return (n, None) };
if !matches!(cbor.first(), Some(0xa1..=0xb8 | 0xbf)) {
return (n, None);
}
let mut pos = 0usize;
let Some(v) = cbor_item(cbor, &mut pos, 0) else { return (n, None) };
if pos != cbor.len() {
return (n, None);
}
let Value::Object(map) = &v else { return (n, None) };
let compiler = map
.get("solc")
.and_then(|s| s.as_str().map(String::from))
.map(|v| format!("solc {v}"))
.or_else(|| map.get("vyper").and_then(Value::as_str).map(|v| format!("vyper {v}")));
let ipfs = map.get("ipfs").and_then(Value::as_str).map(String::from);
let swarm = map.get("bzzr1").or_else(|| map.get("bzzr0")).and_then(Value::as_str).map(String::from);
(start, Some(EvmMetadata { offset: start, length: len + 2, entries: v.clone(), compiler, ipfs, swarm }))
}
fn cbor_arg(b: &[u8], pos: &mut usize, info: u8) -> Option<u64> {
let take = |pos: &mut usize, k: usize| -> Option<u64> {
let s = b.get(*pos..pos.checked_add(k)?)?;
*pos += k;
Some(s.iter().fold(0u64, |a, &x| (a << 8) | u64::from(x)))
};
match info {
0..=23 => Some(u64::from(info)),
24 => take(pos, 1),
25 => take(pos, 2),
26 => take(pos, 4),
27 => take(pos, 8),
_ => None,
}
}
/// Decode one bounded metadata item. An incomplete or unsupported value invalidates the metadata trailer.
fn cbor_item(b: &[u8], pos: &mut usize, depth: u32) -> Option<Value> {
if depth > 4 {
return None;
}
let ib = *b.get(*pos)?;
*pos += 1;
let major = ib >> 5;
let info = ib & 0x1f;
match major {
0 => cbor_arg(b, pos, info).map(Value::from),
2 | 3 => {
let n = usize::try_from(cbor_arg(b, pos, info)?).ok()?;
let s = b.get(*pos..pos.checked_add(n)?)?;
*pos += n;
Some(if major == 3 { Value::from(std::str::from_utf8(s).ok()?) } else { Value::from(bytes_value(s)) })
}
4 => {
let n = usize::try_from(cbor_arg(b, pos, info)?).ok()?;
if n > 64 {
return None;
}
let mut items = Vec::new();
for _ in 0..n {
items.push(cbor_item(b, pos, depth + 1)?);
}
Some(Value::Array(items))
}
5 => {
let n = usize::try_from(cbor_arg(b, pos, info)?).ok()?;
if n > 32 {
return None;
}
let mut m = Map::new();
for _ in 0..n {
// The metadata view uses JSON object keys. Coercing other CBOR key
// types to strings can merge distinct keys and hide bytecode.
if b.get(*pos).map(|byte| byte >> 5) != Some(3) {
return None;
}
let Value::String(k) = cbor_item(b, pos, depth + 1)? else { return None };
if m.contains_key(&k) {
return None;
}
let v = cbor_item(b, pos, depth + 1)?;
let v = match (k.as_str(), &v) {
("solc" | "vyper", Value::Array(items)) if items.len() == 3 && items.iter().all(Value::is_u64) => {
Value::from(items.iter().map(|v| v.to_string()).collect::<Vec<_>>().join("."))
}
("solc", Value::String(s)) if s.starts_with("0x") && s.len() == 8 => {
let d: Vec<u8> = (0..3).filter_map(|i| hex_byte(s.get(2 + 2 * i..4 + 2 * i)?)).collect();
if let [a, bb, c] = d.as_slice() { Value::from(format!("{a}.{bb}.{c}")) } else { v }
}
("ipfs", Value::String(s)) if s.starts_with("0x1220") => Value::from(base58(&hex_decode(s.get(2..).unwrap_or("")))),
_ => v,
};
m.insert(k, v);
}
Some(Value::Object(m))
}
7 => match info {
20 => Some(Value::Bool(false)),
21 => Some(Value::Bool(true)),
22 => Some(Value::Null),
_ => None,
},
_ => None,
}
}
fn bytes_value(s: &[u8]) -> String {
let mut out = String::with_capacity(2 + s.len() * 2);
out.push_str("0x");
for b in s {
out.push_str(&format!("{b:02x}"));
}
out
}
/// One byte from two hex digits; `from_str_radix` alone would also accept a leading `+`.
fn hex_byte(pair: &str) -> Option<u8> {
if pair.bytes().all(|c| c.is_ascii_hexdigit()) { u8::from_str_radix(pair, 16).ok() } else { None }
}
fn hex_decode(s: &str) -> Vec<u8> {
(0..s.len() / 2).filter_map(|i| hex_byte(s.get(2 * i..2 * i + 2)?)).collect()
}
fn base58(b: &[u8]) -> String {
const A: &[u8; 58] = b"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
let zeros = b.iter().take_while(|&&x| x == 0).count();
let mut digits: Vec<u8> = Vec::new();
for &byte in b.iter().take(128) {
let mut carry = u32::from(byte);
for d in digits.iter_mut() {
carry += u32::from(*d) << 8;
*d = (carry % 58) as u8;
carry /= 58;
}
while carry > 0 {
digits.push((carry % 58) as u8);
carry /= 58;
}
}
let mut s: String = std::iter::repeat_n('1', zeros).collect();
s.extend(digits.iter().rev().map(|&d| char::from(*A.get(usize::from(d)).unwrap_or(&b'1'))));
s
}
fn selector_extraction(body: &[u8], ins: &[Ins]) -> Option<(&'static str, usize)> {
let at = |k: usize| ins.get(k);
let op_at = |k: usize| at(k).map(|i| i.op);
// Selector extraction: CALLDATALOAD followed by SHR 224, DIV 2^224 or a 4-byte mask.
let mut extraction: Option<(&'static str, usize)> = None;
for (k, i) in ins.iter().enumerate() {
if i.op != 0x35 {
continue;
}
for d in 1..=6 {
let Some(n) = at(k + d) else { break };
let kind = match n.op {
0x60 if imm(body, n) == [0xe0] && op_at(k + d + 1) == Some(0x1c) => Some("shr-224"),
0x7c if d == 1
&& imm(body, n).first() == Some(&1)
&& imm(body, n).iter().skip(1).all(|&b| b == 0)
&& op_at(k + d + 1) == Some(0x90)
&& op_at(k + d + 2) == Some(0x04) =>
{
Some("div-2^224")
}
0x63 if imm(body, n) == [0xff, 0xff, 0xff, 0xff] && (op_at(k + d + 1) == Some(0x16) || op_at(k + d + 2) == Some(0x16)) => {
Some("and-mask")
}
_ => None,
};
if let Some(kind) = kind {
extraction = Some((kind, k));
break;
}
}
if extraction.is_some() {
break;
}
}
extraction
}
fn short_calldata_path(body: &[u8], ins: &[Ins], disp_start: usize) -> (bool, &'static str) {
let at = |k: usize| ins.get(k);
let op_at = |k: usize| at(k).map(|i| i.op);
// Short calldata path and receive().
let mut short_calldata = false;
let mut receive = "not-detected";
for (k, i) in ins.iter().enumerate().take(disp_start.saturating_add(64)) {
if i.op != 0x36 {
continue;
}
if op_at(k + 1) == Some(0x15) && at(k + 2).is_some_and(|p| is_push(p.op)) && op_at(k + 3) == Some(0x57) {
receive = "present";
}
// LT pops the size first in PUSH 4, CALLDATASIZE, LT.
if k.checked_sub(1).and_then(at).is_some_and(|p| is_push(p.op) && imm_u64(body, p) == Some(4))
&& op_at(k + 1) == Some(0x10)
&& at(k + 2).is_some_and(|p| is_push(p.op))
&& op_at(k + 3) == Some(0x57)
{
short_calldata = true;
}
}
(short_calldata, receive)
}
/// Analyse bytecode (already decoded from hex if needed).
pub fn analyze(code: &[u8]) -> Result<EvmInterface, FormatError> {
if code.is_empty() {
return Err(FormatError::Truncated("no bytecode".into()));
}
if code.len() > MAX_CODE {
return Err(FormatError::TooLarge(format!("{} bytes; the limit is {MAX_CODE}", code.len())));
}
if code.starts_with(&[0xef, 0x00]) {
return Err(FormatError::Unsupported("EVM Object Format (EOF, 0xEF00) containers are not analysed".into()));
}
let mut warnings = Vec::new();
let (end, metadata) = split_metadata(code);
let body = code.get(..end).unwrap_or(code);
let ins = sweep(body);
let jumpdests = ins.iter().filter(|i| i.op == 0x5b).count();
let at = |k: usize| ins.get(k);
let op_at = |k: usize| at(k).map(|i| i.op);
let index_of = |off: usize| ins.binary_search_by_key(&off, |i| i.off).ok();
let extraction = selector_extraction(body, &ins);
let disp_start = extraction.map(|(_, k)| k).unwrap_or(0);
if extraction.is_none() {
warnings.push("no selector extraction (CALLDATALOAD then SHR/DIV/AND) was seen; matches below are less certain".into());
}
// Only a guard on the straight-line entry path can apply to every selector.
let callvalue_before = ins
.iter()
.take(disp_start)
.enumerate()
.take_while(|(_, i)| !matches!(i.op, 0x00 | 0x56 | 0x57 | 0xf3 | 0xfd | 0xfe | 0xff))
.any(|(k, i)| i.op == 0x34 && rejects_value(body, &ins, k, &index_of));
let mut functions: Vec<EvmFunction> = Vec::new();
let mut selectors = BTreeSet::new();
let mut splits = 0usize;
let mut last_jumpi: Option<usize> = None;
let mut solc_like = 0usize;
let mut vyper_like = 0usize;
for k in disp_start..ins.len() {
let Some(i) = at(k) else { break };
let n = push_len(i.op);
if !(1..=4).contains(&n) {
continue;
}
let Some(sel) = imm_u64(body, i) else { continue };
let found = |dk: usize| -> Option<usize> {
let p = at(dk)?;
(is_push(p.op) && p.imm.1 <= 3 && op_at(dk + 1) == Some(0x57)).then_some(dk)
};
// PUSH sel, [DUP2], EQ, PUSH dest, JUMPI
let eq_k = if op_at(k + 1) == Some(0x14) {
Some(k + 1)
} else if matches!(op_at(k + 1), Some(0x80..=0x8f)) && op_at(k + 2) == Some(0x14) {
Some(k + 2)
} else {
None
};
let mut hit: Option<(usize, usize, &'static str)> = None;
if let Some(e) = eq_k {
if let Some(pk) = found(e + 1)
&& let Some(dest) = at(pk).and_then(|p| imm_u64(body, p))
{
hit = Some((usize::try_from(dest).unwrap_or(usize::MAX), pk + 1, "eq-jumpi"));
} else if n == 4 && op_at(e + 1) == Some(0x15) && found(e + 2).is_some() {
// Vyper-style: if selector != x jump to the next check; the body follows.
if let Some(next) = at(e + 4) {
hit = Some((next.off, e + 3, "eq-iszero-fallthrough"));
}
}
} else if n == 4 {
// Vyper also loads the selector from memory: PUSH sel, PUSH1 0, MLOAD, EQ, ISZERO …
let load = at(k + 1).is_some_and(|p| (p.op == 0x5f || is_push(p.op)) && imm_u64(body, p) == Some(0));
if load
&& op_at(k + 2) == Some(0x51)
&& op_at(k + 3) == Some(0x14)
&& op_at(k + 4) == Some(0x15)
&& found(k + 5).is_some()
&& let Some(next) = at(k + 7)
{
hit = Some((next.off, k + 6, "eq-iszero-fallthrough"));
}
let direct = matches!(op_at(k + 1), Some(0x10 | 0x11)) && found(k + 2).is_some();
let via_dup = matches!(op_at(k + 1), Some(0x80..=0x8f)) && matches!(op_at(k + 2), Some(0x10 | 0x11)) && found(k + 3).is_some();
if hit.is_none() && (direct || via_dup) {
splits += 1;
}
}
let Some((dest, jumpi_k, pattern)) = hit else { continue };
if n < 4 && extraction.is_none() {
continue;
}
// Duplicate identities still advance the end of the recognized dispatcher.
// Otherwise the fallback scan starts inside a later comparison, not after it.
last_jumpi = Some(jumpi_k);
if !selectors.insert(sel) {
continue;
}
let selector = format!("0x{sel:08x}");
if pattern == "eq-jumpi" {
solc_like += 1;
} else {
vyper_like += 1;
}
let di = index_of(dest);
let jumpdest_valid = pattern != "eq-jumpi" || di.and_then(at).is_some_and(|x| x.op == 0x5b);
let (mutability, reason) = if !jumpdest_valid {
("unknown", "the destination is not a JUMPDEST".to_owned())
} else if callvalue_before {
("nonpayable", "a CALLVALUE check runs before the dispatcher, so every function refuses payments".to_string())
} else {
match di {
Some(d) => payability(body, &ins, d, &index_of),
None => ("unknown", "the destination is not an instruction boundary".to_string()),
}
};
functions.push(EvmFunction {
selector,
bytecode_offset: dest,
compare_offset: i.off,
dispatch: "abi",
pattern,
mutability,
mutability_reason: reason,
jumpdest_valid,
});
if functions.len() >= MAX_FUNCTIONS {
warnings.push(format!("stopped at {MAX_FUNCTIONS} selectors"));
break;
}
}
if functions.iter().any(|f| !f.jumpdest_valid) {
warnings.push("some destinations are not JUMPDESTs; those matches may be data, not dispatch".into());
}
let (short_calldata, receive) = short_calldata_path(body, &ins, disp_start);
let mut fallback = "unknown";
// At the selector cap the remaining dispatcher has not been scanned.
// Its next comparison is not evidence that a fallback body exists.
if let Some(j) = last_jumpi
&& functions.len() < MAX_FUNCTIONS
&& solc_like > 0
{
fallback = if reverts_soon(body, &ins, j + 1, &index_of) { "absent" } else { "present" };
}
let style = match (solc_like > 0, vyper_like > 0) {
(true, true) => "mixed",
(true, false) => "solc-like",
(false, true) => "vyper-like",
_ => "none",
};
let listing_end = last_jumpi.map(|j| j + 8).unwrap_or(LISTING_CAP).min(LISTING_CAP);
let dispatcher_listing = ins
.iter()
.take(listing_end)
.map(|i| {
let d = imm(body, i);
if d.is_empty() && push_len(i.op) == 0 {
format!("{:#06x}: {}", i.off, mnemonic(i.op))
} else {
format!("{:#06x}: {} {}", i.off, mnemonic(i.op), bytes_value(d))
}
})
.collect();
if functions.is_empty() {
warnings.push(
"no selector dispatcher was recognised (the code may be creation code without runtime, a proxy, a library, or use a jump-table dispatcher)".into(),
);
}
Ok(EvmInterface {
code_size: code.len(),
analysed_size: body.len(),
metadata,
instructions: ins.len(),
jumpdests,
selector_extraction: extraction.map(|(k, _)| k),
dispatcher_offset: extraction.and_then(|(_, k)| at(k)).map(|i| i.off),
style,
functions,
binary_search_splits: splits,
callvalue_check_before_dispatch: callvalue_before,
short_calldata_check: short_calldata,
fallback,
receive,
dispatcher_listing,
warnings,
})
}
/// Resolve the destination of a JUMP to an instruction index, when the PUSH right before it is
/// readable and lands on an instruction boundary.
fn jump_destination(code: &[u8], ins: &[Ins], k: usize, index_of: &dyn Fn(usize) -> Option<usize>) -> Option<usize> {
let push = k.checked_sub(1).and_then(|p| ins.get(p)).filter(|p| is_push(p.op))?;
index_of(usize::try_from(imm_u64(code, push)?).ok()?)
}
/// Follow a function's entry for a few instructions (and up to two unconditional jumps) looking
/// for a CALLVALUE check.
fn payability(code: &[u8], ins: &[Ins], start: usize, index_of: &dyn Fn(usize) -> Option<usize>) -> (&'static str, String) {
let mut k = start;
let mut hops = 0;
for _ in 0..48 {
let Some(i) = ins.get(k) else { break };
match i.op {
0x34 if rejects_value(code, ins, k, index_of) => return ("nonpayable", format!("rejects nonzero CALLVALUE at {:#x}", i.off)),
0x56 => match jump_destination(code, ins, k, index_of) {
Some(t) if hops < 2 && ins.get(t).is_some_and(|target| target.op == 0x5b) => {
hops += 1;
k = t;
continue;
}
_ => return ("unknown", "jumps somewhere we cannot follow before any CALLVALUE check".into()),
},
0x57 => return ("unknown", "branches before any CALLVALUE check".into()),
0xfd | 0xfe => return ("unknown", "halts with an error before any CALLVALUE check".into()),
0x00 | 0xf3 | 0xff | 0x35 | 0x37 | 0x54 | 0x55 | 0xf1 | 0xf4 | 0xfa | 0xa0..=0xa4 => {
return ("payable", format!("reaches {} at {:#x} without a CALLVALUE check", mnemonic(i.op), i.off));
}
_ => {}
}
k += 1;
}
("unknown", "no CALLVALUE check in the first instructions".into())
}
/// CALLVALUE only reads the payment. Recognize a direct test that sends the nonzero path
/// to a rejection, allowing the common DUP1 that preserves the original value for cleanup.
fn rejects_value(code: &[u8], ins: &[Ins], k: usize, index_of: &dyn Fn(usize) -> Option<usize>) -> bool {
let mut next = k + 1;
if ins.get(next).is_some_and(|i| i.op == 0x80) {
next += 1;
}
let jumps_when_zero = ins.get(next).is_some_and(|i| i.op == 0x15);
next += usize::from(jumps_when_zero);
let Some(push) = ins.get(next).filter(|i| is_push(i.op)) else { return false };
if ins.get(next + 1).is_none_or(|i| i.op != 0x57) {
return false;
}
let Some(target) = imm_u64(code, push).and_then(|v| usize::try_from(v).ok()).and_then(index_of) else { return false };
if ins.get(target).is_none_or(|i| i.op != 0x5b) {
return false;
}
reverts_soon(code, ins, if jumps_when_zero { next + 2 } else { target }, index_of)
}
fn reverts_soon(code: &[u8], ins: &[Ins], mut k: usize, index_of: &dyn Fn(usize) -> Option<usize>) -> bool {
let mut hops = 0;
for _ in 0..12 {
let Some(i) = ins.get(k) else { return false };
match i.op {
0xfd | 0xfe => return true,
0x56 => match jump_destination(code, ins, k, index_of) {
Some(t) if hops < 2 => {
hops += 1;
k = t;
continue;
}
_ => return false,
},
0x5b | 0x50 | 0x80..=0x9f | 0x5f | 0x60..=0x7f => {}
_ => return false,
}
k += 1;
}
false
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_support::formats as fx;
#[test]
fn hex_signs_are_not_hex_digits() {
let solc = |v: &str| {
let mut b = vec![0xa1, 0x64];
b.extend(b"solc");
b.push(0x60 + v.len() as u8);
b.extend(v.as_bytes());
cbor_item(&b, &mut 0, 0).unwrap()["solc"].clone()
};
assert_eq!(solc("0x+1+2+3"), "0x+1+2+3");
assert_eq!(solc("0x000008"), "0.0.8");
assert!(hex_decode("+f").is_empty());
assert_eq!(hex_decode("0f"), vec![15]);
}
/// A plausible trailer length alone must not remove instructions from the analyzed bytecode.
#[test]
fn incomplete_cbor_must_not_shorten_the_analyzed_contract() {
// A nested array declares 65 integers but supplies just 64. The top-level map
// and its length suffix otherwise look complete.
let mut short = vec![0xa1, 0x61, b'x', 0x98, 65];
short.extend([0; 64]);
let mut short_map = vec![0xa1, 0x61, b'x', 0xb8, 33];
for key in 0..32 {
short_map.extend([0x18, key, 0]);
}
for cbor in [short, short_map, vec![0xa1, 0x61, b'x', 0x61, 0xff]] {
let mut code = vec![0x00];
code.extend(&cbor);
code.extend((cbor.len() as u16).to_be_bytes());
assert!(split_metadata(&code).1.is_none());
assert_eq!(analyze(&code).unwrap().analysed_size, code.len());
}
}
#[test]
fn dispatcher_selectors_and_metadata() {
let (code, dests) = fx::evm_runtime();
let r = analyze(&code).unwrap();
assert_eq!(r.selector_extraction, Some("shr-224"));
assert_eq!(r.style, "solc-like");
let sels: Vec<_> = r.functions.iter().map(|f| f.selector.clone()).collect();
assert_eq!(sels, fx::EVM_SELECTORS.iter().map(|s| format!("0x{s:08x}")).collect::<Vec<_>>());
for (f, d) in r.functions.iter().zip(dests) {
assert_eq!(f.bytecode_offset, d);
assert!(f.jumpdest_valid);
}
assert_eq!(r.functions[0].mutability, "nonpayable");
assert_eq!(r.functions[1].mutability, "nonpayable");
assert_eq!(r.functions[2].mutability, "payable");
assert!(r.short_calldata_check);
assert_eq!(r.fallback, "absent");
let m = r.metadata.unwrap();
assert_eq!(m.compiler.as_deref(), Some("solc 0.8.19"));
assert!(m.ipfs.unwrap().starts_with("Qm"));
assert_eq!(r.analysed_size + m.length, code.len());
}
#[test]
fn hex_input_rules() {
let (code, _) = fx::evm_runtime();
let hex = fx::to_hex(&code);
assert_eq!(decode_input(format!(" {hex}\n").as_bytes(), Encoding::Auto).unwrap(), (code.clone(), "hex"));
assert_eq!(decode_input(&code, Encoding::Auto).unwrap().1, "raw");
assert!(decode_input(b"0x123", Encoding::Hex).is_err());
assert!(decode_input(b"0xzz", Encoding::Hex).is_err());
assert!(decode_input(b"", Encoding::Hex).is_err());
assert!(matches!(analyze(&[0xef, 0x00, 0x01]), Err(FormatError::Unsupported(_))));
assert_eq!(base58(&[0, 0, 1]), "112");
}
#[test]
fn vyper_style_fallthrough() {
// PUSH1 0 CALLDATALOAD PUSH1 0xe0 SHR PUSH1 0 MSTORE PUSH4 sel PUSH1 0 MLOAD EQ ISZERO PUSH2 next JUMPI <body: CALLVALUE ...>
let mut c = vec![
0x60, 0x00, 0x35, 0x60, 0xe0, 0x1c, 0x60, 0x00, 0x52, 0x63, 0x12, 0x34, 0x56, 0x78, 0x60, 0x00, 0x51, 0x14, 0x15, 0x61, 0x00, 0x20, 0x57,
];
let body = c.len();
c.extend_from_slice(&[0x34, 0x15, 0x00]);
let r = analyze(&c).unwrap();
assert_eq!(r.style, "vyper-like");
assert_eq!(r.functions[0].selector, "0x12345678");
assert_eq!(r.functions[0].bytecode_offset, body);
assert_eq!(r.functions[0].mutability, "payable", "ISZERO followed by STOP never rejects payment");
}
#[test]
fn nonpayable_needs_a_rejecting_nonzero_branch() {
fn dispatch(prefix: &[u8]) -> EvmInterface {
let mut code = prefix.to_vec();
code.extend([0x5f, 0x35, 0x60, 0xe0, 0x1c, 0x63, 1, 2, 3, 4, 0x14, 0x60]);
code.extend([(code.len() + 3) as u8, 0x57, 0x00, 0x5b, 0x00]);
analyze(&code).unwrap()
}
let read_only = dispatch(&[0x34, 0x50]); // CALLVALUE POP
assert!(!read_only.callvalue_check_before_dispatch);
assert_eq!(read_only.functions[0].mutability, "payable");
let guard = dispatch(&[0x34, 0x80, 0x15, 0x60, 9, 0x57, 0x5f, 0x80, 0xfd, 0x5b, 0x50]);
assert!(guard.callvalue_check_before_dispatch);
assert_eq!(guard.functions[0].mutability, "nonpayable");
// The other common form jumps to REVERT for a nonzero value and otherwise skips it.
let direct = dispatch(&[0x34, 0x60, 7, 0x57, 0x60, 11, 0x56, 0x5b, 0x5f, 0x80, 0xfd, 0x5b]);
assert!(direct.callvalue_check_before_dispatch);
// Reversing that conditional rejects zero-value calls, not payments.
let reversed = dispatch(&[0x34, 0x15, 0x60, 8, 0x57, 0x60, 12, 0x56, 0x5b, 0x5f, 0x80, 0xfd, 0x5b]);
assert!(!reversed.callvalue_check_before_dispatch);
// An unconditional jump bypasses the otherwise valid guard before the dispatcher.
let bypassed = dispatch(&[0x60, 12, 0x56, 0x34, 0x80, 0x15, 0x60, 12, 0x57, 0x5f, 0x80, 0xfd, 0x5b]);
assert!(!bypassed.callvalue_check_before_dispatch);
}
#[test]
fn hostile_inputs_do_not_panic() {
let (code, _) = fx::evm_runtime();
for m in crate::test_support::mutations(&code) {
let _ = analyze(&m);
}
for n in 0..code.len() {
let _ = analyze(&code[..n]);
}
for seed in 0..200 {
let n = crate::test_support::noise(seed, 300);
let _ = analyze(&n);
let _ = decode_input(&n, Encoding::Auto);
}
// A metadata length that claims everything, and nested CBOR.
let _ = analyze(&[0xa1, 0xa1, 0xa1, 0xa1, 0xa1, 0xa1, 0xa1, 0x00, 0x07]);
let _ = analyze(&[0x7f; 40]);
}
}
+63
View File
@@ -0,0 +1,63 @@
pub mod formats {
pub const EVM_SELECTORS: [u32; 3] = [0xa905_9cbb, 0x70a0_8231, 0xd0e3_0db0];
/// Runtime bytecode with a compiler-style dispatcher, a fallback that reverts, two non-payable
/// functions (CALLVALUE check), one payable function, and a CBOR metadata tail (ipfs + solc 0.8.19).
/// Returns (bytecode, jump destinations of the three functions).
pub fn evm_runtime() -> (Vec<u8>, [usize; 3]) {
let mut c: Vec<u8> = vec![0x60, 0x80, 0x60, 0x40, 0x52];
// if calldatasize < 4 goto fallback
c.extend_from_slice(&[0x60, 0x04, 0x36, 0x10, 0x61, 0, 0]);
let fb_patch = c.len() - 2;
c.push(0x57);
c.extend_from_slice(&[0x60, 0x00, 0x35, 0x60, 0xe0, 0x1c]);
let mut patches = Vec::new();
for sel in EVM_SELECTORS {
c.push(0x80);
c.push(0x63);
c.extend_from_slice(&sel.to_be_bytes());
c.extend_from_slice(&[0x14, 0x61, 0, 0]);
patches.push(c.len() - 2);
c.push(0x57);
}
let fallback = c.len();
c.extend_from_slice(&[0x5b, 0x60, 0x00, 0x80, 0xfd]);
let mut dests = [0usize; 3];
for (i, dest) in dests.iter_mut().enumerate() {
*dest = c.len();
if i < 2 {
// JUMPDEST CALLVALUE DUP1 ISZERO PUSH2 ok JUMPI PUSH1 0 DUP1 REVERT JUMPDEST POP STOP
c.extend_from_slice(&[0x5b, 0x34, 0x80, 0x15, 0x61, 0, 0]);
let ok_patch = c.len() - 2;
c.extend_from_slice(&[0x57, 0x60, 0x00, 0x80, 0xfd]);
let ok = c.len();
c.extend_from_slice(&[0x5b, 0x50, 0x00]);
c[ok_patch..ok_patch + 2].copy_from_slice(&(ok as u16).to_be_bytes());
} else {
c.extend_from_slice(&[0x5b, 0x60, 0x01, 0x60, 0x00, 0x55, 0x00]);
}
}
c[fb_patch..fb_patch + 2].copy_from_slice(&(fallback as u16).to_be_bytes());
for (p, d) in patches.iter().zip(dests) {
c[*p..*p + 2].copy_from_slice(&(d as u16).to_be_bytes());
}
c.push(0xfe);
let mut meta = vec![0xa2, 0x64, b'i', b'p', b'f', b's', 0x58, 0x22, 0x12, 0x20];
meta.extend((0..32u8).map(|i| i.wrapping_mul(7)));
meta.extend_from_slice(&[0x64, b's', b'o', b'l', b'c', 0x43, 0x00, 0x08, 0x13]);
let len = meta.len() as u16;
c.extend_from_slice(&meta);
c.extend_from_slice(&len.to_be_bytes());
(c, dests)
}
/// Bytecode as `0x`-prefixed lowercase hex.
pub fn to_hex(b: &[u8]) -> String {
let mut s = String::from("0x");
for x in b {
s.push_str(&format!("{x:02x}"));
}
s
}
}
pub use craft_testkit::sample_damage::{mutations, noise};
+39
View File
@@ -0,0 +1,39 @@
use craft_evm as evm;
use serde_json::json;
/// Unrelated three-integer arrays stay arrays while compiler versions stay readable.
#[test]
fn cbor_arrays_are_not_all_compiler_versions() {
// {"sizes": [1, 2, 3], "vyper": [0, 3, 10]}
for (cbor, compiler) in [
(b"\xa2\x65sizes\x83\x01\x02\x03\x65vyper\x83\x00\x03\x0a".as_slice(), "vyper 0.3.10"),
(b"\xa2\x65sizes\x83\x01\x02\x03\x64solc\x83\x00\x08\x13".as_slice(), "solc 0.8.19"),
] {
let mut code = vec![0x00];
code.extend(cbor);
code.extend((cbor.len() as u16).to_be_bytes());
let result = evm::analyze(&code).unwrap();
let meta = result.metadata.unwrap();
assert_eq!(meta.entries["sizes"], json!([1, 2, 3]));
assert_eq!(meta.compiler.as_deref(), Some(compiler));
assert_eq!(result.analysed_size, 1);
}
}
/// A non-version Vyper array stays typed, and a truncated array stays bytecode.
#[test]
fn invalid_version_shapes_are_not_invented_or_silently_consumed() {
let cbor = b"\xa1\x65vyper\x82\x00\x03";
let mut code = vec![0x00];
code.extend(cbor);
code.extend((cbor.len() as u16).to_be_bytes());
let meta = evm::analyze(&code).unwrap().metadata.unwrap();
assert_eq!(meta.compiler, None);
assert_eq!(meta.entries["vyper"], json!([0, 3]));
let mut truncated = code;
truncated[8] = 0x83; // Declare three items but keep only two.
let result = evm::analyze(&truncated).unwrap();
assert!(result.metadata.is_none());
assert_eq!(result.analysed_size, truncated.len());
}
+93
View File
@@ -0,0 +1,93 @@
use craft_evm::analyze;
fn contract_with_trailer(cbor: &[u8]) -> Vec<u8> {
let mut code = vec![0x5b, 0x00];
code.extend_from_slice(cbor);
code.extend_from_slice(&u16::try_from(cbor.len()).unwrap().to_be_bytes());
code
}
fn assert_unrecognized(cbor: &[u8]) {
let code = contract_with_trailer(cbor);
let result = analyze(&code).unwrap();
assert!(result.metadata.is_none(), "ambiguous map must remain bytecode: {cbor:02x?}");
assert_eq!(result.analysed_size, code.len());
}
#[test]
fn duplicate_compiler_keys_do_not_replace_the_reported_version() {
assert_unrecognized(b"\xa2\x64solc\x43\x00\x08\x13\x64solc\x43\x00\x08\x1a");
}
#[test]
fn identical_duplicate_keys_are_also_ambiguous() {
assert_unrecognized(b"\xa2\x64solc\x43\x00\x08\x13\x64solc\x43\x00\x08\x13");
}
#[test]
fn numeric_keys_cannot_collide_with_text_keys() {
assert_unrecognized(b"\xa2\x01\x00\x61\x31\x01");
}
#[test]
fn metadata_map_keys_must_be_encoded_as_text() {
for key in [vec![0x01], vec![0x41, b'x'], vec![0x83, 0, 1, 2], vec![0xf5], vec![0xf6], vec![0xa0]] {
let mut cbor = vec![0xa1];
cbor.extend(key);
cbor.push(0);
assert_unrecognized(&cbor);
}
}
#[test]
fn nested_maps_do_not_silently_overwrite_keys() {
assert_unrecognized(b"\xa1\x65extra\xa2\x61x\x00\x61x\x01");
assert_unrecognized(b"\xa1\x65extra\xa1\x01\x00");
}
#[test]
fn ordinary_compiler_metadata_and_unique_nested_text_keys_still_decode() {
let code = contract_with_trailer(b"\xa2\x64solc\x43\x00\x08\x13\x65extra\xa2\x61x\x00\x61y\x01");
let result = analyze(&code).unwrap();
assert_eq!(result.analysed_size, 2);
let metadata = result.metadata.unwrap();
assert_eq!(metadata.compiler.as_deref(), Some("solc 0.8.19"));
assert_eq!(metadata.entries["extra"]["x"], 0);
assert_eq!(metadata.entries["extra"]["y"], 1);
assert_eq!(metadata.length, code.len() - 2);
}
#[test]
fn equal_keys_in_separate_maps_are_independent() {
let code = contract_with_trailer(b"\xa2\x61a\xa1\x61x\x00\x61b\xa1\x61x\x01");
let result = analyze(&code).unwrap();
assert_eq!(result.analysed_size, 2);
let entries = result.metadata.unwrap().entries;
assert_eq!(entries["a"]["x"], 0);
assert_eq!(entries["b"]["x"], 1);
}
#[test]
fn extended_length_metadata_maps_respect_the_pair_limit() {
let map = |count: u8| {
let mut cbor = vec![0xb8, count];
for index in 0..count {
let key = format!("k{index:02}");
cbor.push(0x63);
cbor.extend_from_slice(key.as_bytes());
cbor.push(0);
}
cbor
};
for count in [24, 32] {
let code = contract_with_trailer(&map(count));
let report = analyze(&code).unwrap();
assert_eq!(report.analysed_size, 2);
assert_eq!(report.metadata.unwrap().entries.as_object().unwrap().len(), usize::from(count));
}
assert_unrecognized(&map(33));
assert_unrecognized(&[0xb8]);
let mut truncated = map(24);
truncated.pop();
assert_unrecognized(&truncated);
}
+115
View File
@@ -0,0 +1,115 @@
use craft_evm as evm;
fn prefix() -> Vec<u8> {
vec![0x5b, 0x00, 0x60, 0x00, 0x35, 0x60, 0xe0, 0x1c]
}
fn comparison(code: &mut Vec<u8>, selector: u32, width: usize, destination: u8) {
code.push(0x5f + u8::try_from(width).unwrap());
code.extend_from_slice(&selector.to_be_bytes()[4 - width..]);
code.extend([0x14, 0x60, destination, 0x57]);
}
#[test]
fn repeated_comparisons_keep_the_first_destination_and_encounter_order() {
let mut code = prefix();
comparison(&mut code, 0xfeed0002, 4, 0);
comparison(&mut code, 0xfeed0001, 4, 0);
let expected = evm::analyze(&code).unwrap().functions;
for _ in 0..2000 {
comparison(&mut code, 0xfeed0001, 4, 1);
comparison(&mut code, 0xfeed0002, 4, 1);
}
assert_eq!(evm::analyze(&code).unwrap().functions, expected);
}
#[test]
fn different_push_widths_share_the_same_numeric_selector() {
let mut code = prefix();
for width in 1..=4 {
comparison(&mut code, 17, width, if width == 1 { 0 } else { 1 });
}
let result = evm::analyze(&code).unwrap();
assert_eq!(result.functions.len(), 1);
assert_eq!(result.functions[0].selector, "0x00000011");
assert_eq!(result.functions[0].bytecode_offset, 0);
}
#[test]
fn rejected_candidates_do_not_spend_selector_identity() {
let mut code = vec![0x5b, 0x00];
// Short comparisons without selector extraction are not considered functions.
comparison(&mut code, 17, 1, 1);
// A selector-shaped immediate without a comparison is not a function either.
code.extend([0x63, 0, 0, 0, 17, 0x50]);
comparison(&mut code, 17, 4, 0);
let result = evm::analyze(&code).unwrap();
assert_eq!(result.functions.len(), 1);
assert_eq!(result.functions[0].bytecode_offset, 0);
assert!(result.functions[0].jumpdest_valid);
}
#[test]
fn selector_cap_counts_unique_matches() {
let mut code = prefix();
for selector in 0..4095 {
comparison(&mut code, selector, 4, 0);
}
for _ in 0..10000 {
comparison(&mut code, 4094, 4, 1);
}
let below = evm::analyze(&code).unwrap();
assert_eq!(below.functions.len(), 4095);
assert!(!below.warnings.iter().any(|warning| warning.contains("stopped at")));
comparison(&mut code, 4095, 4, 0);
comparison(&mut code, 4096, 4, 0);
let capped = evm::analyze(&code).unwrap();
assert_eq!(capped.functions.len(), 4096);
assert_eq!(capped.functions.last().unwrap().selector, "0x00000fff");
assert!(capped.warnings.iter().any(|warning| warning == "stopped at 4096 selectors"));
}
#[test]
fn repeated_comparisons_keep_fallback_scan_after_the_last_dispatch() {
for (ending, expected) in [(&[0x5f, 0x5f, 0xfd][..], "absent"), (&[0x00][..], "present")] {
let mut code = prefix();
comparison(&mut code, 0xfeed0001, 4, 0);
comparison(&mut code, 0xfeed0001, 4, 1);
code.extend_from_slice(ending);
let report = evm::analyze(&code).unwrap();
assert_eq!(report.functions.len(), 1);
assert_eq!(report.functions[0].bytecode_offset, 0);
assert_eq!(report.fallback, expected);
}
}
#[test]
fn selector_cap_leaves_fallback_unknown() {
for ending in [&[0x5f, 0x5f, 0xfd][..], &[0x00][..]] {
let mut code = prefix();
for selector in 0..4097 {
comparison(&mut code, selector, 4, 0);
}
code.extend_from_slice(ending);
let report = evm::analyze(&code).unwrap();
assert_eq!(report.functions.len(), 4096);
assert_eq!(report.fallback, "unknown");
}
}
#[test]
fn payability_only_follows_jumps_to_jumpdest() {
for (target, expected) in [(&[0x5b, 0x00][..], "payable"), (&[0x00][..], "unknown")] {
let mut code = prefix();
let entry = u8::try_from(code.len() + 10).unwrap();
comparison(&mut code, 0xfeed0001, 4, entry);
code.push(0x00);
assert_eq!(code.len(), usize::from(entry));
code.extend([0x5b, 0x60, entry + 4, 0x56]);
code.extend_from_slice(target);
let report = evm::analyze(&code).unwrap();
assert_eq!(report.functions.len(), 1);
assert!(report.functions[0].jumpdest_valid);
assert_eq!(report.functions[0].mutability, expected);
}
}
+5
View File
@@ -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);
+50 -8
View File
@@ -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() {
+15 -3
View File
@@ -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() });
}
}
}

Some files were not shown because too many files have changed in this diff Show More