PhotoCraft: An open-source, photo editor written by scratch in pure Rust
ci: integrate current main while retaining strict test gates
skylartaylor8f58ea462994
diff --cc .config/nextest.tomlindex bfd4e0e68,a082d1351..83ee9cd6f--- a/.config/nextest.toml+++ b/.config/nextest.toml@@@ -13,12 -12,13 +12,13 @@@gpu = { max-threads = 4 }[[profile.default.overrides]]-filter = 'package(photocraft-gpu) | (package(photocraft-ui-egui) & (kind(test) | test(/canvas|gpu|mip|type_tool/)))'+filter = 'package(photocraft-gpu) | (package(photocraft-ui-egui) & (kind(test) | test(/canvas|gpu|mip|type_tool|background_redraw::|floating_group_titles|swap_arrow::tests::rendered_glyph/)))'test-group = 'gpu'- # CI (`--profile ci`): the GPU tests run on WARP, the software adapter, on the Windows runner, and- # under load one occasionally hits that same timeout (1 in ~40 runs while measuring #2933). Retry- # them; nextest reports a test that passes on retry as FLAKY, so it stays visible.- [[profile.ci.overrides]]- filter = 'package(photocraft-gpu) | (package(photocraft-ui-egui) & (kind(test) | test(/canvas|gpu|mip|type_tool|background_redraw::|floating_group_titles|swap_arrow::tests::rendered_glyph/)))'- retries = 2+ # CI (`--profile ci`, .github/workflows/ci.yml). Stops at the first failure so a red PR frees its+ # runner, fails a test that hangs instead of letting it hold the runner, and repeats every failure+ # at the end of the log. The default profile's GPU override still applies.+ [profile.ci]+ fail-fast = true+ slow-timeout = { period = "60s", terminate-after = 10 }+ failure-output = "immediate-final"diff --cc .github/workflows/ci.ymlindex 5489f0700,f2a954c9b..4303f0aac--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@@ -4,6 -4,6 +4,7 @@@ onpush:branches: [main]pull_request:++ types: [opened, synchronize, reopened, ready_for_review]workflow_dispatch:inputs:fuzz:@@@ -83,7 -78,8 +85,8 @@@ jobsfitest:+ timeout-minutes: 100- name: test (${{ matrix.os }})+ name: test (${{ matrix.os }}${{ matrix.part != 'all' && format(', {0}', matrix.part) || '' }})needs: platformsruns-on: ${{ matrix.os }}strategy:@@@ -148,115 -119,48 +151,119 @@@if: runner.os == 'Linux'run: cargo fmt --all -- --check++ # Keep formatting, strict Clippy, layering and scorecard checks ahead of tests.+ - name: Clippy++ if: matrix.part == 'all' || matrix.part == 'integration'+ run: cargo clippy --workspace --all-targets --locked --features heif -- -D warnings++ - name: Dependency layering++ if: matrix.part == 'all' || matrix.part == 'integration'+ run: cargo xtask layers++ # docs/scorecard.md must match its sources (checklists, budgets, baseline, corpus floors,+ # prefs audit). Static: it reads committed files only, no benchmarks run here.+ - name: Scorecard up to date+ if: runner.os == 'Linux'+ run: cargo xtask scorecard --check+- # cargo-nextest runs the test binaries in parallel (`cargo test` runs them one at a time) and- # its `ci` profile (.config/nextest.toml) stops at the first failure and fails hung tests.+ # nextest runs the test binaries in parallel (cargo test runs them one at a time), with the+ # GPU tests capped by the `gpu` group in .config/nextest.toml (#2204).- - uses: taiki-e/install-action@9983c65e42da123ff25d1f78505eb6de315aa172 # v2.87.20+ - uses: taiki-e/install-action@83ac0ad63c0167e6f06796fab0fce28db1bf3db0 # v2.87.22with:tool: [email protected]# `--features heif`: official builds open HEIC photos via the optional photocraft-heif crate.- # nextest doesn't run doctests, so `cargo test --doc` does, with the same selection.- # Separate native commands into steps so Windows reports either command's failure.+ # `--lib --bins --tests` leaves out the examples, which cargo test would build and link but+ # never run (Clippy's `--all-targets` still checks they compile). nextest skips doctests, so+ # they get their own step.+ #+ # On Windows the unit leg runs `--lib --bins` and the integration leg `--test '*'` (every+ # integration-test target); the feature selection stays the same, so both legs share the- # dependency cache. The `ci` profile retries the GPU tests- # (.config/nextest.toml).++ # dependency cache. The `ci` profile fails fast and terminates hung tests++ # (.config/nextest.toml); assertion failures are not retried.- name: Test- run: cargo nextest run --workspace --locked --features heif --profile ci+ env:+ PART: ${{ matrix.part }}+ run: |+ case "$PART" in+ unit) targets=(--lib --bins) ;;+ integration) targets=(--test '*') ;;+ *) targets=(--lib --bins --tests) ;;+ esac- cargo nextest run --profile ci --workspace --locked --features heif "${targets[@]}" --no-fail-fast++ cargo nextest run --profile ci --workspace --locked --features heif "${targets[@]}"+ shell: bash- name: Doctests- run: cargo test --doc --workspace --locked --features heif+ if: matrix.part == 'all' || matrix.part == 'unit'+ run: cargo test --workspace --locked --features heif --doc+- - name: Clippy- if: matrix.part == 'all' || matrix.part == 'integration'- run: cargo clippy --workspace --all-targets --locked --features heif -- -D warnings-- - name: Dependency layering- if: matrix.part == 'all' || matrix.part == 'integration'- run: cargo xtask layers-- # docs/scorecard.md must match its sources (checklists, budgets, baseline, corpus floors,- # prefs audit). Static: it reads committed files only, no benchmarks run here.- - name: Scorecard up to date- if: runner.os == 'Linux'- run: cargo xtask scorecard --check-+ # The Windows tests used to be one job named `test (windows-latest)`; they're now legs named+ # `test (windows-latest, unit)` and `test (windows-latest, integration)`. This job keeps the old+ # name reporting, so a required status check on it (none today) would keep working. It fails- # unless the whole test matrix passed, Linux included, since `needs` reports one result for all- # legs; when a PR runs no Windows legs it passes along the Linux result.++ # unless the whole test matrix and both Linux variants passed. `needs` reports one result++ # for all matrix legs; when a PR runs no Windows legs it still checks every Linux result.+ windows-gate:++ timeout-minutes: 5+ name: test (windows-latest)- needs: [platforms, test]++ needs: [platforms, test, test-variants]+ if: ${{ !cancelled() }}+ runs-on: ubuntu-latest+ steps:+ - env:+ PLATFORMS: ${{ needs.platforms.result }}+ TEST: ${{ needs.test.result }}++ VARIANTS: ${{ needs.test-variants.result }}+ run: |- echo "platforms: $PLATFORMS, test: $TEST"- [ "$PLATFORMS" = success ] && [ "$TEST" = success ]++ echo "platforms: $PLATFORMS, test: $TEST, variants: $VARIANTS"++ [ "$PLATFORMS" = success ] && [ "$TEST" = success ] && [ "$VARIANTS" = success ]++ # The two other builds of the Linux tests, in parallel with the test job instead of after it (they+ # added ~10 min to its critical path). Each restores the test job's cache (`shared-key: test` is+ # that job's key) and saves none: the dependencies are the same, and the 10 GB cache budget is+ # tight (#2688).+ test-variants:++ timeout-minutes: 100+ name: test (${{ matrix.variant }})+ runs-on: ubuntu-latest+ strategy:+ fail-fast: false+ matrix:+ variant: [without heif, with craft-fonts]+ steps:+ - uses: actions/checkout@v4++ - name: Install Linux system dependencies (egui/winit/rfd)+ run: |+ nohup sudo rm -rf /usr/local/lib/android /usr/share/dotnet /opt/ghc /usr/local/.ghcup \+ /opt/hostedtoolcache/CodeQL </dev/null >/dev/null 2>&1 &+ sudo apt-get update+ sudo apt-get install -y --no-install-recommends \+ libxkbcommon-dev libwayland-dev libx11-dev libxrandr-dev libxi-dev \+ libgl1-mesa-dev libgtk-3-dev++ - uses: dtolnay/rust-toolchain@stable++ - uses: Swatinem/rust-cache@v2+ with:+ shared-key: test+ save-if: false+- - uses: taiki-e/install-action@9983c65e42da123ff25d1f78505eb6de315aa172 # v2.87.20- if: matrix.variant == 'with craft-fonts'++ - uses: taiki-e/install-action@83ac0ad63c0167e6f06796fab0fce28db1bf3db0 # v2.87.22+ with:+ tool: [email protected]# The same codecs without the optional decoder: HEIC must stay a clear "not in this build"# error for distributors who leave it out.- name: Test without heif- if: runner.os == 'Linux'+ if: matrix.variant == 'without heif'- run: cargo test -p photocraft-heif -p photocraft-codecs -p photocraft-io --locked+ run: cargo nextest run -p photocraft-heif -p photocraft-codecs -p photocraft-io --locked --profile ci- # The same tests built with the optional craft-fonts input (crates/text/build.rs), so the- # Japanese font tests that skip without it run here. Linux only. Keep the exact `--workspace- # --features heif` of the Test step: any other package or feature selection resolves a- # different feature set, recompiles the whole dependency graph into the same target dir and- # runs the runner out of disk (as `-p photocraft-text -p photocraft-ui-egui` did after #800).- # Only the tests of the crates that read `CRAFT_FONTS` run (the `-E` filter changes what runs,- # not what is built); engine and the apps only pass text on to them (#6120).+ # The tests built with the optional craft-fonts input (crates/text/build.rs), so the Japanese+ # font tests that skip without it run. Keep the test job's exact `--workspace --features heif+ # --lib --bins --tests`, so the restored dependencies match and only the workspace rebuilds.++ # Filter execution to the three crates that read the optional font input (#6127).- name: Check out craft-fonts- if: runner.os == 'Linux'+ if: matrix.variant == 'with craft-fonts'uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4with:repository: storytold/craft-fonts@@@ -268,9 -172,12 +275,12 @@@env:CRAFT_FONTS_DIR: ${{ github.workspace }}/craft-fontsCRAFT_FONTS_REQUIRED: "1"- run: cargo nextest run --profile ci --workspace --locked --features heif --lib --bins --tests --no-fail-fast+ run: >-- cargo nextest run --workspace --locked --features heif --profile ci++ cargo nextest run --profile ci --workspace --locked --features heif --lib --bins --tests+ -E 'package(photocraft-text) | package(photocraft-io) | package(photocraft-ui-egui)'corpus:+ timeout-minutes: 30# Real-file corpus tests (cargo feature `corpus`), on every PR and on main. The corpora are# pinned in xtask/src/corpus_pins.rs and sha256-verified (xtask/*.sha256) after both a cache# restore and a download; a missing corpus fails the tests. The cache key changes only when adiff --cc crates/automation/tests/smart_filter_authorization.rsindex 000000000,a5c1681a5..30f17b795mode 000000,100644..100644--- a/crates/automation/tests/smart_filter_authorization.rs+++ b/crates/automation/tests/smart_filter_authorization.rs@@@ -1,0 -1,261 +1,259 @@@+ //! Stored smart-filter parameters must not grant automation ambient filesystem access.+ use std::path::{Path, PathBuf};+ use std::sync::{+ Arc,+ atomic::{AtomicU64, Ordering},+ };++ use photocraft_automation::{AuthorizedWorkspace, Headless, workspace::authorize_desktop_engine_step};+ use photocraft_doc::{Document, LayerContent, LayerId};+ use photocraft_engine::{Session, actions_cmds::Action, jobs::Started, smart_cmds};+ use serde_json::{Value, json};++ struct Fixture(PathBuf);++ impl Fixture {+ fn new() -> Self {+ static NEXT: AtomicU64 = AtomicU64::new(0);+ let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();+ let base = std::env::temp_dir().join(format!("pc-filter-auth-{}-{stamp}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));+ std::fs::create_dir(&base).unwrap();+ std::fs::create_dir(base.join("workspace")).unwrap();+ std::fs::create_dir(base.join("outside")).unwrap();+ let f = Self(base);+ std::fs::write(f.root().join("stripes.png"), png(|x| if (x / 2) % 2 == 0 { 0 } else { 255 })).unwrap();+ std::fs::write(f.outside("black.png"), png(|_| 0)).unwrap();+ std::fs::write(f.outside("white.png"), png(|_| 255)).unwrap();+ std::fs::write(f.outside("black.cube"), cube(0)).unwrap();+ std::fs::write(f.outside("white.cube"), cube(1)).unwrap();+ f+ }++ fn root(&self) -> PathBuf {+ self.0.join("workspace")+ }+ fn outside(&self, name: &str) -> PathBuf {+ self.0.join("outside").join(name)+ }+ fn headless(&self) -> Headless {+ Headless::with_workspace(AuthorizedWorkspace::new(Some(&self.root()), Some(&self.root())).unwrap())+ }+ fn setup(&self, lookup: bool) -> (Headless, LayerId) {+ let mut h = self.headless();+ h.handle("doc.new", json!({"width": 32, "height": 32, "background": "#808080"})).unwrap();+ h.handle("doc.new", json!({"width": 32, "height": 32})).unwrap();+ let layer = LayerId(h.handle("doc.place", json!({"path": "stripes.png"})).unwrap()["layer"].as_u64().unwrap());+ let (id, params) = if lookup {+ ("image.adjustments.colorLookup", json!({"layer": layer.0, "lut": "none"}))+ } else {+ ("filter.distort.displace", json!({"layer": layer.0, "mapDocument": 0, "horizontal": 50, "vertical": 0}))+ };+ h.session.execute(id, params).unwrap();+ (h, layer)+ }+ fn saved_filter(&self, lookup: bool) -> (Document, LayerId) {+ let (h, layer) = self.setup(lookup);+ let mut doc = (*h.session.active().unwrap().doc).clone();+ let LayerContent::Smart(sm) = &mut doc.layer_mut(layer).unwrap().content else { panic!("smart object") };+ sm.smart_filters[0].params = path_params(lookup, &self.outside(if lookup { "white.cube" } else { "white.png" }));+ let bytes = photocraft_format::save_to_bytes(&doc, &Default::default()).unwrap();+ std::fs::write(self.root().join("stored.pcraft"), bytes).unwrap();+ (doc, layer)+ }+ }+ impl Drop for Fixture {+ fn drop(&mut self) {+ let _ = std::fs::remove_dir_all(&self.0);+ }+ }++ fn png(value: impl Fn(u32) -> u8) -> Vec<u8> {+ let mut pixels = Vec::new();+ for _ in 0..32 {+ for x in 0..32 {+ pixels.extend([value(x); 3]);+ }+ }+ let image = photocraft_codecs::Image::from_u8(32, 32, photocraft_codecs::ChannelLayout::Rgb, pixels).unwrap();+ photocraft_codecs::encode(&image, photocraft_codecs::Format::Png, &Default::default()).unwrap()+ }+ fn cube(value: u8) -> String {+ format!("LUT_3D_SIZE 2\n{}", format!("{value} {value} {value}\n").repeat(8))+ }+ fn path_params(lookup: bool, path: &Path) -> Value {+ if lookup { json!({"file": path}) } else { json!({"mapPath": path, "mapDocument": null}) }+ }+ fn assert_denied<T: std::fmt::Debug>(result: Result<T, impl std::fmt::Display>) {+ match result {+ Err(error) => assert!(error.to_string().contains("ambient filesystem"), "{error}"),+ Ok(value) => panic!("ambient file access was accepted: {value:?}"),+ }+ }++ #[test]+ fn parameter_edits_reject_outside_images_and_luts_without_changing_the_document() {+ for lookup in [false, true] {+ let f = Fixture::new();+ let (mut h, layer) = f.setup(lookup);+ let before = h.render_png(None, 64).unwrap();+ let doc = h.session.active().unwrap().doc.clone();+ let journal = h.session.journal.len();+ for name in if lookup { ["black.cube", "white.cube"] } else { ["black.png", "white.png"] } {+ let params = path_params(lookup, &f.outside(name));+ let id = if lookup { "image.adjustments.colorLookup" } else { "filter.distort.displace" };+ assert_denied(h.session.execute(id, params.clone()));+ assert_denied(h.handle("engine.execute", json!({"command": "layer.smartFilter.setParams", "params": {"layer": layer.0, "params": params}})));+ assert!(Arc::ptr_eq(&doc, &h.session.active().unwrap().doc));+ assert_eq!(h.session.journal.len(), journal);+ assert_eq!(h.render_png(None, 64).unwrap(), before);+ }+ // Safe numeric and embedded-data edits remain usable.+ let safe = if lookup { json!({"data": cube(0), "fileName": "embedded.cube"}) } else { json!({"horizontal": 10}) };+ h.session.execute("layer.smartFilter.setParams", json!({"layer": layer.0, "params": safe})).unwrap();+ }+ }++ #[test]+ fn action_playback_cannot_hide_a_smart_filter_path_edit() {+ let f = Fixture::new();+ let (mut h, layer) = f.setup(false);+ let doc = h.session.active().unwrap().doc.clone();+ h.session.actions.list.push(Action::new(+ "edit filter",+ vec![("layer.smartFilter.setParams".into(), json!({"layer": layer.0, "params": path_params(false, &f.outside("white.png"))}))],+ ));+ let result = h.session.execute("actions.play", json!({"action": "edit filter"})).unwrap();+ assert!(result["failed"]["error"].as_str().unwrap().contains("ambient filesystem"), "{result}");+ assert!(Arc::ptr_eq(&doc, &h.session.active().unwrap().doc));+ }++ #[test]+ fn loaded_filters_are_checked_after_merging_even_when_the_edit_contains_no_path() {+ for lookup in [false, true] {+ let f = Fixture::new();+ let (_, layer) = f.saved_filter(lookup);+ let mut h = f.headless();+ h.open(Path::new("stored.pcraft")).unwrap();+ let doc = h.session.active().unwrap().doc.clone();+ assert_denied(h.session.execute("layer.smartFilter.setParams", json!({"layer": layer.0, "params": {"horizontal": 10, "dither": false}})));+ assert!(Arc::ptr_eq(&doc, &h.session.active().unwrap().doc));+ // Removing an ambient input makes the filter usable again.+ let safe = if lookup { json!({"file": "", "lut": "none"}) } else { json!({"mapPath": ""}) };+ h.session.execute("layer.smartFilter.setParams", json!({"layer": layer.0, "params": safe})).unwrap();+ }+ }++ #[test]+ fn loaded_filters_cannot_read_on_rerender_or_reuse_a_trusted_cached_stage() {+ for lookup in [false, true] {+ let f = Fixture::new();+ let (doc, layer) = f.saved_filter(lookup);+ for warm_cache in [false, true] {+ if warm_cache {+ let mut trusted = doc.clone();+ assert!(smart_cmds::refresh(&mut trusted, layer).unwrap());+ }+ let mut h = f.headless();+ h.open(Path::new("stored.pcraft")).unwrap();+ let before = h.session.active().unwrap().doc.clone();+ assert_denied(h.session.execute("layer.smartFilter.setVisible", json!({"layer": layer.0, "visible": true})));+ assert!(Arc::ptr_eq(&before, &h.session.active().unwrap().doc));+ }+ }+ }++ #[test]+ fn background_rerender_keeps_the_desktop_request_authority() {+ for lookup in [false, true] {+ let f = Fixture::new();+ let (doc, layer) = f.saved_filter(lookup);+ let mut s = Session::new();+ s.add_document(doc, None);+ s.authorize = Some(authorize_desktop_engine_step);+ let before = s.active().unwrap().doc.clone();+ let started = s.start("layer.smartFilter.setVisible", json!({"layer": layer.0, "visible": true})).unwrap();+ // The desktop restores UI authority as soon as the automation request returns.+ s.authorize = None;+ let Started::Job(job) = started else { panic!("expected a background render") };+ assert_denied(s.wait_job(job));+ assert!(Arc::ptr_eq(&before, &s.active().unwrap().doc));+ // The worker's restriction must not leak into subsequent trusted UI work.+ s.execute("layer.smartFilter.setVisible", json!({"layer": layer.0, "visible": true})).unwrap();+ }+ }++ #[test]+ fn transferring_stored_filters_cannot_read_outside_files() {+ for lookup in [false, true] {+ let f = Fixture::new();+ let (_, from) = f.saved_filter(lookup);+ let mut h = f.headless();+ h.open(Path::new("stored.pcraft")).unwrap();+ let to = h.handle("doc.place", json!({"path": "stripes.png"})).unwrap()["layer"].as_u64().unwrap();+ let before = h.session.active().unwrap().doc.clone();+ for copy in [false, true] {+ assert_denied(h.session.execute("layer.smartFilter.transfer", json!({"from": from.0, "to": to, "copy": copy})));+ assert!(Arc::ptr_eq(&before, &h.session.active().unwrap().doc));+ }+ }+ }++ #[test]+ fn trusted_parameter_edits_still_read_maps_and_luts_after_a_denied_request() {+ for lookup in [false, true] {+ let f = Fixture::new();+ let (mut h, layer) = f.setup(lookup);+ let edit = |path: &Path| json!({"layer": layer.0, "params": path_params(lookup, path)});+ assert_denied(h.session.execute("layer.smartFilter.setParams", edit(&f.outside("white.png"))));+ let mut trusted = Headless::trusted_local();+ trusted.session.add_document((*h.session.active().unwrap().doc).clone(), None);+ let mut renders = Vec::new();+ for name in if lookup { ["black.cube", "white.cube", "black.cube"] } else { ["black.png", "white.png", "black.png"] } {+ trusted.session.execute("layer.smartFilter.setParams", edit(&f.outside(name))).unwrap();+ renders.push(trusted.render_png(None, 64).unwrap());+ }+ assert_ne!(renders[0], renders[1], "trusted path-based filter still works");+ assert_eq!(renders[0], renders[2], "trusted rendering remains deterministic");+ }+ }++ #[test]+ fn a_refresh_outside_command_execution_surfaces_the_denial_instead_of_rendering_unfiltered() {+ // link-watch and transform paths re-render through Session::edit, not Session::execute or+ // jobs::run; the gate must reach them and the denial must not silently pass pixels through+ // into the process-wide stack cache.+ for lookup in [false, true] {+ let f = Fixture::new();+ let (doc, layer) = f.saved_filter(lookup);+ let mut h = f.headless();+ h.open(Path::new("stored.pcraft")).unwrap();+ let before = h.session.active().unwrap().doc.clone();+ // Session::edit is the outside-execute mutation path (an edit closure the UI or a+ // linked-file change runs); the stored filter must be denied there too.- assert_denied(h.session.edit("Re-render", |d, _| {- match smart_cmds::refresh(d, layer) {- Ok(_) => Ok(()),- Err(e) => Err(e),- }++ assert_denied(h.session.edit("Re-render", |d, _| match smart_cmds::refresh(d, layer) {++ Ok(_) => Ok(()),++ Err(e) => Err(e),+ }));+ assert!(Arc::ptr_eq(&before, &h.session.active().unwrap().doc));+ // A trusted session (no gate) still renders the same document.+ let mut trusted = Session::new();+ trusted.add_document(doc, None);+ let mut d = (*trusted.active().unwrap().doc).clone();+ assert!(smart_cmds::refresh(&mut d, layer).is_ok());+ }+ }++ #[test]+ fn an_ambient_map_or_lut_never_renders_unfiltered_pixels_into_the_stack_cache() {+ // The denial path must fail the render before any stage is cached process-wide.+ for lookup in [false, true] {+ let f = Fixture::new();+ let (doc, layer) = f.saved_filter(lookup);+ let mut s = Session::new();+ s.add_document(doc, None);+ s.authorize = Some(authorize_desktop_engine_step);+ let bytes = smart_cmds::stack_cache_bytes();+ assert_denied(s.execute("layer.smartFilter.setVisible", json!({"layer": layer.0, "visible": true})));+ assert_eq!(bytes, smart_cmds::stack_cache_bytes(), "a denied render cached no stage");+ }+ }