Skip to content

feat(root): follow directory aliases while rejecting final symlinks - #297

Merged
steipete merged 5 commits into
mainfrom
codex/fs-safe-parent-symlinks
Sep 13, 2026
Merged

steipete merged 5 commits into
mainfrom
codex/fs-safe-parent-symlinks

Conversation

@steipete

@steipete steipete commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Workspace tools need to follow contained directory aliases while refusing a symlink at the final file, but currently have to canonicalize and check those paths outside fs-safe.

Why This Change Was Made

Adds follow-parents-within-root to read policies and a separate opt-in mutationSymlinks policy for Root mutations. The shared path resolver preserves raw path components, and publication checks reject a final symlink introduced during staging. Keeping mutation policy separate preserves the existing read-policy defaults and mutation behavior.

User Impact

Consumers can use directory aliases without following or replacing a final symlink, including paths ending in a slash or dot. Root containment, existing native/fallback identity checks, and omitted-option behavior remain intact. This does not promise an atomic compare-and-swap against external filesystem writers.

Evidence

  • 198 combined tests pass across policy, mutation authority, publication, Windows fallback, cleanup, low-level adapters, and raw-path suites.

  • Before-fix regressions reproduce both staging-time final aliases and absolute-entry aliases that canonicalization previously erased. Public API proof below verifies native and JavaScript paths.

  • Build, generated API inventory, documentation, package, boundary, and whitespace checks passed.

  • Independent review of the complete combined candidate is clean through P2. Reanchoring onto the landed authority commit preserved the tested source tree exactly; final cross-platform CI, coverage, and CodeQL are green.

  • Tests added or updated when behavior changed

  • Security and compatibility impact considered

  • CHANGELOG.md updated when release-relevant

  • No credentials, private paths, private hosts, or sensitive contents included

Absolute-entry behavior proof

Verified the built @openclaw/fs-safe public exports at faae58b8cbaa09e8be4c7de87f1b48755e2e279a on macOS using synthetic temporary files, with both JavaScript fallback (off) and required native mode. A directory alias outside the lexical workspace successfully reads and writes the contained file. A final file alias outside the lexical workspace rejects both operations with symlink; its link and target bytes remain unchanged. Before the repair, both modes accepted the final alias and changed its target bytes.

Reproduction command from the repository checkout after building the host native binding:

pnpm build
node --input-type=module <<'JS'
import assert from "node:assert/strict";
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { configureFsSafeNative, root } from "@openclaw/fs-safe";

const policy = "follow-parents-within-root";
const observe = async (action) => {
  try { await action(); return "accepted"; }
  catch (error) { return error.code ?? error.name; }
};
let passed = true;
for (const mode of ["off", "require"]) {
  configureFsSafeNative({ mode });
  const temp = await fs.mkdtemp(path.join(os.tmpdir(), "fs-safe-absolute-proof-"));
  try {
    const workspace = path.join(temp, "workspace");
    const value = path.join(workspace, "value.txt");
    const parentAlias = path.join(temp, "parent-alias");
    const finalAlias = path.join(temp, "final-alias.txt");
    await fs.mkdir(workspace);
    await fs.writeFile(value, "original");
    await fs.symlink(workspace, parentAlias, process.platform === "win32" ? "junction" : "dir");
    await fs.symlink(value, finalAlias, "file");
    const scoped = await root(workspace, { symlinks: policy, mutationSymlinks: policy });
    const parentPath = path.join(parentAlias, "value.txt");
    assert.equal((await scoped.readAbsolute(parentPath)).buffer.toString(), "original");
    await scoped.write(parentPath, "parent-write");
    assert.equal(await fs.readFile(value, "utf8"), "parent-write");
    const finalRead = await observe(() => scoped.readAbsolute(finalAlias));
    const finalWrite = await observe(() => scoped.write(finalAlias, "forbidden-write"));
    const targetBytesUnchanged = await fs.readFile(value, "utf8") === "parent-write";
    const finalLinkPreserved = (await fs.lstat(finalAlias)).isSymbolicLink();
    const result = { mode, allowedParentRead: true, allowedParentWrite: true, finalRead, finalWrite, targetBytesUnchanged, finalLinkPreserved };
    console.log(JSON.stringify(result));
    passed &&= finalRead === "symlink" && finalWrite === "symlink" && targetBytesUnchanged && finalLinkPreserved;
  } finally {
    await fs.rm(temp, { recursive: true, force: true });
  }
}
console.log(passed ? "PASS: public Root APIs preserve parent aliases and reject absolute final aliases before target I/O" : "FAIL: absolute final alias bypass reproduced");
if (!passed) process.exitCode = 1;
JS

Observed output:

