Skip to content

Commit d733275

Browse files
authored
feat(atomic): add retained-directory file staging (#151)
Add stageFileInDirectory to the advanced API on Linux/macOS, retaining the original directory for abort cleanup after parent or ancestor moves. Keep staged contents private until publication is identity-fenced, record publication and cleanup outcomes, and preserve published or indeterminate names for caller-owned reconciliation. Share the lifecycle with POSIX native pinned writes and consolidate admission, disposal, byte writing, and exact Unix child cleanup. Preserve Windows and documented native-absent/off fallback contracts. Directory-relative cleanup is not destination CAS or atomic conditional unlink; authorization, checks, coordination, and rollback remain caller-owned. Validated with 59 independent live consumer cases, native fault/adjacent regressions, Rust checks, full local checks, and green final-head cross-platform CI, coverage, package smoke, benchmarks, and CodeQL. Net production addition is +623 after the ownership cleanup. No dependency/version change, publication, OpenClaw adoption, or separate Root mode-000 repair is included. Live proof and review disposition: #151 (comment)
1 parent 9603da1 commit d733275

29 files changed

Lines changed: 1929 additions & 195 deletions

‎.github/workflows/ci.yml‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,7 @@ jobs:
113113
- name: Test native security and path equivalence
114114
env:
115115
FS_SAFE_PAX_REQUIRE_NATIVE: "1"
116-
run: pnpm test test/native-integration.test.ts test/native-write-containment.test.ts test/native-archive-equivalence.test.ts test/native-publish-equivalence.test.ts test/private-directory.test.ts test/archive-pax.test.ts test/archive-pax-security.test.ts test/archive-pax-compressed.test.ts
116+
run: pnpm test test/native-integration.test.ts test/native-write-containment.test.ts test/native-staging-regression.test.ts test/staged-file.test.ts test/staged-file-failures.test.ts test/native-archive-equivalence.test.ts test/native-publish-equivalence.test.ts test/private-directory.test.ts test/archive-pax.test.ts test/archive-pax-security.test.ts test/archive-pax-compressed.test.ts
117117

118118
native-musl:
119119
name: Native check (linux-x64-musl)
@@ -135,7 +135,7 @@ jobs:
135135
node scripts/native-mode-smoke.mjs auto
136136
node scripts/native-mode-smoke.mjs require
137137
node scripts/native-mode-smoke.mjs off
138-
FS_SAFE_PAX_REQUIRE_NATIVE=1 pnpm test test/native-write-containment.test.ts test/native-archive-equivalence.test.ts test/native-publish-equivalence.test.ts test/archive-pax.test.ts test/archive-pax-security.test.ts test/archive-pax-compressed.test.ts
138+
FS_SAFE_PAX_REQUIRE_NATIVE=1 pnpm test test/native-write-containment.test.ts test/native-staging-regression.test.ts test/staged-file.test.ts test/staged-file-failures.test.ts test/native-archive-equivalence.test.ts test/native-publish-equivalence.test.ts test/archive-pax.test.ts test/archive-pax-security.test.ts test/archive-pax-compressed.test.ts
139139
'
140140
141141
cargo-quality:

‎CHANGELOG.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@
77
- Preserve underlying command diagnostics (command, timing, timeout flag, exit code/signal, and sanitized stderr) and cause on Windows ACL `permission-unverified` errors without changing verification semantics.
88
- Preserve filesystem failures from `ensureDirectoryWithinRoot()` and `pathScope().ensureDir()` in an optional operational `FsSafeError` diagnostic with the original cause and bounded, escaped display text, instead of misreporting them as containment violations; keep nonthrowing string results and directory safety checks.
99
- Accept bounded local PAX paths, sizes, and descriptive metadata, including inert binary macOS provenance xattrs, consistently in JavaScript and native TAR extraction/reads; reject ambiguous records, extension chains, and sparse semantics while retaining byte/count limits and guarded staging. Return TAR read traversal failures through the public promise instead of escaping the parser callback.
10+
- Add native-required Linux/macOS `stageFileInDirectory()` under `advanced` with retained-directory abort cleanup, private `0600` staging until publication is identity-checked, exact identity checks, explicit publication/cleanup receipts, and async disposal; share that ownership with POSIX native streaming writes so parent moves no longer strand their unpublished temps.
11+
- Share native writer admission and direct-child cleanup mechanisms; preserve combined POSIX coordinator operation/disposal failures with `SuppressedError` while keeping staged preparation/cleanup receipts and Windows close policy unchanged.
1012
- Fail closed when synchronous sidecar compromise checks hit I/O errors and invoke `onCompromised` once instead of throwing from the interval. Thanks @SebTardif.
1113

1214
### Docs and Tooling

‎README.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -284,6 +284,12 @@ publication policy, creation callback, and platform contract.
284284

285285
## Atomic writes
286286

287+
For preparation that must survive a parent rename until abort cleanup, use
288+
[`stageFileInDirectory()`](docs/staged-file.md) from `advanced`. It retains the
289+
original directory on Linux/macOS and requires native support for this operation.
290+
It offers atomic replace/no-replace publication, not expected-inode replacement
291+
or a crash-durability promise; application checks and coordination remain yours.
292+
287293
`replaceFileAtomic()` writes a sibling temp file, applies its exact mode through the still-open descriptor, optionally fsyncs it, and renames it over the destination. It never follows the published destination path to set file permissions. Mode preservation, pinned-destination hardlink rejection, rename retry / copy fallback on `EPERM`, bounded original-content restoration after a torn fallback, parent-directory fsync, and a `beforeRename` hook for backup or observer flows are all opt-in. `movePathWithCopyFallback()` stages cross-device moves before commit and removes only the copied source entries, so concurrent source additions or replacements are preserved.
288294

289295
```ts

‎docs/advanced.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,7 @@ component is followed by another segment, both helpers throw
116116

117117
| Export | Page | Notes |
118118
|---|---|---|
119+
| `stageFileInDirectory`, `StagedFile`, `StagedFileReceipt`, `PublishedFileReceipt`, `StagedFilePublication`, `StagedFileCleanupReceipt`, `StagedFileFailureDetails` | [staged-file.md](staged-file.md) | Native-required Linux/macOS lifecycle retaining the original directory for abort cleanup. |
119120
| `tempFile`, `withTempFile`, `TempFile`, `buildRandomTempFilePath`, `sanitizeTempFileName` | [temp.md](temp.md) | One-file temp primitive; prefer `tempWorkspace` from `@openclaw/fs-safe/temp` for the stable surface. |
120121
| `writeSiblingTempFile`, `writeViaSiblingTempPath`, `WriteSiblingTempFileOptions`, `WriteSiblingTempFileResult` | – | Sibling-temp write building block used by `replaceFileAtomic`. |
121122

‎docs/durability.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,12 @@ into proof for a different directory.
6363

6464
Call `close()` in `finally`. Closing is idempotent; using a closed pin fails.
6565

66+
These checks intentionally reject a moved or replaced pathname. For one file's
67+
abort cleanup through its original directory after a move, use the separate
68+
[retained-directory staging lifecycle](staged-file.md). Its cleanup authority
69+
does not weaken `pinDirectory().assertCurrent()` or `.sync()`, and namespace
70+
cleanup is not proof of crash durability.
71+
6672
## Durable directory creation
6773

6874
`ensureDurableDirectory()` finds and pins the nearest existing ancestor,

‎docs/native-helper.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,11 @@ The equivalent environment variables are `FS_SAFE_NATIVE_MODE` and `OPENCLAW_FS_
2727

2828
Configure the mode once during startup. Loading is lazy and cached; changing from `auto` to `require` after a failed load changes failure policy but does not repeatedly probe the binary.
2929

30+
[`stageFileInDirectory()`](staged-file.md) always requires native support on
31+
Linux/macOS and rejects before creation when off, unavailable, or missing the
32+
required capability. Windows is unsupported for this lifecycle. This does not
33+
change the mode policy of existing fallback-capable APIs.
34+
3035
## Native boundary
3136

3237
The bundled native layer exposes policy-free filesystem mechanisms: beneath-root

‎docs/native.md‎

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -86,9 +86,24 @@ workers rather than the JavaScript event loop.
8686
| `require` | Try once, cache the result | Throw `FsSafeError("helper-unavailable")` |
8787
| `off` | Never attempt a binding load | Always use guarded JavaScript |
8888

89-
The one exception is functionality with no safe JavaScript implementation:
90-
zstd/bzip2 TAR and Windows private-directory creation fail with
91-
`helper-unavailable` when native support is absent or off.
89+
Features without a safe JavaScript implementation, including zstd/bzip2 TAR,
90+
Windows private-directory creation, and [retained-directory staging](staged-file.md),
91+
fail with `helper-unavailable` when native support is absent or off. Staging
92+
is currently Linux/macOS only and rejects Windows with `unsupported-platform`.
93+
94+
The staged-file owner also serves POSIX native pinned writes, including streaming.
95+
Unpublished files remain at `0600`; requested modes are applied through the
96+
owned file descriptor only after rename and published-entry identity validation.
97+
Post-rename chmod or sync failures retain the publication receipt and final name.
98+
Its direct-child exclusive `openat` hands off the descriptor before any fallible
99+
post-open checks; non-following `statat` compares against that descriptor with
100+
exact native identities, and cleanup uses `unlinkat` in the retained parent.
101+
The separate checks and unlink are not atomic conditional deletion. Windows
102+
pinned writes and other fallback-capable APIs retain their existing mechanisms.
103+
Native writers share root and parent admission, but keep their platform identity
104+
checks and leaf ownership. POSIX coordinator disposal uses `SuppressedError` to
105+
retain both an operation failure and a disposal failure, including their receipts;
106+
stage preparation and cleanup keep their documented error mappings.
92107

93108
## JavaScript fallback guarantees and delta
94109

‎docs/security-model.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,14 @@ parent symlink. A same-privilege peer with write access to the parent can
7070
therefore cause an out-of-root side effect before the operation throws. Use
7171
native `require` mode when concurrent hostile mutation is in scope.
7272

73+
The separate [retained-directory staging lifecycle](staged-file.md) keeps abort
74+
cleanup anchored to the original directory after a parent or ancestor move.
75+
It preserves observed substituted temporary entries and never cleans a recorded
76+
publication. Directory anchoring is not expected-inode/CAS replacement, and
77+
identity-check-then-unlink is not atomic conditional unlink. The guarantee
78+
requires the temporary name to remain owned and removal to remain permitted;
79+
application authorization and cooperative coordination remain necessary.
80+
7381
### Hardlink aliasing
7482

7583
When `hardlinks: "reject"` is set, reads stat the target and refuse if `nlink > 1`, on the conservative assumption that a hardlinked file might alias an out-of-tree inode. This is defense-in-depth: the link count check is best-effort and platform-dependent. Treat it as a tripwire, not authorization.

‎docs/staged-file.md‎

Lines changed: 178 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,178 @@
1+
---
2+
title: Retained-directory staging
3+
description: "Prepare and publish one file while retaining its original directory for abort cleanup."
4+
---
5+
6+
# Retained-directory staging
7+
8+
`stageFileInDirectory()` from `@openclaw/fs-safe/advanced` prepares one file in
9+
an existing directory and keeps that directory open until cleanup or disposal.
10+
It requires the native binding on Linux or macOS, even in native mode `auto`.
11+
Native off, an unavailable binding, or a binding without the required mechanism
12+
fails before file creation. Windows is explicitly unsupported for this API.
13+
Existing root, output, temp, lock, and durability APIs retain their documented
14+
platform and fallback contracts.
15+
16+
```ts
17+
import type { DirectoryReceipt } from "@openclaw/fs-safe/durability";
18+
import {
19+
stageFileInDirectory,
20+
type PublishedFileReceipt,
21+
} from "@openclaw/fs-safe/advanced";
22+
23+
// Call while holding the application's cooperative writer lock. The caller
24+
// supplies its authorization, manager, snapshot, and fingerprint checks.
25+
export async function publishReviewedUpdate(options: {
26+
directory: DirectoryReceipt;
27+
basename: string;
28+
bytes: Uint8Array;
29+
assertAuthorizedAndCurrent(): Promise<void>;
30+
}): Promise<PublishedFileReceipt> {
31+
await options.assertAuthorizedAndCurrent();
32+
await using staged = await stageFileInDirectory({
33+
directory: options.directory,
34+
content: options.bytes,
35+
});
36+
await options.assertAuthorizedAndCurrent();
37+
await staged.assertCurrent();
38+
return await staged.publish(options.basename, { overwrite: true });
39+
}
40+
```
41+
42+
`await using` always disposes, including on exceptions. If both the body and
43+
disposal fail, JavaScript preserves both errors in a `SuppressedError`. A
44+
successful return means publication was observed and verified, not that a
45+
separate application transaction committed. Application rollback and recovery
46+
remain with the caller.
47+
48+
## API
49+
50+
```ts
51+
function stageFileInDirectory(options: {
52+
directory: string | DirectoryReceipt;
53+
content: string | Uint8Array;
54+
mode?: number;
55+
}): Promise<StagedFile>;
56+
57+
interface StagedFile extends AsyncDisposable {
58+
readonly receipt: StagedFileReceipt;
59+
assertCurrent(): Promise<void>;
60+
publish(basename: string, options: { overwrite: boolean }): Promise<PublishedFileReceipt>;
61+
cleanup(): Promise<StagedFileCleanupReceipt>;
62+
}
63+
```
64+
65+
Strings are UTF-8. `mode` is the requested **published** mode and defaults to
66+
`0600`; exact final modes, including `000`, are supported. The unpublished file
67+
stays at `0600` throughout preparation and any awaited application checks.
68+
After rename succeeds and the published entry passes identity validation, the
69+
owner applies the requested mode through its retained file descriptor and
70+
synchronizes the file. No parent is created or chmodded.
71+
Creation uses an exclusive, no-follow, close-on-exec open of a generated direct
72+
child name. Writes use that descriptor. Inspection uses non-following metadata
73+
operations, never a potentially blocking reopen of the leaf.
74+
75+
A supplied directory receipt must still match at admission. Its numeric
76+
identity must be exactly representable; ambiguous identity fails closed.
77+
Returned receipts are frozen descriptive snapshots, not mutable authority.
78+
Changing a supplied receipt after admission cannot retarget the lifecycle.
79+
80+
`StagedFileReceipt` contains `directory` (`path`, `realPath`, and exact bigint
81+
`identity.dev`/`identity.ino`), `temporaryBasename`, and the prepared file's
82+
`identity` (`dev`, `ino`, `size`, `nlink`, `mtimeNs`, `ctimeNs` as bigint;
83+
`mode`, `uid`, `gid` as numbers). This is a preparation-time snapshot of the
84+
private stage: its mode is `0600`. Publication does not refresh this snapshot;
85+
neither its mode nor its timestamps are a final-file fingerprint. No raw
86+
descriptors are exposed.
87+
88+
`assertCurrent()` verifies the original pathname's directory identity and the
89+
staged name against the retained file. A failed check does not disable cleanup.
90+
After successful publication there is no staged name to check, so further
91+
checks or publication reject. Cleanup closes the lifecycle; later checks and
92+
publication reject before descriptor use. Rejected publication still carries its
93+
phase, cause, and recorded publication outcome after closure. Concurrent calls
94+
are serialized in invocation order, including cleanup and disposal. Repeated
95+
cleanup returns the recorded outcome, or repeats the recorded error, without
96+
touching descriptors.
97+
98+
## Publication and failure evidence
99+
100+
`publish()` requires an explicit boolean `overwrite` and one direct-child
101+
basename. Empty, dot, dotdot, separators, absolute paths, NUL, control characters,
102+
drive-relative spellings, and the stage's own name are rejected.
103+
104+
With `overwrite: false`, publication is genuine kernel no-replace rename; a
105+
collision leaves both names unchanged and raises `FsSafeError("already-exists")`.
106+
The stage may then be cleaned or published under another name. With
107+
`overwrite: true`, publication is plain atomic replacement. Neither route
108+
copies. Both source and destination resolve through the retained original
109+
parent, with checks immediately before rename and after publication.
110+
111+
`PublishedFileReceipt` has `status: "published"`, `staged`, `basename`, and
112+
`overwrite`. Its `staged` field retains the private preparation snapshot, not
113+
final metadata. Errors from publication carry typed `StagedFileFailureDetails`
114+
in `FsSafeError.details`, including `phase` and `publication`. Publication is
115+
`not-published`, `published` (with its receipt), or `indeterminate` (with the
116+
attempted basename and overwrite policy) if a rename error cannot establish
117+
whether it committed. The underlying error remains in `cause`.
118+
119+
A parent move after the final pre-check cannot divert the rename to a
120+
replacement parent. It can publish inside the moved original and then fail
121+
post-validation. Successful rename is recorded before those checks; cleanup
122+
never deletes or rolls back a published final name. Indeterminate publication
123+
also preserves names for caller-directed recovery.
124+
125+
The same rule applies if applying the published mode, synchronizing, or a later
126+
check fails: the error reports `published`, and cleanup preserves the final
127+
name. The file may still have mode `0600` or may already have the requested
128+
mode, depending on which operation failed. A `published` failure receipt records
129+
rename success, not successful permission finalization.
130+
131+
## Cleanup guarantee and limits
132+
133+
If the temporary basename still names the object created by this lifecycle and
134+
filesystem removal remains permitted, moving or replacing the actual parent
135+
(or an ancestor) does not strand the unpublished temp. Cleanup resolves through
136+
the retained original directory, even after `assertCurrent()` rejects drift.
137+
Same-name sentinels in the replacement parent are not touched.
138+
139+
`StagedFileCleanupReceipt` records `temporaryBasename`, `publication`,
140+
`resources` (`closed` or `close-failed`), and `status`:
141+
142+
| Status | Meaning |
143+
|---|---|
144+
| `removed` | The owned recorded name was unlinked through the retained directory. |
145+
| `name-absent` | That name was absent in the original directory; this does not prove the inode has no other names. |
146+
| `preserved` | An observed substitute or an indeterminate publication was left alone. |
147+
| `failed` | Inspection or removal failed. |
148+
| `not-needed` | Publication was recorded, or preparation failed before creating a file. |
149+
150+
Explicit cleanup returns preservation outcomes. Removal or close failures throw
151+
an `FsSafeError` with the receipt in `details.cleanup` and underlying errors in
152+
`cause`. Disposal also throws for preservation, so ignoring its return value
153+
cannot hide incomplete cleanup. Setup failures preserve the original error;
154+
when cleanup also fails, an aggregate cause retains both failures. Descriptors
155+
are closed on every cleanup outcome, with no retry through recycled numbers.
156+
157+
This is **directory-relative targeting**, not expected-destination-inode/CAS
158+
publication. Checking an identity before rename does not make rename CAS.
159+
Likewise, the identity check followed by `unlinkat` is not an atomic conditional
160+
unlink: an adversary can replace the leaf in that final syscall gap. Observed
161+
substitutions are preserved, but this API does not guarantee recovery after
162+
arbitrary child renames, permission revocation, I/O failure, or process death.
163+
Keep application authorization, manager checks, snapshots, fingerprints,
164+
cooperative locks, and conditional rollback.
165+
166+
Namespace cleanup is not crash durability. Staging retains the native writer's
167+
file synchronization behavior, and publication synchronizes its directory
168+
(with the existing `EPERM` exception); cleanup does not promise a durable unlink.
169+
No successful receipt promises survival across a crash. See [Directory
170+
durability](durability.md) when an application needs a separate durability proof.
171+
`pinDirectory().assertCurrent()` and `.sync()` still require a current pathname;
172+
they do not gain this cleanup authority.
173+
174+
## Related pages
175+
176+
- [Advanced composition](advanced.md)
177+
- [Native architecture](native.md)
178+
- [Security model](security-model.md)

‎native/src/lib.rs‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ use napi_derive::napi;
55

66
mod archive;
77
mod fast_file;
8+
#[cfg(unix)]
9+
mod staged_file;
810
mod tar_meter;
911
mod tar_pax;
1012
#[cfg(unix)]
@@ -80,7 +82,7 @@ pub(crate) fn validate_portable_relative_path(path: &str, allow_root: bool) -> N
8082
validate_relative_path_with_separators(path, allow_root, true)
8183
}
8284

83-
fn into_napi<T>(env: Env, result: NativeResult<T>) -> Result<T> {
85+
pub(crate) fn into_napi<T>(env: Env, result: NativeResult<T>) -> Result<T> {
8486
match result {
8587
Ok(value) => Ok(value),
8688
Err(error) => {
@@ -201,6 +203,8 @@ pub use archive::{
201203
pub use fast_file::{
202204
FileHash, NativeCopyResult, clone_file_exclusive, copy_file_range_exclusive, sha256_file,
203205
};
206+
#[cfg(unix)]
207+
pub use staged_file::{create_staged_file, remove_staged_file, staged_file_matches};
204208
pub use windows_security::{
205209
WindowsAccessControlEntry, WindowsAceFlags, WindowsSecurityFacts, create_private_directory,
206210
read_owner_and_dacl,

0 commit comments

Comments
 (0)