Skip to content

A full-featured download manager.

fix(finalize): publish completed files safely on NFS (#2179)

Dr_rOot84e52ef0ca69
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index dcbecdc5..17208c04 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -427,7 +427,9 @@ jobs:
run: >-
pnpm exec vitest run
src/core/plugin/finalize/native-artifact-operations.integration.test.ts
+ src/core/plugin/finalize/finalize-adversarial.integration.test.ts
src/core/plugin/finalize/finalize-smb-recovery.integration.test.ts
+ src/core/plugin/finalize/finalize-nfs-recovery.integration.test.ts
--reporter=verbose
# SQLite integration tests above use Node. Switch native modules to the
diff --git a/.github/workflows/finalize-nfs.yml b/.github/workflows/finalize-nfs.yml
new file mode 100644
index 00000000..662cf016
--- /dev/null
+++ b/.github/workflows/finalize-nfs.yml
@@ -0,0 +1,85 @@
+name: Finalize NFS
+
+on:
+ pull_request:
+ branches: [main]
+ paths:
+ - 'packages/finalize-fs/**'
+ - 'src/core/plugin/finalize/**'
+ - 'src/core/session/*finalize*'
+ - '.github/workflows/finalize-nfs.yml'
+ push:
+ branches: [main]
+ paths:
+ - 'packages/finalize-fs/**'
+ - 'src/core/plugin/finalize/**'
+ - 'src/core/session/*finalize*'
+ - '.github/workflows/finalize-nfs.yml'
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+concurrency:
+ group: finalize-nfs-${{ github.ref }}
+ cancel-in-progress: true
+
+jobs:
+ linux-nfs:
+ runs-on: ubuntu-24.04
+ timeout-minutes: 20
+ strategy:
+ fail-fast: false
+ matrix:
+ version: ['3', '4.2']
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ - uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0
+ with:
+ version: 12.4.2
+ - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
+ with:
+ node-version: 24
+ cache: pnpm
+ - uses: dtolnay/rust-toolchain@4cda84d5c5c54efe2404f9d843567869ab1699d4 # stable
+ with:
+ toolchain: 1.94.1
+ targets: x86_64-unknown-linux-musl
+ - name: Install dependencies
+ run: pnpm install --frozen-lockfile
+ env:
+ MOTRIX_SKIP_ELECTRON_REBUILD: '1'
+ MOTRIX_SKIP_ENGINE_FETCH: '1'
+ - name: Build native sidecar
+ run: cargo build --manifest-path packages/finalize-fs/Cargo.toml --locked --target x86_64-unknown-linux-musl
+ - name: Exercise an actual root-squashed NFS mount
+ env:
+ NFS_VERSION: ${{ matrix.version }}
+ MOTRIX_FINALIZE_FS_TEST_BIN: packages/finalize-fs/target/x86_64-unknown-linux-musl/debug/motrix-finalize-fs
+ run: |
+ set -euo pipefail
+ sudo apt-get update -qq
+ sudo apt-get install -y nfs-kernel-server nfs-common
+ export_root=$(mktemp -d /tmp/motrix-nfs-export-XXXXXX)
+ mount_root=$(mktemp -d /tmp/motrix-nfs-mount-XXXXXX)
+ export_file=/etc/exports.d/motrix-finalize.exports
+ cleanup() {
+ sudo umount "$mount_root" || true
+ sudo exportfs -u "127.0.0.1:$export_root" || true
+ sudo rm -f "$export_file"
+ sudo rm -rf "$export_root" "$mount_root"
+ }
+ trap cleanup EXIT
+ chmod 1777 "$export_root"
+ sudo mkdir -p /etc/exports.d
+ printf '%s 127.0.0.1(rw,sync,no_subtree_check,root_squash,fsid=0)\n' "$export_root" | sudo tee "$export_file"
+ sudo systemctl restart nfs-kernel-server
+ sudo exportfs -ra
+ remote="$export_root"
+ if [ "$NFS_VERSION" = '4.2' ]; then remote=/; fi
+ sudo mount -t nfs -o "vers=$NFS_VERSION,proto=tcp" "127.0.0.1:$remote" "$mount_root"
+ findmnt "$mount_root"
+ export MOTRIX_FINALIZE_NFS_ROOT="$mount_root"
+ # The test fails if the supplied path is not really an NFS mount.
+ cargo test --manifest-path packages/finalize-fs/Cargo.toml --locked -- --ignored --exact platform::unix::tests::nfs_supports_link_publication_and_private_removal
+ pnpm exec vitest run src/core/plugin/finalize/finalize-nfs-recovery.integration.test.ts src/core/plugin/finalize/finalize-adversarial.integration.test.ts --reporter=verbose
diff --git a/.github/workflows/flatpak.yml b/.github/workflows/flatpak.yml
index eb3f3152..24728f84 100644
--- a/.github/workflows/flatpak.yml
+++ b/.github/workflows/flatpak.yml
@@ -191,14 +191,17 @@ jobs:
- name: Generate Flatpak Cargo sources
run: |
- # native-host's reviewed lock is the vendoring superset;
- # check:third-party-notices enforces finalize-fs remains a subset.
+ # Vendor the union of the two reviewed native dependency locks.
"$RUNNER_TEMP/flatpak-builder-tools/bin/python" \
"$RUNNER_TEMP/flatpak-cargo-generator.py" \
packages/native-host/Cargo.lock \
--output "$RUNNER_TEMP/cargo-sources.json"
+ "$RUNNER_TEMP/flatpak-builder-tools/bin/python" \
+ "$RUNNER_TEMP/flatpak-cargo-generator.py" \
+ packages/finalize-fs/Cargo.lock \
+ --output "$RUNNER_TEMP/finalize-cargo-sources.json"
node scripts/normalize-flatpak-cargo-sources.mjs \
- "$RUNNER_TEMP/cargo-sources.json"
+ "$RUNNER_TEMP/cargo-sources.json" "$RUNNER_TEMP/finalize-cargo-sources.json"
cmp flatpak/cargo-sources.json \
"$RUNNER_TEMP/cargo-sources.json"
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 8e568e84..867ceb10 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -251,6 +251,7 @@ jobs:
run: >-
pnpm exec vitest run
src/core/plugin/finalize/native-artifact-operations.integration.test.ts
+ src/core/plugin/finalize/finalize-adversarial.integration.test.ts
src/core/plugin/finalize/finalize-smb-recovery.integration.test.ts
--reporter=verbose
diff --git a/THIRD_PARTY_LICENSES/rust-bitflags-LICENSE-MIT b/THIRD_PARTY_LICENSES/rust-bitflags-LICENSE-MIT
new file mode 100644
index 00000000..39d4bdb5
--- /dev/null
+++ b/THIRD_PARTY_LICENSES/rust-bitflags-LICENSE-MIT
@@ -0,0 +1,25 @@
+Copyright (c) 2014 The Rust Project Developers
+
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
diff --git a/THIRD_PARTY_LICENSES/rust-errno-LICENSE-MIT b/THIRD_PARTY_LICENSES/rust-errno-LICENSE-MIT
new file mode 100644
index 00000000..66b6578d
--- /dev/null
+++ b/THIRD_PARTY_LICENSES/rust-errno-LICENSE-MIT
@@ -0,0 +1,25 @@
+Copyright (c) 2014 Chris Wong
+
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
diff --git a/THIRD_PARTY_LICENSES/rust-linux-raw-sys-COPYRIGHT b/THIRD_PARTY_LICENSES/rust-linux-raw-sys-COPYRIGHT
new file mode 100644
index 00000000..719e3dbc
--- /dev/null
+++ b/THIRD_PARTY_LICENSES/rust-linux-raw-sys-COPYRIGHT
@@ -0,0 +1,29 @@
+Short version for non-lawyers:
+
+`linux-raw-sys` is triple-licensed under Apache 2.0 with the LLVM Exception,
+Apache 2.0, and MIT terms.
+
+
+Longer version:
+
+Copyrights in the `linux-raw-sys` project are retained by their contributors.
+No copyright assignment is required to contribute to the `linux-raw-sys`
+project.
+
+Some files include code derived from Rust's `libstd`; see the comments in
+the code for details.
+
+Except as otherwise noted (below and/or in individual files), `linux-raw-sys`
+is licensed under:
+
+ - the Apache License, Version 2.0, with the LLVM Exception
+ <LICENSE-Apache-2.0_WITH_LLVM-exception> or
+ <http://llvm.org/foundation/relicensing/LICENSE.txt>
+ - the Apache License, Version 2.0
+ <LICENSE-APACHE> or
+ <http://www.apache.org/licenses/LICENSE-2.0>,
+ - or the MIT license
+ <LICENSE-MIT> or
+ <http://opensource.org/licenses/MIT>,
+
+at your option.
diff --git a/THIRD_PARTY_LICENSES/rust-linux-raw-sys-LICENSE-MIT b/THIRD_PARTY_LICENSES/rust-linux-raw-sys-LICENSE-MIT
new file mode 100644
index 00000000..31aa7938
--- /dev/null
+++ b/THIRD_PARTY_LICENSES/rust-linux-raw-sys-LICENSE-MIT
@@ -0,0 +1,23 @@
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
diff --git a/THIRD_PARTY_LICENSES/rust-rustix-COPYRIGHT b/THIRD_PARTY_LICENSES/rust-rustix-COPYRIGHT
new file mode 100644
index 00000000..a841525e
--- /dev/null
+++ b/THIRD_PARTY_LICENSES/rust-rustix-COPYRIGHT
@@ -0,0 +1,29 @@
+Short version for non-lawyers:
+
+`rustix` is triple-licensed under Apache 2.0 with the LLVM Exception,
+Apache 2.0, and MIT terms.
+
+
+Longer version:
+
+Copyrights in the `rustix` project are retained by their contributors.
+No copyright assignment is required to contribute to the `rustix`
+project.
+
+Some files include code derived from Rust's `libstd`; see the comments in
+the code for details.
+
+Except as otherwise noted (below and/or in individual files), `rustix`
+is licensed under:
+
+ - the Apache License, Version 2.0, with the LLVM Exception
+ <LICENSE-Apache-2.0_WITH_LLVM-exception> or
+ <http://llvm.org/foundation/relicensing/LICENSE.txt>
+ - the Apache License, Version 2.0
+ <LICENSE-APACHE> or
+ <http://www.apache.org/licenses/LICENSE-2.0>,
+ - or the MIT license
+ <LICENSE-MIT> or
+ <http://opensource.org/licenses/MIT>,
+
+at your option.
diff --git a/THIRD_PARTY_LICENSES/rust-rustix-LICENSE-MIT b/THIRD_PARTY_LICENSES/rust-rustix-LICENSE-MIT
new file mode 100644
index 00000000..31aa7938
--- /dev/null
+++ b/THIRD_PARTY_LICENSES/rust-rustix-LICENSE-MIT
@@ -0,0 +1,23 @@
+Permission is hereby granted, free of charge, to any
+person obtaining a copy of this software and associated
+documentation files (the "Software"), to deal in the
+Software without restriction, including without
+limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software
+is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice
+shall be included in all copies or substantial portions
+of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
index 2585033b..4e0b99c1 100644
--- a/THIRD_PARTY_NOTICES.md
+++ b/THIRD_PARTY_NOTICES.md
@@ -200,11 +200,13 @@ the Windows native executable builds.
| Crate | Version | SPDX license expression | Repository |
| --- | --- | --- | --- |
| base64 | 0.22.1 | `MIT OR Apache-2.0` | <https://github.com/marshallpierce/rust-base64> |
+| bitflags | 2.13.1 | `MIT OR Apache-2.0` | <https://github.com/bitflags/bitflags> |
| block-buffer | 0.10.4 | `MIT OR Apache-2.0` | <https://github.com/RustCrypto/utils> |
| cfg-if | 1.0.4 | `MIT OR Apache-2.0` | <https://github.com/rust-lang/cfg-if> |
| cpufeatures | 0.2.17 | `MIT OR Apache-2.0` | <https://github.com/RustCrypto/utils> |
| crypto-common | 0.1.7 | `MIT OR Apache-2.0` | <https://github.com/RustCrypto/traits> |
| digest | 0.10.7 | `MIT OR Apache-2.0` | <https://github.com/RustCrypto/traits> |
+| errno | 0.3.14 | `MIT OR Apache-2.0` | <https://github.com/lambda-fairy/rust-errno> |
| generic-array | 0.14.7 | `MIT` | <https://github.com/fizyk20/generic-array> |
| hkdf | 0.12.4 | `MIT OR Apache-2.0` | <https://github.com/RustCrypto/KDFs> |
| hmac | 0.12.1 | `MIT OR Apache-2.0` | <https://github.com/RustCrypto/MACs> |
@@ -212,9 +214,11 @@ the Windows native executable builds.
| humantime | 2.4.0 | `MIT OR Apache-2.0` | <https://github.com/chronotope/humantime> |
| itoa | 1.0.18 | `MIT OR Apache-2.0` | <https://github.com/dtolnay/itoa> |
| libc | 0.2.189 | `MIT OR Apache-2.0` | <https://github.com/rust-lang/libc> |
+| linux-raw-sys | 0.12.1 | `Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT` | <https://github.com/sunfishcode/linux-raw-sys> |
| memchr | 2.8.3 | `Unlicense OR MIT` | <https://github.com/BurntSushi/memchr> |
| proc-macro2 | 1.0.107 | `MIT OR Apache-2.0` | <https://github.com/dtolnay/proc-macro2> |
| quote | 1.0.47 | `MIT OR Apache-2.0` | <https://github.com/dtolnay/quote> |
+| rustix | 1.1.4 | `Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT` | <https://github.com/bytecodealliance/rustix> |
| serde | 1.0.229 | `MIT OR Apache-2.0` | <https://github.com/serde-rs/serde> |
| serde_core | 1.0.229 | `MIT OR Apache-2.0` | <https://github.com/serde-rs/serde> |
| serde_derive | 1.0.229 | `MIT OR Apache-2.0` | <https://github.com/serde-rs/serde> |
@@ -238,6 +242,12 @@ crate-specific notices are preserved separately:
- `THIRD_PARTY_LICENSES/rust-block-buffer-LICENSE-APACHE`
- `THIRD_PARTY_LICENSES/rust-block-buffer-LICENSE-MIT`
- `THIRD_PARTY_LICENSES/rust-cfg-if-LICENSE-MIT`
+- `THIRD_PARTY_LICENSES/rust-bitflags-LICENSE-MIT`
+- `THIRD_PARTY_LICENSES/rust-errno-LICENSE-MIT`
+- `THIRD_PARTY_LICENSES/rust-linux-raw-sys-COPYRIGHT`
+- `THIRD_PARTY_LICENSES/rust-linux-raw-sys-LICENSE-MIT`
+- `THIRD_PARTY_LICENSES/rust-rustix-COPYRIGHT`
+- `THIRD_PARTY_LICENSES/rust-rustix-LICENSE-MIT`
- `THIRD_PARTY_LICENSES/rust-common-LICENSE-APACHE`
- `THIRD_PARTY_LICENSES/rust-common-LICENSE-MIT`
- `THIRD_PARTY_LICENSES/rust-cpufeatures-LICENSE-MIT`
diff --git a/THIRD_PARTY_NOTICES.zh-CN.md b/THIRD_PARTY_NOTICES.zh-CN.md
index 9a23e5be..aac8fba8 100644
--- a/THIRD_PARTY_NOTICES.zh-CN.md
+++ b/THIRD_PARTY_NOTICES.zh-CN.md
@@ -175,11 +175,13 @@ npm 依赖清单根据根目录声明的运行时依赖,以及 `pnpm-lock.yaml
| Crate | 版本 | SPDX 许可证表达式 | 源码仓库 |
| --- | --- | --- | --- |
| base64 | 0.22.1 | `MIT OR Apache-2.0` | <https://github.com/marshallpierce/rust-base64> |
+| bitflags | 2.13.1 | `MIT OR Apache-2.0` | <https://github.com/bitflags/bitflags> |
| block-buffer | 0.10.4 | `MIT OR Apache-2.0` | <https://github.com/RustCrypto/utils> |
| cfg-if | 1.0.4 | `MIT OR Apache-2.0` | <https://github.com/rust-lang/cfg-if> |
| cpufeatures | 0.2.17 | `MIT OR Apache-2.0` | <https://github.com/RustCrypto/utils> |
| crypto-common | 0.1.7 | `MIT OR Apache-2.0` | <https://github.com/RustCrypto/traits> |
| digest | 0.10.7 | `MIT OR Apache-2.0` | <https://github.com/RustCrypto/traits> |
+| errno | 0.3.14 | `MIT OR Apache-2.0` | <https://github.com/lambda-fairy/rust-errno> |
| generic-array | 0.14.7 | `MIT` | <https://github.com/fizyk20/generic-array> |
| hkdf | 0.12.4 | `MIT OR Apache-2.0` | <https://github.com/RustCrypto/KDFs> |
| hmac | 0.12.1 | `MIT OR Apache-2.0` | <https://github.com/RustCrypto/MACs> |
@@ -187,9 +189,11 @@ npm 依赖清单根据根目录声明的运行时依赖,以及 `pnpm-lock.yaml
| humantime | 2.4.0 | `MIT OR Apache-2.0` | <https://github.com/chronotope/humantime> |
| itoa | 1.0.18 | `MIT OR Apache-2.0` | <https://github.com/dtolnay/itoa> |
| libc | 0.2.189 | `MIT OR Apache-2.0` | <https://github.com/rust-lang/libc> |
+| linux-raw-sys | 0.12.1 | `Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT` | <https://github.com/sunfishcode/linux-raw-sys> |
| memchr | 2.8.3 | `Unlicense OR MIT` | <https://github.com/BurntSushi/memchr> |
| proc-macro2 | 1.0.107 | `MIT OR Apache-2.0` | <https://github.com/dtolnay/proc-macro2> |
| quote | 1.0.47 | `MIT OR Apache-2.0` | <https://github.com/dtolnay/quote> |
+| rustix | 1.1.4 | `Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT` | <https://github.com/bytecodealliance/rustix> |
| serde | 1.0.229 | `MIT OR Apache-2.0` | <https://github.com/serde-rs/serde> |
| serde_core | 1.0.229 | `MIT OR Apache-2.0` | <https://github.com/serde-rs/serde> |
| serde_derive | 1.0.229 | `MIT OR Apache-2.0` | <https://github.com/serde-rs/serde> |
@@ -212,6 +216,12 @@ npm 依赖清单根据根目录声明的运行时依赖,以及 `pnpm-lock.yaml
- `THIRD_PARTY_LICENSES/rust-block-buffer-LICENSE-APACHE`
- `THIRD_PARTY_LICENSES/rust-block-buffer-LICENSE-MIT`
- `THIRD_PARTY_LICENSES/rust-cfg-if-LICENSE-MIT`
+- `THIRD_PARTY_LICENSES/rust-bitflags-LICENSE-MIT`
+- `THIRD_PARTY_LICENSES/rust-errno-LICENSE-MIT`
+- `THIRD_PARTY_LICENSES/rust-linux-raw-sys-COPYRIGHT`
+- `THIRD_PARTY_LICENSES/rust-linux-raw-sys-LICENSE-MIT`
+- `THIRD_PARTY_LICENSES/rust-rustix-COPYRIGHT`
+- `THIRD_PARTY_LICENSES/rust-rustix-LICENSE-MIT`
- `THIRD_PARTY_LICENSES/rust-common-LICENSE-APACHE`
- `THIRD_PARTY_LICENSES/rust-common-LICENSE-MIT`
- `THIRD_PARTY_LICENSES/rust-cpufeatures-LICENSE-MIT`
diff --git a/flatpak/cargo-sources.json b/flatpak/cargo-sources.json
index acb3464e..2d4bf32e 100644
--- a/flatpak/cargo-sources.json
+++ b/flatpak/cargo-sources.json
@@ -12,6 +12,19 @@
"dest": "cargo/vendor/base64-0.22.1",
"dest-filename": ".cargo-checksum.json"
},
+ {
+ "type": "archive",
+ "archive-type": "tar-gzip",
+ "url": "https://static.crates.io/crates/bitflags/bitflags-2.13.1.crate",
+ "sha256": "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da",
+ "dest": "cargo/vendor/bitflags-2.13.1"
+ },
+ {
+ "type": "inline",
+ "contents": "{\"package\": \"b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da\", \"files\": {}}",
+ "dest": "cargo/vendor/bitflags-2.13.1",
+ "dest-filename": ".cargo-checksum.json"
+ },
{
"type": "archive",
"archive-type": "tar-gzip",
@@ -77,6 +90,19 @@
"dest": "cargo/vendor/digest-0.10.7",
"dest-filename": ".cargo-checksum.json"
},
+ {
+ "type": "archive",
+ "archive-type": "tar-gzip",
+ "url": "https://static.crates.io/crates/errno/errno-0.3.14.crate",
+ "sha256": "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb",
+ "dest": "cargo/vendor/errno-0.3.14"
+ },
+ {
+ "type": "inline",
+ "contents": "{\"package\": \"39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb\", \"files\": {}}",
+ "dest": "cargo/vendor/errno-0.3.14",
+ "dest-filename": ".cargo-checksum.json"
+ },
{
"type": "archive",
"archive-type": "tar-gzip",
@@ -168,6 +194,19 @@
"dest": "cargo/vendor/libc-0.2.189",
"dest-filename": ".cargo-checksum.json"
},
+ {
+ "type": "archive",
+ "archive-type": "tar-gzip",
+ "url": "https://static.crates.io/crates/linux-raw-sys/linux-raw-sys-0.12.1.crate",
+ "sha256": "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53",
+ "dest": "cargo/vendor/linux-raw-sys-0.12.1"
+ },
+ {
+ "type": "inline",
+ "contents": "{\"package\": \"32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53\", \"files\": {}}",
+ "dest": "cargo/vendor/linux-raw-sys-0.12.1",
+ "dest-filename": ".cargo-checksum.json"
+ },
{
"type": "archive",
"archive-type": "tar-gzip",
@@ -207,6 +246,19 @@
"dest": "cargo/vendor/quote-1.0.47",
"dest-filename": ".cargo-checksum.json"
},
+ {
+ "type": "archive",
+ "archive-type": "tar-gzip",
+ "url": "https://static.crates.io/crates/rustix/rustix-1.1.4.crate",
+ "sha256": "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190",
+ "dest": "cargo/vendor/rustix-1.1.4"
+ },
+ {
+ "type": "inline",
+ "contents": "{\"package\": \"b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190\", \"files\": {}}",
+ "dest": "cargo/vendor/rustix-1.1.4",
+ "dest-filename": ".cargo-checksum.json"
+ },
{
"type": "archive",
"archive-type": "tar-gzip",
diff --git a/packages/finalize-fs/Cargo.lock b/packages/finalize-fs/Cargo.lock
index 2a076c3e..fd01a744 100644
--- a/packages/finalize-fs/Cargo.lock
+++ b/packages/finalize-fs/Cargo.lock
@@ -2,6 +2,12 @@
# It is not intended for manual editing.
version = 4
+[[package]]
+name = "bitflags"
+version = "2.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da"
+
[[package]]
name = "block-buffer"
version = "0.10.4"
@@ -46,6 +52,16 @@ dependencies = [
"crypto-common",
]
+[[package]]
+name = "errno"
+version = "0.3.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
+dependencies = [
+ "libc",
+ "windows-sys",
+]
+
[[package]]
name = "generic-array"
version = "0.14.7"
@@ -68,6 +84,12 @@ version = "0.2.189"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"
+[[package]]
+name = "linux-raw-sys"
+version = "0.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
+
[[package]]
name = "memchr"
version = "2.8.3"
@@ -79,6 +101,7 @@ name = "motrix-finalize-fs"
version = "0.1.0"
dependencies = [
"libc",
+ "rustix",
"serde",
"serde_json",
"sha2",
@@ -103,6 +126,19 @@ dependencies = [
"proc-macro2",
]
+[[package]]
+name = "rustix"
+version = "1.1.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190"
+dependencies = [
+ "bitflags",
+ "errno",
+ "libc",
+ "linux-raw-sys",
+ "windows-sys",
+]
+
[[package]]
name = "serde"
version = "1.0.229"
diff --git a/packages/finalize-fs/Cargo.toml b/packages/finalize-fs/Cargo.toml
index 50b98cb3..a5f54af4 100644
--- a/packages/finalize-fs/Cargo.toml
+++ b/packages/finalize-fs/Cargo.toml
@@ -9,9 +9,12 @@ publish = false
libc = "0.2"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
+sha2 = "0.10.9"
+
+[target.'cfg(unix)'.dependencies]
+rustix = { version = "1.1", features = ["fs"] }
[target.'cfg(windows)'.dependencies]
-sha2 = "0.10.9"
windows-sys = { version = "0.61.2", features = [
"Wdk_Foundation",
"Wdk_Storage_FileSystem",
diff --git a/packages/finalize-fs/README.md b/packages/finalize-fs/README.md
index 45e40566..5b600e7a 100644
--- a/packages/finalize-fs/README.md
+++ b/packages/finalize-fs/README.md
@@ -4,6 +4,48 @@ The sidecar performs handle-relative, identity-checked file publication and
removal. Renames never replace an existing destination. Reparse points and
unsafe path components remain rejected on Windows.
+## Linux and NFS
+
+Linux NFS mounts can reject `renameat2(RENAME_NOREPLACE)` with `EINVAL` even
+when ordinary rename works. For a regular file only, the native rename call
+reports `rename_unsupported` for `EINVAL`, `EOPNOTSUPP`, or `ENOSYS`. The host
+then journals a hard-link publication intent before installing the target
+name exclusively through the held source descriptor. The source name stays
+available until the target is durable and the task database commits. Copy
+staging on a different filesystem uses this same publication path.
+
+Recovery accepts two names only when their exact identities match a recorded
+link intent and successful publication was durably confirmed. An intent alone
+cannot distinguish our link from a competing client's same-inode link. Lost
+responses or failed confirmation checkpoints with both names present preserve
+both files and quarantine the journal for reconciliation. Confirmed publication
+can roll forward or roll back before DB commit; committed publication retries
+cleanup.
+
+Each file removal first journals a new mode-0700 sibling directory and its
+device/inode identity. Ordinary rename is confined to that empty private
+directory, then a newly opened, identity-checked handle removes the isolated
+file. Every removal, including replay of a pending intent, requires a durable,
+identity-verified survivor: the source/rollback before commit, or the final
+target after commit. Unix removal also revalidates its held survivor name after
+content hashing, immediately before unlink. The separate
+`remove_opened_preserving` operation fails closed with older sidecars.
+Recovery can restart a failed sidecar before preparing or resuming cleanup.
+
+This assumes the application owns its private namespace; processes running
+as the same user can still modify it. POSIX cannot atomically validate one name
+and unlink another against unrestricted external writers. A crash before the
+removal checkpoint can leave an empty private directory, but cannot remove
+source data.
+
+Public targets are never overwritten. Permissions, target conflicts, I/O and
+sync errors remain errors. Directory publication and same-path plugin
+replacement still require native no-replace rename; they do not use the file
+fallback. Filesystems without hard links or a usable Linux `/proc/self/fd`
+retain the journal and return an error. `rustix` supplies the safe Unix syscall
+wrappers; `sha2` supplies the shared digest implementation. Neither replaces
+the application's durable transaction and recovery rules.
+
## Windows and SMB
Windows volumes are checked when opening the actual roots, before the
@@ -77,3 +119,18 @@ native sidecar and SQLite journal, injecting unsupported-root and post-rename
sync failures at the adapter boundary. They cover live retry, startup rollback,
legacy quarantine recovery, conflicts and offline shares. They can use
`MOTRIX_FINALIZE_FS_TEST_BIN` to select the target platform's binary.
+
+
+`.github/workflows/finalize-nfs.yml` provisions real NFSv3 and NFSv4.2 mounts
+with root squashing. The ignored native test
+`nfs_supports_link_publication_and_private_removal` requires a writable
+`MOTRIX_FINALIZE_NFS_ROOT` and rejects non-NFS paths. The Linux application test
+`finalize-nfs-recovery.integration.test.ts` uses a real sidecar and a local
+SQLite database with artifacts on that mount. It covers same-mount and
+cross-device publication, conflicts, lost responses, disconnection during
+rollback, and reopening the database/sidecar after cleanup interruptions.
+`finalize-adversarial.integration.test.ts` additionally injects a competing
+same-inode link, a lost rollback source, a changed survivor at native deletion,
+and sidecar termination. It uses the same real mount when configured.
+Without the NFS variable it uses a local scratch directory and injects only
+the unsupported rename response; all subsequent file operations remain real.
diff --git a/packages/finalize-fs/src/error.rs b/packages/finalize-fs/src/error.rs
index 631e0aff..8738f004 100644
--- a/packages/finalize-fs/src/error.rs
+++ b/packages/finalize-fs/src/error.rs
@@ -1,6 +1,13 @@
use std::io;
pub(crate) fn classify_error(error: &io::Error) -> &'static str {
+ if let Some(code) = error
+ .get_ref()
+ .and_then(|e| e.downcast_ref::<NativeError>())
+ .and_then(|e| e.code)
+ {
+ return code;
+ }
#[cfg(windows)]
match os_code(error) {
Some(17) => return "cross_device",
@@ -27,6 +34,7 @@ pub(crate) fn classify_error(error: &io::Error) -> &'static str {
#[derive(Debug)]
struct NativeError {
+ code: Option<&'static str>,
operation: String,
source: io::Error,
nt_status: Option<i32>,
@@ -47,7 +55,6 @@ impl std::error::Error for NativeError {
}
}
-#[cfg(windows)]
pub(crate) fn native_error(
error: io::Error,
operation: impl Into<String>,
@@ -56,6 +63,7 @@ pub(crate) fn native_error(
io::Error::new(
error.kind(),
NativeError {
+ code: None,
operation: operation.into(),
source: error,
nt_status,
@@ -80,3 +88,52 @@ pub(crate) fn nt_status(error: &io::Error) -> Option<String> {
.nt_status
.map(|status| format!("0x{:08x}", status as u32))
}
+
+#[cfg(unix)]
+pub(crate) fn rename_error(error: io::Error, regular_file: bool) -> io::Error {
+ let unsupported = matches!(
+ error.raw_os_error(),
+ Some(libc::EINVAL | libc::ENOSYS | libc::EOPNOTSUPP)
+ );
+ let code = (unsupported && regular_file).then_some("rename_unsupported");
+ io::Error::new(
+ error.kind(),
+ NativeError {
+ code,
+ operation: "renameat_with(NOREPLACE)".into(),
+ source: error,
+ nt_status: None,
+ },
+ )
+}
+
+#[cfg(all(test, unix))]
+mod rename_tests {
+ use super::*;
+
+ #[test]
+ fn rename_capability_errors_keep_the_original_errno() {
+ for code in [libc::EINVAL, libc::ENOSYS, libc::EOPNOTSUPP] {
+ let error = rename_error(io::Error::from_raw_os_error(code), true);
+ assert_eq!(classify_error(&error), "rename_unsupported");
+ assert_eq!(os_code(&error), Some(code));
+ }
+ for code in [libc::EACCES, libc::ENOSPC, libc::EIO, libc::EROFS] {
+ assert_ne!(
+ classify_error(&rename_error(io::Error::from_raw_os_error(code), true)),
+ "rename_unsupported"
+ );
+ }
+ assert_eq!(
+ classify_error(&io::Error::from_raw_os_error(libc::EINVAL)),
+ "invalid_path"
+ );
+ assert_ne!(
+ classify_error(&rename_error(
+ io::Error::from_raw_os_error(libc::EINVAL),
+ false
+ )),
+ "rename_unsupported"
+ );
+ }
+}
diff --git a/packages/finalize-fs/src/platform/mod.rs b/packages/finalize-fs/src/platform/mod.rs
index 9a5c28e6..256694cd 100644
--- a/packages/finalize-fs/src/platform/mod.rs
+++ b/packages/finalize-fs/src/platform/mod.rs
@@ -35,3 +35,41 @@ pub(crate) fn sync_root_mode(root: &RootHandle) -> std::io::Result<&'static str>
sync_root(root).map(|()| "directory_flushed")
}
}
+
+#[cfg(unix)]
+pub(crate) use unix::{
+ isolate_opened, link_opened_no_replace, remove_opened_preserving, validate_root_identity,
+};
+
+#[cfg(not(unix))]
+pub(crate) fn link_opened_no_replace(
+ _: &ArtifactHandle,
+ _: &RootHandle,
+ _: &str,
+) -> std::io::Result<()> {
+ Err(std::io::Error::new(
+ std::io::ErrorKind::Unsupported,
+ "held hard-link publication is unsupported",
+ ))
+}
+
+#[cfg(not(unix))]
+pub(crate) fn isolate_opened(
+ _: &ArtifactHandle,
+ _: &RootHandle,
+ _: &str,
+ _: &str,
+) -> std::io::Result<()> {
+ Err(std::io::Error::new(
+ std::io::ErrorKind::Unsupported,
+ "private removal isolation is unsupported",
+ ))
+}
+
+#[cfg(not(unix))]
+pub(crate) fn validate_root_identity(_: &RootHandle, _: &str) -> std::io::Result<()> {
+ Err(std::io::Error::new(
+ std::io::ErrorKind::Unsupported,
+ "Unix directory identity is unsupported",
+ ))
+}
diff --git a/packages/finalize-fs/src/platform/unix/digest.rs b/packages/finalize-fs/src/platform/unix/digest.rs
index 962fb3db..57f7e5b7 100644
--- a/packages/finalize-fs/src/platform/unix/digest.rs
+++ b/packages/finalize-fs/src/platform/unix/digest.rs
@@ -1,124 +1,18 @@
+use sha2::{Digest, Sha256};
use std::io;
use std::os::fd::RawFd;
-pub(super) struct Sha256State {
- words: [u32; 8],
- buffer: [u8; 64],
- buffer_len: usize,
- byte_len: u64,
-}
+pub(super) struct Sha256State(Sha256);
impl Sha256State {
pub(super) fn new() -> Self {
- Self {
- words: [
- 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab,
- 0x5be0cd19,
- ],
- buffer: [0; 64],
- buffer_len: 0,
- byte_len: 0,
- }
- }
-
- pub(super) fn update(&mut self, mut input: &[u8]) {
- self.byte_len = self.byte_len.wrapping_add(input.len() as u64);
- if self.buffer_len > 0 {
- let count = (64 - self.buffer_len).min(input.len());
- self.buffer[self.buffer_len..self.buffer_len + count].copy_from_slice(&input[..count]);
- self.buffer_len += count;
- input = &input[count..];
- if self.buffer_len == 64 {
- let block = self.buffer;
- self.compress(&block);
- self.buffer_len = 0;
- }
- }
- while input.len() >= 64 {
- let block: &[u8; 64] = input[..64].try_into().expect("fixed SHA-256 block");
- self.compress(block);
- input = &input[64..];
- }
- self.buffer[..input.len()].copy_from_slice(input);
- self.buffer_len = input.len();
+ Self(Sha256::new())
}
-
- pub(super) fn finalize(mut self) -> [u8; 32] {
- let bit_len = self.byte_len.wrapping_mul(8);
- self.buffer[self.buffer_len] = 0x80;
- self.buffer_len += 1;
- if self.buffer_len > 56 {
- self.buffer[self.buffer_len..].fill(0);
- let block = self.buffer;
- self.compress(&block);
- self.buffer = [0; 64];
- } else {
- self.buffer[self.buffer_len..56].fill(0);
- }
- self.buffer[56..].copy_from_slice(&bit_len.to_be_bytes());
- let block = self.buffer;
- self.compress(&block);
- let mut output = [0_u8; 32];
- for (chunk, word) in output.as_chunks_mut::<4>().0.iter_mut().zip(self.words) {
- chunk.copy_from_slice(&word.to_be_bytes());
- }
- output
+ pub(super) fn update(&mut self, input: &[u8]) {
+ self.0.update(input);
}
-
- fn compress(&mut self, block: &[u8; 64]) {
- const K: [u32; 64] = [
- 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4,
- 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe,
- 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f,
- 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
- 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc,
- 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,
- 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116,
- 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
- 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7,
- 0xc67178f2,
- ];
- let mut schedule = [0_u32; 64];
- for (index, chunk) in block.as_chunks::<4>().0.iter().enumerate() {
- schedule[index] = u32::from_be_bytes(*chunk);
- }
- for index in 16..64 {
- let s0 = schedule[index - 15].rotate_right(7)
- ^ schedule[index - 15].rotate_right(18)
- ^ (schedule[index - 15] >> 3);
- let s1 = schedule[index - 2].rotate_right(17)
- ^ schedule[index - 2].rotate_right(19)
- ^ (schedule[index - 2] >> 10);
- schedule[index] = schedule[index - 16]
- .wrapping_add(s0)
- .wrapping_add(schedule[index - 7])
- .wrapping_add(s1);
- }
-
- let [mut a, mut b, mut c, mut d, mut e, mut f, mut g, mut h] = self.words;
- for index in 0..64 {
- let big_s1 = e.rotate_right(6) ^ e.rotate_right(11) ^ e.rotate_right(25);
- let choice = (e & f) ^ ((!e) & g);
- let first = h
- .wrapping_add(big_s1)
- .wrapping_add(choice)
- .wrapping_add(K[index])
- .wrapping_add(schedule[index]);
- let big_s0 = a.rotate_right(2) ^ a.rotate_right(13) ^ a.rotate_right(22);
- let majority = (a & b) ^ (a & c) ^ (b & c);
- let second = big_s0.wrapping_add(majority);
- h = g;
- g = f;
- f = e;
- e = d.wrapping_add(first);
- d = c;
- c = b;
- b = a;
- a = first.wrapping_add(second);
- }
- for (word, value) in self.words.iter_mut().zip([a, b, c, d, e, f, g, h]) {
- *word = word.wrapping_add(value);
- }
+ pub(super) fn finalize(self) -> [u8; 32] {
+ self.0.finalize().into()
}
}
diff --git a/packages/finalize-fs/src/platform/unix/mod.rs b/packages/finalize-fs/src/platform/unix/mod.rs
index 6eb64adb..22c43ea2 100644
--- a/packages/finalize-fs/src/platform/unix/mod.rs
+++ b/packages/finalize-fs/src/platform/unix/mod.rs
@@ -3,6 +3,7 @@
mod copy;
mod digest;
mod metadata;
+mod publish;
mod remove;
mod rename;
@@ -19,7 +20,8 @@ use std::os::fd::{AsRawFd, FromRawFd, OwnedFd, RawFd};
use std::path::{Component, Path};
pub(crate) use copy::copy_opened;
-pub(crate) use remove::remove_opened;
+pub(crate) use publish::{isolate_opened, link_opened_no_replace, validate_root_identity};
+pub(crate) use remove::{remove_opened, remove_opened_preserving};
pub(crate) use rename::{rename_no_replace, rename_opened_no_replace};
pub(crate) struct RootHandle(OwnedFd);
diff --git a/packages/finalize-fs/src/platform/unix/publish.rs b/packages/finalize-fs/src/platform/unix/publish.rs
new file mode 100644
index 00000000..84bf2b4c
--- /dev/null
+++ b/packages/finalize-fs/src/platform/unix/publish.rs
@@ -0,0 +1,114 @@
+use super::metadata::{artifact_stamp, directory_entries, stat_opened};
+use super::{ArtifactHandle, RootHandle, assert_opened_artifact};
+use crate::error::native_error;
+use crate::path::validate_relative;
+use std::ffi::CString;
+use std::io;
+use std::os::fd::AsRawFd;
+
+fn checked_name(relative: &str) -> io::Result<CString> {
+ let parts = validate_relative(relative)?;
+ if parts.len() != 1 {
+ return Err(io::Error::new(
+ io::ErrorKind::InvalidInput,
+ "publication requires an immediate child",
+ ));
+ }
+ Ok(CString::new(relative).expect("validated name"))
+}
+
+fn unchanged_file(artifact: &ArtifactHandle) -> io::Result<libc::stat> {
+ assert_opened_artifact(artifact, artifact.parent.as_raw_fd(), &artifact.name)?;
+ let stat = stat_opened(artifact.artifact.as_raw_fd())?;
+ if stat.st_mode & libc::S_IFMT != libc::S_IFREG
+ || artifact_stamp(&stat) != artifact.opened_stamp
+ {
+ return Err(io::Error::new(
+ io::ErrorKind::InvalidData,
+ "publication requires an unchanged regular file",
+ ));
+ }
+ Ok(stat)
+}
+
+/// Install a second name. Source removal belongs to the durable host journal.
+#[cfg(target_os = "linux")]
+pub(crate) fn link_opened_no_replace(
+ artifact: &ArtifactHandle,
+ target: &RootHandle,
+ relative: &str,
+) -> io::Result<()> {
+ let name = checked_name(relative)?;
+ unchanged_file(artifact)?;
+ // Only this generated procfs reference follows a symlink. User paths are
+ // still resolved beneath held, no-follow directory descriptors. Unlike
+ // AT_EMPTY_PATH this does not require CAP_DAC_READ_SEARCH in containers.
+ let source = format!("/proc/self/fd/{}", artifact.artifact.as_raw_fd());
+ rustix::fs::linkat(
+ rustix::fs::CWD,
+ source,
+ &target.0,
+ &name,
+ rustix::fs::AtFlags::SYMLINK_FOLLOW,
+ )
+ .map_err(|e| native_error(e.into(), "linkat(held_fd)", None))?;
+ assert_opened_artifact(artifact, target.0.as_raw_fd(), &name)?;
+ rustix::fs::fsync(&target.0)
+ .map_err(|e| native_error(e.into(), "fsync(link_target_parent)", None))?;
+ Ok(())
+}
+
+#[cfg(not(target_os = "linux"))]
+pub(crate) fn link_opened_no_replace(
+ _: &ArtifactHandle,
+ _: &RootHandle,
+ _: &str,
+) -> io::Result<()> {
+ Err(io::Error::new(
+ io::ErrorKind::Unsupported,
+ "held hard-link publication requires Linux procfs",
+ ))
+}
+
+/// The host exclusively creates and journals this private directory before
+/// moving a source name into it. Ordinary rename is confined to this namespace.
+pub(crate) fn isolate_opened(
+ artifact: &ArtifactHandle,
+ target: &RootHandle,
+ relative: &str,
+ expected_root_identity: &str,
+) -> io::Result<()> {
+ let name = checked_name(relative)?;
+ let source = unchanged_file(artifact)?;
+ let directory = stat_opened(target.0.as_raw_fd())?;
+ if format!("{}:{}", directory.st_dev, directory.st_ino) != expected_root_identity
+ || directory.st_mode & 0o777 != 0o700
+ || directory.st_uid != source.st_uid
+ || !directory_entries(target.0.as_raw_fd())?.is_empty()
+ {
+ return Err(io::Error::new(
+ io::ErrorKind::PermissionDenied,
+ "isolation requires an empty private directory owned by the artifact owner",
+ ));
+ }
+ rustix::fs::renameat(&artifact.parent, &artifact.name, &target.0, &name)
+ .map_err(|e| native_error(e.into(), "renameat(private_isolation)", None))?;
+ assert_opened_artifact(artifact, target.0.as_raw_fd(), &name)?;
+ rustix::fs::fsync(&target.0)
+ .map_err(|e| native_error(e.into(), "fsync(isolation_directory)", None))?;
+ rustix::fs::fsync(&artifact.parent)
+ .map_err(|e| native_error(e.into(), "fsync(isolation_source_parent)", None))?;
+ Ok(())
+}
+
+/// Validate the opened directory, including when resuming a cleanup after restart.
+pub(crate) fn validate_root_identity(root: &RootHandle, expected: &str) -> io::Result<()> {
+ let directory = stat_opened(root.0.as_raw_fd())?;
+ if format!("{}:{}", directory.st_dev, directory.st_ino) != expected {
+ return Err(io::Error::new(
+ io::ErrorKind::InvalidData,
+ "held directory identity changed",
+ ));
+ }
+ Ok(())
+}
diff --git a/packages/finalize-fs/src/platform/unix/remove.rs b/packages/finalize-fs/src/platform/unix/remove.rs
index 9cb17a67..197356de 100644
--- a/packages/finalize-fs/src/platform/unix/remove.rs
+++ b/packages/finalize-fs/src/platform/unix/remove.rs
@@ -248,6 +248,62 @@ pub(crate) fn remove_opened(
artifact: &ArtifactHandle,
quarantine_relative: &str,
resume_isolated: bool,
+) -> io::Result<()> {
+ remove_with_survivor(artifact, quarantine_relative, resume_isolated, None)
+}
+
+pub(crate) fn remove_opened_preserving(
+ artifact: &ArtifactHandle,
+ quarantine_relative: &str,
+ resume_isolated: bool,
+ survivor: &ArtifactHandle,
+) -> io::Result<()> {
+ remove_with_survivor(
+ artifact,
+ quarantine_relative,
+ resume_isolated,
+ Some(survivor),
+ )
+}
+
+fn check_survivor(
+ artifact: &ArtifactHandle,
+ isolated_name: &CString,
+ survivor: Option<&ArtifactHandle>,
+) -> io::Result<()> {
+ let Some(survivor) = survivor else {
+ return Ok(());
+ };
+ let removed_parent = stat_opened(artifact.parent.as_raw_fd())?;
+ let survivor_parent = stat_opened(survivor.parent.as_raw_fd())?;
+ if removed_parent.st_dev == survivor_parent.st_dev
+ && removed_parent.st_ino == survivor_parent.st_ino
+ && isolated_name == &survivor.name
+ {
+ return Err(io::Error::new(
+ io::ErrorKind::InvalidInput,
+ "survivor names the artifact being removed",
+ ));
+ }
+ let current = ensure_same_entry(
+ survivor.artifact.as_raw_fd(),
+ survivor.parent.as_raw_fd(),
+ &survivor.name,
+ )?;
+ if !stamp_stable_across_rename(artifact_stamp(&current), survivor.opened_stamp) {
+ return Err(io::Error::new(
+ io::ErrorKind::InvalidData,
+ "surviving artifact changed before removal",
+ ));
+ }
+ Ok(())
+}
+
+fn remove_with_survivor(
+ artifact: &ArtifactHandle,
+ quarantine_relative: &str,
+ resume_isolated: bool,
+ survivor: Option<&ArtifactHandle>,
) -> io::Result<()> {
if artifact.opened_tree.is_none() && artifact.opened_file_sha256.is_none() {
return Err(io::Error::new(
@@ -278,6 +334,7 @@ pub(crate) fn remove_opened(
"opened directory is missing its held tree snapshot",
)
})?;
+ check_survivor(artifact, &isolated_name, survivor)?;
remove_directory_contents(
artifact.artifact.as_raw_fd(),
artifact.opened_stamp,
@@ -288,6 +345,7 @@ pub(crate) fn remove_opened(
artifact.parent.as_raw_fd(),
&isolated_name,
)?;
+ check_survivor(artifact, &isolated_name, survivor)?;
if unsafe {
libc::unlinkat(
artifact.parent.as_raw_fd(),
@@ -322,6 +380,7 @@ pub(crate) fn remove_opened(
"file content changed before removal",
));
}
+ check_survivor(artifact, &isolated_name, survivor)?;
if unsafe { libc::unlinkat(artifact.parent.as_raw_fd(), isolated_name.as_ptr(), 0) } < 0 {
return Err(io::Error::last_os_error());
}
diff --git a/packages/finalize-fs/src/platform/unix/rename.rs b/packages/finalize-fs/src/platform/unix/rename.rs
index af0d57ef..28a131da 100644
--- a/packages/finalize-fs/src/platform/unix/rename.rs
+++ b/packages/finalize-fs/src/platform/unix/rename.rs
@@ -25,36 +25,25 @@ pub(crate) fn rename_opened_no_replace(
));
}
- #[cfg(target_os = "macos")]
- let result = unsafe {
- libc::renameatx_np(
- artifact.parent.as_raw_fd(),
- artifact.name.as_ptr(),
- target_parent.as_raw_fd(),
- target_name.as_ptr(),
- libc::RENAME_EXCL,
+ rustix::fs::renameat_with(
+ &artifact.parent,
+ &artifact.name,
+ &target_parent,
+ &target_name,
+ rustix::fs::RenameFlags::NOREPLACE,
+ )
+ .map_err(|error| {
+ crate::error::rename_error(
+ error.into(),
+ super::metadata::stat_opened(artifact.artifact.as_raw_fd())
+ .is_ok_and(|stat| stat.st_mode & libc::S_IFMT == libc::S_IFREG),
)
- };
- #[cfg(target_os = "linux")]
- let result = unsafe {
- libc::syscall(
- libc::SYS_renameat2,
- artifact.parent.as_raw_fd(),
- artifact.name.as_ptr(),
- target_parent.as_raw_fd(),
- target_name.as_ptr(),
- libc::RENAME_NOREPLACE,
- ) as i32
- };
- if result < 0 {
- return Err(io::Error::last_os_error());
- }
+ })?;
assert_opened_artifact(artifact, target_parent.as_raw_fd(), &target_name)?;
- if unsafe { libc::fsync(target_parent.as_raw_fd()) } < 0
- || unsafe { libc::fsync(artifact.parent.as_raw_fd()) } < 0
- {
- return Err(io::Error::last_os_error());
- }
+ rustix::fs::fsync(&target_parent)
+ .map_err(|e| crate::error::native_error(e.into(), "fsync(rename_target_parent)", None))?;
+ rustix::fs::fsync(&artifact.parent)
+ .map_err(|e| crate::error::native_error(e.into(), "fsync(rename_source_parent)", None))?;
Ok(())
}
@@ -87,30 +76,14 @@ pub(crate) fn rename_no_replace(
let target_name =
CString::new(*target_parts.last().expect("nonempty")).expect("validated component");
- #[cfg(target_os = "macos")]
- let result = unsafe {
- libc::renameatx_np(
- source_parent.as_raw_fd(),
- source_name.as_ptr(),
- target_parent.as_raw_fd(),
- target_name.as_ptr(),
- libc::RENAME_EXCL,
- )
- };
- #[cfg(target_os = "linux")]
- let result = unsafe {
- libc::syscall(
- libc::SYS_renameat2,
- source_parent.as_raw_fd(),
- source_name.as_ptr(),
- target_parent.as_raw_fd(),
- target_name.as_ptr(),
- libc::RENAME_NOREPLACE,
- ) as i32
- };
- if result < 0 {
- return Err(io::Error::last_os_error());
- }
+ rustix::fs::renameat_with(
+ &source_parent,
+ &source_name,
+ &target_parent,
+ &target_name,
+ rustix::fs::RenameFlags::NOREPLACE,
+ )
+ .map_err(|error| crate::error::native_error(error.into(), "renameat_with(NOREPLACE)", None))?;
Ok(())
}
diff --git a/packages/finalize-fs/src/platform/unix/tests.rs b/packages/finalize-fs/src/platform/unix/tests.rs
index df1188db..6dacdb41 100644
--- a/packages/finalize-fs/src/platform/unix/tests.rs
+++ b/packages/finalize-fs/src/platform/unix/tests.rs
@@ -183,3 +183,122 @@ fn rename_only_handles_do_not_read_large_payloads_or_authorize_removal() {
);
std::fs::remove_dir_all(base).unwrap();
}
+
+#[test]
+fn private_isolation_checks_identity_permissions_and_resumes_removal() {
+ use std::os::unix::fs::PermissionsExt;
+ let base = std::env::temp_dir().join(format!("motrix-isolate-{}", std::process::id()));
+ std::fs::create_dir_all(base.join("private")).unwrap();
+ std::fs::set_permissions(base.join("private"), std::fs::Permissions::from_mode(0o700)).unwrap();
+ std::fs::write(base.join("source"), b"complete").unwrap();
+ let base = base.canonicalize().unwrap();
+ let source = open_root(base.to_str().unwrap()).unwrap();
+ let private = open_root(base.join("private").to_str().unwrap()).unwrap();
+ let artifact = super::open_artifact_for_rename(&source, "source").unwrap();
+ let stat = super::metadata::stat_opened(std::os::fd::AsRawFd::as_raw_fd(&private.0)).unwrap();
+ let id = format!("{}:{}", stat.st_dev, stat.st_ino);
+ assert!(super::isolate_opened(&artifact, &private, "payload", "wrong-id").is_err());
+ std::fs::write(base.join("private/payload"), b"unrelated").unwrap();
+ assert!(super::isolate_opened(&artifact, &private, "payload", &id).is_err());
+ assert_eq!(
+ std::fs::read(base.join("private/payload")).unwrap(),
+ b"unrelated"
+ );
+ std::fs::remove_file(base.join("private/payload")).unwrap();
+ std::fs::set_permissions(base.join("private"), std::fs::Permissions::from_mode(0o755)).unwrap();
+ assert!(super::isolate_opened(&artifact, &private, "payload", &id).is_err());
+ std::fs::set_permissions(base.join("private"), std::fs::Permissions::from_mode(0o700)).unwrap();
+ super::isolate_opened(&artifact, &private, "payload", &id).unwrap();
+ assert!(!base.join("source").exists());
+ drop(artifact);
+ let isolated = open_artifact(&private, "payload").unwrap();
+ remove_opened(&isolated, "payload", true).unwrap();
+ drop(isolated);
+ assert!(!base.join("private/payload").exists());
+ std::fs::remove_dir_all(base).unwrap();
+}
+
+#[cfg(target_os = "linux")]
+#[test]
+fn held_link_is_exclusive_and_preserves_the_source() {
+ let base = std::env::temp_dir().join(format!("motrix-link-{}", std::process::id()));
+ std::fs::create_dir_all(&base).unwrap();
+ let base = base.canonicalize().unwrap();
+ std::fs::write(base.join("source"), b"complete").unwrap();
+ std::fs::write(base.join("conflict"), b"unrelated").unwrap();
+ let root = open_root(base.to_str().unwrap()).unwrap();
+ let artifact = super::open_artifact_for_rename(&root, "source").unwrap();
+ assert_eq!(
+ super::link_opened_no_replace(&artifact, &root, "conflict")
+ .unwrap_err()
+ .kind(),
+ std::io::ErrorKind::AlreadyExists
+ );
+ super::link_opened_no_replace(&artifact, &root, "target").unwrap();
+ assert_eq!(std::fs::read(base.join("source")).unwrap(), b"complete");
+ assert_eq!(std::fs::read(base.join("target")).unwrap(), b"complete");
+ assert_eq!(std::fs::read(base.join("conflict")).unwrap(), b"unrelated");
+ // Linking changes ctime. A stale pre-link handle must not authorize another mutation.
+ assert!(super::link_opened_no_replace(&artifact, &root, "second").is_err());
+ std::fs::remove_dir_all(base).unwrap();
+}
+
+#[cfg(target_os = "linux")]
+#[test]
+#[ignore = "requires MOTRIX_FINALIZE_NFS_ROOT pointing at a writable NFS mount"]
+fn nfs_supports_link_publication_and_private_removal() {
+ use std::os::unix::fs::{MetadataExt, PermissionsExt};
+ let parent = std::env::var("MOTRIX_FINALIZE_NFS_ROOT").expect("NFS test root");
+ let nonce = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_nanos();
+ let base =
+ std::path::Path::new(&parent).join(format!("motrix-nfs-{}-{nonce}", std::process::id()));
+ std::fs::create_dir(&base).unwrap();
+ let root = open_root(base.to_str().unwrap()).unwrap();
+ assert_eq!(
+ rustix::fs::fstatfs(&root.0).unwrap().f_type as u64,
+ 0x6969,
+ "test root must really be NFS"
+ );
+ std::fs::write(base.join("source.motrix"), b"complete download").unwrap();
+ let artifact = super::open_artifact_for_rename(&root, "source.motrix").unwrap();
+ let error = super::rename_opened_no_replace(&artifact, &root, "target").unwrap_err();
+ assert_eq!(crate::error::classify_error(&error), "rename_unsupported");
+ assert_eq!(crate::error::os_code(&error), Some(libc::EINVAL));
+ super::link_opened_no_replace(&artifact, &root, "target").unwrap();
+ drop(artifact);
+ assert_eq!(
+ std::fs::metadata(base.join("source.motrix")).unwrap().ino(),
+ std::fs::metadata(base.join("target")).unwrap().ino()
+ );
+ let source = super::open_artifact_for_rename(&root, "source.motrix").unwrap();
+ assert_eq!(
+ super::link_opened_no_replace(&source, &root, "target")
+ .unwrap_err()
+ .kind(),
+ std::io::ErrorKind::AlreadyExists
+ );
+ std::fs::create_dir(base.join("private")).unwrap();
+ std::fs::set_permissions(base.join("private"), std::fs::Permissions::from_mode(0o700)).unwrap();
+ let private = open_root(base.join("private").to_str().unwrap()).unwrap();
+ let metadata = std::fs::metadata(base.join("private")).unwrap();
+ super::isolate_opened(
+ &source,
+ &private,
+ "payload",
+ &format!("{}:{}", metadata.dev(), metadata.ino()),
+ )
+ .unwrap();
+ drop(source);
+ let isolated = open_artifact(&private, "payload").unwrap();
+ remove_opened(&isolated, "payload", true).unwrap();
+ drop(isolated);
+ assert!(!base.join("source.motrix").exists());
+ assert_eq!(
+ std::fs::read(base.join("target")).unwrap(),
+ b"complete download"
+ );
+ std::fs::remove_dir_all(base).unwrap();
+}
diff --git a/packages/finalize-fs/src/protocol.rs b/packages/finalize-fs/src/protocol.rs
index 78ffd7c1..b31bd928 100644
--- a/packages/finalize-fs/src/protocol.rs
+++ b/packages/finalize-fs/src/protocol.rs
@@ -12,6 +12,8 @@ pub(crate) enum Request {
OpenRoot {
request_id: u64,
path: String,
+ #[serde(default)]
+ expected_identity: Option<String>,
},
OpenArtifact {
request_id: u64,
@@ -26,6 +28,19 @@ pub(crate) enum Request {
target_root: u64,
target_relative: String,
},
+ LinkOpenedNoReplace {
+ request_id: u64,
+ artifact: u64,
+ target_root: u64,
+ target_relative: String,
+ },
+ IsolateOpened {
+ expected_root_identity: String,
+ request_id: u64,
+ artifact: u64,
+ target_root: u64,
+ target_relative: String,
+ },
CopyOpened {
request_id: u64,
artifact: u64,
@@ -45,6 +60,13 @@ pub(crate) enum Request {
quarantine_relative: String,
resume_isolated: bool,
},
+ RemoveOpenedPreserving {
+ request_id: u64,
+ artifact: u64,
+ quarantine_relative: String,
+ resume_isolated: bool,
+ survivor: u64,
+ },
SyncRoot {
request_id: u64,
root: u64,
@@ -62,9 +84,12 @@ impl Request {
Self::OpenRoot { .. } => "open_root",
Self::OpenArtifact { .. } => "open_artifact",
Self::RenameOpenedNoReplace { .. } => "rename_opened_no_replace",
+ Self::LinkOpenedNoReplace { .. } => "link_opened_no_replace",
+ Self::IsolateOpened { .. } => "isolate_opened",
Self::CopyOpened { .. } => "copy_opened",
Self::RenameNoReplace { .. } => "rename_no_replace",
Self::RemoveOpened { .. } => "remove_opened",
+ Self::RemoveOpenedPreserving { .. } => "remove_opened_preserving",
Self::SyncRoot { .. } => "sync_root",
Self::Close { .. } => "close",
}
diff --git a/packages/finalize-fs/src/state.rs b/packages/finalize-fs/src/state.rs
index 981882e2..80e0f7a2 100644
--- a/packages/finalize-fs/src/state.rs
+++ b/packages/finalize-fs/src/state.rs
@@ -32,8 +32,18 @@ impl State {
fn dispatch(&mut self, request: Request) -> Response<'static> {
match request {
Request::Capabilities => self.capabilities(),
- Request::OpenRoot { request_id, path } => match open_root(&path) {
+ Request::OpenRoot {
+ request_id,
+ path,
+ expected_identity,
+ } => match open_root(&path) {
Ok(root) => {
+ if let Some(expected) = expected_identity
+ && let Err(error) =
+ crate::platform::validate_root_identity(&root, &expected)
+ {
+ return Response::filesystem_error(request_id, error);
+ }
let handle = self.insert_root(root);
let mut response = Response::ok(Some(request_id));
response.handle = Some(handle);
@@ -86,6 +96,38 @@ impl State {
rename_opened_no_replace(artifact, target, &target_relative),
)
}
+ Request::LinkOpenedNoReplace {
+ request_id,
+ artifact,
+ target_root,
+ target_relative,
+ } => self.publish(
+ request_id,
+ artifact,
+ target_root,
+ &target_relative,
+ crate::platform::link_opened_no_replace,
+ ),
+ Request::IsolateOpened {
+ request_id,
+ artifact,
+ target_root,
+ target_relative,
+ expected_root_identity,
+ } => self.publish(
+ request_id,
+ artifact,
+ target_root,
+ &target_relative,
+ |artifact, root, relative| {
+ crate::platform::isolate_opened(
+ artifact,
+ root,
+ relative,
+ &expected_root_identity,
+ )
+ },
+ ),
Request::CopyOpened {
request_id,
artifact,
@@ -135,19 +177,26 @@ impl State {
artifact,
quarantine_relative,
resume_isolated,
- } => {
- let Some(artifact) = self.artifacts.get_mut(&artifact).and_then(Option::take)
- else {
- return Response::error(Some(request_id), "invalid_handle", "unknown artifact");
- };
- // Removal consumes the held handle so classic SMB delete-on-close
- // can finish. Keep its empty registry slot until the caller closes it.
- #[cfg(windows)]
- let result = remove_opened(artifact, &quarantine_relative, resume_isolated);
- #[cfg(not(windows))]
- let result = remove_opened(&artifact, &quarantine_relative, resume_isolated);
- operation_response(request_id, result)
- }
+ } => self.remove(
+ request_id,
+ artifact,
+ &quarantine_relative,
+ resume_isolated,
+ None,
+ ),
+ Request::RemoveOpenedPreserving {
+ request_id,
+ artifact,
+ quarantine_relative,
+ resume_isolated,
+ survivor,
+ } => self.remove(
+ request_id,
+ artifact,
+ &quarantine_relative,
+ resume_isolated,
+ Some(survivor),
+ ),
Request::SyncRoot { request_id, root } => {
let Some(root) = self.roots.get(&root) else {
@@ -173,6 +222,70 @@ impl State {
}
}
+ fn remove(
+ &mut self,
+ request_id: u64,
+ artifact_id: u64,
+ quarantine_relative: &str,
+ resume_isolated: bool,
+ survivor: Option<u64>,
+ ) -> Response<'static> {
+ // Removal consumes the held handle so classic SMB delete-on-close
+ // can finish. Keep its empty registry slot until the caller closes it.
+ let Some(artifact) = self.artifacts.get_mut(&artifact_id).and_then(Option::take) else {
+ return Response::error(Some(request_id), "invalid_handle", "unknown artifact");
+ };
+ if let Some(survivor_id) = survivor {
+ #[cfg(unix)]
+ {
+ let Some(survivor) = self.artifacts.get(&survivor_id).and_then(Option::as_ref)
+ else {
+ return Response::error(Some(request_id), "invalid_handle", "unknown survivor");
+ };
+ return operation_response(
+ request_id,
+ crate::platform::remove_opened_preserving(
+ &artifact,
+ quarantine_relative,
+ resume_isolated,
+ survivor,
+ ),
+ );
+ }
+ #[cfg(not(unix))]
+ {
+ let _ = survivor_id;
+ return Response::error(
+ Some(request_id),
+ "unsupported",
+ "held survivor removal is unsupported",
+ );
+ }
+ }
+ #[cfg(windows)]
+ let result = remove_opened(artifact, quarantine_relative, resume_isolated);
+ #[cfg(not(windows))]
+ let result = remove_opened(&artifact, quarantine_relative, resume_isolated);
+ operation_response(request_id, result)
+ }
+
+ fn publish(
+ &self,
+ request_id: u64,
+ artifact: u64,
+ target_root: u64,
+ relative: &str,
+ operation: impl FnOnce(&ArtifactHandle, &RootHandle, &str) -> std::io::Result<()>,
+ ) -> Response<'static> {
+ let Some(artifact) = self.artifacts.get(&artifact).and_then(Option::as_ref) else {
+ return Response::error(Some(request_id), "invalid_handle", "unknown artifact");
+ };
+ let Some(root) = self.roots.get(&target_root) else {
+ return Response::error(Some(request_id), "invalid_handle", "unknown target root");
+ };
+ operation_response(request_id, operation(artifact, root, relative))
+ }
+
fn capabilities(&self) -> Response<'static> {
let mut response = Response::ok(None);
response.platform = Some(std::env::consts::OS);
diff --git a/scripts/normalize-flatpak-cargo-sources.mjs b/scripts/normalize-flatpak-cargo-sources.mjs
index 250fe9c9..eadc690f 100644
--- a/scripts/normalize-flatpak-cargo-sources.mjs
+++ b/scripts/normalize-flatpak-cargo-sources.mjs
@@ -19,8 +19,40 @@ export function serializeFlatpakCargoSources(sources) {
return `${JSON.stringify(sources, null, 2)}\n`
}
-export async function normalizeFlatpakCargoSourcesFile(filePath) {
- const sources = JSON.parse(await readFile(filePath, 'utf8'))
+// Both native executables have independent locks. Preserve the generator's
+// source objects, deduplicate identical destinations, and reject disagreements.
+export function mergeFlatpakCargoSources(left, right) {
+ if (!Array.isArray(left) || !Array.isArray(right)) {
+ throw new TypeError('Flatpak Cargo sources must be arrays')
+ }
+ const merged = new Map()
+ for (const source of [...left, ...right]) {
+ const key = `${source.dest}/${source['dest-filename'] ?? ''}`
+ const previous = merged.get(key)
+ if (previous && JSON.stringify(previous) !== JSON.stringify(source)) {
+ throw new Error(`Conflicting Cargo source: ${key}`)
+ }
+ merged.set(key, source)
+ }
+ return [...merged.values()].sort((a, b) => {
+ // Cargo config stays last, after each archive/checksum pair.
+ const key = (s) =>
+ s.dest === 'cargo' ? '~config' : `${s.dest}/${s['dest-filename'] ?? ''}`
+ return key(a) < key(b) ? -1 : key(a) > key(b) ? 1 : 0
+ })
+}
+
+export async function normalizeFlatpakCargoSourcesFile(
+ filePath,
+ additionalPath
+) {
+ let sources = JSON.parse(await readFile(filePath, 'utf8'))
+ if (additionalPath) {
+ sources = mergeFlatpakCargoSources(
+ sources,
+ JSON.parse(await readFile(additionalPath, 'utf8'))
+ )
+ }
await writeFile(filePath, serializeFlatpakCargoSources(sources), 'utf8')
biomeFormatJson(filePath)
return { entries: sources.length }
@@ -28,7 +60,10 @@ export async function normalizeFlatpakCargoSourcesFile(filePath) {
async function main() {
const filePath = path.resolve(process.argv[2] ?? 'flatpak/cargo-sources.json')
- const result = await normalizeFlatpakCargoSourcesFile(filePath)
+ const result = await normalizeFlatpakCargoSourcesFile(
+ filePath,
+ process.argv[3]
+ )
process.stdout.write(
`normalized Flatpak Cargo sources: ${result.entries} entries\n`
)
diff --git a/src/core/plugin/finalize/filesystem-adapter.test.ts b/src/core/plugin/finalize/filesystem-adapter.test.ts
index f2bf73ba..e844efd5 100644
--- a/src/core/plugin/finalize/filesystem-adapter.test.ts
+++ b/src/core/plugin/finalize/filesystem-adapter.test.ts
@@ -47,6 +47,10 @@ describe.runIf(process.platform !== 'win32')(
const send = () => {
const payload = Buffer.from(JSON.stringify({
request_id: request.request_id, status: 'ok',
+ ...(request.op === 'remove_opened_preserving' ? {
+ request_id: null, status: 'error', code: 'invalid_request',
+ message: 'unknown variant remove_opened_preserving',
+ } : {}),
handle: request.op === 'open_root' ? 1 : 2,
platform: 'test', rename_no_replace: true, held_roots: true,
directory_sync: true, held_artifacts: true,
@@ -118,6 +122,33 @@ describe.runIf(process.platform !== 'win32')(
await expect(adapter.capabilities()).rejects.toThrow('disposed')
})
+ it('rejects an old sidecar response with a null request id instead of hanging cleanup', async () => {
+ const adapter = new NativeFinalizeFilesystemAdapter(await framedSidecar())
+ let timeout: ReturnType<typeof setTimeout> | undefined
+ try {
+ const root = await adapter.openRoot(os.tmpdir())
+ const artifact = await adapter.openArtifact(root, 'payload')
+ const survivor = await adapter.openArtifact(root, 'survivor', 'rename')
+ const result = adapter
+ .removeOpened(artifact, 'payload', true, survivor)
+ .then(
+ () => 'unexpected success',
+ (error: { code: string }) => error.code
+ )
+ await expect(
+ Promise.race([
+ result,
+ new Promise<string>((resolve) => {
+ timeout = setTimeout(() => resolve('request hung'), 1000)
+ }),
+ ])
+ ).resolves.toBe('invalid_request')
+ } finally {
+ clearTimeout(timeout)
+ await adapter.dispose()
+ }
+ })
+
it('preserves the native operation and status across the sidecar protocol', async () => {
const adapter = new NativeFinalizeFilesystemAdapter(await framedSidecar())
try {
diff --git a/src/core/plugin/finalize/filesystem-adapter.ts b/src/core/plugin/finalize/filesystem-adapter.ts
index a82dca5f..ca6604bf 100644
--- a/src/core/plugin/finalize/filesystem-adapter.ts
+++ b/src/core/plugin/finalize/filesystem-adapter.ts
@@ -4,10 +4,12 @@ import { getLogger } from '@core/logger'
export type FinalizeFsErrorCode =
| 'unsupported'
+ | 'rename_unsupported'
| 'target_exists'
| 'not_found'
| 'invalid_path'
| 'invalid_handle'
+ | 'invalid_request'
| 'permission_denied'
| 'cross_device'
| 'symlink_rejected'
@@ -37,7 +39,7 @@ export interface FinalizeFsCapabilities {
}
interface WireResponse {
- request_id?: number
+ request_id?: number | null
status: 'ok' | 'error'
handle?: number
code?: FinalizeFsErrorCode
@@ -73,7 +75,10 @@ export interface FinalizeArtifactHandle {
export interface FinalizeFilesystemAdapter {
capabilities(): Promise<FinalizeFsCapabilities>
- openRoot(rootPath: string): Promise<FinalizeRootHandle>
+ openRoot(
+ rootPath: string,
+ expectedIdentity?: string
+ ): Promise<FinalizeRootHandle>
openArtifact(
root: FinalizeRootHandle,
relativePath: string,
@@ -84,6 +89,17 @@ export interface FinalizeFilesystemAdapter {
targetRoot: FinalizeRootHandle,
targetRelative: string
): Promise<void>
+ linkOpenedNoReplace(
+ artifact: FinalizeArtifactHandle,
+ targetRoot: FinalizeRootHandle,
+ targetRelative: string
+ ): Promise<void>
+ isolateOpened(
+ artifact: FinalizeArtifactHandle,
+ targetRoot: FinalizeRootHandle,
+ targetRelative: string,
+ expectedRootIdentity: string
+ ): Promise<void>
copyOpened(
artifact: FinalizeArtifactHandle,
targetRoot: FinalizeRootHandle,
@@ -98,7 +114,8 @@ export interface FinalizeFilesystemAdapter {
removeOpened(
artifact: FinalizeArtifactHandle,
quarantineRelative: string,
- resumeIsolated: boolean
+ resumeIsolated: boolean,
+ survivor?: FinalizeArtifactHandle
): Promise<void>
syncRoot(root: FinalizeRootHandle): Promise<void>
close(root: FinalizeRootHandle | FinalizeArtifactHandle): Promise<void>
@@ -219,6 +236,34 @@ export class NativeFinalizeFilesystemAdapter
})
}
+ async linkOpenedNoReplace(
+ artifact: FinalizeArtifactHandle,
+ targetRoot: FinalizeRootHandle,
+ targetRelative: string
+ ): Promise<void> {
+ await this.request({
+ op: 'link_opened_no_replace',
+ artifact: this.nativeId(artifact),
+ target_root: this.nativeId(targetRoot),
+ target_relative: targetRelative,
+ })
+ }
+
+ async isolateOpened(
+ artifact: FinalizeArtifactHandle,
+ targetRoot: FinalizeRootHandle,
+ targetRelative: string,
+ expectedRootIdentity: string
+ ): Promise<void> {
+ await this.request({
+ op: 'isolate_opened',
+ expected_root_identity: expectedRootIdentity,
+ artifact: this.nativeId(artifact),
+ target_root: this.nativeId(targetRoot),
+ target_relative: targetRelative,
+ })
+ }
+
async copyOpened(
artifact: FinalizeArtifactHandle,
targetRoot: FinalizeRootHandle,
@@ -232,12 +277,19 @@ export class NativeFinalizeFilesystemAdapter
})
}
- async openRoot(rootPath: string): Promise<FinalizeRootHandle> {
+ async openRoot(
+ rootPath: string,
+ expectedIdentity?: string
+ ): Promise<FinalizeRootHandle> {
if (!path.isAbsolute(rootPath)) {
throw new FinalizeFsError('invalid_path', 'root path must be absolute')
}
const generation = this.generation
- const response = await this.request({ op: 'open_root', path: rootPath })
+ const response = await this.request({
+ op: 'open_root',
+ path: rootPath,
+ expected_identity: expectedIdentity,
+ })
if (response.handle === undefined)
throw new Error('sidecar omitted root handle')
return this.heldHandle(response.handle, generation)
@@ -261,10 +313,12 @@ export class NativeFinalizeFilesystemAdapter
async removeOpened(
artifact: FinalizeArtifactHandle,
quarantineRelative: string,
- resumeIsolated: boolean
+ resumeIsolated: boolean,
+ survivor?: FinalizeArtifactHandle
): Promise<void> {
await this.request({
- op: 'remove_opened',
+ op: survivor ? 'remove_opened_preserving' : 'remove_opened',
+ ...(survivor ? { survivor: this.nativeId(survivor) } : {}),
artifact: this.nativeId(artifact),
quarantine_relative: quarantineRelative,
resume_isolated: resumeIsolated,
@@ -411,7 +465,10 @@ export class NativeFinalizeFilesystemAdapter
const key = response.request_id ?? 0
const pending = this.pending.get(key)
if (!pending) {
- if (response.request_id === undefined && this.pending.size > 0) {
+ if (
+ (response.request_id === undefined || response.request_id === null) &&
+ this.pending.size > 0
+ ) {
this.markDead(
new FinalizeFsError(
response.code ?? 'io_error',
diff --git a/src/core/plugin/finalize/finalize-adversarial.integration.test.ts b/src/core/plugin/finalize/finalize-adversarial.integration.test.ts
new file mode 100644
index 00000000..5deae6b9
--- /dev/null
+++ b/src/core/plugin/finalize/finalize-adversarial.integration.test.ts
@@ -0,0 +1,373 @@
+import { existsSync } from 'node:fs'
+import {
+ link,
+ mkdtemp,
+ readFile,
+ realpath,
+ rm,
+ statfs,
+ unlink,
+ writeFile,
+} from 'node:fs/promises'
+import os from 'node:os'
+import path from 'node:path'
+import { SqliteFinalizeJournalRepository } from '@core/session/finalize-journal-repository'
+import { migrate } from '@core/session/migrations'
+import Database from 'better-sqlite3'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import {
+ artifactContentEquals,
+ artifactIdentityEquals,
+} from './artifact-identity'
+import { ArtifactMutationLeaseCoordinator } from './artifact-mutation-lease'
+import {
+ FinalizeFsError,
+ NativeFinalizeFilesystemAdapter,
+} from './filesystem-adapter'
+import {
+ FinalizeCommitter,
+ type FinalizeJournalRecord,
+ prepareRemovalIntent,
+} from './finalize-committer'
+import { FinalizeRecovery } from './finalize-recovery'
+import { NativeFinalizeArtifactOperations } from './native-artifact-operations'
+
+const binary = path.resolve(
+ process.env.MOTRIX_FINALIZE_FS_TEST_BIN ??
+ 'packages/finalize-fs/target/debug/motrix-finalize-fs'
+)
+const nfsRoot = process.env.MOTRIX_FINALIZE_NFS_ROOT
+if (nfsRoot && (process.platform !== 'linux' || !existsSync(binary))) {
+ throw new Error('NFS contract requires Linux and a built native sidecar')
+}
+describe.runIf(process.platform !== 'win32' && existsSync(binary))(
+ 'finalize adversarial recovery',
+ { timeout: 30_000 },
+ () => {
+ const cleanup: (() => Promise<void>)[] = []
+ afterEach(async () => {
+ vi.restoreAllMocks()
+ for (const dispose of cleanup.splice(0)) await dispose()
+ }, 30_000)
+
+ async function setup() {
+ if (nfsRoot) expect((await statfs(nfsRoot)).type).toBe(0x6969)
+ const local = await realpath(
+ await mkdtemp(path.join(os.tmpdir(), 'motrix-adversarial-db-'))
+ )
+ const root = await realpath(
+ await mkdtemp(path.join(nfsRoot ?? local, 'motrix-adversarial-'))
+ )
+ const sourcePath = path.join(root, 'file.motrix')
+ const targetPath = path.join(root, 'file.bin')
+ await writeFile(sourcePath, 'the only complete payload')
+ const adapter = new NativeFinalizeFilesystemAdapter(binary)
+ const fs = new NativeFinalizeArtifactOperations(adapter)
+ const db = new Database(path.join(local, 'journal.sqlite'))
+ migrate(db)
+ const repository = new SqliteFinalizeJournalRepository(db, {
+ commitTerminalBoundary: () => {
+ throw new Error('not used')
+ },
+ })
+ const identity = (await fs.identity(sourcePath))!
+ const plan = {
+ planId: 'adversarial-plan',
+ taskId: 'adversarial-task',
+ saveDir: root,
+ sourcePath,
+ targetPath,
+ sourceIdentity: identity,
+ metadataOps: [],
+ contributors: [],
+ }
+ const recovery = new FinalizeRecovery({
+ fs,
+ repository,
+ leases: new ArtifactMutationLeaseCoordinator([]),
+ exactIdentity: artifactIdentityEquals,
+ sameContent: artifactContentEquals,
+ rollForwardTargetInstalled: false,
+ })
+ cleanup.push(async () => {
+ await adapter.dispose()
+ db.close()
+ await rm(root, { recursive: true, force: true })
+ await rm(local, { recursive: true, force: true })
+ })
+ return { root, plan, adapter, fs, db, repository, recovery, identity }
+ }
+
+ it.each(['before_isolation', 'after_isolation'] as const)(
+ 'rollback must preserve its only surviving payload after %s',
+ async (point) => {
+ const s = await setup()
+ await link(s.plan.sourcePath, s.plan.targetPath)
+ const record: FinalizeJournalRecord = {
+ journalId: s.plan.planId,
+ phase: 'prepared',
+ plan: s.plan,
+ publicationMode: 'move',
+ publicationIntent: {
+ version: 1,
+ method: 'hard_link',
+ sourcePath: s.plan.sourcePath,
+ identity: s.identity,
+ confirmed: true,
+ },
+ }
+ await s.repository.prepare(record)
+ const removalIntent = await prepareRemovalIntent(
+ s.fs,
+ record.journalId,
+ s.plan.targetPath,
+ s.identity
+ )
+ await s.repository.checkpoint(record.journalId, { removalIntent })
+ if (point === 'after_isolation') {
+ const remove = vi
+ .spyOn(s.adapter, 'removeOpened')
+ .mockRejectedValueOnce(new Error('crash before unlink'))
+ await expect(
+ s.fs.removeKnown(
+ removalIntent.artifactPath,
+ removalIntent.identity,
+ removalIntent.quarantinePath,
+ removalIntent.isolation
+ )
+ ).rejects.toThrow('crash before unlink')
+ remove.mockRestore()
+ }
+ // Another client removes the original name during the interruption.
+ await unlink(s.plan.sourcePath)
+ const lastName =
+ point === 'before_isolation'
+ ? s.plan.targetPath
+ : removalIntent.quarantinePath
+ expect(await readFile(lastName, 'utf8')).toBe(
+ 'the only complete payload'
+ )
+ const [persisted] = await s.repository.listRecoverable()
+ await expect(s.recovery.recover(persisted)).rejects.toThrow(
+ 'quarantined'
+ )
+ const survivors = [
+ s.plan.sourcePath,
+ s.plan.targetPath,
+ removalIntent.quarantinePath,
+ ].filter(existsSync)
+ expect(survivors.length).toBeGreaterThan(0)
+ }
+ )
+
+ it.each(['before_clear', 'after_clear'] as const)(
+ 'finishes an interrupted copy rollback after private unlink (%s)',
+ async (point) => {
+ const s = await setup()
+ const privateTargetPath = path.join(s.root, '.private-copy')
+ const privateTargetIdentity = await s.fs.materializePrivate(
+ s.plan.sourcePath,
+ s.identity,
+ privateTargetPath
+ )
+ await link(privateTargetPath, s.plan.targetPath)
+ const record: FinalizeJournalRecord = {
+ journalId: s.plan.planId,
+ phase: 'prepared',
+ plan: s.plan,
+ publicationMode: 'copy',
+ privateTargetPath,
+ privateTargetIdentity,
+ publicationIntent: {
+ version: 1,
+ method: 'hard_link',
+ sourcePath: privateTargetPath,
+ identity: privateTargetIdentity,
+ confirmed: true,
+ },
+ }
+ await s.repository.prepare(record)
+ await s.repository.advance(record.journalId, 'target_staged')
+ // The verified public link has already been rolled back.
+ await unlink(s.plan.targetPath)
+ const intent = await prepareRemovalIntent(
+ s.fs,
+ record.journalId,
+ privateTargetPath,
+ privateTargetIdentity
+ )
+ await s.repository.checkpoint(record.journalId, {
+ removalIntent: intent,
+ })
+ await s.fs.removeKnown(
+ intent.artifactPath,
+ intent.identity,
+ intent.quarantinePath,
+ intent.isolation,
+ { path: s.plan.sourcePath, identity: s.identity }
+ )
+ if (point === 'after_clear')
+ await s.repository.checkpoint(record.journalId, {
+ removalIntent: undefined,
+ })
+ await s.recovery.recoverAll()
+ expect(
+ s.db.prepare('SELECT phase FROM plugin_finalize_journals').get()
+ ).toEqual({ phase: 'cleaned' })
+ expect(await readFile(s.plan.sourcePath, 'utf8')).toBe(
+ 'the only complete payload'
+ )
+ expect(existsSync(s.plan.targetPath)).toBe(false)
+ expect(existsSync(privateTargetPath)).toBe(false)
+ }
+ )
+
+ it('must preserve a competing hard link when publication gets EEXIST', async () => {
+ const s = await setup()
+ vi.spyOn(s.fs, 'moveNoReplace').mockRejectedValue(
+ new FinalizeFsError('rename_unsupported', 'NFS NOREPLACE')
+ )
+ const realLink = s.fs.linkNoReplace.bind(s.fs)
+ vi.spyOn(s.fs, 'linkNoReplace').mockImplementationOnce(
+ async (source, _expected, target) => {
+ // A competing process wins after our target-absent check.
+ await link(source, target)
+ const competitorLink = await s.fs.identity(target)
+ expect(artifactIdentityEquals(competitorLink!, s.identity)).toBe(true)
+ if (process.platform === 'linux')
+ return realLink(source, _expected, target)
+ try {
+ await link(source, target)
+ } catch (error) {
+ expect((error as NodeJS.ErrnoException).code).toBe('EEXIST')
+ throw new FinalizeFsError('target_exists', 'linkat: File exists', {
+ osError: 17,
+ operation: 'link_opened_no_replace',
+ })
+ }
+ }
+ )
+ const committer = new FinalizeCommitter({
+ fs: s.fs,
+ repository: s.repository,
+ leases: new ArtifactMutationLeaseCoordinator([]),
+ exactIdentity: artifactIdentityEquals,
+ sameContent: artifactContentEquals,
+ privatePathFor: () => path.join(s.root, '.private'),
+ rollbackPathFor: () => path.join(s.root, '.rollback'),
+ })
+ await expect(committer.commit(s.plan)).rejects.toThrow(
+ 'ownership is unconfirmed'
+ )
+ expect(existsSync(s.plan.targetPath)).toBe(true)
+ })
+
+ it.each(['missing', 'replaced'] as const)(
+ 'preserves the isolated payload when the survivor becomes %s at native deletion',
+ async (mutation) => {
+ const s = await setup()
+ // A cross-device copy has a distinct inode: removing its name cannot
+ // incidentally trip the held source's ctime validation.
+ await writeFile(s.plan.targetPath, 'the only complete payload')
+ const record: FinalizeJournalRecord = {
+ journalId: s.plan.planId,
+ phase: 'prepared',
+ plan: s.plan,
+ publicationMode: 'copy',
+ targetIdentity: (await s.fs.identity(s.plan.targetPath))!,
+ }
+ await s.repository.prepare(record)
+ s.db
+ .prepare(
+ "UPDATE plugin_finalize_journals SET phase='db_committed', plan_json=?"
+ )
+ .run(JSON.stringify({ ...record, phase: 'db_committed' }))
+ const remove = s.adapter.removeOpened.bind(s.adapter)
+ vi.spyOn(s.adapter, 'removeOpened').mockImplementationOnce(
+ async (...args) => {
+ expect(args[3]).toBeDefined()
+ await unlink(s.plan.targetPath)
+ if (mutation === 'replaced')
+ await writeFile(s.plan.targetPath, 'competitor')
+ return remove(...args)
+ }
+ )
+ const [persisted] = await s.repository.listRecoverable()
+ await expect(s.recovery.recover(persisted)).rejects.toThrow()
+ const [pending] = await s.repository.listRecoverable()
+ expect(
+ await readFile(pending.removalIntent!.quarantinePath, 'utf8')
+ ).toBe('the only complete payload')
+ await s.recovery.recoverAll()
+ expect(
+ s.db
+ .prepare(
+ 'SELECT phase, quarantine_reason FROM plugin_finalize_journals'
+ )
+ .get()
+ ).toEqual({
+ phase: 'quarantined',
+ quarantine_reason: 'committed target identity mismatch',
+ })
+ expect(
+ await readFile(pending.removalIntent!.quarantinePath, 'utf8')
+ ).toBe('the only complete payload')
+ if (mutation === 'replaced')
+ expect(await readFile(s.plan.targetPath, 'utf8')).toBe('competitor')
+ }
+ )
+
+ it('should restart a dead sidecar while resuming journaled private cleanup', async () => {
+ const s = await setup()
+ await link(s.plan.sourcePath, s.plan.targetPath)
+ const record: FinalizeJournalRecord = {
+ journalId: s.plan.planId,
+ phase: 'prepared',
+ plan: s.plan,
+ publicationMode: 'move',
+ publicationIntent: {
+ version: 1,
+ method: 'hard_link',
+ sourcePath: s.plan.sourcePath,
+ identity: s.identity,
+ confirmed: true,
+ },
+ }
+ await s.repository.prepare(record)
+ await s.repository.advance(record.journalId, 'target_installed', {
+ targetIdentity: s.identity,
+ })
+ const committed = {
+ ...record,
+ phase: 'db_committed',
+ targetIdentity: s.identity,
+ }
+ s.db
+ .prepare(
+ "UPDATE plugin_finalize_journals SET phase='db_committed', plan_json=?"
+ )
+ .run(JSON.stringify(committed))
+ const intent = await prepareRemovalIntent(
+ s.fs,
+ record.journalId,
+ s.plan.sourcePath,
+ s.identity
+ )
+ await s.repository.checkpoint(record.journalId, { removalIntent: intent })
+ const child = (
+ s.adapter as unknown as {
+ child: import('node:child_process').ChildProcess
+ }
+ ).child
+ await new Promise<void>((resolve) => {
+ child.once('exit', () => resolve())
+ child.kill('SIGKILL')
+ })
+ await s.recovery.recoverAll()
+ expect(existsSync(s.plan.sourcePath)).toBe(false)
+ expect(await readFile(s.plan.targetPath, 'utf8')).toBe(
+ 'the only complete payload'
+ )
+ })
+ }
+)
diff --git a/src/core/plugin/finalize/finalize-committer.test.ts b/src/core/plugin/finalize/finalize-committer.test.ts
index 01c1a81d..f9350b49 100644
--- a/src/core/plugin/finalize/finalize-committer.test.ts
+++ b/src/core/plugin/finalize/finalize-committer.test.ts
@@ -5,6 +5,7 @@ import {
artifactIdentityEquals,
} from './artifact-identity'
import { ArtifactMutationLeaseCoordinator } from './artifact-mutation-lease'
+import { FinalizeFsError } from './filesystem-adapter'
import {
type FinalizeArtifactOperations,
FinalizeCommitter,
@@ -301,3 +302,158 @@ describe('FinalizeCommitter', () => {
expect(leases.isHeld(plan.taskId)).toBe(false)
})
})
+
+describe('hard-link publication', () => {
+ async function linked(sameDevice = true, commitError?: Error) {
+ const fs = new FakeFilesystem(sameDevice)
+ const plan = makePlan()
+ fs.artifacts.set(plan.sourcePath, sourceIdentity)
+ const state = makeRepository(commitError)
+ const checkpoints: unknown[] = []
+ state.repository.checkpoint = async (_id, patch) => {
+ checkpoints.push(structuredClone(patch))
+ }
+ vi.spyOn(fs, 'moveNoReplace').mockRejectedValue(
+ new FinalizeFsError('rename_unsupported', 'NFS rejects NOREPLACE')
+ )
+ const linkNoReplace = vi.fn(
+ async (source: string, expected: ArtifactIdentity, target: string) => {
+ expect(checkpoints.at(-1)).toEqual({
+ publicationIntent: {
+ version: 1,
+ method: 'hard_link',
+ sourcePath: source,
+ identity: expected,
+ },
+ })
+ if (fs.artifacts.has(target)) throw new Error('target exists')
+ fs.artifacts.set(target, fs.artifacts.get(source)!)
+ }
+ )
+ const operations = Object.assign(fs, { linkNoReplace })
+ return { fs, plan, state, operations, linkNoReplace }
+ }
+
+ it.each([true, false])(
+ 'publishes without overwriting and cleans both staging and source (same device: %s)',
+ async (sameDevice) => {
+ const { fs, plan, state, operations, linkNoReplace } =
+ await linked(sameDevice)
+ state.repository.commitTerminal = async () => {
+ expect(fs.artifacts.has(plan.sourcePath)).toBe(true)
+ expect(fs.artifacts.has(plan.targetPath)).toBe(true)
+ }
+ await makeCommitter(operations, state.repository).commit(plan)
+ expect(linkNoReplace).toHaveBeenCalledOnce()
+ expect([...fs.artifacts.keys()]).toEqual([plan.targetPath])
+ expect(state.quarantines).toEqual([])
+ }
+ )
+
+ it('quarantines both names when a link response was lost', async () => {
+ const { fs, plan, state, operations, linkNoReplace } = await linked()
+ const link = linkNoReplace.getMockImplementation()!
+ linkNoReplace.mockImplementation(async (...args) => {
+ await link(...args)
+ throw new Error('lost response')
+ })
+ await expect(
+ makeCommitter(operations, state.repository).commit(plan)
+ ).rejects.toThrow('ownership is unconfirmed')
+ expect([...fs.artifacts.keys()]).toEqual([plan.sourcePath, plan.targetPath])
+ expect(state.quarantines).toEqual([
+ 'hard-link publication ownership is unconfirmed',
+ ])
+ expect(state.phases.at(-1)).toBe('prepared')
+ })
+
+ it('preserves both names if recording link confirmation fails', async () => {
+ const { fs, plan, state, operations } = await linked()
+ const checkpoint = state.repository.checkpoint
+ state.repository.checkpoint = async (_id, patch) => {
+ await checkpoint(_id, patch)
+ if (patch.publicationIntent?.confirmed)
+ throw new Error('journal write failed')
+ }
+ await expect(
+ makeCommitter(operations, state.repository).commit(plan)
+ ).rejects.toThrow('ownership is unconfirmed')
+ expect([...fs.artifacts.keys()]).toEqual([plan.sourcePath, plan.targetPath])
+ expect(state.quarantines).toEqual([
+ 'hard-link publication ownership is unconfirmed',
+ ])
+ })
+
+ it('does not resume a removal intent whose journal checkpoint failed', async () => {
+ const { fs, plan, state, operations } = await linked(
+ true,
+ new Error('DB unavailable')
+ )
+ const remove = vi.spyOn(operations, 'removeKnown')
+ const originalCheckpoint = state.repository.checkpoint
+ const checkpoint = vi.fn(
+ async (_id: string, patch: Partial<FinalizeJournalRecord>) => {
+ await originalCheckpoint(_id, patch)
+ if (patch.removalIntent) throw new Error('journal write failed')
+ }
+ )
+ state.repository.checkpoint = checkpoint
+ await expect(
+ makeCommitter(operations, state.repository).commit(plan)
+ ).rejects.toThrow('rollback needs recovery')
+ expect(remove).not.toHaveBeenCalled()
+ expect([...fs.artifacts.keys()]).toEqual([plan.sourcePath, plan.targetPath])
+ })
+
+ it('preserves the source when the DB commit fails', async () => {
+ const { fs, plan, state, operations } = await linked(
+ true,
+ new Error('DB unavailable')
+ )
+ await expect(
+ makeCommitter(operations, state.repository).commit(plan)
+ ).rejects.toThrow('DB unavailable')
+ expect([...fs.artifacts.keys()]).toEqual([plan.sourcePath])
+ expect(state.quarantines).toEqual([])
+ })
+
+ it('preserves the source if the target is replaced during DB commit', async () => {
+ const { fs, plan, state, operations } = await linked()
+ state.repository.commitTerminal = async () => {
+ fs.artifacts.set(plan.targetPath, replacementIdentity)
+ }
+ await expect(
+ makeCommitter(operations, state.repository).commit(plan)
+ ).resolves.toMatchObject({ cleanupPending: true })
+ expect(fs.artifacts.get(plan.sourcePath)).toBe(sourceIdentity)
+ expect(fs.artifacts.get(plan.targetPath)).toBe(replacementIdentity)
+ expect(state.quarantines).toHaveLength(1)
+ })
+
+ it('keeps the completed target when cleanup fails', async () => {
+ const { fs, plan, state, operations } = await linked()
+ vi.spyOn(fs, 'removeKnown').mockRejectedValue(new Error('offline'))
+ await expect(
+ makeCommitter(operations, state.repository).commit(plan)
+ ).resolves.toMatchObject({ cleanupPending: true })
+ expect(fs.artifacts.has(plan.targetPath)).toBe(true)
+ expect(state.phases.at(-1)).toBe('db_committed')
+ })
+
+ it.each([
+ 'permission_denied',
+ 'io_error',
+ 'invalid_path',
+ 'target_exists',
+ ] as const)('does not fall back for %s', async (code) => {
+ const { fs, plan, state, operations, linkNoReplace } = await linked()
+ vi.mocked(fs.moveNoReplace).mockRejectedValue(
+ new FinalizeFsError(code, code)
+ )
+ await expect(
+ makeCommitter(operations, state.repository).commit(plan)
+ ).rejects.toThrow(code)
+ expect(linkNoReplace).not.toHaveBeenCalled()
+ expect(fs.artifacts.has(plan.sourcePath)).toBe(true)
+ })
+})
diff --git a/src/core/plugin/finalize/finalize-committer.ts b/src/core/plugin/finalize/finalize-committer.ts
index 3de76af1..5044e058 100644
--- a/src/core/plugin/finalize/finalize-committer.ts
+++ b/src/core/plugin/finalize/finalize-committer.ts
@@ -5,7 +5,9 @@ import type {
ArtifactMutationLease,
ArtifactMutationLeaseCoordinator,
} from './artifact-mutation-lease'
+import { FinalizeFsError } from './filesystem-adapter'
import { FinalizeRecovery } from './finalize-recovery'
+import { selectRemovalSurvivor } from './finalize-removal-safety'
import { assertValidHookPlan, type HookPlan } from './hook-plan'
export type FinalizeJournalPhase =
@@ -26,11 +28,32 @@ export interface FinalizeJournalRecord {
privateTargetIdentity?: ArtifactIdentity
targetIdentity?: ArtifactIdentity
rollbackPath?: string
+ publicationIntent?: FinalizePublicationIntent
removalIntent?: FinalizeRemovalIntent
quarantineReason?: string
}
+export interface FinalizePublicationIntent {
+ /** Written only after the native exclusive link call returns success. */
+ confirmed?: true
+ version: 1
+ method: 'hard_link'
+ sourcePath: string
+ identity: ArtifactIdentity
+}
+
+export interface FinalizeIsolation {
+ directory: string
+ platformFileId: string
+}
+
+export interface FinalizeRemovalSurvivor {
+ path: string
+ identity: ArtifactIdentity
+}
+
export interface FinalizeRemovalIntent {
+ isolation?: FinalizeIsolation
artifactPath: string
quarantinePath: string
identity: ArtifactIdentity
@@ -48,6 +71,7 @@ export interface FinalizeJournalRepository {
| 'targetIdentity'
| 'rollbackPath'
| 'removalIntent'
+ | 'publicationIntent'
>
>
): Promise<void>
@@ -86,11 +110,23 @@ export interface FinalizeArtifactOperations {
expected: ArtifactIdentity,
targetPath: string
): Promise<void>
+ linkNoReplace?(
+ sourcePath: string,
+ expected: ArtifactIdentity,
+ targetPath: string
+ ): Promise<void>
+ prepareRemoval?(
+ artifactPath: string,
+ identity: ArtifactIdentity,
+ quarantinePath: string
+ ): Promise<FinalizeRemovalIntent>
makeDurable(artifactPath: string): Promise<void>
removeKnown(
artifactPath: string,
expected: ArtifactIdentity,
- quarantinePath: string
+ quarantinePath: string,
+ isolation?: FinalizeIsolation,
+ survivor?: FinalizeRemovalSurvivor
): Promise<void>
}
@@ -190,7 +226,8 @@ export class FinalizeCommitter {
} else if (movesSource) {
// moveNoReplace validates the expected source identity while holding the
// artifact and both roots. Avoid hashing large artifacts once more here.
- await this.options.fs.moveNoReplace(
+ await this.publish(
+ record,
plan.sourcePath,
plan.sourceIdentity,
plan.targetPath
@@ -243,7 +280,8 @@ export class FinalizeCommitter {
privateIdentity,
record
)
- await this.options.fs.moveNoReplace(
+ await this.publish(
+ record,
record.privateTargetPath,
privateIdentity,
plan.targetPath
@@ -278,7 +316,7 @@ export class FinalizeCommitter {
record.phase = 'db_committed'
let cleanupPending = false
try {
- if (!samePath && !movesSource) {
+ if (!samePath && (!movesSource || record.publicationIntent)) {
await this.requireExactIdentity(
plan.sourcePath,
plan.sourceIdentity,
@@ -286,6 +324,13 @@ export class FinalizeCommitter {
)
await this.removeTracked(record, plan.sourcePath, plan.sourceIdentity)
}
+ if (record.publicationIntent && record.privateTargetPath) {
+ await this.removeTracked(
+ record,
+ record.privateTargetPath,
+ record.publicationIntent.identity
+ )
+ }
if (record.rollbackPath) {
await this.requireExactIdentity(
record.rollbackPath,
@@ -325,6 +370,44 @@ export class FinalizeCommitter {
}
}
+ private async publish(
+ record: FinalizeJournalRecord,
+ sourcePath: string,
+ identity: ArtifactIdentity,
+ targetPath: string
+ ): Promise<void> {
+ try {
+ await this.options.fs.moveNoReplace(sourcePath, identity, targetPath)
+ } catch (error) {
+ if (
+ !(error instanceof FinalizeFsError) ||
+ error.code !== 'rename_unsupported' ||
+ identity.kind !== 'file' ||
+ !this.options.fs.linkNoReplace
+ )
+ throw error
+ await this.requireExactIdentity(sourcePath, identity, record)
+ if (await this.options.fs.identity(targetPath)) throw error
+ const publicationIntent: FinalizePublicationIntent = {
+ version: 1,
+ method: 'hard_link',
+ sourcePath,
+ identity,
+ }
+ // Persist before the native call: a lost response can leave both names.
+ await this.options.repository.checkpoint(record.journalId, {
+ publicationIntent,
+ })
+ record.publicationIntent = publicationIntent
+ await this.options.fs.linkNoReplace(sourcePath, identity, targetPath)
+ const confirmed = { ...publicationIntent, confirmed: true as const }
+ await this.options.repository.checkpoint(record.journalId, {
+ publicationIntent: confirmed,
+ })
+ record.publicationIntent = confirmed
+ }
+ }
+
private async compensate(
record: FinalizeJournalRecord,
lease: ArtifactMutationLease,
@@ -392,19 +475,29 @@ export class FinalizeCommitter {
artifactPath: string,
identity: ArtifactIdentity
): Promise<void> {
- const removalIntent: FinalizeRemovalIntent = {
+ const removalIntent = await prepareRemovalIntent(
+ this.options.fs,
+ record.journalId,
artifactPath,
- quarantinePath: removalQuarantinePath(record.journalId, artifactPath),
- identity,
- }
- record.removalIntent = removalIntent
+ identity
+ )
await this.options.repository.checkpoint(record.journalId, {
removalIntent,
})
+ record.removalIntent = removalIntent
+ const survivor = await selectRemovalSurvivor(
+ record,
+ removalIntent,
+ this.options.fs,
+ this.options.exactIdentity
+ )
+ if (typeof survivor === 'string') return this.quarantine(record, survivor)
await this.options.fs.removeKnown(
artifactPath,
identity,
- removalIntent.quarantinePath
+ removalIntent.quarantinePath,
+ removalIntent.isolation,
+ survivor
)
record.removalIntent = undefined
await this.options.repository.checkpoint(record.journalId, {
@@ -421,6 +514,18 @@ export class FinalizeCommitter {
}
}
+export async function prepareRemovalIntent(
+ fs: FinalizeArtifactOperations,
+ journalId: string,
+ artifactPath: string,
+ identity: ArtifactIdentity
+): Promise<FinalizeRemovalIntent> {
+ const quarantinePath = removalQuarantinePath(journalId, artifactPath)
+ return fs.prepareRemoval
+ ? fs.prepareRemoval(artifactPath, identity, quarantinePath)
+ : { artifactPath, quarantinePath, identity }
+}
+
export function removalQuarantinePath(
journalId: string,
artifactPath: string
diff --git a/src/core/plugin/finalize/finalize-nfs-recovery.integration.test.ts b/src/core/plugin/finalize/finalize-nfs-recovery.integration.test.ts
new file mode 100644
index 00000000..8b6b7d65
--- /dev/null
+++ b/src/core/plugin/finalize/finalize-nfs-recovery.integration.test.ts
@@ -0,0 +1,268 @@
+import { existsSync } from 'node:fs'
+import {
+ mkdtemp,
+ readdir,
+ readFile,
+ realpath,
+ rm,
+ statfs,
+ writeFile,
+} from 'node:fs/promises'
+import os from 'node:os'
+import path from 'node:path'
+import { DurableFinalizeRuntime } from '@core/session/durable-finalize-runtime'
+import { migrate } from '@core/session/migrations'
+import { makeDownloadTask } from '@test-utils/task'
+import Database from 'better-sqlite3'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import {
+ FinalizeFsError,
+ NativeFinalizeFilesystemAdapter,
+} from './filesystem-adapter'
+import { NativeFinalizeArtifactOperations } from './native-artifact-operations'
+
+const binary = path.resolve(
+ process.env.MOTRIX_FINALIZE_FS_TEST_BIN ??
+ 'packages/finalize-fs/target/debug/motrix-finalize-fs'
+)
+const nfsRoot = process.env.MOTRIX_FINALIZE_NFS_ROOT
+if (nfsRoot && (process.platform !== 'linux' || !existsSync(binary))) {
+ throw new Error('NFS contract requires Linux and a built native sidecar')
+}
+
+describe.runIf(process.platform === 'linux' && existsSync(binary))(
+ 'NFS finalize publication and recovery',
+ { timeout: 30_000 },
+ () => {
+ const cleanup: (() => Promise<void>)[] = []
+ afterEach(async () => {
+ vi.restoreAllMocks()
+ for (const dispose of cleanup.splice(0)) await dispose()
+ }, 30_000)
+
+ async function setup(crossDevice = false) {
+ if (nfsRoot) expect((await statfs(nfsRoot)).type).toBe(0x6969)
+ const local = await realpath(
+ await mkdtemp(path.join(os.tmpdir(), 'motrix-nfs-db-'))
+ )
+ const root = await realpath(
+ await mkdtemp(path.join(nfsRoot ?? local, 'motrix-nfs-'))
+ )
+ const dbPath = path.join(local, 'journal.sqlite')
+ let db = new Database(dbPath)
+ migrate(db)
+ let adapter: NativeFinalizeFilesystemAdapter
+ let fs: NativeFinalizeArtifactOperations
+ function createRuntime() {
+ adapter = new NativeFinalizeFilesystemAdapter(binary)
+ // On local filesystems inject only the missing rename primitive. The
+ // link, isolation, removal, identity checks and SQLite are all real.
+ if (!nfsRoot)
+ vi.spyOn(adapter, 'renameOpenedNoReplace').mockRejectedValue(
+ new FinalizeFsError('rename_unsupported', 'NOREPLACE unsupported')
+ )
+ fs = new NativeFinalizeArtifactOperations(adapter)
+ return new DurableFinalizeRuntime({
+ db,
+ fs,
+ session: {
+ persistFinalizedArtifact: async (
+ _task,
+ _occurrence,
+ _effects,
+ commit
+ ) =>
+ commit((journal) => {
+ const raw = db
+ .prepare(
+ 'SELECT plan_json FROM plugin_finalize_journals WHERE plan_id=?'
+ )
+ .get(journal.journalId) as { plan_json: string }
+ db.prepare(
+ "UPDATE plugin_finalize_journals SET phase='db_committed', plan_json=? WHERE plan_id=?"
+ ).run(
+ JSON.stringify({
+ ...JSON.parse(raw.plan_json),
+ phase: 'db_committed',
+ }),
+ journal.journalId
+ )
+ }),
+ },
+ })
+ }
+ let runtime = createRuntime()
+ cleanup.push(async () => {
+ await adapter.dispose()
+ db.close()
+ await rm(root, { recursive: true, force: true })
+ await rm(local, { recursive: true, force: true })
+ })
+ const sourcePath = path.join(
+ crossDevice ? local : root,
+ 'download.bin.motrix'
+ )
+ const targetPath = path.join(root, 'download.bin')
+ await writeFile(sourcePath, 'complete download')
+ const input = {
+ task: makeDownloadTask({
+ id: 'task-nfs',
+ saveDir: root,
+ diskPath: sourcePath,
+ finalPath: targetPath,
+ }),
+ occurrence: null,
+ sourcePath,
+ targetPath,
+ metadataOps: [],
+ contributors: [],
+ postDeliveries: [],
+ }
+ return {
+ input,
+ root,
+ get adapter() {
+ return adapter
+ },
+ get fs() {
+ return fs
+ },
+ get runtime() {
+ return runtime
+ },
+ row: () =>
+ db
+ .prepare('SELECT phase, plan_json FROM plugin_finalize_journals')
+ .get() as { phase: string; plan_json: string },
+ async restart() {
+ await adapter.dispose()
+ db.close()
+ db = new Database(dbPath)
+ runtime = createRuntime()
+ },
+ }
+ }
+
+ it.each([false, true])(
+ 'publishes and cleans up (cross-device: %s)',
+ async (crossDevice) => {
+ const s = await setup(crossDevice)
+ const link = vi.spyOn(s.adapter, 'linkOpenedNoReplace')
+ const copy = vi.spyOn(s.adapter, 'copyOpened')
+ await s.runtime.commit(s.input)
+ expect(link).toHaveBeenCalledOnce()
+ if (crossDevice && nfsRoot) expect(copy).toHaveBeenCalledOnce()
+ else expect(copy).not.toHaveBeenCalled()
+ expect(s.row().phase).toBe('cleaned')
+ expect(await readdir(s.root)).toEqual(['download.bin'])
+ expect(existsSync(s.input.sourcePath)).toBe(false)
+ expect(await readFile(s.input.targetPath, 'utf8')).toBe(
+ 'complete download'
+ )
+ }
+ )
+
+ it('preserves an existing target and the complete source', async () => {
+ const s = await setup()
+ await writeFile(s.input.targetPath, 'unrelated')
+ await expect(s.runtime.commit(s.input)).rejects.toThrow()
+ expect(await readFile(s.input.targetPath, 'utf8')).toBe('unrelated')
+ expect(await readFile(s.input.sourcePath, 'utf8')).toBe(
+ 'complete download'
+ )
+ })
+
+ it('preserves uncertain link publication across restart and retry', async () => {
+ const s = await setup()
+ const link = s.adapter.linkOpenedNoReplace.bind(s.adapter)
+ vi.spyOn(s.adapter, 'linkOpenedNoReplace').mockImplementationOnce(
+ async (...args) => {
+ await link(...args)
+ throw new Error('lost link response')
+ }
+ )
+ await expect(s.runtime.commit(s.input)).rejects.toThrow(
+ 'ownership is unconfirmed'
+ )
+ expect(s.row().phase).toBe('quarantined')
+ await s.restart()
+ await s.runtime.recoverAll()
+ await expect(s.runtime.commit(s.input)).rejects.toThrow()
+ expect(s.row().phase).toBe('quarantined')
+ for (const name of [s.input.sourcePath, s.input.targetPath]) {
+ expect(await readFile(name, 'utf8')).toBe('complete download')
+ }
+ })
+
+ it('preserves an unconfirmed link after disconnection blocks live rollback', async () => {
+ const s = await setup()
+ let offline = false
+ const identity = s.fs.identity.bind(s.fs)
+ vi.spyOn(s.fs, 'identity').mockImplementation(async (...args) => {
+ if (offline) throw new Error('NFS disconnected')
+ return identity(...args)
+ })
+ const link = s.adapter.linkOpenedNoReplace.bind(s.adapter)
+ vi.spyOn(s.adapter, 'linkOpenedNoReplace').mockImplementationOnce(
+ async (...args) => {
+ await link(...args)
+ offline = true
+ throw new Error('lost link response')
+ }
+ )
+ await expect(s.runtime.commit(s.input)).rejects.toThrow(
+ 'rollback needs recovery'
+ )
+ expect(s.row().phase).toBe('prepared')
+ expect(existsSync(s.input.sourcePath)).toBe(true)
+ expect(existsSync(s.input.targetPath)).toBe(true)
+ await s.restart()
+ await s.runtime.recoverAll()
+ expect(s.row().phase).toBe('quarantined')
+ expect(existsSync(s.input.targetPath)).toBe(true)
+ expect(await readFile(s.input.sourcePath, 'utf8')).toBe(
+ 'complete download'
+ )
+ await expect(s.runtime.commit(s.input)).rejects.toThrow()
+ expect(s.row().phase).toBe('quarantined')
+ })
+
+ it.each(['before_isolation', 'after_isolation', 'after_unlink'] as const)(
+ 'reopens the DB and sidecar after cleanup fails %s',
+ async (point) => {
+ const s = await setup()
+ const isolate = s.adapter.isolateOpened.bind(s.adapter)
+ const remove = s.adapter.removeOpened.bind(s.adapter)
+ if (point === 'after_unlink') {
+ vi.spyOn(s.adapter, 'removeOpened').mockImplementationOnce(
+ async (...args) => {
+ await remove(...args)
+ throw new Error('lost removal response')
+ }
+ )
+ } else {
+ vi.spyOn(s.adapter, 'isolateOpened').mockImplementationOnce(
+ async (...args) => {
+ if (point === 'after_isolation') await isolate(...args)
+ throw new Error('isolation interruption')
+ }
+ )
+ }
+ await s.runtime.commit(s.input)
+ expect(s.row().phase).toBe('db_committed')
+ expect(
+ JSON.parse(s.row().plan_json).removalIntent.isolation
+ ).toBeDefined()
+ await s.restart()
+ await s.runtime.recoverAll()
+ expect(s.row().phase).toBe('cleaned')
+ expect(existsSync(s.input.sourcePath)).toBe(false)
+ expect(await readFile(s.input.targetPath, 'utf8')).toBe(
+ 'complete download'
+ )
+ await s.runtime.recoverAll()
+ expect(s.row().phase).toBe('cleaned')
+ }
+ )
+ }
+)
diff --git a/src/core/plugin/finalize/finalize-recovery.test.ts b/src/core/plugin/finalize/finalize-recovery.test.ts
index 618b6690..9d282576 100644
--- a/src/core/plugin/finalize/finalize-recovery.test.ts
+++ b/src/core/plugin/finalize/finalize-recovery.test.ts
@@ -253,6 +253,21 @@ describe('FinalizeRecovery', () => {
expect(state.phases).toEqual(['cleaned'])
})
+ it.each([undefined, targetIdentity])(
+ 'does not close an empty rollback when the original is missing or changed (%s)',
+ async (source) => {
+ const staged = record('target_staged')
+ staged.privateTargetPath = '/save/.private'
+ staged.privateTargetIdentity = targetIdentity
+ const state = fixture(source ? { '/save/source': source } : {})
+ await expect(state.recovery.recover(staged)).rejects.toThrow(
+ 'source changed before install recovery'
+ )
+ expect(state.phases).not.toContain('cleaned')
+ if (source) expect(state.artifacts.get('/save/source')).toBe(source)
+ }
+ )
+
it('removes replacement staging during committed cleanup', async () => {
const committed = record('db_committed')
committed.plan.replacement = {
@@ -382,3 +397,100 @@ describe('FinalizeRecovery', () => {
)
})
})
+
+describe('hard-link recovery', () => {
+ it.each(['prepared', 'target_installed', 'db_committed'] as const)(
+ 'recovers both names after %s',
+ async (phase) => {
+ const journal = record(phase)
+ journal.publicationMode = 'move'
+ journal.targetIdentity = sourceIdentity
+ journal.publicationIntent = {
+ confirmed: true,
+ version: 1,
+ method: 'hard_link',
+ sourcePath: '/save/source',
+ identity: sourceIdentity,
+ }
+ const state = fixture({
+ '/save/source': sourceIdentity,
+ '/save/target': sourceIdentity,
+ })
+ await state.recovery.recover(journal)
+ expect([...state.artifacts.keys()]).toEqual(['/save/target'])
+ expect(state.quarantines).toEqual([])
+ expect(state.phases.at(-1)).toBe('cleaned')
+ }
+ )
+
+ it('preserves legacy unconfirmed publication intents with both names', async () => {
+ const journal = record('prepared')
+ journal.publicationMode = 'move'
+ journal.publicationIntent = {
+ version: 1,
+ method: 'hard_link',
+ sourcePath: '/save/source',
+ identity: sourceIdentity,
+ }
+ const state = fixture({
+ '/save/source': sourceIdentity,
+ '/save/target': sourceIdentity,
+ })
+ await expect(state.recovery.recover(journal)).rejects.toThrow(
+ 'ownership is unconfirmed'
+ )
+ expect(state.artifacts.size).toBe(2)
+ })
+
+ it('does not reinterpret legacy duplicate names as a completed link', async () => {
+ const journal = record('prepared')
+ journal.publicationMode = 'move'
+ const state = fixture({
+ '/save/source': sourceIdentity,
+ '/save/target': sourceIdentity,
+ })
+ await expect(state.recovery.recover(journal)).rejects.toThrow('quarantined')
+ expect(state.artifacts.size).toBe(2)
+ })
+
+ it('does not resume source deletion when the committed output was replaced', async () => {
+ const journal = record('db_committed')
+ journal.publicationMode = 'move'
+ journal.targetIdentity = sourceIdentity
+ journal.publicationIntent = {
+ version: 1,
+ method: 'hard_link',
+ sourcePath: '/save/source',
+ identity: sourceIdentity,
+ }
+ journal.removalIntent = {
+ artifactPath: '/save/source',
+ identity: sourceIdentity,
+ quarantinePath: '/save/quarantine',
+ }
+ const state = fixture({
+ '/save/source': sourceIdentity,
+ '/save/target': targetIdentity,
+ })
+ await expect(state.recovery.recover(journal)).rejects.toThrow('quarantined')
+ expect(state.artifacts.get('/save/source')).toBe(sourceIdentity)
+ expect(state.artifacts.get('/save/target')).toBe(targetIdentity)
+ })
+
+ it('preserves an unrelated target even with a persisted link intent', async () => {
+ const journal = record('prepared')
+ journal.publicationMode = 'move'
+ journal.publicationIntent = {
+ version: 1,
+ method: 'hard_link',
+ sourcePath: '/save/source',
+ identity: sourceIdentity,
+ }
+ const state = fixture({
+ '/save/source': sourceIdentity,
+ '/save/target': targetIdentity,
+ })
+ await expect(state.recovery.recover(journal)).rejects.toThrow('quarantined')
+ expect(state.artifacts.size).toBe(2)
+ })
+})
diff --git a/src/core/plugin/finalize/finalize-recovery.ts b/src/core/plugin/finalize/finalize-recovery.ts
index 3800633b..c9c7ef47 100644
--- a/src/core/plugin/finalize/finalize-recovery.ts
+++ b/src/core/plugin/finalize/finalize-recovery.ts
@@ -8,9 +8,14 @@ import {
type FinalizeJournalRepository,
FinalizeQuarantinedError,
finalizePathsEquivalent,
- removalQuarantinePath,
+ prepareRemovalIntent,
} from './finalize-committer'
+import {
+ linkPublicationConfirmed,
+ selectRemovalSurvivor,
+} from './finalize-removal-safety'
+
export interface FinalizeRecoveryOptions {
repository: FinalizeJournalRepository
leases: ArtifactMutationLeaseCoordinator
@@ -97,6 +102,38 @@ export class FinalizeRecovery {
? await this.options.fs.identity(record.plan.replacement.stagedPath)
: null
+ const linked = record.publicationIntent
+ if (linked && target && !linkPublicationConfirmed(record)) {
+ await this.quarantine(
+ record,
+ 'hard-link publication ownership is unconfirmed'
+ )
+ }
+ if (
+ linked &&
+ target &&
+ (record.phase === 'prepared' || record.phase === 'target_staged')
+ ) {
+ const linkSource = await this.options.fs.identity(linked.sourcePath)
+ if (
+ !linkSource ||
+ !this.options.exactIdentity(linkSource, linked.identity) ||
+ !this.options.exactIdentity(target, linked.identity)
+ ) {
+ await this.quarantine(record, 'linked publication identity mismatch')
+ }
+ if (this.options.rollForwardTargetInstalled !== false) {
+ await this.options.fs.makeDurable(record.plan.targetPath)
+ await this.options.repository.advance(
+ record.journalId,
+ 'target_installed',
+ { targetIdentity: linked.identity }
+ )
+ record.targetIdentity = linked.identity
+ record.phase = 'target_installed'
+ }
+ }
+
if (record.phase === 'db_committed') {
if (!target || !this.options.exactIdentity(target, installed)) {
await this.quarantine(record, 'committed target identity mismatch')
@@ -106,7 +143,10 @@ export class FinalizeRecovery {
}
if (record.phase === 'target_installed') {
- if (target && this.options.exactIdentity(target, installed)) {
+ if (
+ target &&
+ this.options.exactIdentity(target, record.targetIdentity ?? installed)
+ ) {
if (this.options.rollForwardTargetInstalled !== false) {
await this.options.repository.commitTerminal(record)
record.phase = 'db_committed'
@@ -161,14 +201,14 @@ export class FinalizeRecovery {
if (!this.options.exactIdentity(target, expectedInstalled)) {
await this.quarantine(record, 'unknown target blocks recovery')
}
- if (privateTarget) {
+ if (privateTarget && !record.publicationIntent) {
await this.quarantine(
record,
'target and private target both exist during recovery'
)
}
} else if (
- !privateTarget ||
+ privateTarget &&
(record.privateTargetIdentity
? !this.options.exactIdentity(
privateTarget,
@@ -176,8 +216,10 @@ export class FinalizeRecovery {
)
: !this.options.sameContent(privateTarget, selected))
) {
- await this.quarantine(record, 'private target is missing or changed')
+ await this.quarantine(record, 'private target identity mismatch')
}
+ // Both output names can be gone after an interrupted rollback. The
+ // original must still be verified below before closing that journal.
const samePathReplacement =
record.plan.replacement !== undefined &&
finalizePathsEquivalent(
@@ -294,14 +336,18 @@ export class FinalizeRecovery {
privateTarget: Awaited<ReturnType<FinalizeArtifactOperations['identity']>>,
replacement: Awaited<ReturnType<FinalizeArtifactOperations['identity']>>
): Promise<void> {
- if (record.publicationMode === 'move' && source) {
+ if (
+ record.publicationMode === 'move' &&
+ source &&
+ !record.publicationIntent
+ ) {
await this.quarantine(
record,
'moved source path unexpectedly exists after commit'
)
}
if (
- record.publicationMode !== 'move' &&
+ (record.publicationMode !== 'move' || record.publicationIntent) &&
source &&
!finalizePathsEquivalent(record.plan.sourcePath, record.plan.targetPath)
) {
@@ -359,6 +405,22 @@ export class FinalizeRecovery {
) {
await this.quarantine(record, 'invalid move publication journal')
}
+ if (
+ source &&
+ target &&
+ record.publicationIntent &&
+ this.options.exactIdentity(source, record.plan.sourceIdentity) &&
+ this.options.exactIdentity(target, record.publicationIntent.identity)
+ ) {
+ await this.removeTracked(
+ record,
+ record.plan.targetPath,
+ record.publicationIntent.identity
+ )
+ await this.options.fs.makeDurable(record.plan.sourcePath)
+ await this.options.repository.advance(record.journalId, 'cleaned')
+ return
+ }
if (source && target) {
await this.quarantine(
record,
@@ -474,10 +536,19 @@ export class FinalizeRecovery {
'persisted removal intent identity mismatch'
)
}
+ const survivor = await selectRemovalSurvivor(
+ record,
+ intent,
+ this.options.fs,
+ this.options.exactIdentity
+ )
+ if (typeof survivor === 'string') return this.quarantine(record, survivor)
await this.options.fs.removeKnown(
intent.artifactPath,
intent.identity,
- intent.quarantinePath
+ intent.quarantinePath,
+ intent.isolation,
+ survivor
)
record.removalIntent = undefined
await this.options.repository.checkpoint(record.journalId, {
@@ -490,19 +561,29 @@ export class FinalizeRecovery {
artifactPath: string,
identity: FinalizeJournalRecord['plan']['sourceIdentity']
): Promise<void> {
- const removalIntent = {
+ const removalIntent = await prepareRemovalIntent(
+ this.options.fs,
+ record.journalId,
artifactPath,
- quarantinePath: removalQuarantinePath(record.journalId, artifactPath),
- identity,
- }
- record.removalIntent = removalIntent
+ identity
+ )
await this.options.repository.checkpoint(record.journalId, {
removalIntent,
})
+ record.removalIntent = removalIntent
+ const survivor = await selectRemovalSurvivor(
+ record,
+ removalIntent,
+ this.options.fs,
+ this.options.exactIdentity
+ )
+ if (typeof survivor === 'string') return this.quarantine(record, survivor)
await this.options.fs.removeKnown(
artifactPath,
identity,
- removalIntent.quarantinePath
+ removalIntent.quarantinePath,
+ removalIntent.isolation,
+ survivor
)
record.removalIntent = undefined
await this.options.repository.checkpoint(record.journalId, {
@@ -533,6 +614,7 @@ export function isRetryableMoveQuarantine(
!record.privateTargetIdentity &&
!record.rollbackPath &&
!record.removalIntent &&
+ !record.publicationIntent &&
!finalizePathsEquivalent(record.plan.sourcePath, record.plan.targetPath)
)
}
diff --git a/src/core/plugin/finalize/finalize-removal-safety.ts b/src/core/plugin/finalize/finalize-removal-safety.ts
new file mode 100644
index 00000000..2c1f3c0e
--- /dev/null
+++ b/src/core/plugin/finalize/finalize-removal-safety.ts
@@ -0,0 +1,75 @@
+import type { ArtifactIdentity } from './artifact-identity'
+import type {
+ FinalizeArtifactOperations,
+ FinalizeJournalRecord,
+ FinalizeRemovalIntent,
+ FinalizeRemovalSurvivor,
+} from './finalize-committer'
+import { finalizePathsEquivalent } from './finalize-committer'
+
+/** A recorded intention cannot establish ownership of a public hard link. */
+export function linkPublicationConfirmed(
+ record: FinalizeJournalRecord
+): boolean {
+ return (
+ record.publicationIntent?.confirmed === true ||
+ record.phase === 'target_installed' ||
+ record.phase === 'db_committed'
+ )
+}
+
+/** Re-evaluate the surviving copy at every destructive entry, including replay. */
+export async function selectRemovalSurvivor(
+ record: FinalizeJournalRecord,
+ intent: Pick<FinalizeRemovalIntent, 'artifactPath' | 'quarantinePath'>,
+ fs: FinalizeArtifactOperations,
+ exactIdentity: (left: ArtifactIdentity, right: ArtifactIdentity) => boolean
+): Promise<FinalizeRemovalSurvivor | string> {
+ const removes = (candidate: string) =>
+ finalizePathsEquivalent(candidate, intent.artifactPath) ||
+ finalizePathsEquivalent(candidate, intent.quarantinePath)
+ if (
+ record.publicationIntent &&
+ removes(record.plan.targetPath) &&
+ !linkPublicationConfirmed(record)
+ )
+ return 'hard-link publication ownership is unconfirmed'
+
+ const committed = record.phase === 'db_committed'
+ if (committed && removes(record.plan.targetPath)) {
+ return 'removal would delete the committed target'
+ }
+ const candidates = committed
+ ? [
+ {
+ path: record.plan.targetPath,
+ identity:
+ record.targetIdentity ??
+ record.privateTargetIdentity ??
+ record.plan.replacement?.identity ??
+ record.plan.sourceIdentity,
+ },
+ ]
+ : [
+ { path: record.plan.sourcePath, identity: record.plan.sourceIdentity },
+ ...(record.rollbackPath
+ ? [
+ {
+ path: record.rollbackPath,
+ identity: record.plan.sourceIdentity,
+ },
+ ]
+ : []),
+ ]
+ for (const candidate of candidates) {
+ if (removes(candidate.path)) continue
+ const before = await fs.identity(candidate.path)
+ if (!before || !exactIdentity(before, candidate.identity)) continue
+ await fs.makeDurable(candidate.path)
+ const after = await fs.identity(candidate.path)
+ if (after && exactIdentity(after, candidate.identity)) return candidate
+ }
+ return committed
+ ? 'committed target identity mismatch'
+ : 'rollback survivor is missing or changed'
+}
diff --git a/src/core/plugin/finalize/native-artifact-operations.integration.test.ts b/src/core/plugin/finalize/native-artifact-operations.integration.test.ts
index a16a5847..213bdd9b 100644
--- a/src/core/plugin/finalize/native-artifact-operations.integration.test.ts
+++ b/src/core/plugin/finalize/native-artifact-operations.integration.test.ts
@@ -6,6 +6,7 @@ import {
realpath,
rename,
rm,
+ stat,
symlink,
writeFile,
} from 'node:fs/promises'
@@ -112,6 +113,26 @@ describe.runIf(existsSync(binary))(
}
})
+ it.runIf(process.platform !== 'win32')(
+ 'rejects a different held isolation directory identity',
+ async () => {
+ const { root, adapter } = await setup()
+ try {
+ const metadata = await stat(root, { bigint: true })
+ const held = await adapter.openRoot(
+ root,
+ `${metadata.dev}:${metadata.ino}`
+ )
+ await adapter.close(held)
+ await expect(
+ adapter.openRoot(root, `${metadata.dev}:${metadata.ino + 1n}`)
+ ).rejects.toThrow('held directory identity changed')
+ } finally {
+ await adapter.dispose()
+ }
+ }
+ )
+
it('publishes a held file without replacing an existing target', async () => {
const { root, adapter, operations } = await setup()
const source = path.join(root, 'source.bin')
diff --git a/src/core/plugin/finalize/native-artifact-operations.ts b/src/core/plugin/finalize/native-artifact-operations.ts
index 737d2f70..5f9ae9b5 100644
--- a/src/core/plugin/finalize/native-artifact-operations.ts
+++ b/src/core/plugin/finalize/native-artifact-operations.ts
@@ -1,5 +1,13 @@
import { constants } from 'node:fs'
-import { lstat, mkdir, open, readdir, stat } from 'node:fs/promises'
+import {
+ lstat,
+ mkdir,
+ mkdtemp,
+ open,
+ readdir,
+ rmdir,
+ stat,
+} from 'node:fs/promises'
import path from 'node:path'
import {
type ArtifactIdentity,
@@ -9,7 +17,12 @@ import {
readArtifactIdentity,
} from './artifact-identity'
import type { FinalizeFilesystemAdapter } from './filesystem-adapter'
-import type { FinalizeArtifactOperations } from './finalize-committer'
+import type {
+ FinalizeArtifactOperations,
+ FinalizeIsolation,
+ FinalizeRemovalIntent,
+ FinalizeRemovalSurvivor,
+} from './finalize-committer'
/**
* Production artifact operations. No-replace publication is delegated to the
@@ -129,6 +142,23 @@ export class NativeFinalizeArtifactOperations
sourcePath: string,
expected: ArtifactIdentity,
targetPath: string
+ ): Promise<void> {
+ return this.publishOpened(sourcePath, expected, targetPath, 'rename')
+ }
+
+ async linkNoReplace(
+ sourcePath: string,
+ expected: ArtifactIdentity,
+ targetPath: string
+ ): Promise<void> {
+ return this.publishOpened(sourcePath, expected, targetPath, 'link')
+ }
+
+ private async publishOpened(
+ sourcePath: string,
+ expected: ArtifactIdentity,
+ targetPath: string,
+ method: 'rename' | 'link'
): Promise<void> {
await this.assertSupported()
await this.requireIdentity(sourcePath, expected)
@@ -146,11 +176,19 @@ export class NativeFinalizeArtifactOperations
'rename'
)
await this.requireIdentity(sourcePath, expected)
- await this.adapter.renameOpenedNoReplace(
- artifact,
- targetRoot,
- path.basename(targetPath)
- )
+ if (method === 'link') {
+ await this.adapter.linkOpenedNoReplace(
+ artifact,
+ targetRoot,
+ path.basename(targetPath)
+ )
+ } else {
+ await this.adapter.renameOpenedNoReplace(
+ artifact,
+ targetRoot,
+ path.basename(targetPath)
+ )
+ }
await this.adapter.syncRoot(sourceRoot)
await this.adapter.syncRoot(targetRoot)
await this.requireIdentity(targetPath, expected)
@@ -173,12 +211,183 @@ export class NativeFinalizeArtifactOperations
}
}
+ async prepareRemoval(
+ artifactPath: string,
+ identity: ArtifactIdentity,
+ quarantinePath: string
+ ): Promise<FinalizeRemovalIntent> {
+ await this.assertSupported()
+ if (process.platform === 'win32' || identity.kind !== 'file') {
+ return { artifactPath, identity, quarantinePath }
+ }
+ await this.assertSafeExistingParent(artifactPath)
+ const directory = await mkdtemp(`${quarantinePath}-`)
+ const value = await lstat(directory, { bigint: true })
+ const isolation = { directory, platformFileId: `${value.dev}:${value.ino}` }
+ const held = await this.adapter.openRoot(directory)
+ try {
+ await this.adapter.syncRoot(held)
+ } finally {
+ await this.adapter.close(held)
+ }
+ const parent = await this.adapter.openRoot(path.dirname(directory))
+ try {
+ await this.adapter.syncRoot(parent)
+ } finally {
+ await this.adapter.close(parent)
+ }
+ return {
+ artifactPath,
+ identity,
+ quarantinePath: path.join(directory, 'payload'),
+ isolation,
+ }
+ }
+
+ private async assertIsolation(
+ isolation: FinalizeIsolation
+ ): Promise<boolean> {
+ try {
+ const stat = await lstat(isolation.directory, { bigint: true })
+ if (
+ !stat.isDirectory() ||
+ stat.isSymbolicLink() ||
+ `${stat.dev}:${stat.ino}` !== isolation.platformFileId ||
+ (stat.mode & 0o777n) !== 0o700n
+ ) {
+ throw new ArtifactIdentityError(
+ 'artifact_mutated',
+ 'private isolation directory changed'
+ )
+ }
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false
+ throw error
+ }
+ return true
+ }
+
+ private async removeIsolated(
+ artifactPath: string,
+ expected: ArtifactIdentity,
+ quarantinePath: string,
+ isolation: FinalizeIsolation,
+ survivor?: FinalizeRemovalSurvivor
+ ): Promise<void> {
+ if (
+ expected.kind !== 'file' ||
+ path.dirname(isolation.directory) !== path.dirname(artifactPath) ||
+ quarantinePath !== path.join(isolation.directory, 'payload')
+ ) {
+ throw new ArtifactIdentityError(
+ 'artifact_unsafe_path',
+ 'invalid private removal intent'
+ )
+ }
+ if (!(await this.assertIsolation(isolation))) {
+ if (await this.identity(artifactPath))
+ throw new ArtifactIdentityError(
+ 'artifact_mutated',
+ 'private removal directory is missing'
+ )
+ const parent = await this.adapter.openRoot(path.dirname(artifactPath))
+ try {
+ await this.adapter.syncRoot(parent)
+ } finally {
+ await this.adapter.close(parent)
+ }
+ return
+ }
+ const original = await this.identity(artifactPath)
+ const isolated = await this.identity(quarantinePath)
+ if (
+ (original && isolated) ||
+ (original && !artifactIdentityEquals(original, expected)) ||
+ (isolated && !artifactIdentityEquals(isolated, expected))
+ ) {
+ throw new ArtifactIdentityError(
+ 'artifact_mutated',
+ 'private removal identity mismatch'
+ )
+ }
+ const root = await this.adapter.openRoot(
+ isolation.directory,
+ isolation.platformFileId
+ )
+ try {
+ if (original) {
+ const sourceRoot = await this.adapter.openRoot(
+ path.dirname(artifactPath)
+ )
+ let artifact:
+ | Awaited<ReturnType<typeof this.adapter.openArtifact>>
+ | undefined
+ try {
+ artifact = await this.adapter.openArtifact(
+ sourceRoot,
+ path.basename(artifactPath),
+ 'rename'
+ )
+ await this.requireIdentity(artifactPath, expected)
+ await this.adapter.isolateOpened(
+ artifact,
+ root,
+ 'payload',
+ isolation.platformFileId
+ )
+ } finally {
+ if (artifact)
+ await this.adapter.close(artifact).catch(() => undefined)
+ await this.adapter.close(sourceRoot).catch(() => undefined)
+ }
+ }
+ if (original || isolated) {
+ const artifact = await this.adapter.openArtifact(root, 'payload')
+ try {
+ await this.requireIdentity(quarantinePath, expected)
+ await this.removeOpenedPreserving(artifact, 'payload', true, survivor)
+ } finally {
+ await this.adapter.close(artifact).catch(() => undefined)
+ }
+ }
+ await this.adapter.syncRoot(root)
+ } finally {
+ await this.adapter.close(root).catch(() => undefined)
+ }
+ if (
+ (await this.identity(artifactPath)) ||
+ (await this.identity(quarantinePath))
+ ) {
+ throw new ArtifactIdentityError(
+ 'artifact_mutated',
+ 'name survived private removal'
+ )
+ }
+ if (await this.assertIsolation(isolation)) await rmdir(isolation.directory)
+ const parent = await this.adapter.openRoot(path.dirname(artifactPath))
+ try {
+ await this.adapter.syncRoot(parent)
+ } finally {
+ await this.adapter.close(parent)
+ }
+ }
+
async removeKnown(
artifactPath: string,
expected: ArtifactIdentity,
- quarantinePath: string
+ quarantinePath: string,
+ isolation?: FinalizeIsolation,
+ survivor?: FinalizeRemovalSurvivor
): Promise<void> {
await this.assertSupported()
+ if (isolation)
+ return this.removeIsolated(
+ artifactPath,
+ expected,
+ quarantinePath,
+ isolation,
+ survivor
+ )
if (
path.dirname(quarantinePath) !== path.dirname(artifactPath) ||
path.basename(quarantinePath) === path.basename(artifactPath)
@@ -221,10 +430,11 @@ export class NativeFinalizeArtifactOperations
path.basename(openedPath)
)
await this.requireIdentity(openedPath, expected)
- await this.adapter.removeOpened(
+ await this.removeOpenedPreserving(
artifact,
path.basename(quarantinePath),
- resumeIsolated
+ resumeIsolated,
+ survivor
)
} finally {
if (artifact) await this.adapter.close(artifact).catch(() => undefined)
@@ -245,6 +455,52 @@ export class NativeFinalizeArtifactOperations
}
}
+ private async removeOpenedPreserving(
+ artifact: Parameters<FinalizeFilesystemAdapter['removeOpened']>[0],
+ quarantineRelative: string,
+ resumeIsolated: boolean,
+ survivor?: FinalizeRemovalSurvivor
+ ): Promise<void> {
+ if (!survivor) {
+ return this.adapter.removeOpened(
+ artifact,
+ quarantineRelative,
+ resumeIsolated
+ )
+ }
+ // Windows retains its handle-bound deletion contract. Unix additionally
+ // checks the held surviving name after hashing, immediately before unlink.
+ if (process.platform === 'win32') {
+ await this.requireIdentity(survivor.path, survivor.identity)
+ return this.adapter.removeOpened(
+ artifact,
+ quarantineRelative,
+ resumeIsolated
+ )
+ }
+ const root = await this.adapter.openRoot(path.dirname(survivor.path))
+ let held:
+ | Awaited<ReturnType<FinalizeFilesystemAdapter['openArtifact']>>
+ | undefined
+ try {
+ held = await this.adapter.openArtifact(
+ root,
+ path.basename(survivor.path),
+ 'rename'
+ )
+ await this.requireIdentity(survivor.path, survivor.identity)
+ await this.adapter.removeOpened(
+ artifact,
+ quarantineRelative,
+ resumeIsolated,
+ held
+ )
+ } finally {
+ if (held) await this.adapter.close(held).catch(() => undefined)
+ await this.adapter.close(root).catch(() => undefined)
+ }
+ }
+
private async ensureSafeDirectory(directoryPath: string): Promise<void> {
await assertExistingAncestorsAreDirectories(directoryPath)
await mkdir(directoryPath, { recursive: true })
diff --git a/src/core/session/finalize-journal-repository.test.ts b/src/core/session/finalize-journal-repository.test.ts
index 8cf22fc5..fbe31ef5 100644
--- a/src/core/session/finalize-journal-repository.test.ts
+++ b/src/core/session/finalize-journal-repository.test.ts
@@ -14,6 +14,53 @@ describe('SqliteFinalizeJournalRepository', () => {
afterEach(() => db.close())
+ it('persists and validates the installation source of a hard-link intent', async () => {
+ const repository = new SqliteFinalizeJournalRepository(db, {
+ commitTerminalBoundary: vi.fn(),
+ })
+ const record = makeRecord()
+ record.publicationMode = 'move'
+ record.plan.sourceIdentity = {
+ kind: 'file',
+ size: 4,
+ sha256: 'a'.repeat(64),
+ platformFileId: '1:1',
+ }
+ await repository.prepare(record)
+ const publicationIntent = {
+ version: 1 as const,
+ method: 'hard_link' as const,
+ sourcePath: record.plan.sourcePath,
+ identity: record.plan.sourceIdentity,
+ }
+ await repository.checkpoint(record.journalId, { publicationIntent })
+ expect((await repository.listRecoverable())[0].publicationIntent).toEqual(
+ publicationIntent
+ )
+ await repository.checkpoint(record.journalId, {
+ publicationIntent: { ...publicationIntent, confirmed: true },
+ })
+ expect(
+ (await repository.listRecoverable())[0].publicationIntent?.confirmed
+ ).toBe(true)
+ await expect(
+ repository.checkpoint(record.journalId, {
+ publicationIntent: { ...publicationIntent, sourcePath: '/unrelated' },
+ })
+ ).rejects.toThrow('installation source')
+ const persisted = {
+ ...record,
+ publicationIntent: { ...publicationIntent, version: 99 },
+ }
+ db.prepare('UPDATE plugin_finalize_journals SET plan_json=?').run(
+ JSON.stringify(persisted)
+ )
+ expect(await repository.listRecoverable()).toEqual([])
+ expect(
+ db.prepare('SELECT phase FROM plugin_finalize_journals').get()
+ ).toEqual({ phase: 'quarantined' })
+ })
+
it('reopens only the exact legacy journal snapshot selected for recovery', async () => {
const repository = new SqliteFinalizeJournalRepository(db, {
commitTerminalBoundary: vi.fn(),
diff --git a/src/core/session/finalize-journal-repository.ts b/src/core/session/finalize-journal-repository.ts
index 56347e61..d7fc3c7c 100644
--- a/src/core/session/finalize-journal-repository.ts
+++ b/src/core/session/finalize-journal-repository.ts
@@ -1,3 +1,5 @@
+import path from 'node:path'
+import { artifactIdentityEquals } from '@core/plugin/finalize/artifact-identity'
import type {
FinalizeJournalPhase,
FinalizeJournalRecord,
@@ -7,6 +9,7 @@ import { finalizePathsEquivalent } from '@core/plugin/finalize/finalize-committe
import { isRetryableMoveQuarantine } from '@core/plugin/finalize/finalize-recovery'
import { assertValidHookPlan } from '@core/plugin/finalize/hook-plan'
import type Database from 'better-sqlite3'
+import { z } from 'zod'
interface RawFinalizeJournal {
plan_id: string
@@ -100,6 +103,7 @@ export class SqliteFinalizeJournalRepository
| 'targetIdentity'
| 'rollbackPath'
| 'removalIntent'
+ | 'publicationIntent'
>
>
): Promise<void> {
@@ -109,6 +113,7 @@ export class SqliteFinalizeJournalRepository
throw new Error(`cannot checkpoint terminal finalize journal`)
}
const next: FinalizeJournalRecord = { ...current, ...patch }
+ validateIntents(next)
const changed = this.db
.prepare(
`UPDATE plugin_finalize_journals
@@ -316,6 +321,7 @@ function parseRecord(raw: RawFinalizeJournal): FinalizeJournalRecord {
throw new TypeError('journal move publication plan is invalid')
}
assertValidHookPlan(record.plan)
+ validateIntents(record)
const sourceIdentity = JSON.stringify(record.plan.sourceIdentity)
if (sourceIdentity !== JSON.stringify(JSON.parse(raw.source_identity_json))) {
throw new TypeError('journal source identity column does not match plan')
@@ -330,6 +336,66 @@ function parseRecord(raw: RawFinalizeJournal): FinalizeJournalRecord {
return record
}
+const fileIdentitySchema = z.object({
+ kind: z.literal('file'),
+ size: z.number().int().nonnegative(),
+ sha256: z.string().regex(/^[a-f0-9]{64}$/),
+ platformFileId: z.string().min(1),
+})
+const publicationIntentSchema = z
+ .object({
+ version: z.literal(1),
+ method: z.literal('hard_link'),
+ confirmed: z.literal(true).optional(),
+ sourcePath: z.string(),
+ identity: fileIdentitySchema,
+ })
+ .strict()
+const isolationSchema = z
+ .object({
+ directory: z.string(),
+ platformFileId: z.string().regex(/^\d+:\d+$/),
+ })
+ .strict()
+
+function validateIntents(record: FinalizeJournalRecord): void {
+ if (record.publicationIntent !== undefined) {
+ const intent = publicationIntentSchema.parse(record.publicationIntent)
+ const expectedPath =
+ record.publicationMode === 'move'
+ ? record.plan.sourcePath
+ : record.privateTargetPath
+ const expectedIdentity =
+ record.publicationMode === 'move'
+ ? record.plan.sourceIdentity
+ : record.privateTargetIdentity
+ if (
+ !expectedPath ||
+ !expectedIdentity ||
+ intent.sourcePath !== expectedPath ||
+ !artifactIdentityEquals(intent.identity, expectedIdentity) ||
+ finalizePathsEquivalent(intent.sourcePath, record.plan.targetPath)
+ ) {
+ throw new TypeError(
+ 'journal publication intent does not match its installation source'
+ )
+ }
+ }
+ const removal = record.removalIntent
+ if (removal?.isolation !== undefined) {
+ const isolation = isolationSchema.parse(removal.isolation)
+ if (
+ !path.isAbsolute(isolation.directory) ||
+ path.dirname(isolation.directory) !==
+ path.dirname(removal.artifactPath) ||
+ removal.quarantinePath !== path.join(isolation.directory, 'payload') ||
+ removal.identity.kind !== 'file'
+ ) {
+ throw new TypeError('journal removal isolation is invalid')
+ }
+ }
+}
+
function transitionAllowed(
record: FinalizeJournalRecord,
to: FinalizeJournalPhase
diff --git a/tests/check-third-party-notices.test.ts b/tests/check-third-party-notices.test.ts
index 27bfa06b..ddb8cae4 100644
--- a/tests/check-third-party-notices.test.ts
+++ b/tests/check-third-party-notices.test.ts
@@ -209,7 +209,64 @@ const RUST_NATIVE_HOST_CRATES: RustCrateNotice[] = [
},
]
+const RUST_FINALIZE_ADDITIONAL_CRATES: RustCrateNotice[] = [
+ {
+ name: 'bitflags',
+ version: '2.13.1',
+ license: 'MIT OR Apache-2.0',
+ repository: 'https://github.com/bitflags/bitflags',
+ },
+ {
+ name: 'errno',
+ version: '0.3.14',
+ license: 'MIT OR Apache-2.0',
+ repository: 'https://github.com/lambda-fairy/rust-errno',
+ },
+ {
+ name: 'linux-raw-sys',
+ version: '0.12.1',
+ license: 'Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT',
+ repository: 'https://github.com/sunfishcode/linux-raw-sys',
+ },
+ {
+ name: 'rustix',
+ version: '1.1.4',
+ license: 'Apache-2.0 WITH LLVM-exception OR Apache-2.0 OR MIT',
+ repository: 'https://github.com/bytecodealliance/rustix',
+ },
+]
+
+const RUST_NATIVE_CRATES = [
+ ...RUST_NATIVE_HOST_CRATES,
+ ...RUST_FINALIZE_ADDITIONAL_CRATES,
+]
+
const RUST_LICENSE_FILES = [
+ {
+ file: 'rust-rustix-COPYRIGHT',
+ sha256: '377c2e7c53250cc5905c0b0532d35973392af16ffb9596a41d99d202cf3617c9',
+ },
+ {
+ file: 'rust-linux-raw-sys-COPYRIGHT',
+ sha256: '3290ae0fbc9ddb77d2239121d710f0bb9d31b3b4744e6d97fe01e652b4c1870b',
+ },
+ {
+ file: 'rust-bitflags-LICENSE-MIT',
+ sha256: '6485b8ed310d3f0340bf1ad1f47645069ce4069dcc6bb46c7d5c6faf41de1fdb',
+ },
+ {
+ file: 'rust-errno-LICENSE-MIT',
+ sha256: '8764a597675778ddfd4e25f81b08a05dbcf089ac05662df7613fe67f150e3aa2',
+ },
+ {
+ file: 'rust-linux-raw-sys-LICENSE-MIT',
+ sha256: '23f18e03dc49df91622fe2a76176497404e46ced8a715d9d2b67a7446571cca3',
+ },
+ {
+ file: 'rust-rustix-LICENSE-MIT',
+ sha256: '23f18e03dc49df91622fe2a76176497404e46ced8a715d9d2b67a7446571cca3',
+ },
+
{
file: 'rust-base64-LICENSE-APACHE',
sha256: 'a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2',
@@ -436,7 +493,7 @@ describe('third-party graph dependency notices', () => {
it('keeps every finalize filesystem crate inside the reviewed Rust inventory', async () => {
const cargoLock = await readFile(FINALIZE_FS_CARGO_LOCK, 'utf8')
const reviewed = new Set(
- RUST_NATIVE_HOST_CRATES.map(({ name, version }) => `${name}@${version}`)
+ RUST_NATIVE_CRATES.map(({ name, version }) => `${name}@${version}`)
)
expect(
@@ -447,11 +504,11 @@ describe('third-party graph dependency notices', () => {
})
it.each(['THIRD_PARTY_NOTICES.md', 'THIRD_PARTY_NOTICES.zh-CN.md'])(
- '%s records every locked native-host crate and SPDX expression',
+ '%s records every reviewed native crate and SPDX expression',
async (noticeFile) => {
const notice = await readFile(path.join(ROOT, noticeFile), 'utf8')
- for (const crate of RUST_NATIVE_HOST_CRATES) {
+ for (const crate of RUST_NATIVE_CRATES) {
expect(notice).toContain(
`| ${crate.name} | ${crate.version} | \`${crate.license}\` | <${crate.repository}> |`
)
diff --git a/tests/scripts/normalize-flatpak-cargo-sources.test.ts b/tests/scripts/normalize-flatpak-cargo-sources.test.ts
index 2073614d..e7c16ccd 100644
--- a/tests/scripts/normalize-flatpak-cargo-sources.test.ts
+++ b/tests/scripts/normalize-flatpak-cargo-sources.test.ts
@@ -1,6 +1,9 @@
import { describe, expect, it } from 'vitest'
// @ts-expect-error -- JavaScript packaging script intentionally has no declarations
-import { serializeFlatpakCargoSources } from '../../scripts/normalize-flatpak-cargo-sources.mjs'
+import {
+ mergeFlatpakCargoSources,
+ serializeFlatpakCargoSources,
+} from '../../scripts/normalize-flatpak-cargo-sources.mjs'
describe('serializeFlatpakCargoSources', () => {
it('serializes with two-space indent and a trailing newline', () => {
@@ -14,3 +17,36 @@ describe('serializeFlatpakCargoSources', () => {
)
})
})
+
+describe('mergeFlatpakCargoSources', () => {
+ const archive = { type: 'archive', dest: 'cargo/vendor/a-1', sha256: 'a' }
+ const checksum = {
+ type: 'inline',
+ dest: 'cargo/vendor/a-1',
+ 'dest-filename': '.cargo-checksum.json',
+ contents: 'a',
+ }
+ const config = {
+ type: 'inline',
+ dest: 'cargo',
+ 'dest-filename': 'config',
+ contents: 'registry',
+ }
+ it('merges both locks deterministically without duplicating registry config', () => {
+ const additional = { ...archive, dest: 'cargo/vendor/b-1' }
+ expect(
+ mergeFlatpakCargoSources(
+ [config, checksum, archive],
+ [additional, archive, config]
+ )
+ ).toEqual([archive, checksum, additional, config])
+ })
+ it('rejects conflicting checksums or registry config', () => {
+ expect(() =>
+ mergeFlatpakCargoSources([archive], [{ ...archive, sha256: 'b' }])
+ ).toThrow('Conflicting Cargo source')
+ expect(() =>
+ mergeFlatpakCargoSources([config], [{ ...config, contents: 'different' }])
+ ).toThrow('Conflicting Cargo source')
+ })
+})