{"mode":"off","allowedParentRead":true,"allowedParentWrite":true,"finalRead":"symlink","finalWrite":"symlink","targetBytesUnchanged":true,"finalLinkPreserved":true}
{"mode":"require","allowedParentRead":true,"allowedParentWrite":true,"finalRead":"symlink","finalWrite":"symlink","targetBytesUnchanged":true,"finalLinkPreserved":true}
PASS: public Root APIs preserve parent aliases and reject absolute final aliases before target I/O

The source correction enforces the final-component policy before absolute-entry canonicalization discards the original leaf. Regression coverage also checks final directory aliases with trailing / and /., async/sync low-level public opens, and every supported mutation entry; existing absolute-path rejection for move/remove/mkdir remains unchanged.

Integration validation: 198 targeted tests pass across policy, authority dispatch, publication, Windows fallback, cleanup, adapter, and raw-path suites. Combined append/create regressions complete one real two-byte write, then confirm a symlink swap or authority revocation prevents a second write and preserves the replacement. Managed review is clean through P2. Reanchoring onto the landed authority commit preserves the complete tested tree exactly.

Windows CI exposed four test expectations that assumed POSIX refusal codes. The tests now preserve Windows' existing outside-workspace and symlink results while retaining every source, link, and target-content assertion. This follow-up changes no production code; 66 focused tests and independent review pass. The previous candidate passed all native, package, Linux, macOS, CodeQL, and benchmark checks; the final test revision passed cross-platform CI.

Maintainer decision: accept the separate opt-in read and mutation policies with the documented best-effort publication guarantee. The resolver must preserve final-component provenance, and publication must reject a final symlink after awaited preparation; atomic compare-and-swap against independent filesystem writers is outside this contract. Existing defaults remain unchanged.

Final head 49dc3c0377c2fdade8a3aabbea0d0b37db2782ad passed CI, coverage, and CodeQL. One Node 24 Windows job was rerun after an unchanged PowerShell ACL query hit its existing 30-second timeout; the targeted rerun passed without source or timeout changes.

@clawsweeper

clawsweeper Bot commented Sep 13, 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.

@clawsweeper clawsweeper Bot added P2 Normal priority bug or improvement with limited blast radius. merge-risk: 🚨 security-boundary 🚨 Merging this PR could weaken sandboxing, authorization, credentials, or sensitive data. 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. labels Sep 13, 2026
@clawsweeper

clawsweeper Bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 12, 2026, 11:00 PM ET / September 13, 2026, 03:00 UTC (Revision 5).

ClawSweeper review

What this changes

Adds separate read and mutation policies that allow contained directory aliases while rejecting final symlinks, with publication checks, public types, documentation, and regression coverage.

Merge readiness

✅ Ready for maintainer review

This remains a useful, distinct addition absent from current main and v0.9.0. The earlier absolute-entry defect is fixed, real behavior proof remains applicable, and verified repository-admin acceptance resolves the prior policy-decision blocker. No blocking finding remains.

Priority: P2
Reviewed head: 49dc3c0377c2fdade8a3aabbea0d0b37db2782ad

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused additive implementation with convincing public-API proof, broad regression coverage, and resolved prior blockers.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): The supplied macOS public-Root trace exercises native and JavaScript reads/writes through allowed parent aliases and forbidden final aliases, observing rejection before target mutation and preserved link contents. The current head changes only test expectations, preserving the exercised production implementation.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): The supplied macOS public-Root trace exercises native and JavaScript reads/writes through allowed parent aliases and forbidden final aliases, observing rejection before target mutation and preserved link contents. The current head changes only test expectations, preserving the exercised production implementation.
Evidence reviewed 9 items Repository policy: Read the complete root AGENTS.md and contribution guide. Applied confinement, compatibility, shared-helper, regression-coverage, documentation, and changelog requirements. No nested AGENTS.md or matching maintainer notes were found.
Distinct from current main and release: Current main exposes only reject and follow-within-root read policies, without mutationSymlinks. The v0.9.0 Root implementation likewise has only those two read policies. Recent related merged work covers raw traversal and caller authority, rather than this new policy.
Released API comparison: Read the released Root implementation through GitHub after finding that root-options.ts did not exist at this tag; its policy union contains no parent-only mode.
Findings None None.
Security None None.

How this fits together

fs-safe’s Root API confines filesystem operations to a trusted directory. Caller paths and policies pass through shared resolution and identity checks before reads, writes, moves, or removals reach the filesystem.

flowchart TD
  A[Caller path and policies] --> B[Root boundary resolution]
  B --> C[Resolve contained directory aliases]
  C --> D[Reject final symlink]
  D --> E[Guarded read or mutation]
  E --> F[Publication and identity checks]
  F --> G[Result or refusal]
Loading

Before merge

None.

Agent review details

Security

None.

Review metrics

Metric Value Why it matters
Production and test delta Production +148/-39; tests and API inventory +334/-0 Production growth implements the stated opt-in policy across shared resolution and mutation boundaries, with substantially more regression coverage.

Technical review

Best possible solution:

Keep the additive policies on the shared guarded filesystem paths, preserving existing defaults and the explicitly accepted best-effort publication contract.

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

