Skip to content

fix(switch): atomic no-overwrite backup for --clobber - #2849

Merged
max-sixty merged 2 commits into
mainfrom
switch-clobber-toctou
May 21, 2026
Merged

max-sixty merged 2 commits into
mainfrom
switch-clobber-toctou

Conversation

@max-sixty

@max-sixty max-sixty commented May 21, 2026 •

Copy link
Copy Markdown
Owner

Summary

wt switch --clobber backs up an existing path before clobbering it. The old code checked backup_path.exists() and then, later, called std::fs::rename — which silently overwrites an existing destination on every platform. Anything that appeared at the backup path between the check and the rename (a same-second clobber, or a path that raced in) was destroyed: a time-of-check/time-of-use data-loss race on a --clobber operation.

The fix

The backup now moves with renamore::rename_exclusive — an atomic, no-overwrite rename: renameat2(RENAME_NOREPLACE) on Linux, renamex_np(RENAME_EXCL) on macOS, MoveFileExW on Windows. It fails closed (AlreadyExists) rather than overwriting. renamore keeps the platform FFI — and its unsafe — inside the crate, so worktrunk itself stays unsafe_code = "forbid".

back_up_clobbered_path moves the stale path with that primitive. If the timestamped backup name is already taken, it counts up — …-2, …-3, … — until it finds a free name, so a collision no longer fails the command and an existing backup is never overwritten. The loop terminates because a directory holds finitely many entries; genuine I/O errors still surface as errors.

The timestamp and the move now both happen at execution time, which also closes a smaller stale-plan window — the backup path was previously computed during planning and renamed much later.

Key files

  • src/commands/worktree/resolve.rs — back_up_clobbered_path retry loop.
  • src/commands/worktree/switch.rs — execute_switch uses it; the plan now carries needs_clobber_backup: bool instead of a resolved path.

Notes

  • renamore is a new dependency. rustix / windows-sys are deliberately not added as direct dependencies — calling either's rename API requires an unsafe block, which this crate forbids; renamore encapsulates that.
  • wt step relocate --clobber has the identical check-then-std::fs::rename race. It is not fixed here — a separate branch handles relocate; when that lands it should adopt renamore::rename_exclusive.

Testing

back_up_clobbered_path has unit tests covering every branch — fresh move, -N fallback, many collisions, non-AlreadyExists error. Integration tests cover wt switch --clobber end-to-end, including the collision fallback (which runs on the Windows CI job).

`wt switch --clobber` backs up an existing path before clobbering it.
The old code checked `backup_path.exists()` and later called
`std::fs::rename`, which silently overwrites an existing destination —
a time-of-check/time-of-use race that could destroy whatever appeared
at the backup path in between.

The backup now moves via a new `worktrunk::fs::rename_no_replace`
(`renameat2(NOREPLACE)` on Linux/macOS, `MoveFileExW` on Windows): an
atomic rename that fails closed when the destination already exists.
On a name collision the move counts up to the next free `-N` name, so
a same-second clobber no longer fails and an existing backup is never
overwritten.

`rustix` and `windows-sys` are declared directly to enable the
required features; both were already present transitively.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The Windows backup path used `unsafe { MoveFileExW(...) }`, which the
crate's `unsafe_code = "forbid"` lint rejects — `forbid` cannot be
locally overridden, and `priority.rs` shows the crate deliberately
shells out rather than use unsafe FFI.

Replace the hand-rolled `worktrunk::fs` module with the `renamore`
crate. Its `rename_exclusive` is the same atomic no-overwrite rename
(`renameat2(RENAME_NOREPLACE)` / `renamex_np(RENAME_EXCL)` /
`MoveFileExW`), with the FFI — and its `unsafe` — encapsulated inside
the crate, so worktrunk stays free of unsafe code.

Drops the `src/fs.rs` module and the direct `rustix`/`windows-sys`
dependencies (back to transitive-only); adds `renamore`.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@worktrunk-bot

Copy link
Copy Markdown
Collaborator

nix-flake failure is unrelated to this PR — it's commands::hook_plan::tests::approve_readonly_drops_unapproved_project_keeps_user panicking on Failed to create config directory: Permission denied (os error 13) inside the nix sandbox. hook_plan.rs isn't touched here; the test was added in #2806, so it's been latent on main since then. This PR is the first to trigger the nightly nix-flake gate (it modifies Cargo.{toml,lock}), which is why it's surfacing now.

Same shape as #2615 and #2624 — tests that depend on environment not available under the nix sandbox. Best fixed in a follow-up against hook_plan.rs (e.g. point approve_command at a tempdir-backed approvals path). Approval stays in place.

@max-sixty
max-sixty merged commit 0aff8a8 into main May 21, 2026
35 of 36 checks passed
@max-sixty
max-sixty deleted the switch-clobber-toctou branch May 21, 2026 05:06
max-sixty added a commit that referenced this pull request May 21, 2026
…2853)

The `nix-flake` CI job was red on `main`: the unit test
`commands::hook_plan::tests::approve_readonly_drops_unapproved_project_keeps_user`
panicked with `Failed to create config directory: Permission denied`.

The test called `approve_command(.., None)`. The `None` for
`approvals_path` makes `Approvals` resolve the path through
`approvals_path()`, which — in the lib crate compiled in non-test mode —
points at the real `~/.config/worktrunk/` directory. `approve_command`
then `create_dir_all`s it. Outside a sandbox `$HOME` is writable, so the
test silently passed while writing a stray `[projects.proj]` entry into
the user's `approvals.toml`. The nix build sandbox has no writable
config dir, so it panicked instead.

This was latent on `main` since #2806 (which added the test). It only
started tripping the gate now because the `nix-flake` job runs when a PR
touches `Cargo.{toml,lock}`, and #2849 was the first to do so — so
`nix-flake` failed there for a reason unrelated to that PR's change.

The fix points `approve_command` at a `tempfile::tempdir()`-backed
approvals path via the `Some(&path)` parameter it already accepts — no
process-env mutation (`tests/CLAUDE.md` bans it), matching the in-file
pattern in `src/config/approvals.rs`'s own tests. Same class of fix as
#2615 and #2624.

The two sibling tests in `hook_plan.rs` only *read* via
`Approvals::load()`, which returns the default when no file exists —
never creating a directory or writing — so they pass in the sandbox
unchanged and were left as-is.

Verified by reproducing the sandbox condition locally (test binary run
with `HOME` / `XDG_CONFIG_HOME` pointed at a non-writable dir): the
target test fails before the fix and passes after, and all three
`hook_plan` tests still pass under a plain `cargo test`.

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
max-sixty added a commit that referenced this pull request May 22, 2026
`wt switch --clobber` and `wt step relocate --clobber` each had their
own logic for backing up a path blocking the target, and the two had
diverged. relocate used an `exists()` check followed by
`std::fs::rename` — a time-of-check/time-of-use race, since
`std::fs::rename` silently replaces an existing file or empty directory
on Unix and could destroy a just-created backup. switch (#2849) instead
used `renamore::rename_exclusive`, an atomic no-overwrite rename, and
counted up through suffixes (`…-2`, `…-3`, …) on a name collision rather
than failing.

This PR replaces both with one shared helper in `commands::backup`.
`back_up_clobbered_path_now` computes the timestamped name and delegates
to the suffix-iterating `back_up_clobbered_path`, which moves the
blocker with `renamore::rename_exclusive` — atomic and no-overwrite, so
an existing backup is never clobbered; a name collision just lands on
the next free `-N` name. relocate gains the suffix fallback (previously
it failed closed on `AlreadyExists`), the timestamp computation is no
longer duplicated across the two call sites, and
`renamore::rename_exclusive` now has a single caller.

`renamore` is already a direct dependency and keeps the platform FFI and
its `unsafe` inside that crate, so worktrunk stays `unsafe_code =
"forbid"`.

relocate's backup name changes from `.bak-<timestamp>` to the
extension-aware `.bak.<timestamp>` form used by switch (e.g.
`repo.feature` → `repo.feature.bak.<timestamp>`). The
`test_relocate_clobber_error_backup_exists` regression test asserted the
old fail-closed behavior and is rewritten as
`test_relocate_clobber_falls_back_when_backup_taken`, mirroring the
switch test. CLI help and the generated doc mirrors are updated for the
new naming and fallback.

The shared helper carries the suffix-iteration, collision, and
missing-source unit tests (moved from `resolve.rs`); the relocate
`--clobber` path keeps its integration coverage.

> _This was written by Claude Code on behalf of Maximilian Roos_

---------

Co-authored-by: Claude Opus 4.7 <[email protected]>
max-sixty added a commit that referenced this pull request May 23, 2026
## Summary

`wt switch --clobber` backs up an existing path before clobbering it.
The old code checked `backup_path.exists()` and then, later, called
`std::fs::rename` — which silently overwrites an existing destination on
every platform. Anything that appeared at the backup path between the
check and the rename (a same-second clobber, or a path that raced in)
was destroyed: a time-of-check/time-of-use data-loss race on a
`--clobber` operation.

## The fix

The backup now moves with `renamore::rename_exclusive` — an atomic,
no-overwrite rename: `renameat2(RENAME_NOREPLACE)` on Linux,
`renamex_np(RENAME_EXCL)` on macOS, `MoveFileExW` on Windows. It fails
closed (`AlreadyExists`) rather than overwriting. `renamore` keeps the
platform FFI — and its `unsafe` — inside the crate, so worktrunk itself
stays `unsafe_code = "forbid"`.

`back_up_clobbered_path` moves the stale path with that primitive. If
the timestamped backup name is already taken, it counts up — `…-2`,
`…-3`, … — until it finds a free name, so a collision no longer fails
the command and an existing backup is never overwritten. The loop
terminates because a directory holds finitely many entries; genuine I/O
errors still surface as errors.

The timestamp and the move now both happen at execution time, which also
closes a smaller stale-plan window — the backup path was previously
computed during planning and renamed much later.

## Key files

- `src/commands/worktree/resolve.rs` — `back_up_clobbered_path` retry
loop.
- `src/commands/worktree/switch.rs` — `execute_switch` uses it; the plan
now carries `needs_clobber_backup: bool` instead of a resolved path.

## Notes

- `renamore` is a new dependency. `rustix` / `windows-sys` are
deliberately not added as direct dependencies — calling either's rename
API requires an `unsafe` block, which this crate forbids; `renamore`
encapsulates that.
- `wt step relocate --clobber` has the identical
check-then-`std::fs::rename` race. It is **not** fixed here — a separate
branch handles relocate; when that lands it should adopt
`renamore::rename_exclusive`.

## Testing

`back_up_clobbered_path` has unit tests covering every branch — fresh
move, `-N` fallback, many collisions, non-`AlreadyExists` error.
Integration tests cover `wt switch --clobber` end-to-end, including the
collision fallback (which runs on the Windows CI job).

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
max-sixty added a commit that referenced this pull request May 23, 2026
…2853)

The `nix-flake` CI job was red on `main`: the unit test
`commands::hook_plan::tests::approve_readonly_drops_unapproved_project_keeps_user`
panicked with `Failed to create config directory: Permission denied`.

The test called `approve_command(.., None)`. The `None` for
`approvals_path` makes `Approvals` resolve the path through
`approvals_path()`, which — in the lib crate compiled in non-test mode —
points at the real `~/.config/worktrunk/` directory. `approve_command`
then `create_dir_all`s it. Outside a sandbox `$HOME` is writable, so the
test silently passed while writing a stray `[projects.proj]` entry into
the user's `approvals.toml`. The nix build sandbox has no writable
config dir, so it panicked instead.

This was latent on `main` since #2806 (which added the test). It only
started tripping the gate now because the `nix-flake` job runs when a PR
touches `Cargo.{toml,lock}`, and #2849 was the first to do so — so
`nix-flake` failed there for a reason unrelated to that PR's change.

The fix points `approve_command` at a `tempfile::tempdir()`-backed
approvals path via the `Some(&path)` parameter it already accepts — no
process-env mutation (`tests/CLAUDE.md` bans it), matching the in-file
pattern in `src/config/approvals.rs`'s own tests. Same class of fix as
#2615 and #2624.

The two sibling tests in `hook_plan.rs` only *read* via
`Approvals::load()`, which returns the default when no file exists —
never creating a directory or writing — so they pass in the sandbox
unchanged and were left as-is.

Verified by reproducing the sandbox condition locally (test binary run
with `HOME` / `XDG_CONFIG_HOME` pointed at a non-writable dir): the
target test fails before the fix and passes after, and all three
`hook_plan` tests still pass under a plain `cargo test`.

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
max-sixty added a commit that referenced this pull request May 23, 2026
`wt switch --clobber` and `wt step relocate --clobber` each had their
own logic for backing up a path blocking the target, and the two had
diverged. relocate used an `exists()` check followed by
`std::fs::rename` — a time-of-check/time-of-use race, since
`std::fs::rename` silently replaces an existing file or empty directory
on Unix and could destroy a just-created backup. switch (#2849) instead
used `renamore::rename_exclusive`, an atomic no-overwrite rename, and
counted up through suffixes (`…-2`, `…-3`, …) on a name collision rather
than failing.

This PR replaces both with one shared helper in `commands::backup`.
`back_up_clobbered_path_now` computes the timestamped name and delegates
to the suffix-iterating `back_up_clobbered_path`, which moves the
blocker with `renamore::rename_exclusive` — atomic and no-overwrite, so
an existing backup is never clobbered; a name collision just lands on
the next free `-N` name. relocate gains the suffix fallback (previously
it failed closed on `AlreadyExists`), the timestamp computation is no
longer duplicated across the two call sites, and
`renamore::rename_exclusive` now has a single caller.

`renamore` is already a direct dependency and keeps the platform FFI and
its `unsafe` inside that crate, so worktrunk stays `unsafe_code =
"forbid"`.

relocate's backup name changes from `.bak-<timestamp>` to the
extension-aware `.bak.<timestamp>` form used by switch (e.g.
`repo.feature` → `repo.feature.bak.<timestamp>`). The
`test_relocate_clobber_error_backup_exists` regression test asserted the
old fail-closed behavior and is rewritten as
`test_relocate_clobber_falls_back_when_backup_taken`, mirroring the
switch test. CLI help and the generated doc mirrors are updated for the
new naming and fallback.

The shared helper carries the suffix-iteration, collision, and
missing-source unit tests (moved from `resolve.rs`); the relocate
`--clobber` path keeps its integration coverage.

> _This was written by Claude Code on behalf of Maximilian Roos_

---------

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants