Skip to content

Commit 4896c4d

Browse files
committed
feat(atomic): add retained-directory file staging
Add stageFileInDirectory under advanced with one owner for exclusive preparation, identity checks, publication, abort cleanup, and disposal. Retain the original parent descriptor so moving its pathname cannot strand an otherwise owned unpublished temporary file. Share the lifecycle with POSIX native streaming writes. Keep unpublished contents private until the published entry is identity-checked, preserve native error provenance, and distinguish committed or uncertain outcomes from failures that still permit abort cleanup. The new API requires native support on Linux/macOS. Existing Windows and JavaScript fallback contracts remain intact. Application authorization, cooperative locking, rollback, expected-inode publication, and crash recovery remain outside this lifecycle. Add real-filesystem regressions, fault/lifecycle coverage, public API documentation, and native CI coverage without changing dependencies or publishing a package.
1 parent f88c3d1 commit 4896c4d

25 files changed

Lines changed: 1879 additions & 162 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: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
- 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.
88
- 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.
9+
- 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.
910
- Fail closed when synchronous sidecar compromise checks hit I/O errors and invoke `onCompromised` once instead of throwing from the interval. Thanks @SebTardif.
1011

1112
### 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: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -86,9 +86,20 @@ 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.
92103

93104
## JavaScript fallback guarantees and delta
94105

‎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: 176 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,176 @@
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. Concurrent calls are serialized in
93+
invocation order, including cleanup and disposal. Repeated cleanup returns the
94+
recorded outcome, or repeats the recorded error, without touching descriptors.
95+
96+
## Publication and failure evidence
97+
98+
`publish()` requires an explicit boolean `overwrite` and one direct-child
99+
basename. Empty, dot, dotdot, separators, absolute paths, NUL, control characters,
100+
drive-relative spellings, and the stage's own name are rejected.
101+
102+
With `overwrite: false`, publication is genuine kernel no-replace rename; a
103+
collision leaves both names unchanged and raises `FsSafeError("already-exists")`.
104+
The stage may then be cleaned or published under another name. With
105+
`overwrite: true`, publication is plain atomic replacement. Neither route
106+
copies. Both source and destination resolve through the retained original
107+
parent, with checks immediately before rename and after publication.
108+
109+
`PublishedFileReceipt` has `status: "published"`, `staged`, `basename`, and
110+
`overwrite`. Its `staged` field retains the private preparation snapshot, not
111+
final metadata. Errors from publication carry typed `StagedFileFailureDetails`
112+
in `FsSafeError.details`, including `phase` and `publication`. Publication is
113+
`not-published`, `published` (with its receipt), or `indeterminate` (with the
114+
attempted basename and overwrite policy) if a rename error cannot establish
115+
whether it committed. The underlying error remains in `cause`.
116+
117+
A parent move after the final pre-check cannot divert the rename to a
118+
replacement parent. It can publish inside the moved original and then fail
119+
post-validation. Successful rename is recorded before those checks; cleanup
120+
never deletes or rolls back a published final name. Indeterminate publication
121+
also preserves names for caller-directed recovery.
122+
123+
The same rule applies if applying the published mode, synchronizing, or a later
124+
check fails: the error reports `published`, and cleanup preserves the final
125+
name. The file may still have mode `0600` or may already have the requested
126+
mode, depending on which operation failed. A `published` failure receipt records
127+
rename success, not successful permission finalization.
128+
129+
## Cleanup guarantee and limits
130+
131+
If the temporary basename still names the object created by this lifecycle and
132+
filesystem removal remains permitted, moving or replacing the actual parent
133+
(or an ancestor) does not strand the unpublished temp. Cleanup resolves through
134+
the retained original directory, even after `assertCurrent()` rejects drift.
135+
Same-name sentinels in the replacement parent are not touched.
136+
137+
`StagedFileCleanupReceipt` records `temporaryBasename`, `publication`,
138+
`resources` (`closed` or `close-failed`), and `status`:
139+
140+
| Status | Meaning |
141+
|---|---|
142+
| `removed` | The owned recorded name was unlinked through the retained directory. |
143+
| `name-absent` | That name was absent in the original directory; this does not prove the inode has no other names. |
144+
| `preserved` | An observed substitute or an indeterminate publication was left alone. |
145+
| `failed` | Inspection or removal failed. |
146+
| `not-needed` | Publication was recorded, or preparation failed before creating a file. |
147+
148+
Explicit cleanup returns preservation outcomes. Removal or close failures throw
149+
an `FsSafeError` with the receipt in `details.cleanup` and underlying errors in
150+
`cause`. Disposal also throws for preservation, so ignoring its return value
151+
cannot hide incomplete cleanup. Setup failures preserve the original error;
152+
when cleanup also fails, an aggregate cause retains both failures. Descriptors
153+
are closed on every cleanup outcome, with no retry through recycled numbers.
154+
155+
This is **directory-relative targeting**, not expected-destination-inode/CAS
156+
publication. Checking an identity before rename does not make rename CAS.
157+
Likewise, the identity check followed by `unlinkat` is not an atomic conditional
158+
unlink: an adversary can replace the leaf in that final syscall gap. Observed
159+
substitutions are preserved, but this API does not guarantee recovery after
160+
arbitrary child renames, permission revocation, I/O failure, or process death.
161+
Keep application authorization, manager checks, snapshots, fingerprints,
162+
cooperative locks, and conditional rollback.
163+
164+
Namespace cleanup is not crash durability. Staging retains the native writer's
165+
file synchronization behavior, and publication synchronizes its directory
166+
(with the existing `EPERM` exception); cleanup does not promise a durable unlink.
167+
No successful receipt promises survival across a crash. See [Directory
168+
durability](durability.md) when an application needs a separate durability proof.
169+
`pinDirectory().assertCurrent()` and `.sync()` still require a current pathname;
170+
they do not gain this cleanup authority.
171+
172+
## Related pages
173+
174+
- [Advanced composition](advanced.md)
175+
- [Native architecture](native.md)
176+
- [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)