Not applicable as an existing-behavior bug: this adds a policy mode. The supplied public-API transcript demonstrates its allowed and rejected cases after the fix.

Is this the best way to solve the issue?

Yes. Extending shared resolution and guarded publication avoids consumer-side preflight checks, preserves defaults, and implements the administrator-accepted contract.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against cc10fd89ac85.

Labels

Label changes:

  • remove merge-risk: 🚨 security-boundary: Current PR review selected no merge-risk labels.

Label justifications:

  • P2: This is a bounded, opt-in filesystem-policy improvement with unchanged existing defaults.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): The supplied macOS public-Root trace exercises native and JavaScript reads/writes through allowed parent aliases and forbidden final aliases, observing rejection before target mutation and preserved link contents. The current head changes only test expectations, preserving the exercised production implementation.
  • proof: sufficient: Contributor real behavior proof is sufficient. The supplied macOS public-Root trace exercises native and JavaScript reads/writes through allowed parent aliases and forbidden final aliases, observing rejection before target mutation and preserved link contents. The current head changes only test expectations, preserving the exercised production implementation.

Evidence

What I checked:

  • Repository policy: Read the complete root AGENTS.md and contribution guide. Applied confinement, compatibility, shared-helper, regression-coverage, documentation, and changelog requirements. No nested AGENTS.md or matching maintainer notes were found. (AGENTS.md:1, 49dc3c0377c2)
  • Distinct from current main and release: Current main exposes only reject and follow-within-root read policies, without mutationSymlinks. The v0.9.0 Root implementation likewise has only those two read policies. Recent related merged work covers raw traversal and caller authority, rather than this new policy. (src/root-options.ts:12, cc10fd89ac85)
  • Released API comparison: Read the released Root implementation through GitHub after finding that root-options.ts did not exist at this tag; its policy union contains no parent-only mode. (src/root-impl.ts:95, 0fc5776a510d)
  • Previous absolute-entry finding resolved: The resolver checks the original final component before canonicalization can erase its symlink identity. Tests cover external absolute aliases, directory suffixes, synchronous/asynchronous low-level opens, and mutation entry points. (src/root-path-existing.ts:33, 49dc3c0377c2)
  • Runtime proof and revision continuity: The complete captured PR body reports public-package execution on macOS at faae58b. Both off and require modes permit parent-alias reads/writes, reject final-alias reads/writes with symlink, and preserve the final link and target bytes. GitHub’s exact-head commit patch confirms the subsequent change only adjusts Windows test refusal-code expectations. Captured context sourceRevision: f27f19f9cc4911367449091e24c7b1ed2ed9f9b601ab8c82e152378effbad678. (test/root-parent-symlink-policy.test.ts:194, 49dc3c0377c2)
  • Prior maintainer-decision blocker resolved: The captured body explicitly accepts separate opt-in policies and the documented best-effort publication guarantee. GitHub independently confirms steipete has repository admin permission, establishing authority for that recorded decision despite the supplied CONTRIBUTOR association.

Likely related people:

  • steipete: 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 (4 earlier review cycles)
  • reviewed 2026-09-13T01:03:41.784Z sha a87cc73 :: needs real behavior proof before merge. :: [P1] [P1] Enforce final-symlink rejection during absolute root entry
  • reviewed 2026-09-13T01:20:12.411Z sha 3976203 :: needs real behavior proof before merge. :: [P1] [P1] Enforce final-symlink rejection during absolute root entry
  • reviewed 2026-09-13T01:56:34.432Z sha f008a60 :: needs real behavior proof before merge. :: [P1] Enforce final-symlink rejection during absolute root entry
  • reviewed 2026-09-13T02:49:19.366Z sha faae58b :: blocked before merge. :: none

@steipete
steipete force-pushed the codex/fs-safe-parent-symlinks branch from a87cc73 to 3976203 Compare September 13, 2026 01:12
@steipete
steipete marked this pull request as ready for review September 13, 2026 01:15
@steipete
steipete requested a review from a team as a code owner September 13, 2026 01:15
@steipete
steipete force-pushed the codex/fs-safe-parent-symlinks branch from f008a60 to faae58b Compare September 13, 2026 02:45
@clawsweeper clawsweeper Bot added proof: sufficient Contributor real behavior proof is sufficient. 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 status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Sep 13, 2026
@clawsweeper clawsweeper Bot removed the merge-risk: 🚨 security-boundary 🚨 Merging this PR could weaken sandboxing, authorization, credentials, or sensitive data. label Sep 13, 2026
@steipete
steipete merged commit 1e110fe into main Sep 13, 2026
39 of 41 checks passed
@steipete
steipete deleted the codex/fs-safe-parent-symlinks branch September 13, 2026 05:22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P2 Normal priority bug or improvement with limited blast radius. proof: sufficient Contributor real behavior proof is sufficient. 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.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant