Skip to content

fix(checkout): stop a cloned tree from writing into .sc/ or escaping the checkout - #367

Merged
tonibergholm-codento merged 7 commits into
mainfrom
fix/sc-path-guard
Nov 20, 2026
Merged

tonibergholm-codento merged 7 commits into
mainfrom
fix/sc-path-guard

Conversation

@tonibergholm-codento

Copy link
Copy Markdown
Collaborator

Cloning a hostile repository could write into the cloner's .sc/ control directory. The checkout only refused empty, . and .. path components. A plain git repository that tracks .sc/recipients.toml and is cloned with sc clone file://… victim --git left that file in victim/.sc/, and a native sc remote can do the same. A planted recipients.toml sets trusted signers, so sc verify --require accepts attacker-signed history. It also sets escrow keys, so every later seal is wrapped to the attacker, and the name-to-key map, which redirects --to <name>. On Windows, \ or : in an entry name also escaped the checkout.

This PR stops both:

  • Path check. scl_core::check_tree_path refuses empty, ., .. and NUL components, and .sc at any depth under every alias a filesystem resolves to it:

    • case and Unicode case, including .ſc;
    • HFS-ignorable code points;
    • an NTFS :stream suffix and trailing dots or spaces;
    • the 8.3 short names SC~1 and SC<4 hex>~N.

    On Windows it also refuses \ and :.

  • Before any write. Every checkout flattens its tree through that check before the first write: clone, switch, fast-forward, merge, undo, sparse changes, private branches, sc ws fork and sc work.

  • Symlinked parents. Forward operations refuse to write through a symlinked parent directory. An abort leaves such a path alone and lists it in kept.

  • New snapshots. A new snapshot cannot contain a .sc alias or NUL.

  • sc clone destination. It refuses a non-empty existing destination, as git does. It claims the destination and .sc/ with exclusive creates. A failed clone removes, while still holding its lock, only the directories and .sc/ it created.

  • sc init. It also creates .sc/ exclusively.

Known limits, recorded in the threat model:

  • A failed clone's cleanup can still race a concurrent open of the same half-made directory; closing that needs a staged clone.
  • Refusing .git in trees is left as a follow-up, because the working-tree walk does not skip .git and repositories co-located with git would break.

Proof: the original reproduction now fails with unsafe path in tree: ".sc" and leaves no destination directory. Tests cover the aliases, clone, switch, fast-forward, ws fork, sc work, an unborn merge through a symlink, an abort past a symlink, clone cleanup ownership, and a CLI clone of a real git repository tracking .sc/recipients.toml. cargo test -p scl-core -p scl-vfs -p scl-repo -p scl-cli and workspace clippy pass after the rebase.

Reviewed with sol-loop: 5 rounds with gpt-6.2-sol. Sol's last round found one blocker, writes through a symlinked parent, which is fixed here. It also left one item declined: the cleanup race above. An independent Opus review of the final commits found the abort-contract issue, which is fixed. A Mythos security review found the .ſc alias and the NTFS short-name form in round 1.

Created with Claude Opus 5.5 and Claude Sonnet 5.5 in Claude Code.

Tree decode accepts any entry name and safe_join rejected only empty, `.`
and `..` components. A remote whose tree held `.sc/recipients.toml` got
that file written into the cloner's `.sc/` (native and Git-bridge
clones), and on Windows a name like `..\..\x` or `C:\x` left the
checkout.

Add scl_core::check_tree_path, a pure predicate that refuses empty, `.`,
`..` and NUL components, `.sc` at any depth under its HFS/NTFS aliases
(logic copied from the forge's `.git` guard), and on Windows any `\` or
`:`. The tree flatteners, preflight_view, the private-branch flattener
and safe_join apply it, so clone, switch, merge, undo and friends refuse
before the first write. Worktree::checkout checks every path up front.
Both tree builders refuse to commit such a path (without the Windows
rule, since `:` and `\` are legal unix names).

A clone that fails after init now removes the directory it created (only
its `.sc/` if the directory already existed), for native and `--git`
clones.
- Fold case with Unicode uppercase so `.ſc` (U+017F), which a
  case-insensitive APFS volume resolves to `.sc`, is refused.
- Also refuse NTFS's checksum short name of `.sc`: `sc` + four hex
  digits + `~1` to `~9`, besides `sc~1` to `sc~4`.
- Decide clone-directory ownership by claiming it with `create_dir`
  (`sync::claim_clone_dir`), not from `exists()`: only an `Ok` means the
  clone created it and may remove it on failure; an existing directory
  keeps the "remove only the `.sc/` we made" behaviour.
- `sc ws fork` and `sc work` validate the target tree's paths before they
  clear the old session directory, mint `.sc/local-key` or create the
  session root; on a full clone `preflight_view` did not look at paths.
- A `RepoExists` from `Repo::init` after the destination was claimed means
  another process made `.sc/`: clean up nothing.
- `claim_clone_dir` now returns a `CloneClaim` recording each directory this
  call created (missing parents, then the destination). A failed clone removes
  its own `.sc/`, then those directories deepest first with `remove_dir`, so a
  directory that gained other content is left in place and named on stderr.
- An existing clone destination must be an empty directory (as `git clone`
  requires, both clone paths), so a symlink or junction already inside it
  cannot redirect the checkout's writes.
- Match the NTFS checksum short name (`sc` + 4 hex + `~N`) on the original
  characters with ASCII folding only. Unicode uppercase stays for the `.sc`
  and `sc~1`..`sc~4` comparison (`.ſc`), so `sc<ff ligature>12~1` is no
  longer a false match.
- A clone owns `.sc/` only if its own `create_dir` created it
  (`CloneClaim::init_repo`, `Repo::init_in_claimed_dot_sc`). Two
  initializers can both pass an existence check, so the recursive `.sc/`
  cleanup now runs only for the one whose `create_dir` succeeded; any
  failure where `.sc/` is not ours leaves it alone. This replaces
  `discard_after_init_error`.
- A destination that appears between the initial lookup and our
  `create_dir` (`AlreadyExists`) gets the empty-directory check instead of
  being trusted; a dangling symlink destination is refused.
- Fold the `S` and `C` of the NTFS checksum short name with Unicode
  uppercase, like `.sc` (so `ſC1234~1` is refused), keeping ASCII-only
  matching for the four hex digits and `~1`..`~9`.
- THREAT-MODEL: scope the "changes nothing" guarantee to working-tree
  writes and ref moves, and describe the clone cleanup rules.
… cleanup

- `Repo::init` claims `.sc/` with an exclusive `create_dir`
  (`AlreadyExists` = `RepoExists`), so plain `sc init` can no longer enter
  a clone's freshly created `.sc/`; both paths own `.sc/` only by
  creating it.
- A failed clone removes its `.sc/` while its repo lock is still held
  (the clone body borrows the repo instead of owning it), so a concurrent
  `Repo::open` cannot take the lock in a gap and have its repo deleted.
- `claim_clone_dir` always routes the destination itself through
  `create_dir` and applies the empty-directory check on `AlreadyExists`,
  so a destination that appears after the lookup is not accepted unchecked.
- Docs: a native clone writes branch refs and HEAD in its new `.sc/`
  before the path check and removes them on failure; fix the short-name
  comment in pathname.rs.
`materialize` skips the parent-obstruction checks when there is no old
tree (an unborn merge, a clone), so a remote entry `link/x` would write
through a user's untracked `link -> .sc` or a directory outside the
checkout. Before its first write, for every path it will write and
whatever `old_root` is, refuse when any parent component is a symlink
(`under_symlink`, `symlink_metadata`, never followed). The unborn merge
keeps its documented "no untracked-overwrite refusal" behaviour
otherwise. Docs updated to match.
The symlinked-parent refusal in `materialize` also fired for
`materialize_restore` (merge/pick/rebase abort), which must finish
anyway. In restore mode a path with a symlink among its parents is now
skipped (not written, not removed, not counted in the blocked-parent or
directory-clearable checks) and reported in `kept`, like the leaf-symlink
case; forward operations keep refusing.

`under_symlink` now fails closed on an lstat error other than NotFound or
NotADirectory.

The existing abort test that expected a refusal for a symlink standing
where a directory must be now expects the abort to finish with the path in
`kept` and nothing written through the link. THREAT-MODEL updated.
@coderabbitai

coderabbitai Bot commented Nov 20, 2026

Copy link
Copy Markdown

Important

  • Trigger review

This repository does not receive automatic reviews because it has fewer than 10 stars.

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: b7b6b88a-791e-4bca-a36b-1aa6144db9f0
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-20T10:33:12.744211Z 2afd318 PR opened
🔒 Security Review ✅ Completed 2026-11-20T10:37:00.302405Z 2afd318 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@tonibergholm tonibergholm left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed: sol-loop (5 rounds; last blocker fixed), independent Opus review of the final commits, Mythos security review, required checks green, Codex review has no findings. Reproduction now refused.

@tonibergholm-codento
tonibergholm-codento merged commit e8df713 into main Nov 20, 2026
11 checks passed
@tonibergholm-codento
tonibergholm-codento deleted the fix/sc-path-guard branch November 20, 2026 10:42
tonibergholm-codento added a commit that referenced this pull request Nov 20, 2026
…annot add themselves (#368)

* feat(repo): refuse to seal to a recipient this clone never accepted

Protection rules, secret wrap lists and private-branch KEK wrap labels are
repository data, so a writer with no key could grant their own key and wait
for the victim's next commit, merge or replay reseal, rewrap, secret rotate or
branch revoke to wrap a DEK to them.

.sc/accepted-recipients is a local record of the recipient ids accepted per
scope (path:<prefix>, secret:<NAME>, branch:<name>); local [escrow] keys count
everywhere. encrypt_protected, the one function that turns a rule into wraps,
refuses before sealing anything when a key is not accepted for the winning
rule's prefix. sc protect validates the candidate rule before its first ref
move, secret_rotate and branch_revoke check the final set, and rewrap skips an
entry with an unaccepted key. Carries that copy existing wraps are not gated.

Keys named by the caller are accepted on the spot (protect, grant, secret
add/grant, branch --private, branch grant); the local revoke operations drop
the pair. The record is written atomically under the repo lock and is never
committed, packed or transferred. The test seams that hand-build rules accept
the keys they name.

Refs ADR-0059.

* feat(cli): add sc policy accept and forget

sc policy accept <scope> --key <scl-pk|id>[,...] records recipients in the
local .sc/accepted-recipients; a key in neither [recipients] nor [escrow]
needs --allow-unknown. sc policy forget removes one. Both touch only the local
file, so they work while a merge, pick or rebase is stopped and a refused
completion can be retried.

sc secret rotate --to accepts the keys it names, since the library cannot tell
a named set from one derived from the secret's own wrap labels. The rewrap hint
now mentions the accept route for skipped entries.

Refs ADR-0059.

* docs: ADR-0059 locally accepted recipients

Records the problem, the local accepted-recipients record, the gate sites, the
auto-accept rule, the migration, the alternatives rejected (seal only to
recipients.toml; signed policy) and the deferred items and residual risks.
Adds the matching THREAT-MODEL entries (Protected paths, with one line each
under Committed secrets and Private branches), a CLAUDE.md standing-boundary
bullet, the ADR index row, and status pointers on ADR-0025 and ADR-0027.

* fix(repo): harden accepted-recipient bookkeeping after review

Escrow keys are no longer recorded as approvals. protect and secret add
persist only the keys the user named (the library drops the keys currently in
[escrow] from what it records, the CLI records the named ones), and private
branch creation records the creator and the named recipients only, so removing
a key from [escrow] withdraws its acceptance.

The three local revokes drop the approval after validation and before the new
ref is published, so an interruption cannot leave an approval outliving a
landed revoke.

sc policy accept validates the whole batch and writes the record once; a
path: scope with an id that has no key behind it is an error even with
--allow-unknown.

Refusal messages escape every repository-controlled field with
sanitize_display_line and print no command for a scope with control
characters. A Remove target that starts with "-" is written flags first and
after "--".

The shared seal path loads the record only when something is sealed, and
rewrap loads it at the first entry that wraps anything, so a commit that
wraps nothing no longer depends on the record being readable.

The ADR notes that the record's integrity depends on the working-tree path
guard.

* fix(cli): print one revoke form, warn on a rule-less path scope, document revoke gap

The suggested Remove command is always "flags, --, target", so a target that
starts with "-" cannot be read as a flag (the check ran after quoting before,
so it never fired). The shell quoting is POSIX only, as its comment says.

sc rewrap prints its skipped entries through sanitize_display_line: they carry
paths and names from the repository.

sc policy accept warns when a path: scope names no rule at the tip, and still
records it.

An ignored test (needs PR #367) pins that a cloned tree holding
.sc/accepted-recipients or .sc/recipients.toml is refused, since the record's
integrity does not rest on this change alone.

ADR-0059, THREAT-MODEL and ROADMAP record the residual risk that a revoke made
in another clone leaves this clone's acceptance in place, and the follow-on of
recording the grant epoch with each path: pair.

* test(repo): run the clone-planting check now that the path guard landed

* fix(repo): stage approvals until the plan validates, skip relabeled secrets in rewrap

rewrap skips a registry entry sealed under another name before opening it, as
secret_rotate refuses it: it would otherwise be approved by the registry name
and resealed under the sealed name, so a relabeled secret got wraps under
another secret's approvals.

protect_with_escrow and secret_add_with_escrow take the keys the user named
apart from the escrow keys a command appends. protect stages the named keys in
memory while it validates the rule and the sealing commit, records them after
validation and before either ref moves, and a refusal leaves record, refs and
oplog alone. secret add records the named keys before its ref moves. The CLI
no longer records after the operation landed.

The record is written with atomic_write_durable (fsynced temp file, rename,
fsynced directory), as durable as the ref write. rewrap reads the record only
for an entry that mints a wrap: a secret that opens, a path re-sealed or
rotated, or a target with no wrap yet. A randomized path whose every wrap is
reused copies them and needs no approval.

The refusal text says what is true: no ref moved and no approval was recorded.
sc protect --list, sc secret list, sc branch list and sc policy accept/forget
print repository text through sanitize_display_line.

* fix(repo): drop the shared staging state, refuse relabeled grants, sync unchanged records

protect no longer stages approvals on the Repo handle. snapshot_files_with
takes the approval source as a parameter and protect passes the keys it is
about to record for that call only, so no other operation on the same handle
can see them. snapshot_files keeps its signature and reads the record.

secret grant refuses a registry entry sealed under another name before it
records an approval or wraps anything, as rotate and rewrap do.

rewrap checks a path re-seal against the record only after the ciphertext has
opened, so a corrupt blob is skipped as that when the record is unreadable.

An accept or forget that changes nothing still fsyncs .sc, so a retry after a
failed directory sync cannot report success on an unsynced record.

* fix(repo): authenticate a grant's secret, record approvals after authorization, lock the record

secret grant opens the secret with the identity before it records or wraps
anything. The registry key and the name in the secret's metadata are both
repository data and can be made to agree, but the AEAD binds the name the secret
was sealed under, so an edited name fails to open and the grant is refused.

grant, secret grant and secret rotate --to record the named key only after the
identity is authorized and the operation validated, still before the ref moves.
secret_rotate_with takes the named keys as call-local approvals, and the CLI
passes them instead of recording first, so a refused command leaves no approval.

accept and forget read, change and write the record under .sc/index.lock, so
callers on one handle cannot lose each other's change.

ADR-0059 records the declined residual: an interruption after the approval write
and before the ref move leaves an approval for a key the user named on that
command.

* fix(cli): sc protect --list exits quietly on a closed pipe
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