|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""PreToolUse guard: stop blanket `git add`/`git commit -a` when the worktree |
| 3 | +contains sandbox `/dev/null` device-node masks. |
| 4 | +
|
| 5 | +Under the hardened sandbox, Claude Code bind-mounts /dev/null over sensitive |
| 6 | +config paths (.mcp.json, .gitconfig, .claude/{launch.json,routines,...}, editor |
| 7 | +dirs). Git cannot index a character-device node, so `git add -A` / `git add .` / |
| 8 | +`git commit -a` abort the *whole* commit with: |
| 9 | +
|
| 10 | + error: <path>: can only add regular files, symbolic links or git-directories |
| 11 | + fatal: adding files failed |
| 12 | +
|
| 13 | +Explicit path staging (`git add <path> ...`) skips the masks and works fine, so |
| 14 | +this guard blocks only the blanket forms — and only when masks are actually |
| 15 | +present (i.e. inside the sandbox). Outside the sandbox it is a no-op, so it never |
| 16 | +obstructs consumers who don't run hardened. |
| 17 | +
|
| 18 | +Contract: reads the PreToolUse event JSON on stdin. Exit 0 = allow. Exit 2 = |
| 19 | +block (stderr is shown to the agent). |
| 20 | +""" |
| 21 | +import json |
| 22 | +import os |
| 23 | +import re |
| 24 | +import shlex |
| 25 | +import stat as _stat |
| 26 | +import subprocess |
| 27 | +import sys |
| 28 | + |
| 29 | +# Shell separators that terminate one simple command. |
| 30 | +_SEP = re.compile(r"&&|\|\||;|\||\n") |
| 31 | + |
| 32 | + |
| 33 | +def _segments(cmd): |
| 34 | + return [s.strip() for s in _SEP.split(cmd) if s.strip()] |
| 35 | + |
| 36 | + |
| 37 | +def _tokens(segment): |
| 38 | + try: |
| 39 | + return shlex.split(segment) |
| 40 | + except ValueError: |
| 41 | + # Unbalanced quotes etc. — fall back to whitespace split. |
| 42 | + return segment.split() |
| 43 | + |
| 44 | + |
| 45 | +def _short_flag_has(tok, letter): |
| 46 | + """True if tok is a single-dash short flag bundle containing `letter` |
| 47 | + (e.g. -a, -am). Excludes long options like --all / --amend.""" |
| 48 | + return ( |
| 49 | + tok.startswith("-") |
| 50 | + and not tok.startswith("--") |
| 51 | + and letter in tok[1:] |
| 52 | + ) |
| 53 | + |
| 54 | + |
| 55 | +def _is_blanket(cmd): |
| 56 | + for seg in _segments(cmd): |
| 57 | + toks = _tokens(seg) |
| 58 | + if "git" not in toks: |
| 59 | + continue |
| 60 | + gi = toks.index("git") |
| 61 | + rest = toks[gi + 1 :] |
| 62 | + if "add" in rest: |
| 63 | + args = rest[rest.index("add") + 1 :] |
| 64 | + for a in args: |
| 65 | + if a in ("-A", "--all", "."): |
| 66 | + return True |
| 67 | + if _short_flag_has(a, "A"): # bundled, e.g. -Av |
| 68 | + return True |
| 69 | + if "commit" in rest: |
| 70 | + args = rest[rest.index("commit") + 1 :] |
| 71 | + for a in args: |
| 72 | + if a == "--all": |
| 73 | + return True |
| 74 | + if _short_flag_has(a, "a"): # -a, -am, -a -m (not --amend) |
| 75 | + return True |
| 76 | + return False |
| 77 | + |
| 78 | + |
| 79 | +def _has_device_masks(): |
| 80 | + """True if the worktree contains a /dev/null character-device mask. |
| 81 | +
|
| 82 | + The sandbox bind-mounts /dev/null over sensitive config paths. Crucially, a |
| 83 | + directory entry's readdir `d_type` still reports the *underlying* regular |
| 84 | + file, so `find -type c` (and DirEntry.is_*) miss the mask — only an actual |
| 85 | + `stat()` follows the bind-mount and reports S_IFCHR. So we os.stat() entries |
| 86 | + ourselves. Masks always include repo-root dotfiles (.gitconfig, .mcp.json, |
| 87 | + shell rc, editor dirs) and .claude/* items, so a shallow scan of those two |
| 88 | + dirs is enough and stays fast on every Bash call. |
| 89 | + """ |
| 90 | + try: |
| 91 | + root = subprocess.run( |
| 92 | + ["git", "rev-parse", "--show-toplevel"], |
| 93 | + capture_output=True, text=True, timeout=5, |
| 94 | + ).stdout.strip() or "." |
| 95 | + except Exception: |
| 96 | + root = "." |
| 97 | + for d in (root, os.path.join(root, ".claude")): |
| 98 | + try: |
| 99 | + with os.scandir(d) as it: |
| 100 | + for e in it: |
| 101 | + try: |
| 102 | + if _stat.S_ISCHR(os.stat(e.path).st_mode): |
| 103 | + return True |
| 104 | + except OSError: |
| 105 | + continue |
| 106 | + except OSError: |
| 107 | + continue |
| 108 | + return False |
| 109 | + |
| 110 | + |
| 111 | +def _sandbox_enabled(): |
| 112 | + """True if the Bash sandbox is enabled for this session. |
| 113 | +
|
| 114 | + The PreToolUse hook runs *outside* the sandbox, so it cannot see the |
| 115 | + /dev/null device-node masks — they exist only inside the per-command bwrap |
| 116 | + namespace, and os.stat here reports the masked paths as absent. So instead of |
| 117 | + detecting the symptom (masks), detect the cause: an enabled sandbox. When it |
| 118 | + is on, a blanket `git add` run as a sandboxed Bash command will hit the masks |
| 119 | + and abort, so we block preemptively. When it is off (non-hardened consumers), |
| 120 | + this returns False and the guard is a no-op. |
| 121 | + """ |
| 122 | + home = os.path.expanduser("~") |
| 123 | + pdir = os.environ.get("CLAUDE_PROJECT_DIR", ".") |
| 124 | + for path in ( |
| 125 | + os.path.join(pdir, ".claude", "settings.local.json"), |
| 126 | + os.path.join(pdir, ".claude", "settings.json"), |
| 127 | + os.path.join(home, ".claude", "settings.json"), |
| 128 | + ): |
| 129 | + try: |
| 130 | + with open(path) as f: |
| 131 | + cfg = json.load(f) |
| 132 | + except Exception: |
| 133 | + continue |
| 134 | + if (cfg.get("sandbox") or {}).get("enabled") is True: |
| 135 | + return True |
| 136 | + return False |
| 137 | + |
| 138 | + |
| 139 | +def main(): |
| 140 | + try: |
| 141 | + data = json.load(sys.stdin) |
| 142 | + except Exception: |
| 143 | + return 0 |
| 144 | + if data.get("tool_name") != "Bash": |
| 145 | + return 0 |
| 146 | + cmd = (data.get("tool_input") or {}).get("command", "") |
| 147 | + if not cmd or "git" not in cmd: |
| 148 | + return 0 |
| 149 | + if not _is_blanket(cmd): |
| 150 | + return 0 |
| 151 | + # Fire when the sandbox is active (its masks will abort the blanket add) or, |
| 152 | + # should a future Claude Code run hooks sandboxed, when masks are visible. |
| 153 | + if not (_sandbox_enabled() or _has_device_masks()): |
| 154 | + return 0 |
| 155 | + |
| 156 | + sys.stderr.write( |
| 157 | + "Blocked: a blanket `git add -A/./--all` or `git commit -a` will try to " |
| 158 | + "index this sandbox's /dev/null device-node masks (the `crw-` entries in " |
| 159 | + "`git status`) and abort the whole commit " |
| 160 | + "(`can only add regular files, symbolic links or git-directories`).\n" |
| 161 | + "Stage the files you actually changed, by name:\n" |
| 162 | + ' git add <path1> <path2> && git commit -m "..."\n' |
| 163 | + "The `crw-` entries are sandbox masks, not your work — ignore them. " |
| 164 | + "See docs/HARDENING.md -> Caveats.\n" |
| 165 | + ) |
| 166 | + return 2 |
| 167 | + |
| 168 | + |
| 169 | +if __name__ == "__main__": |
| 170 | + sys.exit(main()) |
0 commit comments