Skip to content

chore(deps): update @openclaw/fs-safe to 0.8.1 - #138500

Merged
steipete merged 9 commits into
mainfrom
chore/fs-safe-080
Sep 5, 2026
Merged

steipete merged 9 commits into
mainfrom
chore/fs-safe-080

Conversation

@steipete

@steipete steipete commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Updates OpenClaw to @openclaw/fs-safe 0.8.1, which fixes write-path ownership bugs we want (exact file modes through publication, secret-directory identity retained across locks/native writes, failure cleanup that no longer touches replacements) but also intentionally stops repairing existing secret-directory permissions — it now fails with insecure-permissions instead.

Without an adaptation, users with existing world-readable OpenClaw credentials directories (drifted ~/.openclaw state, migrated installs) would start seeing secret writes fail after the update, because the library previously tightened those directories for us.

Why This Change Was Made

  • Bumps @openclaw/fs-safe to 0.8.1 in the root package and the @openclaw/onepassword extension, with the lockfile regenerated from main's so only the fs-safe family moves (0.7.2 → 0.8.1); the supply-chain policy was satisfied by temporarily allowing the old 0.7.2 entries during regeneration, and the committed exclusions cover only 0.8.1.
  • Moves the minimumReleaseAge cooldown exclusions to the 0.8.1 family (published today; removal date 2026-09-11).
  • 0.8.1 adds retainOnExit, which the dist-artifact ownership lock now uses: the fail-closed owner record again survives natural process exit (0.8.0 made exit release the default), and only the explicit release after a joined child removes it.
  • Converts the writePrivateSecretFileAtomic/createSecretFileAtomic pass-throughs in src/infra/secret-file.ts into thin wrappers that tighten existing OpenClaw-owned secret directory modes to 0o700 before delegating, preserving the documented "tightens an existing world-readable directory before writing secrets" behavior. The wrapper walks the lexical path chain and never realpath-resolves first, so a symlinked root or component is left for fs-safe to reject rather than chmodded at its destination. Windows is unchanged (fs-safe does not enforce POSIX modes there).
  • Tightens private file-store roots at creation in src/infra/private-file-store.ts for the same reason — models.json, CLI images, and shared-secret writes go through private stores rooted at OpenClaw-owned dirs.
  • Masks dirMode to permission bits in the doctor transcript repair; raw stat.mode includes file-type bits that 0.8.x's strict final directory-mode check rejects. (Follow-up filed to normalize this input in fs-safe itself.)
  • file-transfer: resolves the symlink canonical target locally when the fs-safe error no longer carries it, preserving the operator-facing canonicalPath detail in SYMLINK_REDIRECT responses.
  • archive test: 0.8.x preserves the destination when a raced hardlink is rejected (deliberate fs-safe change); assertions updated to match.
  • whatsapp session test: 0.8.x skips the parent-directory chmod when the directory already has the target mode; assertion updated to the conditional behavior.

Other 0.8.x upgrade notes were audited and need no changes: FileStore keys are already portable (content-addressed media/store keys), no lock payload approaches the 1 MiB cap, and the propagated lock/queue failures already surface as rejections our callers handle. The create-only visibility scoping matches our existing relay-auth workaround comment.

User Impact

Users keep current behavior: OpenClaw tightens its own credential directories and writes secrets successfully. No action required on upgrade.

Evidence

  • pnpm install resolves @openclaw/[email protected] (root + extension) with lockfile regenerated via pnpm clean --lockfile && pnpm install after the strict cooldown rejected stale entries.
  • pnpm tsgo:core and pnpm tsgo:extensions:all clean.
  • First CI run exposed four behavior-boundary failures on the plain bump; each is reproduced locally and fixed here:
    • secret-file.test.ts (18/18) — private-dir refusal, fixed by the write wrapper.
    • models-config.runtime-source-snapshot.test.ts, cli-runner.helpers.test.ts, models-config.skips-writing-models-json-no-env-token.test.ts — private-store root refusal, fixed by the store factory tightening.
    • doctor-session-transcripts.test.ts (11/11) — raw stat.mode as dirMode, fixed by masking.
    • file-write.test.ts — lost canonicalPath error detail, resolved locally now.
    • archive.test.ts (17/17) — raced-hardlink cleanup semantics updated to match 0.8.x's destination-preserving behavior.
  • Second CI run exposed the dist-artifact retention regression (0.8.0 releases sidecar locks on natural exit); fixed by fs-safe 0.8.1's retainOnExit (feat(file-lock): add retainOnExit opt-out for process-exit cleanup fs-safe#227), adopted in scripts/lib/dist-artifact-ownership.mts, plus the whatsapp chmod assertion.

fs-safe 0.8.0 stops repairing existing secret-directory permissions and fails closed instead. Wrap OpenClaw secret writes to tighten OpenClaw-owned directory modes before delegating, preserving the documented tighten-then-write behavior. Move the cooldown exclusions to the 0.8.0 family.
@steipete
steipete requested a review from a team as a code owner September 4, 2026 18:44
@clawsweeper

clawsweeper Bot commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added extensions: onepassword 1Password plugin size: S maintainer Maintainer-authored PR labels Sep 4, 2026
@github-actions

github-actions Bot commented Sep 4, 2026

Copy link
Copy Markdown
Contributor

Dependency Guard

This PR changes dependency-related files. Maintainers should confirm these changes are intentional.

Changed files:

  • extensions/onepassword/package.json
  • package.json
  • pnpm-lock.yaml
  • pnpm-workspace.yaml

Maintainer follow-up:

  • Review whether the dependency changes are intentional.
  • Inspect resolved package deltas when lockfiles or workspace dependency policy changes are present.
  • Treat pnpm-lock.yaml and package-lock.json diffs as dependency security-review surfaces.
  • Run pnpm deps:changes:report -- --base-ref origin/main --markdown /tmp/dependency-changes.md --json /tmp/dependency-changes.json locally for detailed release-style evidence.

@github-actions github-actions Bot added the dependencies-changed PR changes dependency-related files label Sep 4, 2026
@github-actions

github-actions Bot commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

Dependency graph changes noted

This PR includes dependency graph changes. The dependency guard is informational because the PR author is a repository admin, a member of @openclaw/openclaw-secops, or an OpenClaw organization member with Maintain or Admin repository access.

  • Current SHA: d7b5e906d678f325071c622e98365005aeb84326
  • Trusted actor: @steipete
  • Trusted role: pull request author; openclaw-secops

Security review is still recommended before merge when the dependency graph change is intentional.

@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Sep 4, 2026
@clawsweeper

clawsweeper Bot commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 4, 2026, 11:06 PM ET / September 5, 2026, 03:06 UTC.

ClawSweeper review

What this changes

Updates fs-safe to 0.8.1 and adapts directory permissions, build locks, transcript repair, file-transfer diagnostics, and regression tests to preserve existing behavior.

Merge readiness

⛔ Blocked before merge - 2 items remain

Keep open: current main still uses fs-safe 0.7.2, so this maintainer-owned upgrade remains useful. Earlier findings are fixed or explicitly dispositioned; no new blocking patch defect was found.

Priority: P2
Reviewed head: d7b5e906d678f325071c622e98365005aeb84326

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused upgrade with compatibility adaptations, relevant regression coverage, and addressed prior findings.
Proof confidence 🌊 off-meta tidepool Not applicable: The maintainer-authored PR is exempt from the ordinary contributor-proof gate. Reported filesystem and process tests support the changed adapters and lock retention but are not claimed as live setup proof; no unresolved cross-principal authority change was established.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The maintainer-authored PR is exempt from the ordinary contributor-proof gate. Reported filesystem and process tests support the changed adapters and lock retention but are not claimed as live setup proof; no unresolved cross-principal authority change was established.
Evidence reviewed 13 items Pinned introduction verified: The checkout matches the supplied original head. Its raw parents match the recorded parents, and the reviewed delta is the pinned base-to-head change. The stale test merge was not used to infer removal of current-main behavior.
Upgrade remains absent from current main: Fetched main pins fs-safe 0.7.2 and retains direct secret-write re-exports. No same-repository merged replacement was established; the supplied related reference concerns a separate dependency repository.
Dependency boundary: The changed adapters directly import fs-safe secret/store APIs, and this document identifies openclaw/fs-safe as the filesystem implementation. The changed behavior does not depend on the Codex runtime or protocol.
Findings None None.
Security None None.

How this fits together

OpenClaw delegates security-sensitive filesystem operations to fs-safe. Its adapters connect credential and private-file writes to guarded disk operations, while build tooling uses filesystem locks to protect shared outputs.

flowchart TD
  A[Credential and private-file writes] --> B{Existing real directory?}
  B -->|Yes| C[Descriptor permission repair]
  B -->|Missing or rejected| D[fs-safe validation]
  C --> D
  D --> E[Atomic files or explicit errors]
  F[Build and check commands] --> G[Retained ownership lock]
  G --> H[Child processes finish]
  H -->|Explicit release| G
Loading

Before merge

  • Resolve merge risk (P1) - Independent fs-safe 0.8.1 source and artifact verification remains unavailable in this runner; upstream compatibility and provenance rely on the maintainer's documented audit.
  • Resolve review confidence - ClawSweeper must reach high confidence before merge readiness is known.
Agent review details

Security

None.

PR surface

Source +149, Tests +93, Config 0, Other +2. Total +244 across 14 files.

View PR surface stats
Area Files Added Removed Net
Source 5 158 9 +149
Tests 4 97 4 +93
Docs 0 0 0 0
Config 3 11 11 0
Generated 0 0 0 0
Other 2 39 37 +2
Total 14 305 61 +244

Review metrics

Metric Value Why it matters
Production versus test growth Production +151 net lines, including build tooling +2; tests +93 net lines Growth implements the explicitly accepted compatibility boundary after fs-safe stopped repairing existing private-directory permissions; manifests and lockfile churn are excluded.
Release-age exceptions 8 exact-version exceptions updated; removal date 2026-09-11 The dependency family bypasses the normal publication cooldown under the documented maintainer audit.

Merge-risk options

Maintainer options:

  1. Decide the mitigation before merge
    Keep compatibility repair in the shared OpenClaw adapters while fs-safe owns guarded publication, rejection, and lock lifecycle.
  2. Pause or close
    Do not merge this PR until maintainers decide whether the risk is worth taking.

Technical review

Best possible solution:

Keep compatibility repair in the shared OpenClaw adapters while fs-safe owns guarded publication, rejection, and lock lifecycle.

Do we have a high-confidence way to reproduce the issue?

Not applicable as a standalone current-main bug: this is a dependency upgrade. The supplied discussion reports upgrade regressions and passing repairs; no runtime reproduction was executed here.

Is this the best way to solve the issue?

Yes, within the accepted compatibility policy: shared owner-side permission repair preserves existing behavior without replacing fs-safe's guarded writes or adding a new user setting.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 790fbf0304a6.

Labels

Label justifications:

  • P2: This is a bounded dependency upgrade with compatibility adaptations and no established urgent current-main outage.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: The maintainer-authored PR is exempt from the ordinary contributor-proof gate. Reported filesystem and process tests support the changed adapters and lock retention but are not claimed as live setup proof; no unresolved cross-principal authority change was established.

Evidence

What I checked:

  • Pinned introduction verified: The checkout matches the supplied original head. Its raw parents match the recorded parents, and the reviewed delta is the pinned base-to-head change. The stale test merge was not used to infer removal of current-main behavior. (d7b5e906d678)
  • Upgrade remains absent from current main: Fetched main pins fs-safe 0.7.2 and retains direct secret-write re-exports. No same-repository merged replacement was established; the supplied related reference concerns a separate dependency repository. (package.json:2112, 790fbf0304a6)
  • Dependency boundary: The changed adapters directly import fs-safe secret/store APIs, and this document identifies openclaw/fs-safe as the filesystem implementation. The changed behavior does not depend on the Codex runtime or protocol. Public docs: docs/gateway/security/secure-file-operations.md. (docs/gateway/security/secure-file-operations.md:8, d7b5e906d678)
  • Permission repair and callers: Both adapters share no-follow directory opens and descriptor chmod. Secret creation reaches this through browser relay token initialization; model-file generation and CLI image storage use the private-store adapter. Final publication remains delegated to fs-safe. (src/infra/private-dir-mode.ts:18, d7b5e906d678)
  • Filesystem regression coverage: Inspected tests cover fresh private writes, existing permissive directories, and symlink rejection without changing the destination's permissions. The supplied discussion reports 22 passing adapter tests; these were not executed during this read-only review. (src/infra/private-file-store.test.ts:14, d7b5e906d678)
  • Build-lock lifecycle: retainOnExit preserves the existing fail-closed owner record, with explicit release after child completion. Existing process tests exercise supervisor exit and surviving compiler work; synchronous cache locks separately retain their explicit release and stale-recovery policy. (scripts/lib/dist-artifact-ownership.mts:64, d7b5e906d678)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Josh Avant: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (6 earlier review cycles)
  • reviewed 2026-09-04T18:52:04.238Z sha 644e914 :: blocked before merge. :: [P1] Split the unrelated lockfile refresh
  • reviewed 2026-09-04T20:44:03.975Z sha 6f44302 :: blocked before merge. :: [P1] Split the unrelated lockfile refresh | [P1] Reject a symlinked root before resolving it
  • reviewed 2026-09-04T23:49:24.277Z sha 5d8792c :: needs real behavior proof before merge. :: [P1] Pin directory identity before changing permissions
  • reviewed 2026-09-05T00:15:22.233Z sha f00352a :: needs real behavior proof before merge. :: [P1] Preserve ancestor identity through permission repair
  • reviewed 2026-09-05T01:59:30.155Z sha d4b4115 :: blocked before merge. :: none
  • reviewed 2026-09-05T02:38:35.397Z sha 70d48e5 :: blocked before merge. :: none

- privateFileStore: tighten OpenClaw-owned store roots to 0700 at creation, preserving tighten-then-write behavior for drifted dirs
- doctor transcripts: mask dirMode to permission bits; raw stat.mode includes file-type bits that the strict final directory-mode check rejects
- file-transfer: resolve the symlink canonical target locally when the fs-safe error no longer carries it
- archive test: 0.8.0 preserves the destination when a raced hardlink is rejected (PR197); update assertions
…ct lock on exit

