Skip to content

A full-featured download manager.

fix(finalize): support ntfs mount masks during cleanup (#2205)

Dr_rOot0785d5c1a5df
diff --git a/packages/finalize-fs/README.md b/packages/finalize-fs/README.md
index c9a362a8..11e7f76a 100644
--- a/packages/finalize-fs/README.md
+++ b/packages/finalize-fs/README.md
@@ -44,11 +44,11 @@ beyond the forbidden set, so non-Latin names survive untouched. Only the final
component is sanitized: directory components are user-created through native
dialogs and are validated, not rewritten, by the platform open path.
-## Linux and NFS
+## Linux, NFS and mounted NTFS
-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
+Linux NFS and NTFS-3G 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
@@ -62,9 +62,15 @@ 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
+Each file removal first journals a new sibling directory requested with mode
+0700 and its device/inode identity. NTFS mount masks can synthesize 0755 even
+when 0700 is requested. Isolation accepts owner read/write/execute with no
+group/other write access; read/execute access does not permit changing names.
+Both the native isolation operation and host recovery check this condition.
+Mounts exposing group/other write access (such as 0777) retain the source and
+cleanup journal after publication instead of weakening the removal checks.
+Ordinary rename is confined to that empty directory owned by the artifact
+owner, 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
@@ -183,3 +189,24 @@ 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.
+
+The ignored native test `ntfs_supports_link_publication_and_private_removal`
+requires `MOTRIX_FINALIZE_NTFS_ROOT` on a scratch NTFS-3G mount with `umask=022`
+and POSIX permissions disabled. It checks the real `EINVAL` rename response,
+exclusive hard-link publication, synthesized 0755 isolation permissions, and
+removal with a verified surviving target. For example, after mounting a test
+image at `/mnt/ntfs-test`:
+
+```sh
+MOTRIX_FINALIZE_NTFS_ROOT=/mnt/ntfs-test cargo test \
+ --manifest-path packages/finalize-fs/Cargo.toml --locked \
+ ntfs_supports_link_publication_and_private_removal -- --ignored
+```
+
+The application recovery suite accepts the same `MOTRIX_FINALIZE_NTFS_ROOT`
+instead of `MOTRIX_FINALIZE_NFS_ROOT`, keeping SQLite on the local filesystem.
+The ordinary native and application tests model mount masks without requiring
+NTFS. The Linux recovery suite also covers a lost isolation response followed
+by restart with 0755 permissions, and preservation of both hard links when
+0777 permissions make cleanup unsafe. Windows uses its existing handle-based
+removal and SMB flush policy; these Unix permission checks do not apply there.
diff --git a/packages/finalize-fs/src/platform/unix/publish.rs b/packages/finalize-fs/src/platform/unix/publish.rs
index 17183f09..c9a54de1 100644
--- a/packages/finalize-fs/src/platform/unix/publish.rs
+++ b/packages/finalize-fs/src/platform/unix/publish.rs
@@ -83,8 +83,11 @@ pub(crate) fn isolate_opened(
let name = checked_name(relative)?;
let source = unchanged_file(artifact)?;
let directory = stat_opened(target.0.as_raw_fd())?;
+ // NTFS mount masks can report 0755 even for mkdir(0700). Isolation needs
+ // exclusive namespace mutation, not exclusive directory read access.
if format!("{}:{}", directory.st_dev, directory.st_ino) != expected_root_identity
- || directory.st_mode & 0o777 != 0o700
+ || directory.st_mode & 0o700 != 0o700
+ || directory.st_mode & 0o022 != 0
|| directory.st_uid != source.st_uid
|| !directory_entries(target.0.as_raw_fd())?.is_empty()
{
diff --git a/packages/finalize-fs/src/platform/unix/tests.rs b/packages/finalize-fs/src/platform/unix/tests.rs
index 2c458655..d4a27484 100644
--- a/packages/finalize-fs/src/platform/unix/tests.rs
+++ b/packages/finalize-fs/src/platform/unix/tests.rs
@@ -254,9 +254,16 @@ fn private_isolation_checks_identity_permissions_and_resumes_removal() {
b"unrelated"
);
std::fs::remove_file(base.join("private/payload")).unwrap();
+ for mode in [0o770, 0o707, 0o777, 0o500] {
+ std::fs::set_permissions(base.join("private"), std::fs::Permissions::from_mode(mode))
+ .unwrap();
+ assert!(super::isolate_opened(&artifact, &private, "payload", &id).is_err());
+ assert_eq!(std::fs::read(base.join("source")).unwrap(), b"complete");
+ assert!(!base.join("private/payload").exists());
+ }
+ // NTFS-3G without POSIX permissions synthesizes this mode on a umask=022
+ // mount, even when mkdir requests 0700. Only the owner can mutate names.
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);
@@ -308,20 +315,33 @@ fn held_link_is_exclusive_and_preserves_the_source() {
#[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");
+ check_mounted_link_publication(&parent, 0x6969, 0o700);
+}
+
+#[cfg(target_os = "linux")]
+#[test]
+#[ignore = "requires MOTRIX_FINALIZE_NTFS_ROOT on NTFS-3G with umask=022 and no POSIX permissions"]
+fn ntfs_supports_link_publication_and_private_removal() {
+ let parent = std::env::var("MOTRIX_FINALIZE_NTFS_ROOT").expect("NTFS test root");
+ check_mounted_link_publication(&parent, 0x65735546, 0o755);
+}
+
+#[cfg(target_os = "linux")]
+fn check_mounted_link_publication(parent: &str, filesystem_type: u64, isolation_mode: u32) {
+ use std::os::unix::fs::{MetadataExt, PermissionsExt};
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::path::Path::new(parent).join(format!("motrix-mounted-{}-{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"
+ filesystem_type,
+ "test root must use the requested filesystem"
);
std::fs::write(base.join("source.motrix"), b"complete download").unwrap();
let artifact = super::open_artifact_for_rename(&root, "source.motrix").unwrap();
@@ -345,6 +365,7 @@ fn nfs_supports_link_publication_and_private_removal() {
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();
+ assert_eq!(metadata.mode() & 0o777, isolation_mode);
super::isolate_opened(
&source,
&private,
@@ -354,12 +375,14 @@ fn nfs_supports_link_publication_and_private_removal() {
.unwrap();
drop(source);
let isolated = open_artifact(&private, "payload").unwrap();
- remove_opened(&isolated, "payload", true).unwrap();
+ let survivor = super::open_artifact_for_rename(&root, "target").unwrap();
+ super::remove_opened_preserving(&isolated, "payload", true, &survivor).unwrap();
drop(isolated);
assert!(!base.join("source.motrix").exists());
assert_eq!(
std::fs::read(base.join("target")).unwrap(),
b"complete download"
);
+ drop(survivor);
std::fs::remove_dir_all(base).unwrap();
}
diff --git a/src/core/plugin/finalize/finalize-nfs-recovery.integration.test.ts b/src/core/plugin/finalize/finalize-nfs-recovery.integration.test.ts
index 8b6b7d65..c9b8aeec 100644
--- a/src/core/plugin/finalize/finalize-nfs-recovery.integration.test.ts
+++ b/src/core/plugin/finalize/finalize-nfs-recovery.integration.test.ts
@@ -1,5 +1,6 @@
import { existsSync } from 'node:fs'
import {
+ chmod,
mkdtemp,
readdir,
readFile,
@@ -26,12 +27,18 @@ const binary = path.resolve(
'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')
+const ntfsRoot = process.env.MOTRIX_FINALIZE_NTFS_ROOT
+if (nfsRoot && ntfsRoot)
+ throw new Error('select one mounted filesystem per run')
+const mountedRoot = nfsRoot ?? ntfsRoot
+if (mountedRoot && (process.platform !== 'linux' || !existsSync(binary))) {
+ throw new Error(
+ 'mounted filesystem contract requires Linux and a built native sidecar'
+ )
}
describe.runIf(process.platform === 'linux' && existsSync(binary))(
- 'NFS finalize publication and recovery',
+ 'NFS and NTFS finalize publication and recovery',
{ timeout: 30_000 },
() => {
const cleanup: (() => Promise<void>)[] = []
@@ -40,13 +47,16 @@ describe.runIf(process.platform === 'linux' && existsSync(binary))(
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)
+ async function setup(crossDevice = false, isolationMode?: number) {
+ if (mountedRoot)
+ expect((await statfs(mountedRoot)).type).toBe(
+ ntfsRoot ? 0x65735546 : 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-'))
+ await mkdtemp(path.join(mountedRoot ?? local, 'motrix-nfs-'))
)
const dbPath = path.join(local, 'journal.sqlite')
let db = new Database(dbPath)
@@ -57,11 +67,22 @@ describe.runIf(process.platform === 'linux' && existsSync(binary))(
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)
+ if (!mountedRoot)
vi.spyOn(adapter, 'renameOpenedNoReplace').mockRejectedValue(
new FinalizeFsError('rename_unsupported', 'NOREPLACE unsupported')
)
fs = new NativeFinalizeArtifactOperations(adapter)
+ if (isolationMode !== undefined) {
+ const prepareRemoval = fs.prepareRemoval.bind(fs)
+ vi.spyOn(fs, 'prepareRemoval').mockImplementation(async (...args) => {
+ const intent = await prepareRemoval(...args)
+ if (!intent.isolation)
+ throw new Error('missing isolation directory')
+ // Model an NTFS mount mask overriding the requested mkdir mode.
+ await chmod(intent.isolation.directory, isolationMode)
+ return intent
+ })
+ }
return new DurableFinalizeRuntime({
db,
fs,
@@ -143,6 +164,52 @@ describe.runIf(process.platform === 'linux' && existsSync(binary))(
}
}
+ it('recovers linked NTFS publication with owner-only writable mount permissions', async () => {
+ const s = await setup(false, 0o755)
+ const isolate = s.adapter.isolateOpened.bind(s.adapter)
+ vi.spyOn(s.adapter, 'isolateOpened').mockImplementationOnce(
+ async (...args) => {
+ await isolate(...args)
+ throw new Error('lost NTFS isolation response')
+ }
+ )
+ await s.runtime.commit(s.input)
+ expect(s.row().phase).toBe('db_committed')
+ expect(existsSync(s.input.sourcePath)).toBe(false)
+ await s.restart()
+ await s.runtime.recoverAll()
+ expect(s.row().phase).toBe('cleaned')
+ expect(await readdir(s.root)).toEqual(['download.bin'])
+ expect(await readFile(s.input.targetPath, 'utf8')).toBe(
+ 'complete download'
+ )
+ })
+
+ // The real NTFS fixture fixes permissions at 0755, so chmod cannot model 0777 there.
+ it.skipIf(ntfsRoot !== undefined)(
+ 'preserves a linked NTFS source when mount permissions allow other writers',
+ async () => {
+ const s = await setup(false, 0o777)
+ await s.runtime.commit(s.input)
+ expect(s.row().phase).toBe('db_committed')
+ await s.restart()
+ await expect(s.runtime.recoverAll()).rejects.toMatchObject({
+ errors: [
+ expect.objectContaining({
+ message: 'private isolation directory changed',
+ }),
+ ],
+ })
+ expect(s.row().phase).toBe('db_committed')
+ expect(await readFile(s.input.sourcePath, 'utf8')).toBe(
+ 'complete download'
+ )
+ expect(await readFile(s.input.targetPath, 'utf8')).toBe(
+ 'complete download'
+ )
+ }
+ )
+
it.each([false, true])(
'publishes and cleans up (cross-device: %s)',
async (crossDevice) => {
@@ -151,7 +218,7 @@ describe.runIf(process.platform === 'linux' && existsSync(binary))(
const copy = vi.spyOn(s.adapter, 'copyOpened')
await s.runtime.commit(s.input)
expect(link).toHaveBeenCalledOnce()
- if (crossDevice && nfsRoot) expect(copy).toHaveBeenCalledOnce()
+ if (crossDevice && mountedRoot) expect(copy).toHaveBeenCalledOnce()
else expect(copy).not.toHaveBeenCalled()
expect(s.row().phase).toBe('cleaned')
expect(await readdir(s.root)).toEqual(['download.bin'])
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 213bdd9b..f42eb651 100644
--- a/src/core/plugin/finalize/native-artifact-operations.integration.test.ts
+++ b/src/core/plugin/finalize/native-artifact-operations.integration.test.ts
@@ -1,5 +1,7 @@
import { existsSync } from 'node:fs'
import {
+ chmod,
+ link,
mkdir,
mkdtemp,
readFile,
@@ -244,6 +246,50 @@ describe.runIf(existsSync(binary))(
await adapter.dispose()
})
+ it.runIf(process.platform !== 'win32').each([0o700, 0o755, 0o770, 0o777])(
+ 'checks exclusive directory write access during isolated cleanup (mode %s)',
+ async (mode) => {
+ const { root, adapter, operations } = await setup()
+ const source = path.join(root, 'download.motrix')
+ const target = path.join(root, 'download')
+ try {
+ await writeFile(source, 'complete download')
+ await link(source, target)
+ const identity = await readArtifactIdentity(source)
+ const intent = await operations.prepareRemoval(
+ source,
+ identity,
+ removalQuarantinePath('ntfs-mode', source)
+ )
+ if (!intent.isolation) throw new Error('missing isolation directory')
+ // Model NTFS mount masks overriding mkdir(0700), including on replay
+ // through a new operations instance with no in-memory state.
+ await chmod(intent.isolation.directory, mode)
+ const replay = new NativeFinalizeArtifactOperations(adapter)
+ const removal = replay.removeKnown(
+ source,
+ identity,
+ intent.quarantinePath,
+ intent.isolation,
+ { path: target, identity }
+ )
+ if (mode & 0o022) {
+ await expect(removal).rejects.toThrow(
+ 'private isolation directory changed'
+ )
+ expect(await readFile(source, 'utf8')).toBe('complete download')
+ } else {
+ await removal
+ expect(existsSync(source)).toBe(false)
+ expect(existsSync(intent.isolation.directory)).toBe(false)
+ }
+ expect(await readFile(target, 'utf8')).toBe('complete download')
+ } finally {
+ await adapter.dispose()
+ }
+ }
+ )
+
it('resumes the exact journal quarantine left by a removal crash', async () => {
const { root, adapter, operations } = await setup()
const original = path.join(root, 'crash.bin')
diff --git a/src/core/plugin/finalize/native-artifact-operations.ts b/src/core/plugin/finalize/native-artifact-operations.ts
index 5f9ae9b5..3cda06d8 100644
--- a/src/core/plugin/finalize/native-artifact-operations.ts
+++ b/src/core/plugin/finalize/native-artifact-operations.ts
@@ -253,7 +253,10 @@ export class NativeFinalizeArtifactOperations
!stat.isDirectory() ||
stat.isSymbolicLink() ||
`${stat.dev}:${stat.ino}` !== isolation.platformFileId ||
- (stat.mode & 0o777n) !== 0o700n
+ // NTFS mount masks may expose read/execute bits despite mkdir(0700).
+ // Match the native isolation check: only the owner may mutate names.
+ (stat.mode & 0o700n) !== 0o700n ||
+ (stat.mode & 0o022n) !== 0n
) {
throw new ArtifactIdentityError(
'artifact_mutated',