fs-safe 0.8.0 made process-exit sidecar release the default, which broke
the deliberately fail-closed dist-artifact owner record. 0.8.1 adds the
retainOnExit opt-out (openclaw/fs-safe#227); adopt it so only the explicit
release after a joined child removes the record. Also update the whatsapp
session assertion for the conditional parent-directory chmod.
@steipete steipete changed the title chore(deps): update @openclaw/fs-safe to 0.8.0 chore(deps): update @openclaw/fs-safe to 0.8.1 Sep 4, 2026
The 0.8.x tightening wrapper resolved rootDir with realpath before its
lstat walk, so a symlinked root had its destination chmodded before
fs-safe could reject the write. Walk the lexical chain instead; any
symlinked component, including the root, is left for fs-safe to reject.
Adds a regression test asserting the destination's mode is untouched.
The previous lockfile was rebuilt from scratch, drifting unrelated
resolutions. Regenerate from main's lockfile so only the fs-safe family
moves 0.7.2 -> 0.8.1 (temporarily allowing the old entries for the
supply-chain policy check during regeneration).
@steipete

steipete commented Sep 4, 2026

Copy link
Copy Markdown
Contributor Author

Addressing the 20:44 UTC review (head 6f44302). Both P1 findings are fixed in the current head 5d8792c:

P1 — symlinked root chmodded before rejection: agreed, real flaw. The wrapper resolved rootDir with realpath and then chmodded the resolved destination. It now walks the lexical chain from the unresolved root; every component (root included) is lstat'd and any symlink stops the walk untouched, leaving the rejection to fs-safe (which lstat-rejects symlinked roots itself). Regression coverage: secret-file.test.ts now asserts a symlinked root's destination keeps its exact mode while the write rejects with "must not be a symlink". private-file-store.ts was audited — it already lstat'd directly without realpath.

P1 — unrelated lockfile refresh: agreed. The lockfile is regenerated from main's, so only the fs-safe family moves (0.7.2 → 0.8.1); diff vs main is 35+/35-, all fs-safe entries. The strict supply-chain policy rejected main's stale 0.7.2 entries during regeneration (the branch exclusions had moved to 0.8.1), so the old entries were temporarily re-allowed for the regeneration pass only; the committed exclusions cover only the 0.8.1 family. Every new integrity hash in the lockfile matches the fs-safe 0.8.1 release manifest, cross-verified against live npm.

The same push bumps to 0.8.1 for retainOnExit (openclaw/fs-safe#227), which restores the dist-artifact owner record's deliberate survive-exit behavior after 0.8.0 made exit release the default — this was the second CI round's failure. dist-artifact-ownership, lint-status, secret-file (19/19), whatsapp session, doctor-transcripts, file-write, and archive suites all pass locally against the published 0.8.1; tsgo:core and tsgo:extensions:all are clean.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Sep 4, 2026
Both 0.8.x permission adapters checked a directory with lstat and then
chmodded it by pathname, leaving a check/use window where a swapped
component redirected the chmod. Open each component with
O_NOFOLLOW|O_DIRECTORY and fchmod the pinned descriptor instead; swapped
or symlinked directories are never mutated and remain fs-safe's to
reject. Adds private-file-store coverage for the tighten and
symlinked-root paths.
@openclaw-barnacle openclaw-barnacle Bot added channel: whatsapp-web Channel integration: whatsapp-web scripts Repository scripts size: M and removed size: S labels Sep 5, 2026
@steipete

steipete commented Sep 5, 2026

Copy link
Copy Markdown
Contributor Author

Addressing the 23:49 UTC review (head 5d8792c). The remaining P1 is fixed in f00352a:

P1 — pin directory identity before changing permissions: agreed. Both adapters had a check/use gap between lstat and a pathname chmod. They now open each directory with O_RDONLY|O_NOFOLLOW|O_DIRECTORY and fchmod the pinned descriptor — there is no pathname re-resolution to redirect, and a swapped or symlinked component fails the no-follow open outright, so its destination is never mutated and fs-safe's own rejection stands. The secret-file wrapper applies this per chain component (root through file parent); the private-store factory applies it to the store root. This matches the library's own descriptor-pinned identity model.

Behavior proof (the requested final-effect evidence — legitimate repair succeeds; a substituted target retains its permissions):

$ pnpm vitest run src/infra/private-file-store.test.ts src/infra/secret-file.test.ts
 Test Files  2 passed (2)
      Tests  22 passed (22)

Covers: world-readable root tightened 0o777 → 0o700 with a successful secret write (legitimate repair), symlinked root rejected by fs-safe with the destination's mode byte-identical afterward (substituted target untouched), same for the sync store factory, plus the pre-existing symlinked-child and symlinked-target rejections.

fs-safe 0.8.1 package verification (the review could not check the release blob): the lockfile's eight new integrity hashes match the signed release manifest from the tag-driven release run byte-for-byte, cross-verified against live npm (npm view @openclaw/[email protected] dist.integrity = sha512-I11v+xiet4RCE1G1bmWFLEMmd9nBnZMmKqHPT9gkqVtoqacY7GtFvpt1O7cffUDD6C2YlAt7Z5Z2Vlbq5rYxDg==, matching the manifest and the release notes provenance table). The 0.8.1 change itself (retainOnExit) was reviewed and merged as openclaw/fs-safe#227 with its own CI matrix green.

tsgo:core and tsgo:extensions:all remain clean; dist-artifact/lint-status/whatsapp/doctor/file-transfer/archive suites all pass against the published 0.8.1.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot removed the merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. label Sep 5, 2026
Both permission adapters now use one module (private-dir-mode): an async
chain walk for secret writes and a sync single-root tighten for store
factories, eliminating the duplicated safety logic. The module documents
the residual same-principal bound: Node has no dirfd-relative open, so
inter-component traversal is by absolute pathname; an actor able to
replace an OpenClaw-owned directory mid-walk already holds write access
to that tree, and fs-safe still validates the final write.
@steipete

steipete commented Sep 5, 2026

Copy link
Copy Markdown
Contributor Author

Addressing the 00:15 UTC review (head f00352a). Current head: d4b4115.

P1 — preserve ancestor identity through permission repair: the descriptor pinning stays, and I've accepted the residual as a documented, bounded same-principal limitation rather than an exploitable boundary — for three concrete reasons:

  1. Node cannot do better. A fully ancestor-pinned walk needs dirfd-relative opens (openat); Node's fs API has no such capability. Every remaining pathname resolution is therefore inherent to the platform, not a shortcut.
  2. No privilege boundary is crossed. Replacing a component mid-walk requires rename/write capability inside the user's own OpenClaw directory tree. An actor with that capability can already chmod, replace, or read those directories directly; the race grants nothing. The review itself asserts no remote exploit.
  3. fs-safe remains the final authority. The tightening preflight only ever narrows modes on directories OpenClaw owns; the secret write itself is still validated by fs-safe against the real path, with symlinked components rejected. Worst case under the residual race is a same-principal process having narrowed permissions on a directory it could already modify.

The bound is now documented in code (src/infra/private-dir-mode.ts module comment).

Divergence risk (the second merge-risk bullet): fixed — both adapters now share src/infra/private-dir-mode.ts (async chain walk for secret writes, sync single-root tighten for store factories). The duplicated safety logic is gone; 22/22 adapter tests pass, tsgo:core clean.

The wrapper's existence is deliberate compat: fs-safe 0.8 stopped repairing drifted directory modes by design, and without this preflight, users with world-readable ~/.openclaw state would hit hard insecure-permissions failures on upgrade. Tightening OpenClaw-owned directories keeps the documented behavior while leaving all rejection semantics to fs-safe.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event exact_review_queue).
Result: when the review finishes, ClawSweeper will create the durable review comment if needed or update the existing comment in place.

Re-review progress:

@clawsweeper clawsweeper Bot added merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 5, 2026
@steipete

steipete commented Sep 5, 2026

Copy link
Copy Markdown
Contributor Author

Closing the last open item — the package-provenance audit the reviewer's environment couldn't perform. I maintain both repositories and verified the published 0.8.1 artifacts directly:

Source identity: 0.8.1 is exactly PR openclaw/fs-safe#227 (retainOnExit), merged at 141e2a5 after three review rounds with the full CI matrix green (Node 22/24 × ubuntu/macos/windows, native builds, CodeQL, bundled-package smoke). The release commit 5872f54 contains only version bumps and the changelog retitle — no source changes.

Package provenance: the tag-driven release run (33925528844) packed all eight packages and recorded their integrity in its signed run manifest. I downloaded that manifest from the run's artifacts and cross-checked every hash against live npm: all eight dist.integrity values match the manifest byte-for-byte (main package sha512-I11v+xiet4RCE1G1bmWFLEMmd9nBnZMmKqHPT9gkqVtoqacY7GtFvpt1O7cffUDD6C2YlAt7Z5Z2Vlbq5rYxDg==), and npm reports provenance attestations for each. The full table with per-package tarball, integrity, and attestation links is on the v0.8.1 release.

Lockfile chain: this PR's lockfile entries carry exactly those verified hashes — the diff vs main touches only the fs-safe family, and I compared each new integrity value against the release manifest before committing.

One transparency note: the release run shows as cancelled because an external actor cancelled it during the finalization step, after all eight npm publishes had completed; I verified publication state directly (all packages live, latest → 0.8.1) and completed the GitHub Release finalization with the workflow's own scripts rather than re-running the publish.

Compatibility clearance is complete on the maintainer side. @clawsweeper re-review

Reruns route to GitHub-hosted runners (run_attempt > 1), where the
dashboard-gallery Playwright test exceeds its 30s locator timeout. The
full shard passes locally (228/228) on this head and the identical UI
code passed CI at 9cbd8c6; a fresh run restores attempt-1 placement.
@clawsweeper clawsweeper Bot removed the merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. label Sep 5, 2026
@steipete
steipete merged commit f91bb7b into main Sep 5, 2026
184 checks passed
@steipete
steipete deleted the chore/fs-safe-080 branch September 5, 2026 03:16
@steipete

steipete commented Sep 5, 2026

Copy link
Copy Markdown
Contributor Author

Landed as f91bb7b. Testing summary:

  • Targeted suites (against the published @openclaw/fs-safe 0.8.1): secret-file (19/19, including the symlinked-root no-chmod regression), private-file-store (new, 3/3: tighten + symlinked-root untouched for both factories), dist-artifact-ownership, lint-status, whatsapp session, doctor-session-transcripts, file-transfer file-write, archive — all green locally.
  • Full local shard proof: the CI-failing checks-ui-e2e (6/7) shard runs 228/228 green locally on the exact merge-ref tree; the CI failures were shard-placement timeouts on main's new dashboard-gallery test (passes on main's own CI in 2.2s), resolved after merging main.
  • Type checks: tsgo:core, tsgo:extensions:all clean.
  • CI: full matrix green at head d7b5e90 (run 33940535868 and the checks pipeline), including the previously failing dist-artifact retention and lint-status suites.
  • Reviews: three ClawSweeper rounds — lockfile drift and symlinked-root chmod (fixed), lstat→chmod check/use gap (fixed with descriptor-pinned fchmod), ancestor-traversal bound (accepted as a documented same-principal limitation; Node has no dirfd-relative open) — final review reports no findings. Autoreview clean on every commit and the final branch diff.
  • Upstream provenance: fs-safe 0.8.1 = fs-safe#227 with full CI; the lockfile's eight integrity hashes match the v0.8.1 release manifest, cross-verified against live npm.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 5, 2026
* chore(deps): update @openclaw/fs-safe to 0.8.0

fs-safe 0.8.0 stops repairing existing secret-directory permissions and fails closed instead. Wrap OpenClaw secret writes to tighten OpenClaw-owned directory modes before delegating, preserving the documented tighten-then-write behavior. Move the cooldown exclusions to the 0.8.0 family.

* fix(infra): adapt to fs-safe 0.8.0 fail-closed boundaries

- privateFileStore: tighten OpenClaw-owned store roots to 0700 at creation, preserving tighten-then-write behavior for drifted dirs
- doctor transcripts: mask dirMode to permission bits; raw stat.mode includes file-type bits that the strict final directory-mode check rejects
- file-transfer: resolve the symlink canonical target locally when the fs-safe error no longer carries it
- archive test: 0.8.0 preserves the destination when a raced hardlink is rejected (PR197); update assertions

* chore(deps): update @openclaw/fs-safe to 0.8.1 and retain dist-artifact lock on exit

fs-safe 0.8.0 made process-exit sidecar release the default, which broke
the deliberately fail-closed dist-artifact owner record. 0.8.1 adds the
retainOnExit opt-out (openclaw/fs-safe#227); adopt it so only the explicit
release after a joined child removes the record. Also update the whatsapp
session assertion for the conditional parent-directory chmod.

* fix(infra): never chmod through a symlinked secret root

The 0.8.x tightening wrapper resolved rootDir with realpath before its
lstat walk, so a symlinked root had its destination chmodded before
fs-safe could reject the write. Walk the lexical chain instead; any
symlinked component, including the root, is left for fs-safe to reject.
Adds a regression test asserting the destination's mode is untouched.

* chore(deps): narrow the lockfile refresh to the fs-safe bump

The previous lockfile was rebuilt from scratch, drifting unrelated
resolutions. Regenerate from main's lockfile so only the fs-safe family
moves 0.7.2 -> 0.8.1 (temporarily allowing the old entries for the
supply-chain policy check during regeneration).

* fix(infra): pin directory identity through permission tightening

Both 0.8.x permission adapters checked a directory with lstat and then
chmodded it by pathname, leaving a check/use window where a swapped
component redirected the chmod. Open each component with
O_NOFOLLOW|O_DIRECTORY and fchmod the pinned descriptor instead; swapped
or symlinked directories are never mutated and remain fs-safe's to
reject. Adds private-file-store coverage for the tighten and
symlinked-root paths.

* refactor(infra): share descriptor-pinned directory tightening

Both permission adapters now use one module (private-dir-mode): an async
chain walk for secret writes and a sync single-root tighten for store
factories, eliminating the duplicated safety logic. The module documents
the residual same-principal bound: Node has no dirfd-relative open, so
inter-component traversal is by absolute pathname; an actor able to
replace an OpenClaw-owned directory mid-walk already holds write access
to that tree, and fs-safe still validates the final write.

* ci: retrigger checks-ui-e2e on the control-ui runner class

Reruns route to GitHub-hosted runners (run_attempt > 1), where the
dashboard-gallery Playwright test exceeds its 30s locator timeout. The
full shard passes locally (228/228) on this head and the identical UI
code passed CI at 9cbd8c6; a fresh run restores attempt-1 placement.
vincentkoc added a commit to LiuwqGit/openclaw that referenced this pull request Sep 5, 2026
* refs/remotes/origin/main: (602 commits)
  fix(plugins): trace trust refusals and repair legacy provenance (openclaw#138746)
  perf(sqlite): reuse compiled plugin state point reads (openclaw#138758)
  refactor: type chat prefetch dependencies and clean loading tests (openclaw#138793)
  ci: reduce Doctor test startup and core lint jobs (openclaw#138796)
  feat(update): retain run history and share outcome reports (openclaw#138690)
  chore(deps): update @openclaw/fs-safe to 0.8.1 (openclaw#138500)
  fix: preserve global board ownership from pinning to notifications (openclaw#138675)
  fix(gateway): deliver session catalog updates from slow hosts (openclaw#138674)
  perf(sessions): index pending conversation replies (openclaw#127182)
  perf(auth): reuse ordered provider alias entries (openclaw#138805)
  docs(diagnostics): clarify whole-process CPU metrics (openclaw#138804)
  perf(memory): narrow source reads and stream embedding cache rows (openclaw#138766)
  fix: allow older source on newer Testbox checkouts (openclaw#138782)
  fix(agents): preserve recovered task progress and lifecycle ownership (openclaw#138785)
  perf(codex): reduce rollout tail scan CPU (openclaw#138784)
  perf(gateway): stop projecting history deltas at the byte budget (openclaw#138655)
  fix(build): bound native declaration inputs to checkout (openclaw#138742)
  fix(cli): preserve foreground Gateway argument handling (openclaw#138765)
  fix(ui): align task toolbar with side-panel tabs (openclaw#138769)
  fix(logbook): drain accepted work before closing SQLite (openclaw#138754)
  ...

# Conflicts:
#	src/agents/embedded-agent-runner/compact.queued.ts
william-antoline-boon added a commit to getboon/openclaw that referenced this pull request Nov 5, 2026
…writes

fs-safe 0.3.0 chmod'ed the private root and every component to 0700 on
each secret/private-store write. fs-safe 0.8 only sets the mode on
directories it creates itself and throws "Private secret directory ... has
insecure permissions" for an existing directory at any other mode. Hosts
run with umask 0002, so directories created by earlier code paths sit at
0775 and every private write into them (session transcript rewrites,
models.json, commitments, device identity, auth stores) would throw.

Port upstream's adapter (openclaw f91bb7b, openclaw#138500, as shipped in
v2026.9.4): new src/infra/private-dir-mode.ts opens each directory
O_NOFOLLOW|O_DIRECTORY and fchmods the pinned descriptor, so symlinked or
swapped components are never mutated and stay fs-safe's to reject.
privateFileStore/privateFileStoreSync tighten their root at creation;
writePrivateSecretFileAtomic tightens root -> parent before delegating.

Fork addition: a drifted directory owned by another user is never chmod'ed.
On the secret-write path it now fails with a message naming the path,
owner, and fix instead of a raw EPERM; the store factory (which also serves
reads) leaves it for fs-safe's insecure-permissions error on write. The
check itself stays on: nothing here relaxes fs-safe's mode enforcement.

Tests: upstream's private-file-store tests and symlinked-root regression,
plus private-dir-mode tests for 0775 chains, missing components, and the
not-owned case.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
william-antoline-boon added a commit to getboon/openclaw that referenced this pull request Nov 5, 2026
…nk refusals

fs-safe 0.8 no longer attaches the canonical target to its symlink error,
so SYMLINK_REDIRECT refusals lost the canonicalPath the operator needs to
update allowWritePaths. Port upstream's resolver (openclaw f91bb7b,
openclaw#138500): use the error's canonical path when present, else realpath the
target (final-component symlink) or walk the existing ancestor (symlinked
parent of a missing leaf).

fs-safe also now reports a final symlink during path resolution, so with
the default followSymlinks=false it is refused as SYMLINK_REDIRECT instead
of SYMLINK_TARGET_DENIED. Port upstream's split test (9094e10,
openclaw#120082): the default case expects SYMLINK_REDIRECT plus the canonical
target, and a new followSymlinks=true case still expects
SYMLINK_TARGET_DENIED. Both assert the target file is untouched.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
william-antoline-boon added a commit to getboon/openclaw that referenced this pull request Nov 5, 2026
fs-safe 0.8 writes WhatsApp creds through descriptors: an "wx" temp handle,
handle writes, fchmod/fsync on the handle, and a pinned O_NOFOLLOW parent
directory. The test helper faked path-based fs.writeFile/fs.open calls, so
it threw "unexpected fs.open call" and saw no writes, failing 5 tests
(QR socket, backup rotation, corrupted-backup guard, serialized saves,
atomic write).

Port upstream's helper (openclaw 6aee279, openclaw#119621): wrap real
fs.open handles and spy on their chmod/sync/close, and record the writes
made through them. The atomic-write test now runs against a real temp auth
dir and asserts more than before: temp file mode 0600 and flags "wx",
fchmod(0600) + fsync + close on the temp handle, a single rename from temp to
creds.json, parent pinned with O_RDONLY|O_DIRECTORY|O_NOFOLLOW|O_NONBLOCK,
final contents, creds.json 0600, and auth dir 0700. Per f91bb7b
(openclaw#138500), fs-safe 0.8 skips the parent chmod when it is already 0700.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
william-antoline-boon added a commit to getboon/openclaw that referenced this pull request Nov 6, 2026
…sted tar) + owner-scoped lock migration, 2026.6.35-boon.4 (#327)

* test(archive): pin npm-pack tarball extraction through the fs-safe facade

Adds a case that builds a real .tgz with the system tar (PAX format,
nested dirs, a 120-char file name), extracts it through extractArchive,
and asserts identical bytes, mode 0644, no symlinks and an exact file set,
plus a second tarball with a "../escape.js" member that must be rejected.

Passes on @openclaw/fs-safe 0.3.0; it guards the 0.8.5 bump (ENG-22031),
whose tar backend no longer depends on the npm `tar` package.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(locks): pin session/file lock nesting before the fs-safe 0.8.5 migration

fs-safe 0.5 replaced the process-scoped `allowReentrant` lock option with
owner-scoped `reentrantOwner`. Pin today's behaviour on the real call paths
so the migration (ENG-22031) can be checked against it:

- transcript append / event / append transaction and the session-accessor
  transcript turn (persistSessionTranscriptTurn) complete while this process
  already holds the session write lock (compaction / rewrite shape), instead
  of timing out behind it;
- two independent session-lock holders on the same session still
  serialize (second waits for release, or times out);
- the plugin SDK file lock lets the same caller nest acquireFileLock and
  withFileLock on one file, keeping the sidecar until the final release.

All pass on @openclaw/fs-safe 0.3.0. Flipping the transcript writers to
non-reentrant makes the two nesting cases fail (verified).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(deps): bump @openclaw/fs-safe 0.3.0 -> 0.8.5 and migrate locks to owner-scoped re-entry (ENG-22031)

fs-safe 0.3.0 pins an exact optional `tar: 7.5.13`, which npm global
installs nest under openclaw/node_modules/@openclaw/fs-safe (overrides do
not apply to `npm i -g`). fs-safe 0.8.2+ drops `tar` entirely; 0.8.5 ships
prebuilt native helpers (incl. linux-arm64-gnu) as optional deps.

Lock migration. fs-safe 0.5 removed the process-scoped `allowReentrant`
option in favour of owner-scoped `reentrantOwner` (only acquisitions with
the same owner share a held lock). Ported from upstream openclaw#113705
("scope lock reentrancy to logical owners", "preserve owner-scoped file
lock nesting"), adapted to the fork:

- acquireSessionWriteLock takes `reentrantOwner?: string` and
  `allowReentrant?: never`. Every acquisition now carries an owner (a fresh
  `session-write-lock:<pid>:<uuid>` when omitted) recorded in the held
  entry's metadata, so independent acquisitions still serialize.
- New resolveSessionTranscriptWriteLockOwner(sessionFile): the owner of the
  session lock this process currently holds for that file (agent attempt,
  compaction, transcript rewrite, tool-result truncation), else a fresh one.
  transcript-append (withSessionTranscriptWriteLock) and the session-accessor
  transcript-turn batch pass it, so a transcript write nested inside the
  holding operation joins its lock exactly as `allowReentrant: true` did.
- sandbox/registry: dropped `allowReentrant: false` (now the default).
- plugin-sdk/file-lock: new optional `FileLockOptions.reentrantOwner`;
  omitted means one process-wide owner, preserving the documented
  re-entrant contract for existing plugin callers (no call-site changes).

Other 0.8.5 API drift fixed at the call site: shouldReclaim /
shouldRemoveStaleLock payloads are `unknown` (narrowed, no casts), and
tempWorkspace().cleanup() returns a receipt (cli-runner helpers, discord
voice send). Archive tests updated for 0.8.5's error shapes (tar traversal
-> ArchiveSecurityError code "entry-path"; under-declared ZIP central
directory -> "invalid ZIP metadata"; hardlink race no longer truncates the
shared inode; preflight counts rejected entries), each still asserting the
rejection and that nothing lands outside the destination. Session-lock
stale-diagnostics tests now key on the fork's own diagnostics read (fs-safe
no longer reads sidecars via fs.readFile).

Root npm-shrinkwrap.json: fs-safe 0.8.5 + its 7 platform optional entries,
edited from pnpm-lock.yaml metadata because generate-npm-shrinkwrap.mjs
still fails on boon (pre-existing @sentry/node @opentelemetry 2.12.0
registry drift, see #311). No extension shrinkwrap references fs-safe.
pnpm-workspace: removed the [email protected] minimumReleaseAge exclusion.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* chore(release): bump version 2026.6.35-boon.2 -> 2026.6.35-boon.3

Cuts the fork release carrying the ENG-22031 fs-safe 0.8.5 bump (drops
the nested tar 7.5.13 from global installs) plus #311-#315 merged since
boon.2.

Bump root package.json/npm-shrinkwrap.json, all bundled plugin
manifests, and the version + openclaw peer floor in every extension
npm-shrinkwrap.json (same 206 files / 469 strings as #308). Add the
2026.6.35-boon.3 CHANGELOG.md section and the matrix plugin changelog
alignment entry.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(build): scope peer-suffixed forked deps in the shrinkwrap generator; regenerate shrinkwraps

generate-npm-shrinkwrap.mjs derives scoped npm overrides from pnpm-lock
snapshots for packages locked at more than one version, but skipped every
edge whose spec carries pnpm's peer suffix (e.g.
"2.11.0(@opentelemetry/[email protected])"), because the suffix fails the exact
version check. @sentry/node's nested @opentelemetry/sdk-trace-base and
resources therefore got no override, npm floated them to 2.12.0 (absent
from pnpm-lock.yaml), and the npm shrinkwrap guard in `pnpm check` failed on
boon (the drift #309/#311 worked around by hand).

Strip the peer suffix before the exact-version check (extracted as
collectPnpmLockScopedVersionOverrides, unit-tested: RED returned {}, GREEN
returns the per-parent pins). Regenerated with
`node scripts/generate-npm-shrinkwrap.mjs --all`; `--all --check` passes.
Root shrinkwrap now comes from the generator (fs-safe 0.8.5 + platform
entries replace the hand edit); discord/tlon/amazon-bedrock(-mantle) pick up
pnpm-locked versions and registry `deprecated` metadata. No tar < 7.5.22,
no fs-safe 0.3.0.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* chore(release): bump version 2026.6.35-boon.3 -> 2026.6.35-boon.4

boon already shipped 2026.6.35-boon.3 (#316), so the ENG-22031 fs-safe
0.8.5 release is re-cut as boon.4. Same 206 manifest/shrinkwrap files and
469 strings as #316. Shrinkwraps regenerated with the fixed generator
(--all, --check exits 0): apart from the version strings they match
boon's hand-edited pins for #317/#318/#323/#324. Adds the boon.4
CHANGELOG section (ENG-22031 plus #318, #323, #324, #326) and the matrix
plugin alignment entry.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(fs-safe): default native helper off instead of the retired Python mode

fs-safe 0.5+ deprecates configureFsSafePython; calling it prints an
FS_SAFE_PYTHON_DEPRECATED warning to stderr on every process start, which
broke every CLI script test that asserts clean stderr. Port upstream's
replacement (openclaw 0d7fb8e, openclaw#113705, as shipped in v2026.9.4):
configureFsSafeNative({ mode: "off" }) unless any
(OPENCLAW_)FS_SAFE_(NATIVE|PYTHON)_MODE override is set, so fs-safe can
still migrate a legacy PYTHON_MODE=require. Same default as before: the
guarded JavaScript paths, no helper process or binding.

Applied to src/infra/fs-safe-defaults.ts and the memory-host-sdk fs facade,
with upstream's defaults test and the secure-file-operations docs.

Also ports upstream 2d06d46 ("restore missing extra-path reads"):
fs-safe 0.8 reports a non-directory parent as code "not-file", so a
missing memory file below a regular file was rejected as "path required"
instead of reading as empty. Symlinked parents still fail closed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(secrets): tighten OpenClaw-owned private dirs before fs-safe 0.8 writes

fs-safe 0.3.0 chmod'ed the private root and every component to 0700 on
each secret/private-store write. fs-safe 0.8 only sets the mode on
directories it creates itself and throws "Private secret directory ... has
insecure permissions" for an existing directory at any other mode. Hosts
run with umask 0002, so directories created by earlier code paths sit at
0775 and every private write into them (session transcript rewrites,
models.json, commitments, device identity, auth stores) would throw.

Port upstream's adapter (openclaw f91bb7b, openclaw#138500, as shipped in
v2026.9.4): new src/infra/private-dir-mode.ts opens each directory
O_NOFOLLOW|O_DIRECTORY and fchmods the pinned descriptor, so symlinked or
swapped components are never mutated and stay fs-safe's to reject.
privateFileStore/privateFileStoreSync tighten their root at creation;
writePrivateSecretFileAtomic tightens root -> parent before delegating.

Fork addition: a drifted directory owned by another user is never chmod'ed.
On the secret-write path it now fails with a message naming the path,
owner, and fix instead of a raw EPERM; the store factory (which also serves
reads) leaves it for fs-safe's insecure-permissions error on write. The
check itself stays on: nothing here relaxes fs-safe's mode enforcement.

Tests: upstream's private-file-store tests and symlinked-root regression,
plus private-dir-mode tests for 0775 chains, missing components, and the
not-owned case.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(fs): drive fault injection through fs-safe 0.8's sync metadata calls

fs-safe 0.8 resolves path components with realpathSync.native and checks
child metadata with lstatSync. The symlink-rebind race helper and the
workspace EAGAIN injection still patched the async APIs, so the injected
races never fired: the remove/mkdir/apply-patch race tests asserted a
rejection that no longer happened, and the workspace retry test counted 0
attempts. Port upstream's helper and fixtures (openclaw 870195a,
openclaw#141165): withRealpathSymlinkRebindRace gains realpathApi: "native-sync",
and the race cases use it. With the race actually firing again fs-safe
rejects each operation and the out-of-root file/directory stays untouched,
so these security tests are exercised again rather than relaxed.

Also from upstream (v2026.9.4):
- workspace retry counts >= 2 lstat attempts (0.8 lstats the child more
  than once per successful open); the file must still load.
- apply-patch symlink update accepts fs-safe's "unsafe path" boundary-read
  message (58025dd, openclaw#119363); the patch is still rejected and the
  symlink target is still unchanged.
- resolveOpenedFileRealPathForHandle returns the canonical real path of the
  moved inside file (macOS reports /private/var for /var); compare against
  realpath(movedPath), still never the outside symlink target.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(fs): keep workspace, operator, and avatar symlink contracts on fs-safe 0.8

fs-safe 0.5.2+ rejects every symlink path component by default and
atomically replaces a final symlink on write. That broke documented
contracts (in-workspace directory aliases, symlinked skill/hook roots) and,
for the workspaceOnly write tool, silently turned "refuse to write through a
symlink" into "replace the symlink". Port upstream's fixes (openclaw
58025dd, openclaw#119363; 5295f25, openclaw#121508; as shipped in v2026.9.4):

- agent-tools workspaceOnly: reject writes whose final component is a
  symlink (restores the security contract), and canonicalize contained
  symlink parents for read/edit/access like the write path already did.
- boundary-file-read: openRootFileFollowingParents canonicalizes contained
  parent aliases; workspace bootstrap reads use it. Final symlinks and
  out-of-root escapes are still rejected by openRootFile.
- skills, hooks, config includes, control-ui, sandbox fs-bridge: pass
  rejectSymlinks: false so in-root symlink hops work; fs-safe still rejects
  any hop whose canonical target escapes the root.
- sandbox fs-bridge: map fs-safe's generic "not-file" to the
  operation-specific "Sandbox boundary checks failed; cannot <action>".

Fork addition with the same pattern: gateway avatar reads pass
rejectSymlinks: false so avatars symlinked inside the workspace keep
working; the existing test that an avatar symlink escaping the workspace is
refused still passes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(media): never leave a failed producer's temp file beside media

fs-safe 0.8's writeSiblingTempFile only removes a sibling temp it has
pinned. When the producer callback throws first (an oversized media stream
hitting its byte cap), the partial ".<uuid>...tmp" it wrote is left in the
media directory, where 0.3.0 removed it.

Port upstream's owned-temp handoff (openclaw src/infra/owned-temp-file.ts
and the sibling-temp-file wrapper, 75bcd26, as shipped in v2026.9.4):
the producer writes into a private fs-safe temp workspace that is cleaned up
on failure and moved into place only after it succeeds, with directory
identity guards on both sides so a swapped parent is never deleted from.
The infra fs-safe-advanced re-export (and so plugin-sdk security-runtime)
now hands out the wrapper too.

Tests: upstream's owned-temp-file tests (fixture paths canonicalized for the
macOS /var -> /private/var tmpdir), plus a producer-failure cleanup case.
media store "rejects oversized streams before writing a final artifact"
passes again.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(fs): accept fs-safe 0.8 filename sanitization and read-path metadata

Port upstream's test alignment for fs-safe's untrusted-filename sanitizer
and descriptor handling (openclaw 58025dd, openclaw#119363, as shipped in
v2026.9.4). Each is a stricter or equivalent behaviour, accepted rather than
worked around:

- file-context / openresponses: fs-safe strips Windows-invalid characters
  (<>:"/\|?*) from untrusted filenames before XML-escaping, so injected
  markup never reaches the name attribute at all. Content escaping of
  </file> markers is unchanged and still asserted.
- media store: the same sanitizer drops Windows-invalid characters instead
  of turning them into "_".
- media-understanding: local attachment opens may add O_NONBLOCK (so a raced
  FIFO cannot pin a worker); O_RDONLY|O_NOFOLLOW is still required.
- json-files: non-durable writes still open pinned descriptors, so open-call
  counting no longer proxies fsync work; the write must still land.
- web-media: classify fs-safe's pre-open identity drift (path-mismatch) as
  "path-not-allowed" rather than a bad path, as upstream does.

Fork-only: the json-files "File changed during read" retry tests now inject
the identity change through fs.lstatSync, which fs-safe 0.8 uses for the
pre-open check; the retry, exhaustion and tryReadJson-null assertions are
unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(channels): keep session-store fixtures out of the shared temp root

fs-safe's replaceFileAtomic has always set the parent directory to dirMode
(0700) on each write. 0.3.0 did it with a best-effort chmod that followed
symlinks and ignored errors. 0.8 pins the parent with O_NOFOLLOW and fchmods
the descriptor, so it now fails when the parent is a symlink (macOS /tmp:
"Atomic replace parent must be a real directory") or is not owned by the
writer (root-owned sticky /tmp: EPERM fchmod).

Real session stores live in OpenClaw-owned directories, so production
writes are unaffected. Several tests, however, wrote stores straight into
/tmp or the OS temp root. Move those fixtures into private mkdtemp
directories, as upstream's tests do (v2026.9.4): directive-handling.model,
telegram bot / create-bot harness, telegram and slack approval-native, and
discord /think autocomplete. Assertions are unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(file-transfer): report the canonical target for fs-safe 0.8 symlink refusals

fs-safe 0.8 no longer attaches the canonical target to its symlink error,
so SYMLINK_REDIRECT refusals lost the canonicalPath the operator needs to
update allowWritePaths. Port upstream's resolver (openclaw f91bb7b,
openclaw#138500): use the error's canonical path when present, else realpath the
target (final-component symlink) or walk the existing ancestor (symlinked
parent of a missing leaf).

fs-safe also now reports a final symlink during path resolution, so with
the default followSymlinks=false it is refused as SYMLINK_REDIRECT instead
of SYMLINK_TARGET_DENIED. Port upstream's split test (9094e10,
openclaw#120082): the default case expects SYMLINK_REDIRECT plus the canonical
target, and a new followSymlinks=true case still expects
SYMLINK_TARGET_DENIED. Both assert the target file is untouched.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(whatsapp): observe real credential descriptors under fs-safe 0.8

fs-safe 0.8 writes WhatsApp creds through descriptors: an "wx" temp handle,
handle writes, fchmod/fsync on the handle, and a pinned O_NOFOLLOW parent
directory. The test helper faked path-based fs.writeFile/fs.open calls, so
it threw "unexpected fs.open call" and saw no writes, failing 5 tests
(QR socket, backup rotation, corrupted-backup guard, serialized saves,
atomic write).

Port upstream's helper (openclaw 6aee279, openclaw#119621): wrap real
fs.open handles and spy on their chmod/sync/close, and record the writes
made through them. The atomic-write test now runs against a real temp auth
dir and asserts more than before: temp file mode 0600 and flags "wx",
fchmod(0600) + fsync + close on the temp handle, a single rename from temp to
creds.json, parent pinned with O_RDONLY|O_DIRECTORY|O_NOFOLLOW|O_NONBLOCK,
final contents, creds.json 0600, and auth dir 0700. Per f91bb7b
(openclaw#138500), fs-safe 0.8 skips the parent chmod when it is already 0700.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(archive): real ZIP fixtures for fs-safe 0.8 preflight; restore strict limits

fs-safe 0.8 preflights ZIP bytes (local records, central directory) before
JSZip parses anything. Fixtures that were placeholder text, or that held a
central directory with no local records, now fail as "invalid ZIP
metadata" / "failed while reading the downloaded archive" before reaching
the limit under test. Port upstream's fixtures (openclaw v2026.9.4:
zip-central-directory-fixture with valid local records and file/directory
entry types; 8f295f1 / 75bcd26):

- archive.test: the actual-central-directory entry-limit case asserts
  "archive entry count exceeds limit" exactly again. The earlier bump had
  widened it to also accept "invalid ZIP metadata"; that is reverted, so
  the limit check is pinned rather than relaxed.
- clawhub: the _meta.json size-limit case uses a real ZIP on disk (the
  oversized entry is still injected through the loadAsync mock), and the
  two entry-limit cases become upstream's file/directory it.each over a
  real 50,001-entry central directory. Each asserts JSZip is never invoked
  and nothing is installed.
- hooks install (eaa614a, openclaw#138870): tar/zip traversal must fail with
  an ArchiveSecurityError, and the test now also asserts that no hooks dir
  was created.
- json-file: fs-safe names sibling temps ".fs-safe-<uuid>.tmp"; assert a
  same-directory temp renamed onto the target, as upstream does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(memory): inject faults through fs-safe 0.8's descriptor and unlink paths

fs-safe 0.8 writes atomic temps through file handles, removes its owned
temps with identity-checked unlink(), and reads through lstatSync and handle
reads. Four memory tests injected faults or stubs on the old path-based
calls, so the injected failure never fired. The production code is
unchanged and each assertion keeps its intent:

- short-term-promotion: the EFBIG mid-write is now also injected on handles
  opened for MEMORY.md.promotion*, as upstream does (v2026.9.4). MEMORY.md
  must still be byte-identical afterwards, with no promotion temp left.
- dreaming-narrative: the cleanup failure is injected on fs.unlink, so the
  "replace failed ... cleanup also failed" error must still surface.
- qmd-manager (fork-only; upstream removed qmd): write the exported session
  file for real instead of stubbing fs.lstat/readFile. The
  collection-scoped read must still return its content.
- active-memory: fs-safe renames a temp workspace aside before removing it,
  so assert that the temp transcript directory no longer exists after the
  hook, not the exact rm() argument.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(security): follow fs-safe 0.8's fail-closed Windows ACL verification

fs-safe 0.8 changed how inspectWindowsAcl stays locale-independent (openclaw#35834).
It no longer passes /sid to icacls. Instead it translates each principal
name to a SID through PowerShell (NTAccount -> SecurityIdentifier), and the
permission inspector first runs a PowerShell owner query. If any principal
cannot be verified, the inspection fails closed with ok:false. That is
stricter than 0.3.0, which trusted whatever names icacls printed.

The tests mocked only the icacls call, so every inspection now failed
closed, and the audit test's "no findings" cases passed only because the
ACL was "unknown". Update the mocks to the new contract instead of relaxing
anything:

- windows-acl: icacls is invoked as [path]; name-based listings get a
  PowerShell translation response, and the test asserts the resolved SIDs
  and the trusted classification. New case: an untranslatable principal
  must fail closed (ok:false, no entries).
- audit-filesystem-windows: answer the PowerShell owner query with
  upstream's fixture (v2026.9.4), so the world-writable (S-1-5-7) and
  BUILTIN\Users-readable findings are produced from a verified ACL again.

Windows-only; the paid fleet is Linux.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(signal): keep the tool-result session store out of /tmp

The signal tool-result harness wrote its session store to
/tmp/openclaw-signal-tool-result-sessions-<pid>.json. fs-safe 0.8 pins and
chmods the store's parent on atomic replace, which fails for a symlinked or
root-owned /tmp ("Atomic replace parent must be a real directory: /tmp").
The debounce flush therefore failed and no reply was sent. Move the store
into a private mkdtemp directory.

This is not a lock problem. The review asked us to rule that out, and the
failure output contains no SessionWriteLockTimeoutError or "session file
locked"; the only error is the /tmp atomic-replace refusal above.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(locks): reject allowReentrant at runtime; resolve the join owner per attempt

Review M2: acquireSessionWriteLock typed allowReentrant as never, but JS
callers (compiled plugins) could still pass allowReentrant: true, and it was
silently dropped. Their nested acquire would then contend with its own
outer hold and fail with "session file locked" after the timeout. It now
throws a TypeError that names the replacements. allowReentrant: false
matches the default and is still accepted.

Review M1: transcript writers resolved the holder's owner before
acquireSessionWriteLock ran its own realpath/mkdir awaits. An operation that
took the lock inside that window was contended instead of joined, which
could stall a transcript write until its timeout. A new
joinInProcessHolder: true option looks the holder up synchronously right
before each SESSION_LOCKS.acquire call; transcript-append and the
session-accessor transcript turn use it. This shrinks the window back to the
size it had under fs-safe 0.3.0. Passing it together with reentrantOwner is
a TypeError.

Review M3: the plugin file-lock nesting test released the inner handle
twice. fs-safe's release is not idempotent per handle, so the second call
dropped the outer reference and the final ENOENT check could not catch a
broken outer release. Each handle is now released exactly once.

Tests (TDD): allowReentrant true/false; joinInProcessHolder joining via
symlinks, fresh-owner behaviour, mutual exclusion with reentrantOwner, and a
window test. The window test takes the lock during the joiner's mkdir. It
fails if the owner is precomputed (checked by mutation) and passes with the
late lookup.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* docs(changelog): record fs-safe 0.8 behaviour changes and lock API for boon.4

Adds the ENG-22031 file-handling notes (private-dir tightening, native-mode
default, symlink contracts, media temp cleanup, atomic-replace parent
pinning, Windows ACL fail-closed) and the joinInProcessHolder /
allowReentrant TypeError lock changes. Review M5: the plugin line now names
the generator-driven shrinkwrap pin changes instead of claiming
version-only.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(file-lock): release each nested handle exactly once without a flag

Restructure the review-M3 fix so oxlint's no-useless-assignment is
satisfied: outer is released in finally, inner once in the body. The final
ENOENT check still proves that it is outer.release() that removes the lock.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(secrets): stall file-provider reads through FileHandle.read for fs-safe 0.8

fs-safe 0.8 reads secret files with a bounded FileHandle.read loop instead of
FileHandle.readFile, so the stall injected on readFile never fired and the
file-provider timeout test resolved the secret. Stub read instead, as upstream
does (openclaw v2026.9.4); the timeout assertion is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(infra): compare full private-dir mode and surface failed tightens

Compare all 0o7777 permission bits so a setgid/sticky 0700 directory is
tightened (fs-safe compares them too). tightenPrivateDirRootSync now only
ignores open/close failures; a failed fchmod on an owned root throws, and
privateFileStore logs it with the real cause. Shorten the module comment.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* refactor(agents): drop unused transcript-owner helpers; joinInProcessHolder is the path

resolveSessionTranscriptWriteLockOwner and resolveSessionWriteLockHolderOwner
had no production callers (transcript writers pass joinInProcessHolder: true),
and a precomputed holder owner is the racy pattern joinInProcessHolder avoids.
Remove them, keep the private held-owner lookup, and move their coverage onto
joinInProcessHolder tests. Clarify a test title, make the nesting suite
hermetic against the acquire-timeout env override, and use American spelling.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(media): report fs-safe path-mismatch as a retryable read error, not a denial

A path-mismatch from readLocalFileSafely is a transient swap race, not a
policy decision. Mapping it to path-not-allowed made the image and PDF tools
return a silent 'outside allowed directories' denial that skips Sentry.
Keep it an invalid-path error with a retry hint and the fs-safe cause, and
cover it with a web-media test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(memory-host-sdk): keep not-file out of isFileMissingError

fs-safe's not-file means an existing directory or special file, so treating
it as missing made memory reads and indexing silently skip real paths.
Handle the regular-file-parent case locally in
isAllowedAdditionalDirectoryPath, where assertNoSymlinkParents reports it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(sandbox): make the apply-patch mkdir rebind race fire; scope the fs-bridge comment

fs-safe 0.8 resolves the existing ancestor with realpathSync.native, so the
mkdir race test's async realpath spy never rebound the alias. Spy on the
native API, rebind on the parent re-check that precedes mkdir, and assert
the rebind happened. Narrow the fs-bridge rejectSymlinks comment: reads rely
on fs-safe's mount-root containment; only mutations re-check the canonical
container path.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test: restore mocks, remove leaked temp dirs, assert durable fsync options

- fs-safe-defaults: restore the process.platform spy after each test.
- json-files: assert durable:false (and the default) reach replaceFileAtomic
  as syncTempFile/syncParentDir instead of only checking the write lands.
- discord, slack, telegram, directive-handling: remove the private store
  temp dirs in afterAll.
- file-transfer: reuse canonicalPathFromFsSafeError; drop upstream commit
  and PR references from test comments (also archive-helpers).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(infra): satisfy unbound-method lint in the platform-restore check

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test(locks): pin that a released holder's owner is never reused; document the path-walk bound

Address review: the joinInProcessHolder stale-owner test now gives the
released holder a known owner and asserts that owner contends afterwards
(mutation-checked: reusing the last owner makes it fail). Restore the
note that ancestor tightening walks by path, so a same-user swap can
redirect a chmod while fs-safe still validates the final write.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* test: route new test temp dirs through the shared helper or mark extension exceptions

Address check-guards warnings: src tests use test/helpers/temp-dir.ts
(makeTempDir / createTempDirTracker); extension tests, which cannot import
root test helpers, carry the repo's openclaw-temp-dir allow marker.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

channel: whatsapp-web Channel integration: whatsapp-web commands Command implementations dependencies-changed PR changes dependency-related files extensions: onepassword 1Password plugin maintainer Maintainer-authored PR P2 Normal backlog priority with limited blast radius. plugin: file-transfer rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. scripts Repository scripts size: M status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant