diff --git a/.claude/hooks/restrict_repo_access.py b/.claude/hooks/restrict_repo_access.py index 218d408..73bd657 100644 --- a/.claude/hooks/restrict_repo_access.py +++ b/.claude/hooks/restrict_repo_access.py @@ -17,21 +17,55 @@ - Edit / NotebookEdit: 既存ファイルの書き換えなので拒否する - インライン実行(python -c 等): 削除系の呼び出しがありリポジトリ外のパスを 含む場合と,既知の上書き呼び出し(open(..., 'w') 等)の対象が既存ファイルの場合に拒否する -- 禁止リスト(deny_read)に該当するパスは,どの操作でも拒否する +- 禁止リスト(deny_read)に該当するパスは,どの操作でも拒否する(許可ゾーン・allow_write より優先) +- 入力の読み取りや判定で想定外の例外が起きたら拒否する(壊れた入力を含む.対象がリポジトリ外かは問わない) +- Bash / PowerShell のコマンドに NUL 文字があれば拒否する(コマンドの種類・対象を問わない) +- Bash / PowerShell のコマンドと Write / Edit / MultiEdit / NotebookEdit の書き込み先のパスが, + 項目はあるのに文字列でなければ拒否する(対象がリポジトリ外かは問わない) リポジトリの基準は CLAUDE_PROJECT_DIR(無ければフック入力の cwd).相対パスは フック入力の cwd を起点に,コマンド内の cd / pushd / Set-Location 等を追跡して解決する. -禁止リスト: <リポジトリ>/.claude/repo-access.json - {"deny_read": ["~/.ssh", "/etc", "secrets"]} - 絶対パス・`~` 始まり・リポジトリルート相対を受け付ける.ファイルが無ければ空, - 壊れていれば空として扱い stderr に警告する. +設定ファイル: <リポジトリ>/.claude/repo-access.json + {"deny_read": ["~/.ssh", "/etc", "secrets"], "allow_write": ["../sibling-repo", "~/work/data-repo"]} + deny_read(禁止リスト): 読み取り・書き込みとも拒否するパス. + allow_write(書き込み許可ディレクトリ): リポジトリ外でも上書き・Edit・削除・移動を許可する + ディレクトリ(配下だけ.ディレクトリ自体の削除・移動は許可しない).deny_read に当たるパスは拒否が優先する. + どちらも絶対パス・`~` 始まり・リポジトリルート相対(`../` で隣のフォルダ)を受け付ける.ファイルが無ければ空, + 壊れていれば空として扱い stderr に警告する(警告を書けなければ想定外の例外として拒否する). + deny_read が不正なときは allow_write も空として扱う(禁止リストが効かないまま書き込みだけ許可しない). + allow_write の次の指定は無視して stderr に警告する: 配列でない(全体)・文字列でない要素, + ワイルドカード・波括弧を含む,`~user`,存在しない・ディレクトリでない,ファイルシステムのルート, + ホームディレクトリそのもの・その祖先,リポジトリ自身・その祖先(`..` 等),~/.claude の中. 許可ゾーン(リポジトリ外でも削除・上書きを許可する): - システム一時ディレクトリ(/tmp・%TEMP% 等.Claude Code のスクラッチパッドを含む) (/sync-template・/set-mode がテンプレートを mktemp -d に clone して cp・rm -rf - するため.一時ディレクトリは使い捨て領域であり,許可しても失うものがない) + するため.一時ディレクトリは使い捨て領域であり,許可しても失うものがない). + Linux / macOS ではリンクを解決した実パスで判定するので,一時ディレクトリの外へのリンク越しの + 操作は許可しない(rm 等がリンク自体を消すだけの場合は許可する) - /dev/null・NUL・$null 等の特殊デバイス +- 今のプロジェクトの Claude メモのフォルダの配下(フック入力の transcript_path の親 + フォルダ直下の memory の中.メモの更新・修正・削除は Claude の通常の作業のため). + memory フォルダ自体の削除・移動,memory がシンボリックリンクの場合,他のプロジェクトの + メモ,transcript_path が無い・絶対パスでない場合は許可しない. + 実際の対象を文字列から確定できないパス(波括弧・`..` を含む,途中の階層にワイルドカードを + 含む,コマンド内の cd 等の移動先がそれらやワイルドカードを含む)も許可しない.最後の要素 + だけのワイルドカード(memory/*・memory/*.md)は許可する(rm 等が一致したリンク自体を消すだけの + 場合はリンク先を判定しない.Bash で末尾に / があるとリンク先の中身が消えるので,その場合は判定する). + transcript_path の親の階層に [ や { があると,メモのフォルダの許可は効かない(安全側の制限) +- repo-access.json の allow_write に書いたディレクトリの配下.許可ディレクトリ・対象ともリンクを解決した + 実パスで判定するので,許可ディレクトリの外へのリンク越しの操作は許可しない(rm 等がリンク自体を + 消すだけの場合は許可する).実際の対象を文字列から確定できないパスはメモのフォルダと同じく許可しない + +パスの展開と解決(削除・上書き・作成の対象について): +- 波括弧は Bash 系の方言でだけ展開して,元の文字列のままの判定に加えて展開後の各パスも判定する + (PowerShell・cmd.exe は波括弧を展開しない).展開数が上限を超えた語が削除・上書きの対象なら拒否する +- ワイルドカードはフック実行時に実際に展開して,一致した各パスも判定する(Bash・PowerShell. + 一致が無ければ文字列のままの判定だけ) +- `..` は文字列の正規化に加え,OS と同じ順に要素をたどる解決(リンク・ジャンクションを解決してから + 親に上がる)でも判定する.どちらかでリポジトリ外や既存ファイルに当たれば拒否・上書き扱いにする +- cd - / pushd - / Set-Location - / + / Push-Location - / + は,同じコマンド内で追跡できる場合だけ移動先を解決する 限界(重要): 本フックはコマンド文字列の静的解析であり,原理的に完全には防げない.変数展開 @@ -40,6 +74,14 @@ コマンド,未対応のコマンドによる削除・上書き,インライン実行中の未対応の書き方 (変数に入れたパス・Perl の open 等)は検出できない.存在判定はフック実行時点の ものであり,同じコマンド内で先に作ったファイルを上書きする場合等は許可される. + トークナイザーがクォートの情報を落とすため,クォート内の波括弧・ワイルドカードも展開して + 判定する(安全側).`**` は 1 階層のワイルドカードとして扱う(globstar の再帰は追わない). + ワイルドカードの一致が多すぎると残りは調べず,基点がリポジトリ内・一時ディレクトリならそのまま + 許可,それ以外は拒否する.読み取り(禁止リスト)の判定はワイルドカードを展開しない. + cmd.exe のコマンド・インライン実行のコードは波括弧・ワイルドカード・リンクの展開の対象外. + Windows PowerShell 5.1 は Set-Location - / Push-Location - を受け付けず元の場所に留まるが,追跡は 7 系の挙動に合わせる. + pushd -n (実際には移動しないが移動として扱う),サブシェル内の pushd / popd + (スタックを復元しない)は,実際の対象とずれることがある. 逆にインライン実行は,削除系の呼び出しとリポジトリ外のパス(文字列・コメント中の ものも含む)が同時に現れると,削除対象でなくても拒否することがある. cmd.exe の引数のうち /opt のように / の後に要素が 1 つだけのパスは,スイッチ @@ -51,12 +93,15 @@ from __future__ import annotations +import fnmatch import json import os import posixpath import re +import stat import sys import tempfile +import traceback CONFIG_RELPATH = ".claude/repo-access.json" @@ -72,6 +117,18 @@ "ユーザーが読ませたくない場所として指定しているパスです." "別の書き方で迂回して読まないでください" ) +NUL_COMMAND_DENY_REASON = ( + "コマンドに NUL 文字が含まれていて対象を判定できないため,ブロックしました." + "別の書き方(変数・スクリプトファイル・インライン実行等)で迂回しないでください." + "NUL が意図しないものならコマンドを見直し,必要な操作であればユーザーに報告してください" +) +INVALID_VALUE_TYPE_DENY_REASON = ( + "ツールの入力のコマンドまたは書き込み先のパスが文字列ではなく,型が不正で対象を判定できないため,ブロックしました." + "別の書き方(変数・スクリプトファイル・インライン実行等)で迂回しないでください." + "入力を見直し,解決しなければユーザーに報告してください" +) +# 書き込みとして判定するファイル操作ツールと,そのパスの項目 +WRITE_TOOL_PATH_KEYS = {"Write": "file_path", "Edit": "file_path", "MultiEdit": "file_path", "NotebookEdit": "notebook_path"} # 解決できないパスを表す(変数展開を含む等).判定をスキップする UNKNOWN = None @@ -93,6 +150,18 @@ DELETE = "delete" OVERWRITE = "overwrite" CREATE = "create" +# ワイルドカードの一致が多すぎて全部は調べられなかった.基点が許可ゾーンでなければ拒否する +UNDECIDABLE = "undecidable" + +# 波括弧の展開の上限(1 語あたりの展開数・語の長さ・ネストの深さ).超えた語が削除・上書きの対象なら拒否する +MAX_BRACE_EXPANSIONS = 256 +MAX_BRACE_WORD_LENGTH = 4096 +MAX_BRACE_DEPTH = 32 +# ワイルドカードの展開の上限(1 パスあたりの一致数・1 コマンドあたりの調べるディレクトリエントリ数). +# フックの実行時間を抑えるため(タイムアウトすると検査が効かない) +MAX_WILDCARD_MATCHES = 1000 +MAX_WILDCARD_SCANS = 10000 +_wildcard_scans_left = [MAX_WILDCARD_SCANS] # --------------------------------------------------------------------------- # Bash: コマンドの分類 @@ -246,18 +315,45 @@ return real_target.startswith(real_base) -def is_temp_path(path: str) -> bool: +def is_real_path_in_temp(path: str, keep_final_link: bool) -> bool: + """POSIX で,リンクを解決した path の実パスが /tmp か tempfile.gettempdir() の中にあるかを判定する. + + 基準も実パスに解決して比べる(macOS の /tmp → /private/tmp,/var/folders/... → /private/var/folders/...). + 存在しない要素は realpath が文字どおりに残すので,新規作成のパスは存在する部分までの解決で判定される. + keep_final_link なら最後の要素のリンクを解決しない(リンク自体を消す操作の判定用). + """ + head, tail = os.path.split(path) + if keep_final_link and tail not in ("", ".", ".."): + real = os.path.join(os.path.realpath(head), tail) + else: + real = os.path.realpath(path) + for base in ("/tmp", tempfile.gettempdir()): + real_base = os.path.realpath(base) + if real == real_base or real.startswith(real_base.rstrip("/") + "/"): + return True + return False + + +def is_temp_path(path: str, keep_final_link: bool = False) -> bool: """path がシステム一時ディレクトリ配下かを判定する. - OS ネイティブの一時ディレクトリ(tempfile.gettempdir())に加え, - Git Bash 等の POSIX 形式 /tmp も文字列正規化で判定する - (Windows では /tmp が実パスに解決できないため realpath に頼れない). - `..` は正規化してから判定するので /tmp/../etc のような脱出は温存されない. + POSIX では文字列で /tmp 配下に見えても,リンクを解決した実パスが一時ディレクトリの中になければ + 配下と見なさない(/tmp/x/escape/file の escape が外へのリンクのとき,実際に壊れるのは外のファイル). + Windows では /tmp(Git Bash)が実パスに解決できないので文字列正規化で判定し, + OS ネイティブの一時ディレクトリ(tempfile.gettempdir())は実パスで判定する. + どちらも `..` を畳んでから判定するので /tmp/../etc のような脱出は温存されない. + keep_final_link は POSIX でだけ効く(Windows は従来どおりの判定のまま). + 想定外の失敗は例外を外へ漏らさず,一時ディレクトリの外として扱う(安全側). """ - normalized = posixpath.normpath(path.replace("\\", "/")) - if normalized == "/tmp" or normalized.startswith("/tmp/"): - return True - return is_within_directory(path, tempfile.gettempdir()) + try: + if os.name != "nt": + return is_real_path_in_temp(path, keep_final_link) + normalized = posixpath.normpath(path.replace("\\", "/")) + if normalized == "/tmp" or normalized.startswith("/tmp/"): + return True + return is_within_directory(path, tempfile.gettempdir()) + except Exception: + return False def home_dir() -> str: @@ -325,6 +421,14 @@ 特殊デバイスは SPECIAL,解決できない(未知の変数を含む・cwd 不明で相対)ものは UNKNOWN(None)を返す. """ + joined = absolute_unnormalized(token, cwd, dialect) + if joined in (UNKNOWN, SPECIAL): + return joined + return os.path.normpath(joined) + + +def absolute_unnormalized(token: str, cwd: str | None, dialect: str = "bash") -> str | None: + """resolve_path の手前まで(`..` を畳まない絶対パス)を返す.戻り値の扱いは resolve_path と同じ.""" if not token: return UNKNOWN if dialect == "powershell": @@ -350,7 +454,281 @@ if cwd is None: return UNKNOWN token = os.path.join(cwd, token) - return os.path.normpath(token) + return token + + +def is_ambiguous_path(path: str) -> bool: + """実際の対象を文字列から確定できないパスかを判定する(メモのフォルダ・書き込み許可ディレクトリの判定用). + + 波括弧はシェルが展開すると `..` で外に出ることがあり,`..` は途中のリンクの先の親として + OS が解決し(memory/link/../x),途中の階層のワイルドカードはリンクに一致しうる. + いずれも normpath の結果からは分からない.最後の要素だけのワイルドカードは対象にしない. + """ + if "{" in path or "}" in path: + return True + parts = re.split(r"[/\\]", path) + return ".." in parts or any(re.search(r"[*?\[]", part) for part in parts[:-1]) + + +# --------------------------------------------------------------------------- +# 波括弧の展開(Bash 系の方言のみ) +# --------------------------------------------------------------------------- +class BraceLimitExceeded(Exception): + """波括弧の展開が上限を超えた.""" + + +BRACE_INT_SEQUENCE = re.compile(r"^(-?\d+)\.\.(-?\d+)(?:\.\.(-?\d+))?$") +BRACE_CHAR_SEQUENCE = re.compile(r"^([A-Za-z])\.\.([A-Za-z])(?:\.\.(-?\d+))?$") +BRACE_ZERO_PADDED = re.compile(r"^-?0\d") + + +def expand_brace_sequence(body: str) -> list | None: + """{1..3}・{a..e}・{01..10..2} の中身を展開する.順序式でなければ None を返す.""" + m = BRACE_INT_SEQUENCE.match(body) + if m: + start, end = int(m.group(1)), int(m.group(2)) + padded = BRACE_ZERO_PADDED.match(m.group(1)) or BRACE_ZERO_PADDED.match(m.group(2)) + width = max(len(m.group(1)), len(m.group(2))) if padded else 0 + else: + m = BRACE_CHAR_SEQUENCE.match(body) + if not m: + return None + start, end = ord(m.group(1)), ord(m.group(2)) + width = None + step = abs(int(m.group(3))) if m.group(3) else 1 + step = step or 1 + if abs(end - start) // step + 1 > MAX_BRACE_EXPANSIONS: + raise BraceLimitExceeded() + numbers = range(start, end + 1, step) if start <= end else range(start, end - 1, -step) + if width is None: + return [chr(n) for n in numbers] + return ["%0*d" % (width, n) for n in numbers] + + +def split_brace_body(word: str, start: int) -> tuple | None: + """word[start] の `{` に対応する `}` を探し,(閉じ位置, トップレベルのコンマの位置のリスト) を返す.""" + depth = 0 + commas: list = [] + for i in range(start, len(word)): + c = word[i] + if c == "{": + depth += 1 + elif c == "}": + depth -= 1 + if depth == 0: + return i, commas + elif c == "," and depth == 1: + commas.append(i) + return None + + +def expand_brace_recursive(word: str, depth: int) -> list: + if depth > MAX_BRACE_DEPTH: + raise BraceLimitExceeded() + i = 0 + while i < len(word): + if word[i] != "{": + i += 1 + continue + found = split_brace_body(word, i) + if i > 0 and word[i - 1] == "$": # ${VAR} は波括弧の展開ではない + if found is None: + return [word] + i = found[0] + 1 + continue + if found is None: + i += 1 # 閉じていない `{` は文字どおり(後ろに別の組があれば Bash はそれを展開する) + continue + end, commas = found + if commas: + bounds = [i] + commas + [end] + alternatives: list = [] + for left, right in zip(bounds, bounds[1:]): + alternatives += expand_brace_recursive(word[left + 1:right], depth + 1) + if len(alternatives) > MAX_BRACE_EXPANSIONS: + raise BraceLimitExceeded() + else: + alternatives = expand_brace_sequence(word[i + 1:end]) + if alternatives is None: + i += 1 # {a} や {} は文字どおり(内側の {{a,b}} は続きの走査で展開される) + continue + rest = expand_brace_recursive(word[end + 1:], depth + 1) + if len(alternatives) * len(rest) > MAX_BRACE_EXPANSIONS: + raise BraceLimitExceeded() + return [word[:i] + a + r for a in alternatives for r in rest] + return [word] + + +def expand_braces(word: str) -> list | None: + """Bash の波括弧展開の結果を返す.展開しない語は [word],上限を超えた・解釈に失敗した語は None.""" + if "{" not in word: + return [word] + if len(word) > MAX_BRACE_WORD_LENGTH: + return None + try: + return expand_brace_recursive(word, 0) + except Exception: # 上限超過・想定外の失敗はどちらも「展開できなかった」として安全側で扱う + return None + + +def raw_comes_from_word(raw: str, word: str) -> bool: + """エントリの文字列 raw が語 word(of=x・--output=x・-ox の形を含む)に由来するかを判定する.""" + if not raw: + return False + return raw == word or word.endswith("=" + raw) or (word.startswith("-") and word.endswith(raw)) + + +# --------------------------------------------------------------------------- +# OS と同じ順に要素をたどる解決(リンクの後の `..`・ワイルドカード) +# --------------------------------------------------------------------------- +# 一致したリンク自体を消すだけのコマンド(リンク先の中身には触らない). +# truncate・shred・Clear-Content はリンク先の中身を壊すので含めない +REMOVES_LINK_ITSELF = ( + (BASH_DELETE - {"truncate", "shred", "srm"}) | {"mv"} | PS_MOVE | PS_RENAME + | (PS_DELETE - {"clear-content", "clc", "clear-item", "cli"}) +) + + +def has_wildcard(text: str) -> bool: + return re.search(r"[*?\[]", text) is not None + + +def is_link_or_junction(path: str) -> bool: + """path がシンボリックリンク・ジャンクションかを判定する(Python 3.7 でも使える書き方).""" + try: + st = os.lstat(path) + except (OSError, ValueError): + return False + if stat.S_ISLNK(st.st_mode): + return True + return bool(getattr(st, "st_file_attributes", 0) & getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0)) + + +def split_path_elements(path: str) -> tuple: + """絶対パスを (起点, 要素のリスト) に分ける.""" + drive, rest = os.path.splitdrive(path) + separators = r"[/\\]" if os.name == "nt" else "/" + anchor = drive + os.sep if re.match(separators, rest) else drive + return anchor, [part for part in re.split(separators, rest) if part not in ("", ".")] + + +def wildcard_matches(directory: str, pattern: str) -> tuple: + """directory 直下で pattern に一致する名前を (名前のリスト, 打ち切ったか) で返す. + + ドットで始まる名前も一致させる(PowerShell は一致する.Bash では dotglob の場合だけなので安全側). + """ + names: list = [] + try: + with os.scandir(directory) as it: + for entry in it: + if _wildcard_scans_left[0] <= 0 or len(names) >= MAX_WILDCARD_MATCHES: + return names, True + _wildcard_scans_left[0] -= 1 + if fnmatch.fnmatch(entry.name, pattern): + names.append(entry.name) + except OSError: + pass + return names, False + + +def walk_path(path: str, wildcards: bool, skip_final_links: bool) -> tuple: + """OS と同じ順に要素をたどって実際の対象を求め,(パスのリスト, 打ち切ったか) を返す. + + 途中のリンク・ジャンクションは解決してから次の要素へ進むので,`..` はリンク先の親へ上がる. + 最後の要素のリンクは解決しない(判定側で見る).存在しない要素は文字どおりに進める. + 要素と同じ名前のものが実在するときはワイルドカードとして扱わない(親の階層の `[x]` 等). + ワイルドカードを含むパスは,最後まで実在するものだけを一致とする. + """ + anchor, elements = split_path_elements(path) + current = [anchor] + truncated = False + expanded = False + for index, element in enumerate(elements): + is_last = index == len(elements) - 1 + following: list = [] + for base in current: + if element == "..": + following.append(os.path.dirname(base) or base) + continue + names = [element] + wild = wildcards and has_wildcard(element) and not os.path.lexists(os.path.join(base, element)) + if wild: + expanded = True + names, cut = wildcard_matches(base, element) + truncated = truncated or cut + for name in names: + candidate = os.path.join(base, name) + if is_link_or_junction(candidate): + if is_last and wild and skip_final_links: + continue + if not is_last: + candidate = os.path.realpath(candidate) + following.append(candidate) + current = list(dict.fromkeys(following)) + if len(current) > MAX_WILDCARD_MATCHES: + current = current[:MAX_WILDCARD_MATCHES] + truncated = True + if expanded: + current = [p for p in current if os.path.lexists(p)] + return current, truncated + + +def reaches_link_target_by_trailing_separator(raw: str, dialect: str) -> bool: + """raw の末尾の区切りで,一致したリンクの先までたどられるかを判定する. + + Bash の rm -rf `*/` はリンク自体を残してリンク先の中身を消す(Git Bash・WSL で実測). + PowerShell の Remove-Item `*/` は末尾の区切りがあってもリンク自体を消すだけなので対象にしない + (Windows の 5.1・7.6 で実測).`\\` が区切りになるのは Windows だけ. + """ + if dialect == "powershell": + return False + return raw.endswith(("/", "\\") if os.name == "nt" else "/") + + +def walked_targets(raw: str, cwd: str | None, dialect: str, wildcards: bool = True, + skip_final_links: bool = False) -> tuple: + """raw の実際の対象を (パスのリスト, 打ち切ったか) で返す.`..` もワイルドカードも無ければ空. + + OS と同じ順にたどる解決に加え,`..` を文字列で畳んだ形(Windows の PowerShell の解決)のワイルドカードも + 展開する.想定外の失敗は例外を外へ漏らさず「打ち切った」として返す(基点が許可ゾーンでなければ拒否される). + """ + try: + joined = absolute_unnormalized(raw, cwd, dialect) + if joined in (UNKNOWN, SPECIAL): + return [], False + follow_final_links = skip_final_links and reaches_link_target_by_trailing_separator(raw, dialect) + if follow_final_links: + skip_final_links = False + elements = split_path_elements(joined)[1] + has_parent = ".." in elements + wild = wildcards and any(has_wildcard(e) for e in elements) + if not (has_parent or wild or follow_final_links): + return [], False + found, truncated = walk_path(joined, wildcards, skip_final_links) + if has_parent and wild: + more, cut = walk_path(os.path.normpath(joined), wildcards, skip_final_links) + found = list(dict.fromkeys(found + more)) + truncated = truncated or cut + if follow_final_links: + # 実際に消えるのはリンク先の中身なので,その実パスも判定する.リンク自体のパスのままだと, + # リンク自体を消す操作として(removes_only_link)一時ディレクトリの中と見なされ素通りする + found += [os.path.realpath(path) for path in found if is_link_or_junction(path)] + return found, truncated + except Exception: + return [], True + + +def path_entries(name: str, raw: str, cwd: str | None, dialect: str, kind: str, wildcards: bool = True) -> list: + """raw の判定エントリを作る.文字列のままの解決に,実際にたどった結果のパスを加える.""" + resolved = resolve_path(raw, cwd, dialect) + result = [(name, raw, resolved, kind)] + if resolved in (UNKNOWN, SPECIAL): + return result + found, truncated = walked_targets(raw, cwd, dialect, wildcards, name in REMOVES_LINK_ITSELF) + result += [(name, raw, path, kind) for path in found if path != resolved] + if truncated and kind != CREATE: + result.append((name, raw, glob_base(resolved), UNDECIDABLE)) + return result def looks_absolute(text: str) -> bool: @@ -364,9 +742,13 @@ # 判定コンテキスト # --------------------------------------------------------------------------- class Policy: - def __init__(self, repo_root: str, deny_read: list) -> None: + def __init__(self, repo_root: str, deny_read: list, transcript_path: str | None = None, + allow_write: list | None = None) -> None: self.repo_root = repo_root self.deny_read = deny_read + self.transcript_path = transcript_path + # load_allow_write で検証済みのディレクトリ.比較用に実パス + normcase に揃える(済みなら変わらない) + self.allow_write = [norm(p) for p in (allow_write or [])] def denied_entry(self, path: str) -> str | None: """path が禁止リストのいずれかの配下なら,その禁止エントリを返す.""" @@ -387,8 +769,52 @@ def is_inside_repo(self, path: str) -> bool: return is_within_directory(path, self.repo_root) - def is_write_allowed(self, path: str) -> bool: - return self.is_inside_repo(path) or is_temp_path(path) + def is_inside_memory(self, path: str) -> bool: + """path が今のプロジェクトのメモのフォルダの配下かを判定する(フォルダ自体は含まない). + + 基準は親フォルダだけを実パスに解決し,memory の部分は解決しない.両方を解決して + 比べると,memory がシンボリックリンクのときにリンク先の配下まで許可してしまう. + この形なら対象の実パスがリンク先に解決されるので基準から外れて拒否になる. + """ + transcript = self.transcript_path + if not isinstance(transcript, str) or not transcript or "\0" in transcript or not is_absolute(transcript): + return False # NUL を含むと realpath が例外を出し,どのパスの判定でも拒否になってしまう + base = os.path.join(norm(os.path.dirname(os.path.normpath(transcript))), "memory") + return norm(path).startswith(base + os.sep) + + def is_inside_allow_write(self, path: str, keep_final_link: bool = False) -> bool: + """path が書き込み許可ディレクトリ(allow_write)の配下かを判定する(ディレクトリ自体は含まない). + + 許可ディレクトリは読み込み時に実パスに解決済み.対象も実パスに解決して比べるので, + 許可ディレクトリの中から外へのリンク越しの操作は基準から外れて拒否になる. + keep_final_link なら最後の要素のリンクを解決しない(リンク自体を消すだけの操作の判定用). + 想定外の失敗は例外を外へ漏らさず,許可しない(安全側). + """ + if not self.allow_write: + return False + try: + head, tail = os.path.split(path) + if keep_final_link and tail not in ("", ".", ".."): + real = os.path.normcase(os.path.join(os.path.realpath(head), tail)) + else: + real = norm(path) + return any(real.startswith(base.rstrip("/\\") + os.sep) for base in self.allow_write) + except Exception: + return False + + def is_write_allowed(self, path: str, raw: str | None = None, keep_final_link: bool = False) -> bool: + """path(解決済み)への書き込みを許可するかを判定する.raw はコマンド中の元の文字列. + + resolve_path の normpath で `..` が消えるので,元の文字列も見る.コピー先のエントリでは + コピー元の名前に由来する部分が解決済みのパスにしか現れないので,両方を見る必要がある. + keep_final_link は一時ディレクトリの判定で最後の要素のリンクを解決しない(removes_only_link 参照). + """ + if self.is_inside_repo(path) or is_temp_path(path, keep_final_link): + return True + # メモのフォルダと書き込み許可ディレクトリは,実際の対象を文字列から確定できるパスだけ許可する + if is_ambiguous_path(path) or (raw is not None and is_ambiguous_path(raw)): + return False + return self.is_inside_memory(path) or self.is_inside_allow_write(path, keep_final_link) def deny_read_message(target: str, entry: str) -> str: @@ -399,22 +825,28 @@ ) +def read_config(repo_root: str): + """`.claude/repo-access.json` を読み込む.ファイルが無ければ None.読めない・壊れていれば OSError / ValueError.""" + config_path = os.path.join(repo_root, *CONFIG_RELPATH.split("/")) + if not os.path.exists(config_path): + return None + with open(config_path, encoding="utf-8") as f: + return json.load(f) + + def load_deny_read(repo_root: str) -> list: """`.claude/repo-access.json` の deny_read を絶対パスのリストとして読み込む.""" - config_path = os.path.join(repo_root, ".claude", "repo-access.json") - if not os.path.exists(config_path): - return [] try: - with open(config_path, encoding="utf-8") as f: - config = json.load(f) + config = read_config(repo_root) + if config is None: + return [] entries = config.get("deny_read", []) if isinstance(config, dict) else None if not isinstance(entries, list) or not all(isinstance(e, str) for e in entries): raise ValueError("deny_read は文字列の配列で指定してください") except (OSError, ValueError) as e: - print( - f"[restrict_repo_access] {CONFIG_RELPATH} を読み込めないため禁止リストを空として扱います: {e}", - file=sys.stderr, - ) + # print(file=sys.stderr) は sys.stderr が None だと stdout に出て,拒否の JSON を壊す. + # write なら例外になり,stderr に書けないときと同じく deny_on_exception で拒否される + sys.stderr.write(f"[restrict_repo_access] {CONFIG_RELPATH} を読み込めないため禁止リストを空として扱います: {e}\n") return [] result = [] for entry in entries: @@ -428,6 +860,88 @@ return result +def warn_config(message: str) -> None: + """設定ファイルに関する警告を stderr に書く(書けなければ例外になり deny_on_exception で拒否される).""" + sys.stderr.write(f"[restrict_repo_access] {CONFIG_RELPATH}: {message}\n") + + +def allow_write_rejection(real: str, repo_root: str) -> str | None: + """書き込み許可ディレクトリとして危険・無意味な指定なら,無視する理由を返す. + + real は実パスに解決済みの絶対パス.比較は is_within_directory(実パス + normcase)で行う. + """ + if not os.path.isdir(real): + return "存在しないかディレクトリではありません" + if os.path.dirname(real) == real: + return "ファイルシステムのルートです" + if is_within_directory(home_dir(), real): + return "ホームディレクトリそのもの,またはその祖先です" + if is_within_directory(repo_root, real): + return "リポジトリ自身,またはその祖先(親ディレクトリ等)です" + if is_within_directory(real, os.path.join(home_dir(), ".claude")): + return "Claude Code の設定フォルダ(~/.claude)の中です" + return None + + +def resolve_allow_write_entry(text: str, repo_root: str) -> tuple: + """allow_write の 1 要素を実パスに解決する.(実パス, None) か,無視する場合は (None, 理由) を返す.""" + if "\0" in text or "{" in text or "}" in text or has_wildcard(text): + return None, "ワイルドカード・波括弧等を含み,対象を確定できません" + expanded = convert_posix_drive(expand_home(text)) + if expanded.startswith("~"): + return None, "~user 形式は解決しません" + if not is_absolute(expanded): + expanded = os.path.join(repo_root, expanded) + try: + real = os.path.realpath(os.path.normpath(expanded)) + reason = allow_write_rejection(real, repo_root) + except (OSError, ValueError) as e: + return None, f"パスを解決できません({e})" + return (None, reason) if reason else (real, None) + + +def load_allow_write(repo_root: str) -> list: + """`.claude/repo-access.json` の allow_write を,比較用の実パス(normcase 済み)のリストとして読み込む. + + 安全側に倒すため,以下は空・無視として扱い stderr に警告する. + - ファイルが読めない・JSON として壊れている・オブジェクトでない・deny_read が不正(全体を空として扱う. + 禁止リストが効かない状態で書き込みだけ許可されないようにする) + - allow_write が配列でない(全体を無視),要素が文字列でない(その要素を無視) + - 実際の対象を文字列から確定できない指定(ワイルドカード・波括弧・NUL・`~user`) + - 危険・無意味な指定(allow_write_rejection 参照) + """ + try: + config = read_config(repo_root) + if config is None: + return [] + if not isinstance(config, dict): + raise ValueError("オブジェクトではありません") + deny_entries = config.get("deny_read", []) + if not isinstance(deny_entries, list) or not all(isinstance(e, str) for e in deny_entries): + raise ValueError("deny_read が文字列の配列ではありません") + except (OSError, ValueError) as e: + warn_config(f"読み込めないため書き込み許可(allow_write)を空として扱います: {e}") + return [] + entries = config.get("allow_write", []) + if not isinstance(entries, list): + warn_config("allow_write は文字列の配列で指定してください.allow_write を無視します") + return [] + result = [] + for entry in entries: + if not isinstance(entry, str): + warn_config(f"allow_write の文字列でない要素を無視します: {entry!r}") + continue + text = entry.strip() + if not text: + continue + real, reason = resolve_allow_write_entry(text, repo_root) + if reason: + warn_config(f"allow_write の `{text}` を無視します: {reason}") + continue + result.append(os.path.normcase(real)) + return list(dict.fromkeys(result)) + + # --------------------------------------------------------------------------- # トークナイザー # --------------------------------------------------------------------------- @@ -701,6 +1215,14 @@ self.writes: list = [] # (コマンド名, 元の文字列, 解決済みパス, 操作種別) self.reads: list = [] # (コマンド名, 元の文字列, 解決済みパス, 再帰的か) self.inline: list = [] # (コマンド名, リテラル, 解決済みパス, 操作種別) + # cd 等の移動先を文字列から確定できなかった(追跡中の cwd からはメモのフォルダ・書き込み許可ディレクトリの配下と言えない) + self.ambiguous_cd = False + self.unexpandable: list = [] # (コマンド名, 元の文字列) 波括弧を展開できなかった削除・上書きの対象 + + def note_location_change(self, dest: str) -> None: + """cd 等の移動先を記録する.移動先は最後の要素のワイルドカードも確定できない.""" + if is_ambiguous_path(dest + "/"): # 末尾に区切りを足して最後の要素も途中の階層として見る + self.ambiguous_cd = True def normalize_literal(literal: str) -> str: @@ -891,15 +1413,26 @@ dest = resolve_path(dest_raw, cwd, dialect) if dest in (UNKNOWN, SPECIAL): return [] - if not (into_dir or os.path.isdir(dest)): - return [(name, dest_raw, dest, OVERWRITE)] - entries = [] + walked_dests, truncated = walked_targets(dest_raw, cwd, dialect) + bases: list = [] for src in srcs: if contents_on_slash and src.endswith(("/", "\\")): continue base = posixpath.basename(src.replace("\\", "/").rstrip("/").split("?")[0]) if base and base not in (".", "..") and "$" not in base: - entries.append((name, dest_raw, os.path.join(dest, base), OVERWRITE)) + bases.append(base) + if has_wildcard(base): # コピー元のワイルドカードは,一致した各ファイルの名前で書き込まれる + matched, cut = walked_targets(src, cwd, dialect) + bases += [os.path.basename(path) for path in matched] + truncated = truncated or cut + entries = [] + for target in [dest] + [path for path in walked_dests if path != dest]: + if into_dir or os.path.isdir(target): + entries += [(name, dest_raw, os.path.join(target, base), OVERWRITE) for base in bases] + else: + entries.append((name, dest_raw, target, OVERWRITE)) + if truncated: + entries.append((name, dest_raw, glob_base(dest), UNDECIDABLE)) return entries @@ -920,7 +1453,7 @@ """Bash の単純コマンドから削除・上書き・作成の対象を (名前, 文字列, 解決済みパス, 種別) で取り出す.""" def entries(raws: list, kind: str) -> list: - return [(cmd, r, resolve_path(r, cwd, dialect), kind) for r in raws] + return [e for r in raws for e in path_entries(cmd, r, cwd, dialect, kind)] if cmd in BASH_DELETE: positional, _ = split_option_args(cmd, args) @@ -1030,6 +1563,13 @@ return starts or ["."] +def record_bash_arg_reads(cmd: str, arg: str, cwd: str | None, findings: Findings) -> None: + """Bash の引数 arg(--x=y・of=y の y も)を読み取り(禁止リスト判定用)として記録する.""" + for candidate in (arg, arg.split("=", 1)[1] if "=" in arg else None): + if candidate: + findings.reads.append((cmd, candidate, resolve_path(candidate, cwd), cmd in RECURSIVE_READ_COMMANDS)) + + def analyze_bash(command: str, cwd: str | None, findings: Findings, depth: int = 0) -> None: """Bash コマンドを解析して findings に書き込み・読み取りを追加する.""" if depth > 3: @@ -1037,13 +1577,14 @@ tokens = tokenize_bash(command) dir_stack: list = [] subshell_stack: list = [] + previous_cwd = UNKNOWN # cd - / pushd - の移動先(コマンド開始時点の OLDPWD は分からない) for segment in split_segments(tokens): if segment == "open": - subshell_stack.append(cwd) + subshell_stack.append((cwd, previous_cwd)) continue if segment == "close": if subshell_stack: - cwd = subshell_stack.pop() + cwd, previous_cwd = subshell_stack.pop() continue words: list = [] heredoc_bodies: list = [] @@ -1063,13 +1604,19 @@ continue if text in (">&", "<&") and (target.isdigit() or target == "-"): continue # ファイルディスクリプタの複製 - resolved = resolve_path(target, cwd) + expansions = expand_braces(target) + variants = [target] + [v for v in (expansions or []) if v != target] if text == "<": - findings.reads.append(("<", target, resolved, False)) + findings.reads += [("<", target, resolve_path(v, cwd), False) for v in variants] else: # >> / &>> は追記,<> は切り詰めずに開くので新規作成扱い.> / >| / &> は上書き op_kind = CREATE if text in (">>", "&>>", "<>") else OVERWRITE - findings.writes.append((text, target, resolved, op_kind)) + if expansions is None and op_kind != CREATE: + findings.unexpandable.append((text, target)) + for variant in variants: + # 元の文字列を残す(波括弧を含むパスはメモのフォルダで許可しないため) + findings.writes += [(text, target, e[2], e[3]) + for e in path_entries(text, variant, cwd, "bash", op_kind)] continue if kind == "heredoc": if text: @@ -1086,34 +1633,76 @@ # 引数はすべて読み取り(禁止リスト判定用)として記録する for a in args: - for candidate in (a, a.split("=", 1)[1] if "=" in a else None): - if candidate: - findings.reads.append((cmd, candidate, resolve_path(candidate, cwd), cmd in RECURSIVE_READ_COMMANDS)) + record_bash_arg_reads(cmd, a, cwd, findings) # cd / pushd / popd の追跡 if cmd in ("cd", "pushd", "popd"): if cmd == "popd": + previous_cwd = cwd cwd = dir_stack.pop() if dir_stack else UNKNOWN continue dest = [a for a in args if not (a.startswith("-") and a != "-")] if not dest: new_cwd = home_dir() elif dest[0] == "-": - new_cwd = UNKNOWN + # pushd - は cd - と同じ場所へ移動する.pushd -n はディレクトリを移動しないので追跡しない + new_cwd = previous_cwd if cmd == "cd" or "-n" not in args else UNKNOWN else: + findings.note_location_change(dest[0]) new_cwd = resolve_path(dest[0], cwd) if new_cwd == SPECIAL: new_cwd = UNKNOWN if cmd == "pushd": dir_stack.append(cwd) + previous_cwd = cwd cwd = new_cwd continue - findings.writes += write_targets_bash(cmd, args, cwd) + literal_entries = write_targets_bash(cmd, args, cwd) + findings.writes += literal_entries + collect_brace_expansions(words, cmd, literal_entries, cwd, findings) analyze_inline(cmd, args, heredoc_bodies + herestrings, cwd, findings, depth, "bash") +def collect_brace_expansions(words: list, cmd: str, literal_entries: list, cwd: str | None, findings: Findings) -> None: + """単純コマンドの語を波括弧展開した場合の削除・上書きの対象と読み取りを追加する. + + 元の語のままの判定(literal_entries)は残す.クォートされた波括弧は展開されないが,トークナイザーが + クォートの情報を落とすので両方を見る.展開後のエントリの文字列は元の語に戻す(`{` を含むパスは + メモのフォルダで許可しないため).インライン実行のコードは呼び出し側が展開前の語で解析する. + """ + expanded_words: list = [] + sources: dict = {} # 展開後の語 → 元の語 + destructive = [e for e in literal_entries if e[3] != CREATE] + for word in words: + expansions = expand_braces(word) + if expansions is None: + # 判定の対象になる語だけを拒否する(echo '<長い JSON>' > file の JSON 等は対象にしない). + # コピー元の語はエントリの文字列に現れないので,コピー系は引数であれば対象とみなす + if any(raw_comes_from_word(e[1], word) for e in destructive) or (cmd in BASH_COPY and destructive): + findings.unexpandable.append((cmd, word)) + expanded_words.append(word) + continue + expanded_words += expansions + if expansions != [word]: + for expanded in expansions: + sources[expanded] = word + if not sources: + return + argv = strip_bash_prefixes(expanded_words) + if not argv: + return + expanded_cmd = command_basename(argv[0]) + expanded_args = argv[1:] + for a in expanded_args: + if a in sources: + record_bash_arg_reads(expanded_cmd, a, cwd, findings) + for name, raw, resolved, kind in write_targets_bash(expanded_cmd, expanded_args, cwd): + origin = next((word for expanded, word in sources.items() if raw_comes_from_word(raw, expanded)), raw) + findings.writes.append((name, origin, resolved, kind)) + + def analyze_inline(cmd: str, args: list, stdin_codes: list, cwd: str | None, findings: Findings, depth: int, dialect: str) -> None: """インライン実行(bash -c・pwsh -Command・cmd /c・python -c 等)のコードを解析する. @@ -1199,7 +1788,7 @@ positional, named = parse_ps_args(args) def entries(raws: list, kind: str) -> list: - return [(cmd, r, resolve_path(r, cwd, "powershell"), kind) for r in raws] + return [e for r in raws for e in path_entries(cmd, r, cwd, "powershell", kind)] def targets(first_only: bool) -> list: result = positional[:1] if first_only else list(positional) @@ -1267,6 +1856,9 @@ collect_dotnet_calls(command, cwd, findings) tokens = tokenize_powershell(command) dir_stack: list = [] + # Set-Location - / + と Push-Location - / + の履歴(コマンド開始より前の履歴は分からない) + location_back: list = [] + location_forward: list = [] for segment in split_segments(tokens): if segment in ("open", "close"): continue @@ -1283,7 +1875,7 @@ findings.reads.append(("<", target, resolve_path(target, cwd, "powershell"), False)) else: op_kind = CREATE if text == ">>" else OVERWRITE - findings.writes.append((text, target, resolve_path(target, cwd, "powershell"), op_kind)) + findings.writes += path_entries(text, target, cwd, "powershell", op_kind) continue words.append(text) idx += 1 @@ -1298,18 +1890,31 @@ findings.reads.append((cmd, value, resolve_path(value, cwd, "powershell"), recursive)) if cmd in PS_LOCATION_SET or cmd in PS_LOCATION_PUSH or cmd in PS_LOCATION_POP: + # Push-Location / Pop-Location も Set-Location と同じ履歴を更新する(PowerShell 7.6 で実測) if cmd in PS_LOCATION_POP: - cwd = dir_stack.pop() if dir_stack else UNKNOWN + if dir_stack: + location_back.append(cwd) + location_forward = [] + cwd = dir_stack.pop() + else: # コマンド開始より前のスタックは分からないので,移動先も以降の - / + も未解決にする + location_back, location_forward = [], [] + cwd = UNKNOWN continue dest = named.get("path", []) + named.get("literalpath", []) + positional - if not dest: - new_cwd = home_dir() if cmd in PS_LOCATION_SET else cwd - elif dest[0] in ("-", "+"): - new_cwd = UNKNOWN + if dest and dest[0] in ("-", "+"): + source, other = (location_back, location_forward) if dest[0] == "-" else (location_forward, location_back) + new_cwd = source.pop() if source else UNKNOWN + other.append(cwd) else: - new_cwd = resolve_path(dest[0], cwd, "powershell") - if new_cwd == SPECIAL: - new_cwd = UNKNOWN + if not dest: + new_cwd = home_dir() if cmd in PS_LOCATION_SET else cwd + else: + findings.note_location_change(dest[0]) + new_cwd = resolve_path(dest[0], cwd, "powershell") + if new_cwd == SPECIAL: + new_cwd = UNKNOWN + location_back.append(cwd) + location_forward = [] if cmd in PS_LOCATION_PUSH: dir_stack.append(cwd) cwd = new_cwd @@ -1322,12 +1927,22 @@ # --------------------------------------------------------------------------- # 判定 # --------------------------------------------------------------------------- -def destructive_reason(kind: str, resolved: str, policy: Policy) -> str | None: +def removes_only_link(name: str, raw: str, kind: str) -> bool: + """最後の要素がリンクでも,リンク自体を消すだけでリンク先に触らない操作かを判定する. + + 末尾に区切りがあるとリンク先の中身に届くことがある(reaches_link_target_by_trailing_separator)ので含めない. + """ + return kind == DELETE and name in REMOVES_LINK_ITSELF and not raw.endswith(("/", "\\")) + + +def destructive_reason(kind: str, raw: str, resolved: str, policy: Policy, name: str = "") -> str | None: """リポジトリ外の削除・既存ファイルの上書きなら,その説明(「削除」等)を返す.""" - if kind == CREATE or policy.is_write_allowed(resolved): + if kind == CREATE or policy.is_write_allowed(resolved, raw, removes_only_link(name, raw, kind)): return None if kind == DELETE: return "ファイルの削除(移動を含む)" + if kind == UNDECIDABLE: + return "削除・上書き(ワイルドカードの一致が多すぎて対象を確定できません)" if os.path.lexists(resolved): return "既存ファイルの上書き" return None # 存在しないパスへの書き込みは新規作成なので許可する @@ -1335,13 +1950,22 @@ def evaluate_findings(findings: Findings, policy: Policy) -> str | None: """解析結果を判定し,拒否する場合は理由文字列を返す.""" + if findings.ambiguous_cd: + policy = Policy(policy.repo_root, policy.deny_read) # メモのフォルダ・書き込み許可ディレクトリの許可だけを外す + if findings.unexpandable: + name, raw = findings.unexpandable[0] + return ( + f"波括弧の展開数が多すぎて対象を確定できないため,リポジトリ外を指しうる削除・上書きとして" + f"ブロックしました: `{name}` が `{raw[:200]}` を対象としています.対象を分けて指定してください." + f"{WRITE_DENY_GUIDANCE}" + ) for name, raw, resolved, kind in findings.writes: if resolved in (UNKNOWN, SPECIAL): continue entry = policy.denied_entry(resolved) if entry: return deny_read_message(f"`{name}` が `{raw}` を対象としています", entry) - action = destructive_reason(kind, resolved, policy) + action = destructive_reason(kind, raw, resolved, policy, name) if action: return ( f"リポジトリ外の{action}をブロックしました: " @@ -1353,7 +1977,7 @@ entry = policy.denied_entry(resolved) if entry: return deny_read_message(f"`{name}` のコード中に `{raw}` が含まれています", entry) - action = destructive_reason(kind, resolved, policy) + action = destructive_reason(kind, raw, resolved, policy) if action: detail = "削除系の呼び出しとリポジトリ外のパス" if kind == DELETE else "リポジトリ外の既存ファイルへの上書き" return ( @@ -1373,19 +1997,24 @@ def check_shell_command(analyzer, command: str, cwd: str, policy: Policy) -> str | None: """コマンドを analyzer(analyze_bash / analyze_powershell)で解析して判定する.""" + _wildcard_scans_left[0] = MAX_WILDCARD_SCANS findings = Findings() analyzer(command, cwd, findings) return evaluate_findings(findings, policy) -def check_bash_command(command: str, cwd: str, repo_root: str | None = None, deny_read: list | None = None) -> str | None: +def check_bash_command(command: str, cwd: str, repo_root: str | None = None, deny_read: list | None = None, + transcript_path: str | None = None, allow_write: list | None = None) -> str | None: """Bash コマンドがリポジトリ外の削除・上書き,禁止パスへのアクセスを含むか判定する.""" - return check_shell_command(analyze_bash, command, cwd, Policy(repo_root or cwd, deny_read or [])) + return check_shell_command(analyze_bash, command, cwd, + Policy(repo_root or cwd, deny_read or [], transcript_path, allow_write)) -def check_powershell_command(command: str, cwd: str, repo_root: str | None = None, deny_read: list | None = None) -> str | None: +def check_powershell_command(command: str, cwd: str, repo_root: str | None = None, deny_read: list | None = None, + transcript_path: str | None = None, allow_write: list | None = None) -> str | None: """PowerShell コマンドがリポジトリ外の削除・上書き,禁止パスへのアクセスを含むか判定する.""" - return check_shell_command(analyze_powershell, command, cwd, Policy(repo_root or cwd, deny_read or [])) + return check_shell_command(analyze_powershell, command, cwd, + Policy(repo_root or cwd, deny_read or [], transcript_path, allow_write)) def glob_base(pattern: str) -> str: @@ -1415,17 +2044,18 @@ for raw in paths: if not isinstance(raw, str) or not raw: continue - resolved = resolve_path(raw, cwd) - if resolved in (UNKNOWN, SPECIAL): - continue - entry = policy.denied_entry(resolved) - if entry is None and tool_name in ("Glob", "Grep"): - entry = policy.contained_denied_entry(resolved) - if entry: - return deny_read_message(raw, entry) - if destructive_reason(kind, resolved, policy): - action = "既存ファイルの上書き" if kind == OVERWRITE else "既存ファイルの書き換え" - return f"リポジトリ外の{action}をブロックしました: {raw}.{WRITE_DENY_GUIDANCE}" + # ファイル操作ツールはワイルドカードを展開しない(文字どおりの名前).`..` だけ要素をたどって解決する + for _, _, resolved, entry_kind in path_entries(tool_name, raw, cwd, "bash", kind, wildcards=False): + if resolved in (UNKNOWN, SPECIAL): + continue + entry = policy.denied_entry(resolved) + if entry is None and tool_name in ("Glob", "Grep"): + entry = policy.contained_denied_entry(resolved) + if entry: + return deny_read_message(raw, entry) + if destructive_reason(entry_kind, raw, resolved, policy): + action = "既存ファイルの上書き" if kind == OVERWRITE else "既存ファイルの書き換え" + return f"リポジトリ外の{action}をブロックしました: {raw}.{WRITE_DENY_GUIDANCE}" return None @@ -1439,6 +2069,8 @@ } } json.dump(result, sys.stdout) + # 終了時の flush に任せると,失敗しても例外にならず終了コード 120(非ブロック)になって素通りする + sys.stdout.flush() sys.exit(0) @@ -1449,17 +2081,62 @@ return cwd -def main() -> None: - data = json.load(sys.stdin) +def deny_on_exception(error: Exception) -> None: + """想定外の例外が起きたときにツール呼び出しを拒否する(異常終了すると非ブロックのエラーとして素通りする).""" + try: + # print(file=sys.stderr) は sys.stderr が None だと stdout に出て,拒否の JSON を壊す + sys.stderr.write(traceback.format_exc()) + except Exception: + pass # stderr への出力に失敗しても拒否は続ける + try: + deny( + f"リポジトリ外アクセス制限フックが想定外の例外({type(error).__name__})で判定できなかったため," + "安全のためツール呼び出しをブロックしました.フックの不具合の可能性があります." + "`.claude/hooks/restrict_repo_access.py` を確認してください(詳細は stderr に出力しています)." + "別の書き方で迂回せず,解決しなければユーザーに報告してください" + ) + except SystemExit: + # 拒否の出力は済んでいる.stderr のバッファに残ったトレースバックの flush が終了時に失敗すると, + # 終了コードが 120 に変わるので,ここで試してから終了時の flush を通らずに終わる + try: + sys.stderr.flush() + except Exception: + pass + os._exit(0) + except Exception: + # stdout に書けないので終了コード 2 でブロックする.sys.exit だと終了時の flush の失敗で 120 に変わる + os._exit(2) + + +def has_invalid_value_type(tool_name: str, tool_input: dict) -> bool: + """判定の対象の値(コマンド・書き込み先のパス)が,存在するのに文字列でないかを判定する. + + 0・[]・None も文字列ではないので該当する(項目が無い場合と空文字列は該当しない). + 読み取り系などの他のツールは対象にしない. + """ + key = "command" if tool_name in ("Bash", "PowerShell") else WRITE_TOOL_PATH_KEYS.get(tool_name) + return key is not None and key in tool_input and not isinstance(tool_input[key], str) + + +def run_check() -> None: + # 入力は UTF-8 の JSON.sys.stdin のテキストモードはロケールの文字コードで読むので,cp932 の Windows では + # 日本語の直後の \" が壊れて JSONDecodeError になる(例外を拒否にしたので,正常な入力まで止まってしまう) + data = json.load(sys.stdin.buffer) tool_name = data.get("tool_name", "") tool_input = data.get("tool_input", {}) or {} cwd = data.get("cwd") or os.getcwd() repo_root = get_repo_root(cwd) - policy = Policy(repo_root, load_deny_read(repo_root)) + policy = Policy(repo_root, load_deny_read(repo_root), data.get("transcript_path"), load_allow_write(repo_root)) + + if has_invalid_value_type(tool_name, tool_input): + deny(INVALID_VALUE_TYPE_DENY_REASON) if tool_name in ("Bash", "PowerShell"): analyzer = analyze_bash if tool_name == "Bash" else analyze_powershell - reason = check_shell_command(analyzer, tool_input.get("command", "") or "", cwd, policy) + command = tool_input.get("command", "") # 文字列でない値は has_invalid_value_type で拒否済み + # 実際の argv に NUL は入らず,シェルが取り除くかどうかで対象が変わる.OS によって例外になったり + # 一時ディレクトリとして許可されたりするので,解析の前にコマンドの種類を問わず一律に拒否する + reason = NUL_COMMAND_DENY_REASON if "\0" in command else check_shell_command(analyzer, command, cwd, policy) else: reason = check_file_tool(tool_name, tool_input, cwd, policy) @@ -1468,5 +2145,12 @@ sys.exit(0) +def main() -> None: + try: + run_check() + except Exception as error: # SystemExit(deny の sys.exit)・KeyboardInterrupt は Exception ではないので通す + deny_on_exception(error) + + if __name__ == "__main__": main() diff --git a/.claude/hooks/run_python.sh b/.claude/hooks/run_python.sh index 1073d8a..dd7003a 100644 --- a/.claude/hooks/run_python.sh +++ b/.claude/hooks/run_python.sh @@ -1,6 +1,6 @@ #!/usr/bin/env bash # Python フックの起動ラッパー. -# 使い方: bash .claude/hooks/run_python.sh [--fail-closed] [args...] +# 使い方: bash "$CLAUDE_PROJECT_DIR/.claude/hooks/run_python.sh" [--fail-closed] [args...] # # 環境ごとに Python のコマンド名が異なるため (Debian/Ubuntu 系・macOS は python3 のみ, # Windows の python.org 版は python / py のみで python3 は Microsoft Store を開くダミー), diff --git a/.claude/hooks/tests/test_hooks.py b/.claude/hooks/tests/test_hooks.py index 85b42c9..cf81756 100644 --- a/.claude/hooks/tests/test_hooks.py +++ b/.claude/hooks/tests/test_hooks.py @@ -18,6 +18,7 @@ import os import posixpath import re +import shlex import shutil import subprocess import sys @@ -35,6 +36,14 @@ NOTIFY = os.path.join(HOOKS_DIR, "notify.py") CHECK_SYNC = os.path.join(HOOKS_DIR, "check_sync.sh") +# settings.json のフックコマンド(Issue #69: 作業フォルダが移っても見つかるよう $CLAUDE_PROJECT_DIR 起点で書く) +PROJECT_DIR_VAR = "$CLAUDE_PROJECT_DIR" +WRAPPER_SETTINGS_PREFIX = 'bash "$CLAUDE_PROJECT_DIR/.claude/hooks/run_python.sh" ' +RESTRICT_SETTINGS_COMMAND = ( + WRAPPER_SETTINGS_PREFIX + '--fail-closed "$CLAUDE_PROJECT_DIR/.claude/hooks/restrict_repo_access.py"' +) +NOTIFY_SETTINGS_COMMAND = WRAPPER_SETTINGS_PREFIX + '"$CLAUDE_PROJECT_DIR/.claude/hooks/notify.py"' + TIMEOUT = 60 @@ -322,10 +331,7 @@ def test_restrict_repo_access_uses_wrapper_with_fail_closed(self): cmds = [h["command"] for _, _, h in self.commands if "restrict_repo_access.py" in h["command"]] - self.assertEqual( - cmds, - ["bash .claude/hooks/run_python.sh --fail-closed .claude/hooks/restrict_repo_access.py"], - ) + self.assertEqual(cmds, [RESTRICT_SETTINGS_COMMAND]) def test_restrict_repo_access_is_pretooluse_for_file_tools(self): entries = [(e, m) for e, m, h in self.commands if "restrict_repo_access.py" in h["command"]] @@ -339,7 +345,7 @@ cmds = [h["command"] for _, _, h in self.commands if "notify.py" in h["command"]] self.assertEqual(len(cmds), 3) for cmd in cmds: - self.assertEqual(cmd, "bash .claude/hooks/run_python.sh .claude/hooks/notify.py") + self.assertEqual(cmd, NOTIFY_SETTINGS_COMMAND) self.assertNotIn("--fail-closed", cmd) def test_notify_events(self): @@ -354,26 +360,220 @@ for _, _, hook in self.commands: if ".py" in hook["command"]: self.assertTrue( - hook["command"].startswith("bash .claude/hooks/run_python.sh "), + hook["command"].startswith(WRAPPER_SETTINGS_PREFIX), hook["command"], ) + @staticmethod + def hook_path_tokens(command: str) -> list: + """コマンド中の `.claude/hooks/` を参照するトークン(クォートは外す.$ は展開しない).""" + return [t for t in shlex.split(command) if ".claude/hooks/" in t] + def test_referenced_scripts_exist(self): + checked = 0 for _, _, hook in self.commands: - for token in hook["command"].split(): - if token.startswith(".claude/hooks/"): - self.assertTrue(os.path.isfile(os.path.join(REPO_ROOT, token)), token) + for token in self.hook_path_tokens(hook["command"]): + self.assertTrue(token.startswith(PROJECT_DIR_VAR + "/"), token) + rel = token[len(PROJECT_DIR_VAR) + 1:] + self.assertTrue(os.path.isfile(os.path.join(REPO_ROOT, rel)), token) + checked += 1 + self.assertGreater(checked, 0) + + def test_hook_paths_are_project_dir_based_and_quoted(self): + """Issue #69: 相対パス(.claude/hooks/...)だと cd 後にフックが見つからず,制限フックが素通りになる.""" + for _, _, hook in self.commands: + cmd = hook["command"] + with self.subTest(command=cmd): + self.assertNotIn( + ".claude/hooks/", + cmd.replace(PROJECT_DIR_VAR + "/.claude/hooks/", ""), + "相対パスの .claude/hooks/ 参照が残っている", + ) + # $CLAUDE_PROJECT_DIR を使うパスはすべてダブルクォートで囲む(Windows の C:\... やスペース対策) + for m in re.finditer(r"\$CLAUDE_PROJECT_DIR/\S*", cmd): + start = m.start() + self.assertTrue(start > 0 and cmd[start - 1] == '"', cmd) + self.assertTrue(m.group(0).endswith('"'), cmd) + + def test_skill_snippets_use_project_dir(self): + """setup / set-mode が settings.json に書き込む SessionStart(check_sync) も $CLAUDE_PROJECT_DIR 起点にする.""" + for rel in ( + os.path.join(".claude", "skills", "setup", "SKILL.md"), + os.path.join(".claude", "skills", "set-mode", "SKILL.md"), + ): + with self.subTest(file=rel): + with open(os.path.join(REPO_ROOT, rel), encoding="utf-8") as f: + text = f.read() + self.assertNotIn('"command": "bash .claude/hooks/', text) + self.assertIn('"command": "bash \\"$CLAUDE_PROJECT_DIR/.claude/hooks/check_sync.sh\\""', text) + + def test_docs_show_project_dir_based_wiring(self): + """GUIDE_01・hooks-cross-platform ルールの起動例も $CLAUDE_PROJECT_DIR 起点(相対パスの例を残さない).""" + guide_dir = os.path.join(REPO_ROOT, "docs", "01_GUIDE") + guides = [n for n in os.listdir(guide_dir) if n.startswith("GUIDE_01_")] + self.assertEqual(len(guides), 1, guides) + for path in ( + os.path.join(guide_dir, guides[0]), + os.path.join(REPO_ROOT, ".claude", "rules", "hooks-cross-platform.md"), + ): + with self.subTest(file=os.path.basename(path)): + with open(path, encoding="utf-8") as f: + text = f.read() + self.assertNotIn("bash .claude/hooks/", text) + self.assertIn('bash "$CLAUDE_PROJECT_DIR/.claude/hooks/run_python.sh"', text) + + def test_sync_template_reference_replaces_relative_wiring(self): + """/sync-template は旧形式・相対パスの配線を $CLAUDE_PROJECT_DIR 起点に置き換える手順を持つ.""" + path = os.path.join(REPO_ROOT, ".claude", "skills", "sync-template", "reference.md") + with open(path, encoding="utf-8") as f: + text = f.read() + self.assertIn( + 'bash "$CLAUDE_PROJECT_DIR/.claude/hooks/run_python.sh" [--fail-closed] ' + '"$CLAUDE_PROJECT_DIR/.claude/hooks/<名前>.py"', + text, + ) + self.assertIn('bash "$CLAUDE_PROJECT_DIR/.claude/hooks/check_sync.sh"', text) + + +def run_settings_command(cmd: str, data: dict, project_dir: str, cwd: str) -> subprocess.CompletedProcess: + """settings.json のフックコマンドを Claude Code と同じく bash -c で起動する(ntfy には送らない).""" + env = dict(os.environ) + env["CLAUDE_PROJECT_DIR"] = project_dir # Claude Code と同じくホスト OS 形式のルートを渡す + env.pop("NTFY_TOPIC", None) + env["NTFY_SERVER"] = "http://127.0.0.1:9" # 万一送信しても外部に出ない + return subprocess.run( + [BASH, "-c", cmd], + input=json.dumps(data).encode("utf-8"), + capture_output=True, + env=env, + cwd=cwd, + timeout=TIMEOUT, + ) + + +def edit_outside_input(path: str, cwd: str) -> dict: + """リポジトリ外の既存ファイルを Edit する入力(制限フックが deny する).""" + return { + "tool_name": "Edit", + "tool_input": {"file_path": path, "old_string": "a", "new_string": "b"}, + "cwd": cwd, + } + + +def permission_decision(result: subprocess.CompletedProcess) -> str: + return json.loads(result.stdout.decode("utf-8"))["hookSpecificOutput"]["permissionDecision"] # --------------------------------------------------------------------------- -# restrict_repo_access.py をラッパー経由で(settings.json と同じコマンドで)起動 +# settings.json のコマンドをそのまま,リポジトリのルート以外の作業フォルダから起動(Issue #69) +# --------------------------------------------------------------------------- +class TestSettingsCommandFromOtherCwd(TempDirMixin, unittest.TestCase): + OUTSIDE = os.path.join(os.path.dirname(REPO_ROOT), "outside_of_repo_dummy.txt") + + @classmethod + def setUpClass(cls) -> None: + with open(SETTINGS, encoding="utf-8") as f: + settings = json.load(f) + cls.commands = {} + for groups in settings.get("hooks", {}).values(): + for group in groups: + for hook in group.get("hooks", []): + cmd = hook.get("command", "") + for name in ("restrict_repo_access.py", "notify.py"): + if name in cmd: + cls.commands[name] = cmd + + def run_settings_command(self, name: str, data: dict, cwd: str) -> subprocess.CompletedProcess: + return run_settings_command(self.commands[name], data, REPO_ROOT, cwd) + + def other_cwds(self): + yield "subdir", os.path.join(REPO_ROOT, ".claude", "hooks") + yield "outside repo", self.work + + def test_restrict_hook_found_and_blocks_from_other_cwd(self): + for label, cwd in self.other_cwds(): + with self.subTest(cwd=label): + data = edit_outside_input(self.OUTSIDE, cwd) + result = self.run_settings_command("restrict_repo_access.py", data, cwd) + self.assertNotEqual(result.returncode, 127, result.stderr) + self.assertTrue(TestRestrictViaWrapper.is_blocked(result), (result.returncode, result.stdout, result.stderr)) + + def test_notify_hook_found_from_other_cwd(self): + for label, cwd in self.other_cwds(): + with self.subTest(cwd=label): + result = self.run_settings_command("notify.py", {"hook_event_name": "Stop", "cwd": cwd}, cwd) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(result.stderr, b"") + + def test_restrict_hook_script_itself_runs_from_other_cwd(self): + """制限フック本体が動いていること(exit 2 は .py が見つからないときも返るので,判定結果で確かめる).""" + for label, cwd in self.other_cwds(): + with self.subTest(cwd=label, op="Edit outside"): + data = edit_outside_input(self.OUTSIDE, cwd) + result = self.run_settings_command("restrict_repo_access.py", data, cwd) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(permission_decision(result), "deny") + with self.subTest(cwd=label, op="Read outside"): + # 読み取りは許可される(フックが見つからない・起動できないなら fail-closed で exit 2 になる) + data = {"tool_name": "Read", "tool_input": {"file_path": self.OUTSIDE}, "cwd": cwd} + result = self.run_settings_command("restrict_repo_access.py", data, cwd) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertFalse(TestRestrictViaWrapper.is_blocked(result), result.stdout) + + def test_old_relative_command_fails_from_subdir(self): + """修正前の相対パスの配線は,作業フォルダが移ると見つからない(Issue #69 の再現.修正の前提の確認).""" + old = "bash .claude/hooks/run_python.sh --fail-closed .claude/hooks/restrict_repo_access.py" + result = subprocess.run( + [BASH, "-c", old], + input=b"{}", + capture_output=True, + env=dict(os.environ), + cwd=os.path.join(REPO_ROOT, ".claude", "hooks"), + timeout=TIMEOUT, + ) + self.assertEqual(result.returncode, 127, result.stderr) + + +# --------------------------------------------------------------------------- +# CLAUDE_PROJECT_DIR にスペースを含むパスでも settings.json のコマンドで起動できる(Issue #69) +# --------------------------------------------------------------------------- +class TestSettingsCommandWithSpacedProjectDir(TempDirMixin, unittest.TestCase): + OUTSIDE = TestSettingsCommandFromOtherCwd.OUTSIDE + + def setUp(self) -> None: + super().setUp() + self.project = os.path.join(self.work, "dir with space", "my repo") + shutil.copytree( + HOOKS_DIR, + os.path.join(self.project, ".claude", "hooks"), + ignore=shutil.ignore_patterns("tests", "__pycache__"), + ) + self.cwd = os.path.join(self.work, "dir with space") + + def run_cmd(self, cmd: str, data: dict) -> subprocess.CompletedProcess: + return run_settings_command(cmd, data, self.project, self.cwd) + + def test_restrict_hook_runs_with_spaced_project_dir(self): + result = self.run_cmd(RESTRICT_SETTINGS_COMMAND, edit_outside_input(self.OUTSIDE, self.cwd)) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(permission_decision(result), "deny") + + def test_notify_hook_runs_with_spaced_project_dir(self): + result = self.run_cmd(NOTIFY_SETTINGS_COMMAND, {"hook_event_name": "Stop", "cwd": self.cwd}) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(result.stderr, b"") + + +# --------------------------------------------------------------------------- +# restrict_repo_access.py をラッパー経由で起動 # --------------------------------------------------------------------------- class TestRestrictViaWrapper(TempDirMixin, unittest.TestCase): OUTSIDE = os.path.join(os.path.dirname(REPO_ROOT), "outside_of_repo_dummy.txt") INSIDE = os.path.join(REPO_ROOT, "CLAUDE.md") def run_hook(self, data: dict, env: dict) -> subprocess.CompletedProcess: - # settings.json の command と同じ相対パス・cwd で起動する + # リポジトリのルートから相対パスで起動する(ラッパー自体の動作確認. + # settings.json の command そのままの起動は TestSettingsCommandFromOtherCwd 等で確かめる) return subprocess.run( [BASH, ".claude/hooks/run_python.sh", "--fail-closed", ".claude/hooks/restrict_repo_access.py"], input=json.dumps(data).encode("utf-8"), @@ -846,19 +1046,22 @@ self.existing = os.path.join(self.out, "existing.txt") self.missing = os.path.join(self.out, "new_file.txt") self.deny = [] + self.transcript_path = None # フック入力の transcript_path に相当(既定は無し) def tearDown(self) -> None: shutil.rmtree(self.base, ignore_errors=True) # --- 判定ヘルパー --- def bash(self, command: str, cwd: str | None = None): - return self.rra.check_bash_command(command, cwd or self.repo, repo_root=self.repo, deny_read=self.deny) + return self.rra.check_bash_command(command, cwd or self.repo, repo_root=self.repo, deny_read=self.deny, + transcript_path=self.transcript_path) def ps(self, command: str, cwd: str | None = None): - return self.rra.check_powershell_command(command, cwd or self.repo, repo_root=self.repo, deny_read=self.deny) + return self.rra.check_powershell_command(command, cwd or self.repo, repo_root=self.repo, deny_read=self.deny, + transcript_path=self.transcript_path) def tool(self, name: str, tool_input: dict, cwd: str | None = None): - policy = self.rra.Policy(self.repo, self.deny) + policy = self.rra.Policy(self.repo, self.deny, self.transcript_path) return self.rra.check_file_tool(name, tool_input, cwd or self.repo, policy) def fake_home(self): @@ -1741,5 +1944,3147 @@ self.assertNotIn("`!", reason) +# --------------------------------------------------------------------------- +# 今のプロジェクトのメモのフォルダの許可(Issue #58) +# --------------------------------------------------------------------------- +class MemorySandboxMixin(RestrictSandboxMixin): + """home/.claude/ + settings.json + projects/ + memory/note.md projects 直下の memory(別の場所) + proj/ 今のプロジェクト + session.jsonl transcript_path + memory/note.md・sub/deep.md + memory2/note.md 等 名前の似たフォルダ + nested/memory/note.md 別の場所の memory + other/ 他のプロジェクト + session.jsonl・memory/note.md + """ + + SIMILAR_NAMES = ("memory2", "memory-old", "memory.bak", "memor", "xmemory") + + def setUp(self) -> None: + super().setUp() + self.dot_claude = os.path.join(self.home, ".claude") + self.projects = os.path.join(self.dot_claude, "projects") + self.proj = os.path.join(self.projects, "proj") + self.other = os.path.join(self.projects, "other") + self.memory = os.path.join(self.proj, "memory") + self.note = os.path.join(self.memory, "note.md") + self.deep_dir = os.path.join(self.memory, "sub") + self.deep = os.path.join(self.deep_dir, "deep.md") + self.new_note = os.path.join(self.memory, "new_note.md") + self.session = os.path.join(self.proj, "session.jsonl") + self.settings = os.path.join(self.dot_claude, "settings.json") + self.other_session = os.path.join(self.other, "session.jsonl") + self.other_note = os.path.join(self.other, "memory", "note.md") + self.elsewhere = [ + os.path.join(self.out, "memory", "note.md"), + os.path.join(self.dot_claude, "memory", "note.md"), + os.path.join(self.projects, "memory", "note.md"), + os.path.join(self.proj, "nested", "memory", "note.md"), + os.path.join(self.memory, "..", "nested", "memory", "note.md"), + ] + self.similar = [os.path.join(self.proj, name, "note.md") for name in self.SIMILAR_NAMES] + for f in [self.note, self.deep, self.session, self.settings, self.other_session, self.other_note, + *self.elsewhere, *self.similar]: + os.makedirs(os.path.dirname(f), exist_ok=True) + with open(f, "w", encoding="utf-8") as fh: + fh.write("x") + self.transcript_path = self.session + + def link_dir(self, target: str, link: str) -> None: + """ディレクトリへのリンクを作る(Windows で権限が無ければジャンクションを使う).""" + try: + os.symlink(target, link, target_is_directory=True) + return + except OSError: + if os.name != "nt": + raise + result = subprocess.run(["cmd", "/c", "mklink", "/J", link, target], capture_output=True) + if result.returncode != 0: + self.skipTest("Windows でシンボリックリンクの権限が無く,ジャンクションも作成できない") + + def write_ops(self, path: str) -> dict: + """既存ファイルを壊す操作(Edit・Write・rm・上書き)を Bash / PowerShell を含めて判定する.""" + f = _fwd(path) + return { + "Edit": self.tool("Edit", {"file_path": path, "old_string": "x", "new_string": "y"}), + "Write": self.tool("Write", {"file_path": path, "content": "y"}), + "MultiEdit": self.tool("MultiEdit", {"file_path": path, "edits": []}), + "bash rm": self.bash(f'rm "{f}"'), + "bash rm -rf": self.bash(f'rm -rf "{f}"'), + "bash redirect": self.bash(f'echo y > "{f}"'), + "bash tee": self.bash(f'echo y | tee "{f}"'), + "bash sed -i": self.bash(f"sed -i s/x/y/ \"{f}\""), + "bash truncate": self.bash(f'truncate -s 0 "{f}"'), + "bash cp": self.bash(f'cp file.txt "{f}"'), + "bash mv": self.bash(f'mv "{f}" "{f}.moved"'), + "ps Remove-Item": self.ps(f'Remove-Item "{path}"'), + "ps Remove-Item -Force": self.ps(f'Remove-Item "{path}" -Recurse -Force'), + "ps redirect": self.ps(f'echo y > "{path}"'), + "ps Set-Content": self.ps(f'Set-Content "{path}" y'), + "ps Out-File": self.ps(f'echo y | Out-File "{path}"'), + "ps Copy-Item": self.ps(f'Copy-Item file.txt "{path}"'), + "ps Move-Item": self.ps(f'Move-Item "{path}" "{path}.moved"'), + } + + def assertAllWriteOpsAllowed(self, path: str) -> None: + for label, reason in self.write_ops(path).items(): + with self.subTest(op=label, path=path): + self.assertAllowed(reason, label) + + def assertAllWriteOpsDenied(self, path: str) -> None: + for label, reason in self.write_ops(path).items(): + with self.subTest(op=label, path=path): + self.assertDenied(reason, label) + + +class TestRestrictMemoryAllowed(MemorySandboxMixin, unittest.TestCase): + """memory の配下は Edit・Write・rm・上書きのすべてが許可される(文字列から確定できないパスを除く).""" + + def test_all_write_ops_on_existing_file(self): + self.assertAllWriteOpsAllowed(self.note) + + def test_all_write_ops_in_subfolder(self): + self.assertAllWriteOpsAllowed(self.deep) + + def test_all_write_ops_on_missing_file(self): + self.assertAllWriteOpsAllowed(self.new_note) + + def test_notebook_edit(self): + self.assertAllowed(self.tool("NotebookEdit", {"notebook_path": os.path.join(self.memory, "n.ipynb"), "new_source": "x"})) + + def test_memory_folder_not_created_yet(self): + """memory がまだ無くても,配下への操作は許可される(判定は文字列の位置で決まる).""" + shutil.rmtree(self.memory) + self.assertAllWriteOpsAllowed(self.note) + + def test_delete_subfolder(self): + d = _fwd(self.deep_dir) + self.assertAllowed(self.bash(f'rm -rf "{d}"')) + self.assertAllowed(self.bash(f'rmdir "{d}"')) + self.assertAllowed(self.ps(f'Remove-Item "{self.deep_dir}" -Recurse -Force')) + + def test_relative_paths_from_cwd(self): + self.assertAllowed(self.bash("rm note.md", cwd=self.memory)) + self.assertAllowed(self.bash("rm -rf sub", cwd=self.memory)) + self.assertAllowed(self.bash("echo y > note.md", cwd=self.memory)) + self.assertDenied(self.bash("rm ../note.md", cwd=self.deep_dir)) + self.assertAllowed(self.bash("rm memory/note.md", cwd=self.proj)) + self.assertAllowed(self.ps("Remove-Item note.md", cwd=self.memory)) + self.assertAllowed(self.ps("Set-Content note.md y", cwd=self.memory)) + self.assertDenied(self.ps("Remove-Item ..\\note.md", cwd=self.deep_dir)) + self.assertAllowed(self.tool("Edit", {"file_path": "note.md"}, cwd=self.memory)) + self.assertDenied(self.tool("Write", {"file_path": "../note.md"}, cwd=self.deep_dir)) + + def test_cd_into_memory_then_delete(self): + self.assertAllowed(self.bash(f'cd "{_fwd(self.memory)}" && rm note.md')) + self.assertAllowed(self.ps(f'Set-Location "{self.memory}"; Remove-Item note.md')) + + def test_dot_dot_staying_inside_memory_is_denied(self): + """`..` を含むパスは,正規化すると配下に留まる場合も許可しない(途中がリンクだと外に出るため).""" + path = os.path.join(self.deep_dir, "..", "note.md") + self.assertDenied(self.tool("Edit", {"file_path": path})) + self.assertDenied(self.bash(f'rm "{_fwd(path)}"')) + self.assertDenied(self.ps(f'Remove-Item "{path}"')) + + def test_home_shorthand(self): + with self.fake_home(): + self.assertAllowed(self.bash("rm ~/.claude/projects/proj/memory/note.md")) + self.assertAllowed(self.bash("echo y > $HOME/.claude/projects/proj/memory/note.md")) + self.assertAllowed(self.ps("Remove-Item $HOME/.claude/projects/proj/memory/note.md")) + self.assertAllowed(self.tool("Edit", {"file_path": "~/.claude/projects/proj/memory/note.md"})) + + def test_inline_python(self): + n = _fwd(self.note) + self.assertAllowed(self.bash(f"python -c \"import os; os.remove('{n}')\"")) + self.assertAllowed(self.bash(f"python -c \"open('{n}', 'w').write('y')\"")) + + def test_glob_under_memory(self): + """memory の中身だけを指すワイルドカードは配下への操作なので許可される.""" + self.assertAllowed(self.bash(f'rm -rf "{_fwd(self.memory)}"/*')) + self.assertAllowed(self.ps(f'Remove-Item "{os.path.join(self.memory, "*")}"')) + + def test_brace_expansion_under_memory_is_denied(self): + """波括弧を含むパスは,展開後がすべて配下に留まる場合も許可しない.""" + m = _fwd(self.memory) + self.assertDenied(self.bash(f"rm {m}/{{note.md,sub/deep.md}}")) + self.assertDenied(self.bash(f"rm -rf {m}/{{note.md,sub}}")) + + def test_transcript_with_forward_slashes(self): + self.transcript_path = _fwd(self.session) + self.assertAllWriteOpsAllowed(self.note) + + def test_transcript_with_dot_dot_is_normalized(self): + self.transcript_path = os.path.join(self.proj, "memory", "..", "session.jsonl") + self.assertAllowed(self.tool("Edit", {"file_path": self.note})) + + def test_transcript_file_need_not_exist(self): + os.remove(self.session) + self.assertAllowed(self.tool("Edit", {"file_path": self.note})) + + def test_transcript_parent_reached_through_link(self): + """親フォルダまでのリンクは同じ場所として扱う(macOS の /tmp 等).""" + linked = os.path.join(self.projects, "linked") + self.link_dir(self.proj, linked) + self.transcript_path = os.path.join(linked, "session.jsonl") + self.assertAllowed(self.tool("Edit", {"file_path": self.note})) + self.assertAllowed(self.tool("Edit", {"file_path": os.path.join(linked, "memory", "note.md")})) + self.transcript_path = self.session + self.assertAllowed(self.tool("Edit", {"file_path": os.path.join(linked, "memory", "note.md")})) + + def test_other_zones_still_work(self): + self.assertAllowed(self.bash(f'rm "{_fwd(os.path.join(self.repo, "file.txt"))}"')) + self.assertDenied(self.bash(f'rm "{_fwd(self.existing)}"')) + self.assertAllowed(self.tool("Write", {"file_path": self.missing})) + + def test_is_inside_memory(self): + policy = self.rra.Policy(self.repo, [], self.session) + self.assertTrue(policy.is_inside_memory(self.note)) + self.assertTrue(policy.is_inside_memory(self.deep)) + self.assertTrue(policy.is_inside_memory(self.new_note)) + self.assertFalse(policy.is_inside_memory(self.other_note)) + self.assertFalse(policy.is_inside_memory(self.session)) + + +class TestRestrictMemoryInvalidTranscript(MemorySandboxMixin, unittest.TestCase): + """transcript_path が使えないときは許可を追加しない(例外も出さない).""" + + def invalid_values(self): + return { + "None": None, + "empty": "", + "int": 123, + "zero": 0, + "bool": True, + "list": [self.session], + "dict": {"path": self.session}, + "relative file": "session.jsonl", + "relative dir": os.path.join("proj", "session.jsonl"), + "dot relative": os.path.join(".", "session.jsonl"), + "dot dot relative": os.path.join("..", "proj", "session.jsonl"), + "NUL at end": self.session + "\0", + "NUL in folder": os.path.join(self.proj + "\0", "session.jsonl"), + } + + def test_policy_does_not_allow_memory(self): + for label, value in self.invalid_values().items(): + with self.subTest(label): + policy = self.rra.Policy(self.repo, [], value) + self.assertFalse(policy.is_inside_memory(self.note)) + self.assertFalse(policy.is_write_allowed(self.note)) + + def test_all_write_ops_denied(self): + for label, value in self.invalid_values().items(): + self.transcript_path = value + with self.subTest(label): + self.assertAllWriteOpsDenied(self.note) + + def test_relative_transcript_is_not_resolved_from_cwd(self): + """cwd から解決すれば今のプロジェクトになる相対パスでも許可しない.""" + self.transcript_path = "session.jsonl" + self.assertDenied(self.bash("rm memory/note.md", cwd=self.proj)) + self.assertDenied(self.ps("Remove-Item memory/note.md", cwd=self.proj)) + self.assertDenied(self.tool("Edit", {"file_path": "memory/note.md"}, cwd=self.proj)) + + def test_omitted_argument_means_no_permission(self): + """transcript_path を渡さない既存の呼び方では許可されない.""" + n = _fwd(self.note) + self.assertDenied(self.rra.check_bash_command(f'rm "{n}"', self.repo, repo_root=self.repo)) + self.assertDenied(self.rra.check_powershell_command(f'Remove-Item "{self.note}"', self.repo, repo_root=self.repo)) + self.assertDenied(self.rra.check_file_tool("Edit", {"file_path": self.note}, self.repo, self.rra.Policy(self.repo, []))) + + +class TestRestrictMemoryDeniedPaths(MemorySandboxMixin, unittest.TestCase): + """memory の配下でないパスは transcript_path があっても拒否される.""" + + def test_other_project_memory(self): + self.assertAllWriteOpsDenied(self.other_note) + + def test_other_project_transcript(self): + self.assertAllWriteOpsDenied(self.other_session) + + def test_own_transcript(self): + self.assertAllWriteOpsDenied(self.session) + + def test_settings_json(self): + self.assertAllWriteOpsDenied(self.settings) + + def test_memory_folder_elsewhere(self): + for path in self.elsewhere: + self.assertAllWriteOpsDenied(path) + + def test_similar_folder_names(self): + for path in self.similar: + self.assertAllWriteOpsDenied(path) + + def test_dot_dot_escaping_memory(self): + for path in (os.path.join(self.memory, "..", "session.jsonl"), + os.path.join(self.deep_dir, "..", "..", "session.jsonl"), + os.path.join(self.memory, "..", "..", "other", "memory", "note.md"), + os.path.join(self.memory, "..", "memory2", "note.md"), + os.path.join(self.memory, "..", "..", "..", "settings.json")): + self.assertAllWriteOpsDenied(path) + + def test_dot_dot_escaping_relative(self): + self.assertDenied(self.bash("rm ../session.jsonl", cwd=self.memory)) + self.assertDenied(self.bash("echo y > ../session.jsonl", cwd=self.memory)) + self.assertDenied(self.bash("rm ../../session.jsonl", cwd=self.deep_dir)) + self.assertDenied(self.ps("Remove-Item ..\\session.jsonl", cwd=self.memory)) + self.assertDenied(self.ps("Set-Content ..\\session.jsonl y", cwd=self.memory)) + self.assertDenied(self.ps("Remove-Item ..\\..\\session.jsonl", cwd=self.deep_dir)) + self.assertDenied(self.tool("Edit", {"file_path": "../session.jsonl"}, cwd=self.memory)) + self.assertDenied(self.tool("Write", {"file_path": "../session.jsonl"}, cwd=self.memory)) + + def test_brace_expansion_escaping_memory(self): + """Bash は memory/{a,../x} を memory/a と memory/../x に展開する(`..` で外に出る).""" + m = _fwd(self.memory) + for cmd in (f"rm -rf {m}/{{a,../../other/memory}}", f"rm -rf {m}/{{../session.jsonl,note.md}}", + f"rm -rf {m}/{{a,..}}"): + with self.subTest(cmd): + self.assertDenied(self.bash(cmd), cmd) + + def test_transcript_of_other_project_does_not_allow_this_memory(self): + self.transcript_path = self.other_session + self.assertAllWriteOpsDenied(self.note) + + def test_memory_is_directly_under_transcript_parent_only(self): + """transcript_path の親の親の memory や,親フォルダの下の別の階層の memory は対象外.""" + self.transcript_path = os.path.join(self.proj, "nested", "session.jsonl") + self.assertAllWriteOpsDenied(self.note) + + def test_home_shorthand(self): + with self.fake_home(): + self.assertDenied(self.bash("rm -rf ~/.claude/projects/other/memory")) + self.assertDenied(self.bash("echo y > ~/.claude/settings.json")) + self.assertDenied(self.ps("Remove-Item $HOME/.claude/projects/other/memory/note.md")) + self.assertDenied(self.tool("Edit", {"file_path": "~/.claude/projects/other/memory/note.md"})) + + def test_move_between_memory_and_outside(self): + """移動の両端を見る(移動元が外の削除,移動先が外の既存ファイルの上書き).""" + n, ex = _fwd(self.note), _fwd(self.existing) + self.assertDenied(self.bash(f'mv "{ex}" "{n}"')) + self.assertDenied(self.bash(f'mv "{n}" "{ex}"')) + self.assertDenied(self.ps(f'Move-Item "{self.existing}" "{self.note}"')) + self.assertDenied(self.ps(f'Move-Item "{self.note}" "{self.existing}"')) + + def test_inline_python(self): + self.assertDenied(self.bash(f"python -c \"import os; os.remove('{_fwd(self.other_note)}')\"")) + self.assertDenied(self.bash(f"python -c \"open('{_fwd(self.session)}', 'w').write('y')\"")) + + +class TestRestrictMemoryFolderItself(MemorySandboxMixin, unittest.TestCase): + """memory フォルダ自体の削除・移動は拒否される(memory/・memory/. も).""" + + def forms(self): + return ( + self.memory, + self.memory + os.sep, + os.path.join(self.memory, "."), + os.path.join(self.memory, "sub", ".."), + os.path.join(self.proj, ".", "memory"), + os.path.join(self.proj, "nested", "..", "memory"), + ) + + def test_is_inside_memory_is_false_for_folder_itself(self): + policy = self.rra.Policy(self.repo, [], self.session) + for path in self.forms(): + with self.subTest(path): + self.assertFalse(policy.is_inside_memory(self.rra.resolve_path(path, self.repo))) + self.assertFalse(policy.is_inside_memory(path)) + + def test_bash_delete_and_move(self): + for path in self.forms(): + p = _fwd(path) + for cmd in (f'rm -rf "{p}"', f'rm -r "{p}"', f'rmdir "{p}"', f'mv "{p}" "{_fwd(self.missing)}"', + f'mv "{p}" "{_fwd(os.path.join(self.proj, "renamed"))}"', + f"python -c \"import shutil; shutil.rmtree('{p}')\""): + with self.subTest(cmd): + self.assertDenied(self.bash(cmd), cmd) + + def test_powershell_delete_and_move(self): + for path in self.forms(): + for cmd in (f'Remove-Item "{path}"', f'Remove-Item "{path}" -Recurse -Force', f'rd "{path}"', + f'Move-Item "{path}" "{self.missing}"', f'Rename-Item "{path}" renamed'): + with self.subTest(cmd): + self.assertDenied(self.ps(cmd), cmd) + + def test_file_tools(self): + for path in self.forms(): + with self.subTest(path): + self.assertDenied(self.tool("Edit", {"file_path": path})) + self.assertDenied(self.tool("Write", {"file_path": path})) + + def test_overwrite_folder_path(self): + for path in self.forms(): + with self.subTest(path): + self.assertDenied(self.bash(f'echo y > "{_fwd(path)}"')) + self.assertDenied(self.ps(f'Set-Content "{path}" y')) + + def test_relative_from_parent(self): + for cmd in ("rm -rf memory", "rm -rf memory/", "rm -rf memory/.", "rm -rf ./memory", "mv memory renamed", + "rm -rf nested/../memory"): + with self.subTest(cmd): + self.assertDenied(self.bash(cmd, cwd=self.proj), cmd) + for cmd in ("Remove-Item memory -Recurse", "Remove-Item memory\\ -Recurse", "Remove-Item memory\\. -Recurse", + "Remove-Item .\\memory -Recurse", "Move-Item memory renamed", "Rename-Item memory renamed"): + with self.subTest(cmd): + self.assertDenied(self.ps(cmd, cwd=self.proj), cmd) + + def test_relative_from_inside(self): + for cmd in ("rm -rf .", "rm -rf ./", "rm -rf ../memory", "mv ../memory ../renamed"): + with self.subTest(cmd): + self.assertDenied(self.bash(cmd, cwd=self.memory), cmd) + self.assertDenied(self.bash("rm -rf ..", cwd=self.deep_dir)) + for cmd in ("Remove-Item . -Recurse", "Remove-Item ..\\memory -Recurse"): + with self.subTest(cmd): + self.assertDenied(self.ps(cmd, cwd=self.memory), cmd) + self.assertDenied(self.ps("Remove-Item .. -Recurse", cwd=self.deep_dir)) + + def test_cd_then_delete(self): + self.assertDenied(self.bash(f'cd "{_fwd(self.proj)}" && rm -rf memory')) + self.assertDenied(self.bash(f'cd "{_fwd(self.memory)}" && rm -rf .')) + self.assertDenied(self.bash(f'cd "{_fwd(self.memory)}" && cd .. && rm -rf memory')) + self.assertDenied(self.ps(f'Set-Location "{self.proj}"; Remove-Item memory -Recurse')) + self.assertDenied(self.ps(f'Set-Location "{self.memory}"; Remove-Item . -Recurse')) + + def test_parent_folder_delete(self): + self.assertDenied(self.bash(f'rm -rf "{_fwd(self.proj)}"')) + self.assertDenied(self.ps(f'Remove-Item "{self.proj}" -Recurse')) + + def test_glob_resolving_to_folder_itself(self): + self.assertDenied(self.bash(f'rm -rf "{_fwd(self.memory)}"/*/..')) + + +class TestRestrictMemoryWildcards(MemorySandboxMixin, unittest.TestCase): + """memory の配下だと確定できないワイルドカードは拒否される.""" + + def test_delete_from_absolute(self): + projects = _fwd(self.projects) + for tail in ("*/memory", "*/memory/note.md", "*/memory/*", "pro*/memory/note.md", "pro?/memory/note.md", + "proj/mem*", "proj/mem*/note.md", "proj/memory*", "proj/memory?/note.md", "proj/*", "*"): + with self.subTest(tail): + self.assertDenied(self.bash(f"rm -rf {projects}/{tail}"), tail) + self.assertDenied(self.ps(f"Remove-Item {projects}/{tail} -Recurse"), tail) + + def test_delete_from_relative(self): + self.assertDenied(self.bash("rm -rf */memory", cwd=self.projects)) + self.assertDenied(self.bash("rm -rf ../*/memory", cwd=self.proj)) + self.assertDenied(self.bash("rm -rf ../../*/memory", cwd=self.memory)) + self.assertDenied(self.bash("rm -rf mem*", cwd=self.proj)) + self.assertDenied(self.ps("Remove-Item */memory -Recurse", cwd=self.projects)) + self.assertDenied(self.ps("Remove-Item mem* -Recurse", cwd=self.proj)) + + def test_dot_dot_after_memory_then_wildcard(self): + m = _fwd(self.memory) + self.assertDenied(self.bash(f"rm -rf {m}/../../*/memory")) + self.assertDenied(self.ps(f"Remove-Item {m}/../../*/memory -Recurse")) + + def test_edit_with_wildcard_path(self): + path = os.path.join(self.projects, "*", "memory", "note.md") + self.assertDenied(self.tool("Edit", {"file_path": path})) + + +class TestRestrictMemoryLinks(MemorySandboxMixin, unittest.TestCase): + """シンボリックリンク(Windows で権限が無ければジャンクション)で外に出るパスは拒否される.""" + + def replace_memory_with_link(self, target: str) -> None: + shutil.rmtree(self.memory) + self.link_dir(target, self.memory) + + def test_memory_links_outside(self): + target = os.path.join(self.out, "dir") + self.replace_memory_with_link(target) + self.assertAllWriteOpsDenied(os.path.join(self.memory, "file.txt")) + + def test_memory_links_outside_missing_file(self): + self.replace_memory_with_link(os.path.join(self.out, "dir")) + path = os.path.join(self.memory, "no_such_file.txt") + self.assertDenied(self.tool("Edit", {"file_path": path})) + self.assertDenied(self.bash(f'rm "{_fwd(path)}"')) + self.assertDenied(self.ps(f'Remove-Item "{path}"')) + + def test_memory_links_to_other_project_memory(self): + self.replace_memory_with_link(os.path.join(self.other, "memory")) + self.assertAllWriteOpsDenied(self.note) + + def test_memory_links_to_similar_name(self): + self.replace_memory_with_link(os.path.join(self.proj, "memory2")) + self.assertAllWriteOpsDenied(self.note) + + def test_memory_link_dangling(self): + target = os.path.join(self.out, "will_be_removed") + os.makedirs(target) + self.replace_memory_with_link(target) + os.rmdir(target) + path = os.path.join(self.memory, "x.md") + self.assertDenied(self.tool("Edit", {"file_path": path})) + self.assertDenied(self.bash(f'rm "{_fwd(path)}"')) + self.assertDenied(self.ps(f'Remove-Item "{path}"')) + + def test_memory_link_itself_is_denied(self): + self.replace_memory_with_link(os.path.join(self.out, "dir")) + self.assertDenied(self.bash(f'rm -rf "{_fwd(self.memory)}"')) + self.assertDenied(self.ps(f'Remove-Item "{self.memory}" -Recurse')) + + def test_is_inside_memory_false_when_memory_is_link(self): + self.replace_memory_with_link(os.path.join(self.out, "dir")) + policy = self.rra.Policy(self.repo, [], self.session) + self.assertFalse(policy.is_inside_memory(os.path.join(self.memory, "file.txt"))) + self.assertFalse(policy.is_inside_memory(os.path.join(self.out, "dir", "file.txt"))) + + def test_link_inside_memory_to_outside(self): + link = os.path.join(self.memory, "escape") + self.link_dir(os.path.join(self.out, "dir"), link) + self.assertAllWriteOpsDenied(os.path.join(link, "file.txt")) + + def test_link_inside_memory_to_transcript_folder(self): + link = os.path.join(self.memory, "up") + self.link_dir(self.proj, link) + self.assertAllWriteOpsDenied(os.path.join(link, "session.jsonl")) + + def test_link_inside_memory_then_dot_dot(self): + """memory/escape/../x は OS が escape の先の親(memory の外)として解決する(上書き系を含む全操作).""" + link = os.path.join(self.memory, "escape") + self.link_dir(os.path.join(self.out, "dir"), link) + self.assertAllWriteOpsDenied(os.path.join(link, "..", "existing.txt")) + + def test_wildcard_matching_link_inside_memory(self): + """memory/*/file.txt はシェルが展開すると memory/escape/file.txt(memory の外の実体)になる.""" + link = os.path.join(self.memory, "escape") + self.link_dir(os.path.join(self.out, "dir"), link) + path = _fwd(os.path.join(self.memory, "*", "file.txt")) + self.assertDenied(self.bash(f"rm {path}")) + self.assertDenied(self.ps(f"Remove-Item {path}")) + + def test_cwd_inside_link_then_relative(self): + link = os.path.join(self.memory, "escape") + self.link_dir(os.path.join(self.out, "dir"), link) + self.assertDenied(self.bash("rm file.txt", cwd=link)) + self.assertDenied(self.ps("Remove-Item file.txt", cwd=link)) + self.assertDenied(self.tool("Edit", {"file_path": "file.txt"}, cwd=link)) + + def test_file_symlink_inside_memory_to_outside(self): + link = os.path.join(self.memory, "link.txt") + try: + os.symlink(self.existing, link) + except OSError: + if os.name != "nt": + raise + self.skipTest("Windows でシンボリックリンクの作成権限が無い(ファイルにはジャンクションを使えない)") + self.assertDenied(self.tool("Edit", {"file_path": link})) + self.assertDenied(self.tool("Write", {"file_path": link})) + self.assertDenied(self.bash(f'echo y > "{_fwd(link)}"')) + self.assertDenied(self.ps(f'Set-Content "{link}" y')) + + +class TestRestrictMemoryLocationChange(MemorySandboxMixin, unittest.TestCase): + """cd 等の移動先を文字列から確定できないコマンドには memory の許可を与えない. + + cd -P や PowerShell の Set-Location はリンクの先へ移動するので,その後の `..` は memory の外を + 指しうる.判定上の cwd は memory の配下に見えるので,移動先の文字列で判断する必要がある. + """ + + def setUp(self) -> None: + super().setUp() + self.m = _fwd(self.memory) + self.link_dir(os.path.join(self.out, "dir"), os.path.join(self.memory, "escape")) + + def test_bash_cd_physical_through_link_is_denied(self): + m = self.m + for cmd in (f'cd -P "{m}/escape/.." && rm x', + f'cd -P "{m}/escape" && cd .. && rm x', + f'cd -P "{m}/escape" && cd ../ && rm x', + f'(cd -P "{m}/escape/.." && rm x)'): + with self.subTest(cmd): + self.assertDenied(self.bash(cmd), cmd) + + def test_pushd_is_denied(self): + m = self.m + for cmd in (f'pushd "{m}/escape/.." && rm x', f'pushd "{m}/escape" && cd .. && rm x'): + with self.subTest(cmd): + self.assertDenied(self.bash(cmd), cmd) + + def test_set_location_is_denied(self): + m = self.m + for cmd in (f'Set-Location "{m}/escape/.."; Remove-Item x', + f'Set-Location "{m}/escape"; Set-Location ..; Remove-Item x', + f'Set-Location -Path "{m}/escape/.."; Remove-Item x', + f'Set-Location -LiteralPath "{m}/escape/.."; Remove-Item x', + f'sl "{m}/escape/.."; Remove-Item x', + f'Push-Location "{m}/escape/.."; Remove-Item x'): + with self.subTest(cmd): + self.assertDenied(self.ps(cmd), cmd) + + def test_inside_bash_c_is_denied(self): + m = self.m + for cmd in (f"bash -c 'cd -P \"{m}/escape/..\" && rm x'", + f"bash -c 'cd -P \"{m}/escape\" && cd .. && rm x'"): + with self.subTest(cmd): + self.assertDenied(self.bash(cmd), cmd) + + def test_wildcard_destination_is_denied(self): + """移動先のワイルドカードは最後の要素でも確定できない(リンクに一致しうる).""" + m = self.m + for cmd in (f'cd "{m}"/* && rm -rf .', f'cd "{m}"/* && rm x', f'cd "{m}"/esc* && rm x'): + with self.subTest(cmd): + self.assertDenied(self.bash(cmd), cmd) + for cmd in (f'Set-Location "{m}/*"; Remove-Item x', f'Set-Location "{m}/esc*"; Remove-Item x'): + with self.subTest(cmd): + self.assertDenied(self.ps(cmd), cmd) + + def test_brace_destination_is_denied(self): + self.assertDenied(self.bash(f'cd "{self.m}"/{{sub,escape}} && rm x')) + + def test_plain_cd_is_allowed(self): + m = self.m + for cmd in (f'cd "{m}" && rm note.md', f'cd "{m}/" && rm note.md', f'cd "{m}/sub" && rm deep.md', + f'cd "{m}" && rm -rf sub', f'pushd "{m}/sub" && rm deep.md', + f"bash -c 'cd \"{m}\" && rm note.md'"): + with self.subTest(cmd): + self.assertAllowed(self.bash(cmd), cmd) + for cmd in (f'Set-Location "{m}"; Remove-Item note.md', f'Set-Location "{m}/sub"; Remove-Item deep.md', + f'Set-Location -Path "{m}"; Remove-Item note.md'): + with self.subTest(cmd): + self.assertAllowed(self.ps(cmd), cmd) + + +class TestRestrictMemoryTailWildcard(MemorySandboxMixin, unittest.TestCase): + """最後の要素だけのワイルドカードは許可し,途中の階層のワイルドカードは許可しない.""" + + def test_tail_wildcard_is_allowed(self): + m = _fwd(self.memory) + for tail in ("*", "*.md", "sub/*", "sub/*.md"): + with self.subTest(tail): + self.assertAllowed(self.bash(f'rm "{m}"/{tail}'), tail) + self.assertAllowed(self.ps(f'Remove-Item "{m}/{tail}"'), tail) + + def test_trailing_slash_makes_wildcard_intermediate(self): + """`*/` はディレクトリ(リンクの先を含む)に一致するので,途中の階層と同じに扱う.""" + m = _fwd(self.memory) + self.assertDenied(self.bash(f'rm -rf "{m}"/*/')) + self.assertDenied(self.ps(f'Remove-Item "{m}/*/" -Recurse')) + + def test_intermediate_wildcard_is_denied(self): + m = _fwd(self.memory) + for tail in ("*/deep.md", "*/*", "s*/deep.md", "su?/deep.md", "[s]ub/deep.md"): + with self.subTest(tail): + self.assertDenied(self.bash(f'rm "{m}"/{tail}'), tail) + self.assertDenied(self.ps(f'Remove-Item "{m}/{tail}"'), tail) + + +class TestRestrictMemoryCopyDest(MemorySandboxMixin, unittest.TestCase): + """コピー元の名前に由来する波括弧(copy_dest_entries が解決済みのパスにだけ付ける)の扱い.""" + + def setUp(self) -> None: + super().setUp() + self.src = os.path.join(self.out, "x") + os.makedirs(self.src) + for name in ("a", "b"): + with open(os.path.join(self.src, name), "w", encoding="utf-8") as fh: + fh.write("x") + + def m_dir(self) -> str: + return _fwd(self.memory) + "/" + + def verdicts(self, command: str) -> tuple: + """transcript_path があるとき・無いときの判定(拒否なら True)を返す.""" + with_transcript = self.bash(command) is not None + self.transcript_path = None + without_transcript = self.bash(command) is not None + self.transcript_path = self.session + return with_transcript, without_transcript + + def test_entry_keeps_brace_and_gets_no_permission(self): + """コマンド中の書き込み先の文字列に波括弧が無くても,解決済みのパスで許可を与えない.""" + raw = self.m_dir() + entries = self.rra.copy_dest_entries("cp", raw, [f"{_fwd(self.src)}/{{a,b}}"], self.repo, "bash") + self.assertEqual(len(entries), 1) + _, entry_raw, resolved, _ = entries[0] + self.assertEqual(entry_raw, raw) + self.assertEqual(os.path.basename(resolved), "{a,b}") + self.assertFalse(self.rra.Policy(self.repo, [], self.session).is_write_allowed(resolved, entry_raw)) + + def test_brace_source_when_literal_name_exists_is_denied(self): + with open(os.path.join(self.memory, "{a,b}"), "w", encoding="utf-8") as fh: + fh.write("x") + command = f'cp "{_fwd(self.src)}"/{{a,b}} "{self.m_dir()}"' + self.assertEqual(self.verdicts(command), (True, True)) + + def test_brace_source_does_not_depend_on_transcript(self): + """memory の許可に頼らないので,transcript_path の有無で判定が変わらない.""" + for dest in (self.m_dir(), _fwd(self.memory)): + command = f'cp "{_fwd(self.src)}"/{{a,b}} "{dest}"' + with self.subTest(command): + with_transcript, without_transcript = self.verdicts(command) + self.assertEqual(with_transcript, without_transcript, command) + + def test_plain_source_uses_memory_permission(self): + """比較用: 波括弧が無ければ memory の既存ファイルへのコピーは transcript_path で許可される.""" + with open(os.path.join(self.memory, "a"), "w", encoding="utf-8") as fh: + fh.write("x") + command = f'cp "{_fwd(self.src)}/a" "{self.m_dir()}"' + self.assertEqual(self.verdicts(command), (False, True)) + + +class TestRestrictMemoryKeepsOtherZones(MemorySandboxMixin, unittest.TestCase): + """リポジトリ内・一時ディレクトリの判定は,曖昧なパスでも transcript_path の有無で変わらない.""" + + def setUp(self) -> None: + super().setUp() + self.r = _fwd(self.repo) + self.t = _fwd(tempfile.gettempdir()) + + def verdicts(self, check, *args, **kwargs) -> tuple: + """transcript_path があるとき・無いときの判定(拒否なら True)を返す.""" + with_transcript = check(*args, **kwargs) is not None + self.transcript_path = None + without_transcript = check(*args, **kwargs) is not None + self.transcript_path = self.session + return with_transcript, without_transcript + + def bash_commands(self, base: str) -> list: + return [f'rm "{base}"/{{file.txt,sub}}', f'rm "{base}/sub/../file.txt"', f'rm "{base}"/*/x', + f'rm -rf "{base}"/*/', f'cd "{base}/sub/.." && rm file.txt', f'cd "{base}"/* && rm x', + f'cd "{base}"/{{sub,other}} && rm x'] + + def ps_commands(self, base: str) -> list: + return [f'Remove-Item "{base}/sub/../file.txt"', f'Remove-Item "{base}/*/x"', + f'Set-Location "{base}/sub/.."; Remove-Item file.txt', f'Set-Location "{base}/*"; Remove-Item x'] + + def test_repo_is_allowed(self): + for cmd in self.bash_commands(self.r): + with self.subTest(cmd): + self.assertEqual(self.verdicts(self.bash, cmd), (False, False), cmd) + for cmd in self.ps_commands(self.r): + with self.subTest(cmd): + self.assertEqual(self.verdicts(self.ps, cmd), (False, False), cmd) + + def test_temp_is_allowed(self): + for cmd in self.bash_commands(self.t): + with self.subTest(cmd): + self.assertEqual(self.verdicts(self.bash, cmd), (False, False), cmd) + for cmd in self.ps_commands(self.t): + with self.subTest(cmd): + self.assertEqual(self.verdicts(self.ps, cmd), (False, False), cmd) + + def test_file_tools(self): + for path in (os.path.join(self.repo, "sub", "..", "file.txt"), os.path.join(self.repo, "{a,b}", "x"), + os.path.join(self.repo, "*", "x"), os.path.join(tempfile.gettempdir(), "a", "..", "x"), + os.path.join(tempfile.gettempdir(), "{a,b}", "x"), os.path.join(tempfile.gettempdir(), "*", "x")): + for name in ("Edit", "Write"): + with self.subTest(name=name, path=path): + self.assertEqual(self.verdicts(self.tool, name, {"file_path": path}), (False, False)) + + def test_relative_cd_up_inside_repo(self): + """移動先が曖昧でも外れるのは memory の許可だけで,リポジトリ内の許可は残る.""" + self.assertEqual(self.verdicts(self.bash, "cd .. && rm file.txt", cwd=self.sub), (False, False)) + self.assertEqual(self.verdicts(self.ps, "Set-Location ..; Remove-Item file.txt", cwd=self.sub), (False, False)) + + def test_outside_is_denied_either_way(self): + out = _fwd(self.out) + for cmd in (f'rm "{self.r}/../outside/existing.txt"', f'cd "{self.r}/.." && rm outside/existing.txt', + f'rm "{out}"/{{existing.txt,dir}}', f'rm "{out}"/*/file.txt'): + with self.subTest(cmd): + self.assertEqual(self.verdicts(self.bash, cmd), (True, True), cmd) + + def test_brace_leaving_repo_does_not_depend_on_transcript(self): + """リポジトリから波括弧で出るパスも,transcript_path の有無で判定が変わらない.""" + command = f'rm "{self.r}"/{{file.txt,../outside/existing.txt}}' + with_transcript, without_transcript = self.verdicts(self.bash, command) + self.assertEqual(with_transcript, without_transcript) + + +class TestRestrictMemoryDenyRead(MemorySandboxMixin, unittest.TestCase): + """deny_read は memory の許可より優先する.""" + + def assertDenyRead(self, reason, label=""): + self.assertIsNotNone(reason, label) + self.assertNotIn("! <コマンド>", reason, label) + + def test_entry_inside_memory(self): + secret = os.path.join(self.memory, "sub") + self.deny = [secret] + for label, reason in self.write_ops(self.deep).items(): + with self.subTest(label): + self.assertDenyRead(reason, label) + self.assertDenyRead(self.tool("Read", {"file_path": self.deep})) + self.assertDenyRead(self.bash(f'cat "{_fwd(self.deep)}"')) + self.assertDenyRead(self.ps(f'Get-Content "{self.deep}"')) + self.assertAllWriteOpsAllowed(self.note) + + def test_memory_folder_is_denied_entirely(self): + self.deny = [self.memory] + for label, reason in self.write_ops(self.note).items(): + with self.subTest(label): + self.assertDenyRead(reason, label) + + def test_entry_above_memory(self): + self.deny = [self.projects] + self.assertDenyRead(self.tool("Edit", {"file_path": self.note})) + self.assertDenyRead(self.bash(f'rm "{_fwd(self.note)}"')) + self.assertDenyRead(self.ps(f'Remove-Item "{self.note}"')) + + +class TestRestrictMemoryViaMain(MemorySandboxMixin, unittest.TestCase): + """main に標準入力で JSON を渡す経路で transcript_path が実際に使われること.""" + + def env(self) -> dict: + return dict(os.environ, CLAUDE_PROJECT_DIR=self.repo) + + def hook_inputs(self, path: str) -> dict: + f = _fwd(path) + return { + "Edit": ("Edit", {"file_path": path, "old_string": "x", "new_string": "y"}), + "Write": ("Write", {"file_path": path, "content": "y"}), + "Bash rm": ("Bash", {"command": f'rm "{f}"'}), + "Bash redirect": ("Bash", {"command": f'echo y > "{f}"'}), + "PowerShell Remove-Item": ("PowerShell", {"command": f'Remove-Item "{path}"'}), + "PowerShell Set-Content": ("PowerShell", {"command": f'Set-Content "{path}" y'}), + } + + def run_tool(self, tool_name: str, tool_input: dict, **extra): + data = dict({"tool_name": tool_name, "tool_input": tool_input, "cwd": self.repo}, **extra) + return self.run_main(data, self.env()) + + def assertHookAllows(self, result, label=""): + self.assertEqual(result.returncode, 0, (label, result.stderr)) + self.assertIsNone(self.decision(result), (label, result.stdout)) + + def assertHookDenies(self, result, label=""): + self.assertEqual(result.returncode, 0, (label, result.stderr)) + self.assertEqual(self.decision(result), "deny", (label, result.stdout)) + + def test_allowed_with_transcript_path(self): + for label, (name, tool_input) in self.hook_inputs(self.note).items(): + with self.subTest(label): + self.assertHookAllows(self.run_tool(name, tool_input, transcript_path=self.session), label) + + def test_denied_without_transcript_path(self): + for label, (name, tool_input) in self.hook_inputs(self.note).items(): + with self.subTest(label): + self.assertHookDenies(self.run_tool(name, tool_input), label) + + def test_denied_with_unusable_transcript_path(self): + name, tool_input = self.hook_inputs(self.note)["Edit"] + for value in (None, "", 123, True, [self.session], {"a": 1}, "session.jsonl", self.session + "\0"): + with self.subTest(repr(value)): + self.assertHookDenies(self.run_tool(name, tool_input, transcript_path=value)) + + def test_denied_for_other_project(self): + for label, (name, tool_input) in self.hook_inputs(self.other_note).items(): + with self.subTest(label): + self.assertHookDenies(self.run_tool(name, tool_input, transcript_path=self.session), label) + + def test_denied_for_memory_folder_itself(self): + cases = [("Bash", {"command": f'rm -rf "{_fwd(self.memory)}"'}), + ("Bash", {"command": f'rm -rf "{_fwd(self.memory)}/"'}), + ("Bash", {"command": f'rm -rf "{_fwd(self.memory)}/."'}), + ("PowerShell", {"command": f'Remove-Item "{self.memory}" -Recurse'})] + for name, tool_input in cases: + with self.subTest(tool_input["command"]): + self.assertHookDenies(self.run_tool(name, tool_input, transcript_path=self.session)) + + def test_deny_read_config_wins(self): + with open(os.path.join(self.repo, ".claude", "repo-access.json"), "w", encoding="utf-8") as fh: + json.dump({"deny_read": [self.memory]}, fh) + name, tool_input = self.hook_inputs(self.note)["Edit"] + self.assertHookDenies(self.run_tool(name, tool_input, transcript_path=self.session)) + + def test_via_wrapper_like_settings_json(self): + """settings.json と同じコマンド(run_python.sh 経由)でも transcript_path が届く.""" + data = {"tool_name": "Edit", "tool_input": {"file_path": self.note, "old_string": "x", "new_string": "y"}, + "cwd": self.repo} + command = [BASH, ".claude/hooks/run_python.sh", "--fail-closed", ".claude/hooks/restrict_repo_access.py"] + + def run(payload): + return subprocess.run(command, input=json.dumps(payload).encode("utf-8"), capture_output=True, + env=self.env(), cwd=REPO_ROOT, timeout=TIMEOUT) + + self.assertHookAllows(run(dict(data, transcript_path=self.session))) + self.assertHookDenies(run(data)) + + +@unittest.skipUnless(os.name == "nt", "ドライブレター・Git Bash 形式・大文字小文字の同一視は Windows 固有のため") +class TestRestrictMemoryWindows(MemorySandboxMixin, unittest.TestCase): + def test_git_bash_form_paths(self): + self.assertAllowed(self.bash(f'rm "{_gitbash(self.note)}"')) + self.assertAllowed(self.bash(f'echo y > "{_gitbash(self.note)}"')) + self.assertDenied(self.bash(f'rm -rf "{_gitbash(self.memory)}"')) + self.assertDenied(self.bash(f'rm "{_gitbash(self.other_note)}"')) + + def test_case_insensitive(self): + upper = os.path.join(self.proj, "MEMORY", "NOTE.md") + self.assertAllowed(self.tool("Edit", {"file_path": upper})) + self.assertAllowed(self.ps(f'Remove-Item "{upper}"')) + self.assertDenied(self.ps(f'Remove-Item "{os.path.join(self.proj, "MEMORY")}" -Recurse')) + self.transcript_path = self.session.upper() + self.assertAllowed(self.tool("Edit", {"file_path": self.note})) + + def test_drive_relative_transcript_is_not_absolute(self): + self.transcript_path = self.session[:2] + os.path.relpath(self.session, self.session[:3]) + self.assertDenied(self.tool("Edit", {"file_path": self.note})) + + def test_junction_memory_explicitly(self): + """シンボリックリンクの権限の有無によらず,ジャンクションでも許可しない.""" + target = os.path.join(self.out, "dir") + shutil.rmtree(self.memory) + result = subprocess.run(["cmd", "/c", "mklink", "/J", self.memory, target], capture_output=True) + if result.returncode != 0: + self.skipTest("ジャンクションを作成できない環境") + self.assertAllWriteOpsDenied(os.path.join(self.memory, "file.txt")) + + +# --------------------------------------------------------------------------- +# Issue #59: 波括弧・ワイルドカード・cd -・リンクの後の `..` の検出漏れ +# --------------------------------------------------------------------------- +class TestExpandBraces(unittest.TestCase): + """expand_braces が実際の Bash の波括弧展開と同じ結果を返すこと(期待値は bash 5 で確認したもの).""" + + @classmethod + def setUpClass(cls) -> None: + cls.rra = _load_restrict() + + def test_same_as_bash(self): + cases = { + "plain": ["plain"], + "a{b,c}d": ["abd", "acd"], + "{a,{b,c}}": ["a", "b", "c"], + "{{a,b}}": ["{a}", "{b}"], + "a{b,c}d{e,f}": ["abde", "abdf", "acde", "acdf"], + "x/{a,../y/z}": ["x/a", "x/../y/z"], + "{1..3}": ["1", "2", "3"], + "{3..1}": ["3", "2", "1"], + "{01..03}": ["01", "02", "03"], + "{a..c}": ["a", "b", "c"], + "{c..a}": ["c", "b", "a"], + "{1..5..2}": ["1", "3", "5"], + "{-1..1}": ["-1", "0", "1"], + "{1..2}{a,b}": ["1a", "1b", "2a", "2b"], + "{a,b}}": ["a}", "b}"], + "{{a,b}": ["{a", "{b"], + "x{a,b}y}z": ["xay}z", "xby}z"], + "{a,b{c,d}}e": ["ae", "bce", "bde"], + } + for word, expected in cases.items(): + with self.subTest(word): + self.assertEqual(self.rra.expand_braces(word), expected) + + def test_literal_when_bash_does_not_expand(self): + for word in ("{a}", "{}", "{a,b", "a,b}", "{1..a}", "{a..1}", "${VAR}", "${a,b}", "{../outside/x}"): + with self.subTest(word): + self.assertEqual(self.rra.expand_braces(word), [word]) + + def test_variable_followed_by_brace(self): + self.assertEqual(self.rra.expand_braces("${x}{a,b}"), ["${x}a", "${x}b"]) + + def test_expansion_limit_boundary(self): + limit = self.rra.MAX_BRACE_EXPANSIONS + self.assertEqual(limit, 256) + self.assertEqual(len(self.rra.expand_braces("{1..256}")), 256) + self.assertIsNone(self.rra.expand_braces("{1..257}")) + self.assertEqual(len(self.rra.expand_braces("{a,b}{1..128}")), 256) + self.assertIsNone(self.rra.expand_braces("{a,b}{1..129}")) + self.assertEqual(len(self.rra.expand_braces("{%s}" % ",".join(str(n) for n in range(256)))), 256) + self.assertIsNone(self.rra.expand_braces("{%s}" % ",".join(str(n) for n in range(257)))) + + def test_huge_or_deep_words_end_quickly(self): + """巨大な順序式・多重の波括弧でフックが止まらない(タイムアウトすると検査が効かない).""" + for word in ("{1..1000000000}", "{a,b}" * 40, "{,}" * 40, "{a," * 1000 + "}" * 1000, "x" * 5000 + "{a,b}"): + with self.subTest(word[:20]): + self.assertIsNone(self.rra.expand_braces(word)) + + +class Issue59SandboxMixin(MemorySandboxMixin): + """リポジトリ内に src/ 等を足す(誤拒否のテスト用).""" + + def setUp(self) -> None: + super().setUp() + self.o = _fwd(self.out) + self.r = _fwd(self.repo) + self.m = _fwd(self.memory) + self.p = _fwd(self.projects) + + def touch(self, *parts: str) -> str: + path = os.path.join(*parts) + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, "w", encoding="utf-8") as fh: + fh.write("x") + return path + + def make_repo_escape(self) -> str: + """repo/escape → outside/dir のリンクを作る.""" + link = os.path.join(self.repo, "escape") + self.link_dir(os.path.join(self.out, "dir"), link) + return link + + def make_memory_escape(self) -> str: + link = os.path.join(self.memory, "escape") + self.link_dir(os.path.join(self.out, "dir"), link) + return link + + def assertBashDenied(self, commands, cwd: str | None = None) -> None: + for cmd in commands: + with self.subTest(cmd): + self.assertDenied(self.bash(cmd, cwd=cwd), cmd) + + def assertBashAllowed(self, commands, cwd: str | None = None) -> None: + for cmd in commands: + with self.subTest(cmd): + self.assertAllowed(self.bash(cmd, cwd=cwd), cmd) + + def assertPsDenied(self, commands, cwd: str | None = None) -> None: + for cmd in commands: + with self.subTest(cmd): + self.assertDenied(self.ps(cmd, cwd=cwd), cmd) + + def assertPsAllowed(self, commands, cwd: str | None = None) -> None: + for cmd in commands: + with self.subTest(cmd): + self.assertAllowed(self.ps(cmd, cwd=cwd), cmd) + + +class TestRestrictBraceDelete(Issue59SandboxMixin, unittest.TestCase): + """波括弧で外に出る削除は拒否される.""" + + def test_brace_escape_from_repo(self): + r = self.r + self.assertBashDenied([ + f"rm {r}/{{a,../outside/existing.txt}}", + f"rm -f {r}/{{a,../outside/existing.txt}}", + f'rm "{r}"/{{a,../outside/existing.txt}}', + f"rm {r}/{{a,../outside}}/existing.txt", + f"rm {r}/{{a,..}}/outside/existing.txt", + f"rm -rf {r}/{{a,../outside/dir}}", + f"rm {r}/{{../outside,x}}/*", + f"rmdir {r}/{{a,../outside/dir}}", + f"mv {r}/{{a,../outside/existing.txt}} {r}/sub/", + ]) + + def test_relative_brace_escape(self): + self.assertBashDenied(["rm {a,../outside/existing.txt}", "rm -rf sub/{a,../../outside/dir}"]) + + def test_brace_escape_via_prefix_and_nested_shell(self): + r = self.r + self.assertBashDenied([ + f"sudo rm {r}/{{a,../outside/existing.txt}}", + f"env X=1 rm {r}/{{a,../outside/existing.txt}}", + f"bash -c 'rm {r}/{{a,../outside/existing.txt}}'", + f"true && rm {r}/{{a,../outside/existing.txt}}", + ]) + + def test_brace_directly_outside(self): + self.assertBashDenied([f"rm {self.o}/{{existing.txt,dir/file.txt}}", f"rm {self.o}/{{dir,other}}/*"]) + + def test_single_alternative_is_not_expanded(self): + """`{x}` はコンマが無いので Bash は展開しない(文字どおりの,リポジトリ内の名前).""" + self.assertBashAllowed([f"rm {self.r}/{{../outside/existing.txt}}"]) + + +class TestRestrictBraceWithinRepoAllowed(Issue59SandboxMixin, unittest.TestCase): + """リポジトリ内で閉じる波括弧・ワイルドカードは拒否しない(実体の有無によらない).""" + + COMMANDS = ("rm src/{a,b}.txt", "rm src/*/x.txt", "cp a.txt {b,c}/", "mv src/*.txt dst/", "rm src/{1..3}.txt", + "rm -rf src/{a,b}", "sed -i s/x/y/ src/{a,b}.txt", "echo y | tee src/{a,b}.txt", "echo y > src/a.txt") + + def test_without_files(self): + self.assertBashAllowed(self.COMMANDS) + + def test_with_files(self): + for name in ("a.txt", "b.txt", "1.txt", "2.txt", "3.txt", os.path.join("d1", "x.txt"), os.path.join("d2", "x.txt")): + self.touch(self.repo, "src", name) + self.touch(self.repo, "a.txt") + for d in ("b", "c", "dst"): + os.makedirs(os.path.join(self.repo, d)) + self.assertBashAllowed(self.COMMANDS) + + def test_absolute_paths(self): + self.touch(self.repo, "src", "d1", "x.txt") + self.assertBashAllowed([f"rm {self.r}/src/{{a,b}}.txt", f"rm {self.r}/src/*/x.txt", f"rm {self.r}/src/{{1..3}}.txt"]) + + def test_dot_dot_staying_inside_repo(self): + self.assertBashAllowed([f"rm {self.r}/sub/{{a,../file.txt}}", "rm sub/{a,../file.txt}"]) + + +class TestRestrictBraceNotPathArgument(Issue59SandboxMixin, unittest.TestCase): + """パス引数でない波括弧で誤拒否しない.""" + + def test_echo(self): + self.assertBashAllowed(["echo '{a,b}'", "echo {a,b}", 'echo "{a,../../../outside/existing.txt}"']) + + def test_json_redirected_into_repo(self): + self.assertBashAllowed([ + """echo '{"a": 1, "b": 2}' > out.json""", + """echo '{"a":{"b":[1,2]},"c":"../../x"}' > out.json""", + """printf '{"a":1,"b":2}' | tee out.json""", + ]) + + def test_variable_reference(self): + self.assertBashAllowed(["echo ${HOME}", "echo ${a,b}"]) + + +class TestRestrictBraceLimit(Issue59SandboxMixin, unittest.TestCase): + """波括弧の上限超え(1 語 256 展開超)が削除・上書きの対象なら拒否する.""" + + def test_over_limit_targets_are_denied(self): + for base in (self.r + "/f", "f", self.o + "/f"): + with self.subTest(base): + self.assertBashDenied([ + f"rm {base}{{1..257}}", + f"rm {base}{{1..1000000000}}", + f"echo y > {base}{{1..257}}", + f"echo y | tee {base}{{1..257}}", + f"sed -i s/x/y/ {base}{{1..257}}", + f"cp file.txt {base}{{1..257}}", + f"mv {base}{{1..257}} sub/", + ]) + + def test_over_limit_copy_source_is_denied(self): + self.assertBashDenied([f"cp x{{1..257}} {self.o}/dir/", f"cp {self.r}/x{{1..257}} {self.o}/dir/"]) + + def test_over_limit_in_other_form_is_denied(self): + self.assertBashDenied(["dd if=/dev/zero of=f{1..257}", "rm f{a,b}{1..129}"]) + + def test_at_limit_is_judged_normally(self): + self.assertBashAllowed(["rm f{1..256}", "echo y | tee f{1..256}", "rm f{a,b}{1..128}"]) + + def test_over_limit_not_a_target_is_allowed(self): + self.assertBashAllowed([ + "echo {1..257}", + "echo {1..257} > out.txt", + "seq 1 3 | grep x{1..257}", + "ls f{1..257}", + "echo " + "x" * 5000 + "{a,b} > out.txt", + ]) + + def test_powershell_does_not_expand(self): + self.assertPsAllowed([f"Remove-Item {self.r}/f{{1..257}}", "Set-Content f{1..257} y"]) + + def test_via_main_is_denied(self): + env = dict(os.environ, CLAUDE_PROJECT_DIR=self.repo) + data = {"tool_name": "Bash", "tool_input": {"command": "rm f{1..257}"}, "cwd": self.repo} + self.assertEqual(self.decision(self.run_main(data, env)), "deny") + data["tool_input"] = {"command": "rm f{1..256}"} + self.assertIsNone(self.decision(self.run_main(data, env))) + + +class TestRestrictWildcardOverwrite(Issue59SandboxMixin, unittest.TestCase): + """途中の階層のワイルドカードが既存ファイルに一致する上書きは拒否する.""" + + def forms_bash(self, path: str) -> list: + return [f"echo y > {path}", f"echo y | tee {path}", f"sed -i s/x/y/ {path}"] + + def forms_ps(self, path: str) -> list: + return [f"Set-Content {path} y", f"echo y > {path}", f"echo y | Out-File {path}"] + + def test_projects_wildcard(self): + path = f"{self.p}/*/memory/note.md" + self.assertBashDenied(self.forms_bash(path)) + self.assertPsDenied(self.forms_ps(path)) + + def test_projects_wildcard_without_transcript(self): + self.transcript_path = None + path = f"{self.p}/*/memory/note.md" + self.assertBashDenied(self.forms_bash(path)) + self.assertPsDenied(self.forms_ps(path)) + + def test_outside_wildcards(self): + for tail in ("*/file.txt", "d*/file.txt", "di?/file.txt", "[d]ir/file.txt", "*.txt", "exist*"): + path = f"{self.o}/{tail}" + self.assertBashDenied(self.forms_bash(path)) + self.assertPsDenied(self.forms_ps(path)) + + def test_relative_wildcard(self): + self.assertBashDenied(["echo y > ../outside/*/file.txt"]) + self.assertBashDenied(["echo y > */file.txt"], cwd=self.out) + self.assertPsDenied(["Set-Content */file.txt y"], cwd=self.out) + + def test_hidden_name_is_matched_on_the_safe_side(self): + self.touch(self.out, ".hidden", "only.txt") + self.assertBashDenied([f"echo y > {self.o}/*/only.txt"]) + self.assertPsDenied([f"Set-Content {self.o}/*/only.txt y"]) + + +class TestRestrictOutsideCreateAllowed(Issue59SandboxMixin, unittest.TestCase): + """リポジトリ外への新規作成は拒否しない(一致の無いワイルドカードを含む).""" + + def test_new_file(self): + self.assertBashAllowed([f"echo y > {self.o}/new.txt", f"echo y | tee {self.o}/new.txt"]) + self.assertPsAllowed([f"Set-Content {self.o}/new.txt y", f"echo y > {self.o}/new.txt"]) + + def test_wildcard_without_match(self): + path = f"{self.o}/*/none/new.txt" + self.assertBashAllowed([f"echo y > {path}", f"echo y | tee {path}"]) + self.assertPsAllowed([f"Set-Content {path} y", f"echo y > {path}"]) + self.assertBashAllowed([f"echo y > {self.o}/none*.txt"]) + + def test_brace_to_new_files(self): + self.assertBashAllowed([f"echo y | tee {self.o}/{{new1,new2}}.txt"]) + + +class TestRestrictBraceOverwriteFromMemory(Issue59SandboxMixin, unittest.TestCase): + """波括弧でメモのフォルダの外に出る上書きは拒否する.""" + + def test_brace_escape_to_transcript(self): + tail = "{note.md,../session.jsonl}" + self.touch(self.out, "x", "a") + self.assertBashDenied([ + f"sed -i s/x/y/ {self.m}/{tail}", + f"echo y | tee {self.m}/{tail}", + f"cp {self.o}/x/a {self.m}/{{a,../session.jsonl}}", + f"rm {self.m}/{tail}", + f"echo y > {self.m}/{tail}", + ]) + + def test_brace_with_transcript_outside_repo(self): + self.transcript_path = None + self.assertBashDenied([f"sed -i s/x/y/ {self.m}/{{note.md,../session.jsonl}}"]) + + +class TestRestrictMemoryBraceStaysDenied(Issue59SandboxMixin, unittest.TestCase): + """メモのフォルダの中で閉じていても,波括弧・`..` は従来どおり許可しない(緩めていない).""" + + def setUp(self) -> None: + super().setUp() + self.touch(self.deep_dir, "x") + + def test_brace_inside_memory(self): + m = self.m + self.assertBashDenied([ + f"rm {m}/{{note.md,sub/x}}", + f"echo y > {m}/{{note.md,sub/x}}", + f"sed -i s/x/y/ {m}/{{note.md,sub/x}}", + ]) + + def test_dot_dot_inside_memory(self): + self.assertBashDenied([f"rm {self.m}/sub/../note.md"]) + self.assertPsDenied([f"Remove-Item {self.m}/sub/../note.md"]) + + +class TestRestrictMemoryTailStaysAllowed(Issue59SandboxMixin, unittest.TestCase): + """既存のメモのフォルダの許可が,リンクがある状態でも保たれること.""" + + def setUp(self) -> None: + super().setUp() + self.make_memory_escape() + + def test_tail_wildcard_with_link_present(self): + m = self.m + self.assertBashAllowed([f"rm {m}/*", f"rm {m}/*.md", f"rm {m}/sub/*", f"rm -rf {m}/*"]) + self.assertPsAllowed([f"Remove-Item {m}/*", f"Remove-Item {m}/*.md", f"Remove-Item {m}/sub/*"]) + + def test_plain_overwrite_with_link_present(self): + self.assertBashAllowed([f"echo y > {self.m}/note.md", f"echo y | tee {self.m}/note.md"]) + self.assertPsAllowed([f"Set-Content {self.m}/note.md y"]) + + def test_content_destroying_commands_follow_the_link(self): + """truncate・shred・Clear-Content はリンク先の中身を壊すので,一致したリンクのリンク先も判定する.""" + m = self.m + self.assertBashDenied([f"truncate -s 0 {m}/*", f"shred {m}/*", f"truncate -s 0 {m}/esc*"]) + self.assertPsDenied([f"Clear-Content {m}/*", f"Clear-Content {m}/esc*"]) + + +class TestRestrictCopySourceBrace(Issue59SandboxMixin, unittest.TestCase): + """コピー元の波括弧・ワイルドカードは,展開後の名前でコピー先の既存ファイルを判定する.""" + + def setUp(self) -> None: + super().setUp() + for root in (self.repo, self.out): + self.touch(root, "src", "x", "a") + self.touch(root, "src", "x", "b") + self.dest = os.path.join(self.out, "dest") + os.makedirs(self.dest) + self.d = _fwd(self.dest) + + def test_existing_in_dest_is_denied(self): + self.touch(self.dest, "a") + for src in (f"{self.r}/src", f"{self.o}/src", "src"): + for dest in (f"{self.d}/", self.d): + self.assertBashDenied([f"cp {src}/x/{{a,b}} {dest}", f"cp {src}/x/* {dest}", f"mv {src}/x/{{a,b}} {dest}"]) + self.assertPsDenied([f"Copy-Item {self.r}/src/x/* {self.d}/"]) + + def test_second_alternative_existing_is_denied(self): + self.touch(self.dest, "b") + self.assertBashDenied([f"cp {self.r}/src/x/{{a,b}} {self.d}/"]) + + def test_nothing_existing_in_dest_is_allowed(self): + self.touch(self.dest, "c") + self.assertBashAllowed([f"cp {self.r}/src/x/{{a,b}} {self.d}/", f"cp {self.r}/src/x/* {self.d}/"]) + self.assertPsAllowed([f"Copy-Item {self.r}/src/x/* {self.d}/"]) + + +class TestRestrictLinkThenDotDotInRepo(Issue59SandboxMixin, unittest.TestCase): + """リポジトリ内の途中のリンクの後の `..` はリンク先の親へ上がる.""" + + def test_all_write_ops(self): + link = self.make_repo_escape() + self.assertAllWriteOpsDenied(os.path.join(link, "..", "existing.txt")) + + def test_new_file_through_link_is_allowed(self): + link = self.make_repo_escape() + path = _fwd(os.path.join(link, "..", "brand_new.txt")) + self.assertBashAllowed([f"echo y > {path}", f"echo y | tee {path}"]) + self.assertPsAllowed([f"Set-Content {path} y"]) + self.assertAllowed(self.tool("Write", {"file_path": os.path.join(link, "..", "brand_new.txt"), "content": "y"})) + + def test_dot_dot_without_link_stays_in_repo(self): + path = os.path.join(self.repo, "sub", "..", "file.txt") + self.assertAllWriteOpsAllowed(path) + + def test_relative_path(self): + self.make_repo_escape() + self.assertBashDenied(["rm escape/../existing.txt", "echo y > escape/../existing.txt"]) + self.assertPsDenied(["Set-Content escape/../existing.txt y"]) + self.assertDenied(self.tool("Write", {"file_path": os.path.join("escape", "..", "existing.txt"), "content": "y"})) + + +class TestRestrictWildcardMatchingLinkInRepo(Issue59SandboxMixin, unittest.TestCase): + """リポジトリ内のワイルドカードが外へのリンクに一致する場合.""" + + def setUp(self) -> None: + super().setUp() + self.make_repo_escape() + + def test_intermediate_wildcard_is_denied(self): + path = f"{self.r}/*/file.txt" + self.assertBashDenied([f"rm {path}", f"echo y > {path}", f"echo y | tee {path}", f"sed -i s/x/y/ {path}", + "rm */file.txt"]) + self.assertPsDenied([f"Remove-Item {path}", f"Set-Content {path} y", f"echo y > {path}"]) + + def test_intermediate_wildcard_new_file_is_allowed(self): + path = f"{self.r}/*/brand_new.txt" + self.assertBashAllowed([f"echo y > {path}"]) + self.assertPsAllowed([f"Set-Content {path} y"]) + + def test_brace_to_outside_directory(self): + self.assertBashDenied([f"rm -rf {self.r}/{{a,../outside/dir}}"]) + + def test_tail_wildcard_only_removes_the_link(self): + """rm 等は一致したリンク自体を消すだけで,リンク先には触らない.""" + r = self.r + self.assertBashAllowed([f"rm {r}/*", f"rm -rf {r}/*", f"rm -rf {r}/esc*", "rm -rf *", f"mv {r}/esc* {r}/sub/"]) + self.assertPsAllowed([f"Remove-Item {r}/*", f"Remove-Item {r}/* -Recurse", f"Remove-Item {r}/esc* -Recurse"]) + + def test_tail_wildcard_with_slash_reaches_link_target(self): + """`*/` は末尾の / でリンクをたどるので,rm -rf はリンク先の中身を消す(Git Bash・Linux の rm で確認).""" + r = self.r + self.assertBashDenied([f"rm -rf {r}/*/", f"rm -rf {r}/esc*/", "rm -rf */"]) + + def test_tail_wildcard_with_content_destroying_commands_is_denied(self): + r = self.r + self.assertBashDenied([f"truncate -s 0 {r}/*", f"shred {r}/*", f"truncate -s 0 {r}/esc*"]) + self.assertPsDenied([f"Clear-Content {r}/*", f"Clear-Content {r}/esc*"]) + + def test_tail_wildcard_file_link_with_content_destroying_commands(self): + link = os.path.join(self.repo, "link.txt") + try: + os.symlink(self.existing, link) + except OSError: + if os.name != "nt": + raise + self.skipTest("Windows でシンボリックリンクの作成権限が無い(ファイルにはジャンクションを使えない)") + r = self.r + self.assertBashDenied([f"truncate -s 0 {r}/*.txt", f"shred {r}/link*"]) + self.assertPsDenied([f"Clear-Content {r}/link*"]) + self.assertBashAllowed([f"rm {r}/link*"]) + + def test_copy_into_link_matched_by_wildcard(self): + """cp・mv のコピー先のワイルドカードがリンクに一致すると,リンク先のディレクトリへ書き込む.""" + r = self.r + self.assertBashDenied([f"cp {r}/x/file.txt {r}/esc*", f"mv {r}/x/file.txt {r}/esc*"]) + self.assertBashAllowed([f"cp {r}/x/brand_new.txt {r}/esc*"]) + + +class TestRestrictPowerShellBraceIsLiteral(Issue59SandboxMixin, unittest.TestCase): + """PowerShell は波括弧を展開しないので文字どおりの名前として扱う.""" + + def test_literal_brace_stays_inside_repo(self): + self.assertPsAllowed([ + f"Remove-Item '{self.r}/{{a,../outside/existing.txt}}'", + f"Remove-Item {self.r}/{{a,../outside/existing.txt}}", + f"Set-Content '{self.r}/{{a,../outside/existing.txt}}' y", + ]) + + def test_bash_c_inside_powershell_expands(self): + self.assertPsDenied([f"bash -c 'rm {self.r}/{{a,../outside/existing.txt}}'"]) + + +class TestRestrictCdMinus(Issue59SandboxMixin, unittest.TestCase): + """cd - / Set-Location - は同じコマンド内で追跡できる場合だけ解決する.""" + + def setUp(self) -> None: + super().setUp() + self.x = self.touch(self.out, "x") + + def test_returns_to_outside_is_denied(self): + for d in (f"{self.o}/dir", f"{self.r}/sub", f"{self.m}/sub", f"{self.r}"): + self.assertBashDenied([f"cd {d} && cd - && rm x", f"cd {d}; cd -; rm -f x"], cwd=self.out) + self.assertPsDenied([f"Set-Location {d}; Set-Location -; Remove-Item x", f"sl {d}; sl -; Remove-Item x"], + cwd=self.out) + + def test_inside_nested_shell_is_denied(self): + self.assertBashDenied([f"bash -c 'cd {self.r}/sub && cd - && rm x'"], cwd=self.out) + + def test_returns_to_repo_is_allowed(self): + for d in (f"{self.m}/sub", f"{self.o}/dir", f"{self.r}/sub"): + self.assertBashAllowed([f"cd {d} && cd - && rm x"]) + self.assertPsAllowed([f"Set-Location {d}; Set-Location -; Remove-Item x"]) + + def test_cd_minus_twice_toggles(self): + self.assertBashDenied([f"cd {self.r}/sub && cd {self.o} && cd - && cd - && rm x"]) + self.assertBashAllowed([f"cd {self.o} && cd - && rm x", f"cd {self.o} && cd - && cd - && cd - && rm x"]) + + def test_set_location_plus_goes_forward(self): + self.assertPsDenied([f"Set-Location {self.o}; Set-Location -; Set-Location +; Remove-Item x"]) + self.assertPsAllowed([f"Set-Location {self.o}; Set-Location -; Remove-Item x"]) + + def test_subshell_restores_previous_directory(self): + self.assertBashDenied([f"cd {self.r}/sub && (cd {self.o}/dir) && cd - && rm x"], cwd=self.out) + self.assertBashDenied([f"cd {self.o} && (cd - && rm x) && rm x"]) + + def test_untrackable_stays_unresolved(self): + """コマンドより前の移動先は分からないので,従来どおり未解決(判定しない).""" + for cwd in (self.repo, self.out): + self.assertBashAllowed(["cd - && rm x", "cd -; rm x"], cwd=cwd) + self.assertPsAllowed(["Set-Location -; Remove-Item x", "Set-Location +; Remove-Item x"], cwd=cwd) + self.assertBashAllowed([f"(cd {self.r}/sub) && cd - && rm x"], cwd=self.out) + + def test_absolute_target_after_unresolved_is_still_denied(self): + self.assertBashDenied([f"cd - && rm {self.o}/x"]) + self.assertPsDenied([f"Set-Location -; Remove-Item {self.o}/x"]) + + +class TestRestrictWildcardMatchLimit(Issue59SandboxMixin, unittest.TestCase): + """一致が上限(1 パス 1000 件)を超えると,基点がリポジトリ内・一時ディレクトリなら許可,それ以外は拒否.""" + + def make_dirs(self, parent: str, start: int, stop: int) -> None: + for n in range(start, stop): + os.makedirs(os.path.join(parent, "d%d" % n)) + + def test_outside_boundary(self): + many = os.path.join(self.out, "many") + self.make_dirs(many, 0, 1000) + cmd = f"echo y > {_fwd(many)}/*/nope.txt" + ps_cmd = f"Set-Content {_fwd(many)}/*/nope.txt y" + self.assertAllowed(self.bash(cmd), "ちょうど上限なら全部調べられる") + self.assertAllowed(self.ps(ps_cmd), "ちょうど上限なら全部調べられる") + self.make_dirs(many, 1000, 1001) + self.assertDenied(self.bash(cmd), "上限超え") + self.assertDenied(self.ps(ps_cmd), "上限超え") + + def test_inside_repo_over_limit_is_allowed(self): + many = os.path.join(self.repo, "many") + self.make_dirs(many, 0, 1001) + self.assertAllowed(self.bash(f"echo y > {_fwd(many)}/*/nope.txt")) + self.assertAllowed(self.bash(f"rm {_fwd(many)}/*")) + self.assertAllowed(self.ps(f"Remove-Item {_fwd(many)}/*")) + + def test_with_small_limit(self): + temp = tempfile.mkdtemp(prefix="_restrict_limit_") + self.addCleanup(shutil.rmtree, temp, True) + for parent in (os.path.join(self.repo, "many"), os.path.join(self.out, "many"), os.path.join(temp, "many")): + self.make_dirs(parent, 0, 6) + with mock.patch.object(self.rra, "MAX_WILDCARD_MATCHES", 5): + self.assertAllowed(self.bash(f"echo y > {self.r}/many/*/nope.txt")) + self.assertAllowed(self.bash(f"echo y > {_fwd(temp)}/many/*/nope.txt")) + self.assertDenied(self.bash(f"echo y > {self.o}/many/*/nope.txt")) + self.assertAllowed(self.ps(f"Set-Content {self.r}/many/*/nope.txt y")) + self.assertAllowed(self.ps(f"Set-Content {_fwd(temp)}/many/*/nope.txt y")) + self.assertDenied(self.ps(f"Set-Content {self.o}/many/*/nope.txt y")) + + def test_memory_base_over_limit_is_denied(self): + """基点がメモのフォルダでも,リポジトリ内・一時ディレクトリではないので拒否する.""" + self.make_dirs(self.memory, 0, 6) + with mock.patch.object(self.rra, "MAX_WILDCARD_MATCHES", 5): + self.assertDenied(self.bash(f"rm {self.m}/*")) + + def test_new_file_append_is_not_undecidable(self): + many = os.path.join(self.out, "many") + self.make_dirs(many, 0, 6) + with mock.patch.object(self.rra, "MAX_WILDCARD_MATCHES", 5): + self.assertAllowed(self.bash(f"echo y >> {_fwd(many)}/*/nope.txt")) + + def test_scan_budget_is_reset_per_command(self): + many = os.path.join(self.out, "many") + self.make_dirs(many, 0, 3) + cmd = f"echo y > {_fwd(many)}/*/nope.txt" + with mock.patch.object(self.rra, "MAX_WILDCARD_SCANS", 5): + for _ in range(4): + self.assertAllowed(self.bash(cmd)) + with mock.patch.object(self.rra, "MAX_WILDCARD_SCANS", 1): + self.assertDenied(self.bash(cmd)) + + +class TestRestrictExpansionInTemp(Issue59SandboxMixin, unittest.TestCase): + """一時ディレクトリ配下の波括弧・ワイルドカードも誤拒否しない.""" + + def setUp(self) -> None: + super().setUp() + self.temp = tempfile.mkdtemp(prefix="_restrict_expansion_") + self.addCleanup(shutil.rmtree, self.temp, True) + self.t = _fwd(self.temp) + self.assertTrue(self.rra.is_temp_path(self.temp)) + + def fill(self) -> None: + for name in ("a.txt", "b.txt", "1.txt", "2.txt", os.path.join("d1", "x.txt"), os.path.join("d2", "x.txt")): + self.touch(self.temp, "src", name) + self.touch(self.temp, "a.txt") + for d in ("b", "c", "dst"): + os.makedirs(os.path.join(self.temp, d)) + + def test_relative_and_absolute(self): + t = self.t + self.fill() + self.assertBashAllowed(["rm src/{a,b}.txt", "rm src/*/x.txt", "cp a.txt {b,c}/", "mv src/*.txt dst/", + "rm src/{1..3}.txt", "echo y > src/*/x.txt", "sed -i s/x/y/ src/*/x.txt"], cwd=self.temp) + self.assertBashAllowed([f"rm {t}/src/{{a,b}}.txt", f"rm {t}/src/*/x.txt", f"cp {t}/a.txt {t}/{{b,c}}/", + f"mv {t}/src/*.txt {t}/dst/", f"rm {t}/src/{{1..3}}.txt", f"echo y > {t}/src/*/x.txt"]) + self.assertPsAllowed([f"Remove-Item {t}/src/*/x.txt", f"Set-Content {t}/src/*/x.txt y"]) + + def test_link_out_of_temp_is_denied(self): + self.link_dir(os.path.join(self.out, "dir"), os.path.join(self.temp, "escape")) + t = self.t + self.assertBashDenied([f"rm {t}/*/file.txt", f"echo y > {t}/*/file.txt", f"rm {t}/escape/../existing.txt"]) + self.assertPsDenied([f"Set-Content {t}/*/file.txt y"]) + + +class TestRestrictFileToolsLiteralWildcard(Issue59SandboxMixin, unittest.TestCase): + """ファイル操作ツールは `..` だけをたどり,ワイルドカード・波括弧は文字どおりの名前として扱う.""" + + def test_wildcard_is_not_expanded_by_write(self): + self.make_repo_escape() + self.assertAllowed(self.tool("Write", {"file_path": os.path.join(self.out, "*", "file.txt"), "content": "y"})) + self.assertAllowed(self.tool("Write", {"file_path": os.path.join(self.repo, "*", "file.txt"), "content": "y"})) + self.assertAllowed(self.tool("Edit", {"file_path": os.path.join(self.repo, "*", "file.txt")})) + + def test_brace_is_not_expanded(self): + path = self.r + "/{a,../outside/existing.txt}" + self.assertAllowed(self.tool("Write", {"file_path": path, "content": "y"})) + + def test_dot_dot_after_link_is_followed(self): + link = self.make_memory_escape() + path = os.path.join(link, "..", "existing.txt") + self.assertDenied(self.tool("Write", {"file_path": path, "content": "y"})) + self.assertDenied(self.tool("Edit", {"file_path": path})) + + def test_via_main(self): + link = self.make_memory_escape() + path = os.path.join(link, "..", "existing.txt") + env = dict(os.environ, CLAUDE_PROJECT_DIR=self.repo) + data = {"tool_name": "Write", "tool_input": {"file_path": path, "content": "y"}, "cwd": self.repo, + "transcript_path": self.session} + self.assertEqual(self.decision(self.run_main(data, env)), "deny") + data["tool_input"] = {"file_path": self.note, "content": "y"} + self.assertIsNone(self.decision(self.run_main(data, env))) + + +class TestRestrictTrailingSeparatorLinkInRepo(Issue59SandboxMixin, unittest.TestCase): + """リポジトリ内の外へのリンク.Bash は末尾の / でリンク先の中身を消す.PowerShell はリンクしか消さない.""" + + def setUp(self) -> None: + super().setUp() + self.make_repo_escape() + + def test_wildcard_with_trailing_slash_is_denied(self): + r = self.r + self.assertBashDenied([f"rm -rf {r}/esc*/", f"rm -rf {r}/*/", "rm -rf ./*/", "rm -rf esc*//", "rm -rf {esc*,sub}/"]) + + def test_through_command_prefix_and_nested_shell_is_denied(self): + r = self.r + self.assertBashDenied(["sudo rm -rf */", f"bash -c 'rm -rf {r}/*/'"]) + + def test_literal_link_with_trailing_slash_is_denied(self): + r = self.r + self.assertBashDenied([f"rm -rf {r}/escape/", f"rm -rf {r}/escape//", "rm -rf escape//", + f"rm -rf {r}/sub/../escape/", "rm -rf sub/../escape/"]) + + def test_without_trailing_slash_is_allowed(self): + r = self.r + self.assertBashAllowed([f"rm {r}/*", f"rm -rf {r}/*", "rm -rf esc*", "rm -rf *", f"mv {r}/esc* {r}/sub/"]) + + def test_powershell_removes_only_the_link(self): + r = self.r + self.assertPsAllowed([f"Remove-Item {r}/*/ -Recurse", f"Remove-Item {r}/esc*/ -Recurse", + "Remove-Item esc*/ -Recurse"]) + + @unittest.skipUnless(os.name == "nt", "\\ が PowerShell のパスの末尾の区切りとして実測できているのは Windows だけ") + def test_powershell_backslash_removes_only_the_link(self): + self.assertPsAllowed([f"Remove-Item {self.r}/esc*\\ -Recurse", "Remove-Item esc*\\ -Recurse"]) + + +class TestRestrictTrailingSeparatorNoLinkInRepo(Issue59SandboxMixin, unittest.TestCase): + """リンクが無ければ,末尾の / があってもリポジトリ内の削除は誤拒否しない.""" + + def setUp(self) -> None: + super().setUp() + self.touch(self.repo, "src", "a", "x.txt") + + def test_is_allowed(self): + self.assertBashAllowed(["rm -rf src/*/", "rm -rf */", f"rm -rf {self.r}/src/"]) + + +class TestRestrictTrailingSeparatorInTemp(Issue59SandboxMixin, unittest.TestCase): + """一時ディレクトリの中の外へのリンク.文字列では一時ディレクトリの中でも,消えるのはリンク先の中身.""" + + def setUp(self) -> None: + super().setUp() + self.temp = tempfile.mkdtemp(prefix="_restrict_trailing_") + self.addCleanup(shutil.rmtree, self.temp, True) + self.t = _fwd(self.temp) + self.assertTrue(self.rra.is_temp_path(self.temp)) + self.touch(self.temp, "src", "a", "x.txt") + + def test_link_with_trailing_slash_is_denied(self): + self.link_dir(os.path.join(self.out, "dir"), os.path.join(self.temp, "escape")) + t = self.t + self.assertBashDenied([f"rm -rf {t}/*/", f"rm -rf {t}/esc*/", f"rm -rf {t}/escape/"]) + + def test_no_link_is_allowed(self): + t = self.t + self.assertBashAllowed([f"rm -rf {t}/*/", f"rm -rf {t}/src/*/", f"rm -rf {t}/src/"]) + self.assertBashAllowed(["rm -rf src/*/", "rm -rf */"], cwd=self.temp) + + +class TestRestrictTrailingSeparatorInMemory(Issue59SandboxMixin, unittest.TestCase): + """メモのフォルダの中の外へのリンク.""" + + def test_wildcard_with_trailing_slash_is_denied(self): + self.make_memory_escape() + m = self.m + self.assertBashDenied([f"rm -rf {m}/*/", f"rm -rf {m}/esc*/", f"rm -rf {m}/sub/*/"]) + + def test_without_trailing_slash_is_allowed(self): + self.make_memory_escape() + self.assertBashAllowed([f"rm {self.m}/*"]) + + def test_no_link_is_allowed(self): + self.assertBashAllowed([f"rm -rf {self.m}/sub/"]) + + +class TestRestrictPushdMinus(Issue59SandboxMixin, unittest.TestCase): + """pushd - / Push-Location - は同じコマンド内で追跡できる場合だけ解決する(cwd はリポジトリ外で x が既存).""" + + def setUp(self) -> None: + super().setUp() + self.x = self.touch(self.out, "x") + + def test_bash_returns_to_outside_is_denied(self): + s = f"{self.r}/sub" + self.assertBashDenied([f"cd {s} && pushd - && rm x", f"cd {s}; pushd -; rm x", + f"bash -c 'cd {s} && pushd - && rm x'"], cwd=self.out) + + def test_powershell_returns_to_outside_is_denied(self): + s = f"{self.r}/sub" + self.assertPsDenied([f"Set-Location {s}; Push-Location -; Remove-Item x", + f"Push-Location {s}; Set-Location -; Remove-Item x"], cwd=self.out) + + def test_popd_returns_to_repo_is_allowed(self): + self.assertBashAllowed([f"cd {self.r}/sub && pushd - && popd && rm x"], cwd=self.out) + + def test_popd_location_is_tracked(self): + """popd の戻り先が未解決に落ちていないこと(未解決だと上の許可のテストも通ってしまう).""" + self.assertBashDenied([f"cd {self.r}/sub && pushd - && popd && rm ../../outside/x"], cwd=self.out) + + def test_untrackable_stays_unresolved(self): + """コマンドより前の移動先は分からないので,従来どおり未解決(判定しない).""" + self.assertBashAllowed(["pushd - && rm x"], cwd=self.out) + self.assertPsAllowed(["Push-Location -; Remove-Item x"], cwd=self.out) + + +# --------------------------------------------------------------------------- +# is_temp_path: Linux / macOS はリンクを解決した実パスで一時ディレクトリを判定する +# --------------------------------------------------------------------------- +REAL_PATH_TEMP_REASON = ( + "実パスでの一時ディレクトリの判定は Linux / macOS だけの仕様のため" + "(Windows は Git Bash の /tmp を実パスに解決できず,従来の文字列判定のまま)" +) + + +class TempLinkSandboxMixin(Issue59SandboxMixin): + """実際の一時ディレクトリの中にサンドボックスを作り,リンク先はその外(self.out)に作る. + + /file.txt・realdir/f.txt + /escape → outside/dir(既存の file.txt を含む).make_escape で作る + /filelink → outside/existing.txt.make_filelink で作る + /innerlink → /realdir.make_innerlink で作る + """ + + temp_parent = None # None は tempfile.gettempdir() + + def setUp(self) -> None: + super().setUp() + self.temp = tempfile.mkdtemp(prefix="_restrict_temp_link_", dir=self.temp_parent) + self.addCleanup(shutil.rmtree, self.temp, True) + self.t = _fwd(self.temp) + self.assertTrue(self.rra.is_temp_path(self.temp), "サンドボックスが一時ディレクトリの中にあること") + self.assertFalse(self.rra.is_temp_path(self.out), "リンク先が一時ディレクトリの外にあること") + self.touch(self.temp, "file.txt") + self.touch(self.temp, "realdir", "f.txt") + + def make_escape(self) -> str: + link = os.path.join(self.temp, "escape") + self.link_dir(os.path.join(self.out, "dir"), link) + self.assertTrue(os.path.isfile(os.path.join(link, "file.txt")), "リンク先は既存のファイルであること") + return link + + def make_filelink(self) -> str: + link = os.path.join(self.temp, "filelink") + os.symlink(self.existing, link) + self.assertTrue(os.path.isfile(link), "リンク先は既存のファイルであること") + return link + + def make_innerlink(self) -> str: + link = os.path.join(self.temp, "innerlink") + self.link_dir(os.path.join(self.temp, "realdir"), link) + return link + + +@unittest.skipIf(os.name == "nt", REAL_PATH_TEMP_REASON) +class TestRestrictTempLinkEscapeDenied(TempLinkSandboxMixin, unittest.TestCase): + """一時ディレクトリの中に見えても,リンク越しに壊れるのが外のファイルなら拒否する.""" + + def test_operations_through_directory_link(self): + self.make_escape() + t, r = self.t, self.r + self.assertBashDenied([ + f"rm {t}/escape/file.txt", + f"rm -rf {t}/escape/file.txt", + f"echo y > {t}/escape/file.txt", + f"cp {r}/file.txt {t}/escape/file.txt", + f"mv {t}/escape/file.txt {t}/moved", + f"sed -i s/x/y/ {t}/escape/file.txt", + ]) + + def test_relative_path_through_directory_link(self): + self.make_escape() + self.assertBashDenied(["rm escape/file.txt", "echo y > escape/file.txt"], cwd=self.temp) + + def test_operations_on_file_link(self): + """> ・cp・truncate・shred はリンク自体ではなくリンク先のファイルを壊す.""" + self.make_filelink() + t, r = self.t, self.r + self.assertBashDenied([ + f"echo y > {t}/filelink", + f"cp {r}/file.txt {t}/filelink", + f"truncate -s 0 {t}/filelink", + f"shred {t}/filelink", + ]) + + def test_find_delete_from_link(self): + self.make_escape() + self.assertBashDenied([f"find {self.t}/escape -delete"]) + + def test_nested_shell_prefix_and_inline_code(self): + self.make_escape() + t = self.t + self.assertBashDenied([ + f"bash -c 'rm {t}/escape/file.txt'", + f"sudo rm {t}/escape/file.txt", + f"python3 -c \"import os; os.remove('{t}/escape/file.txt')\"", + ]) + + def test_link_inside_the_link_target(self): + """最後の要素がリンクでも,その親がリンク越しに外にあれば,リンク自体を消す操作も外の変更になる.""" + self.make_escape() + os.symlink(self.existing, os.path.join(self.out, "dir", "inner")) + self.assertBashDenied([f"rm {self.t}/escape/inner"]) + + def test_dotdot_escape(self): + rel = _fwd(os.path.relpath(self.existing, self.temp)) + self.assertTrue(rel.startswith(".."), rel) + self.assertBashDenied([f"rm {self.t}/{rel}", f"rm -rf {self.t}/{rel}", f"echo y > {self.t}/{rel}"]) + + def test_powershell_and_file_tools(self): + """実パスでの判定はシェルの種類やツールによらない.""" + escape = self.make_escape() + filelink = self.make_filelink() + target = os.path.join(escape, "file.txt") + self.assertPsDenied([f"Remove-Item {self.t}/escape/file.txt", f"Set-Content {self.t}/escape/file.txt y"]) + for path in (target, filelink): + with self.subTest(path): + self.assertDenied(self.tool("Write", {"file_path": path, "content": "y"}), path) + self.assertDenied(self.tool("Edit", {"file_path": path, "old_string": "x", "new_string": "y"}), path) + + +@unittest.skipIf(os.name == "nt", REAL_PATH_TEMP_REASON + ".Windows のリンク自体の削除は keep_final_link の対象外") +class TestRestrictTempLinkItselfAllowed(TempLinkSandboxMixin, unittest.TestCase): + """リンク自体を消す・動かすだけの操作はリンク先に触らないので,許可のまま.""" + + def test_remove_link_itself(self): + self.make_escape() + self.make_filelink() + for link in ("escape", "filelink"): + f = f"{self.t}/{link}" + self.assertBashAllowed([f"rm {f}", f"rm -rf {f}", f"unlink {f}", f"mv {f} {self.t}/other"]) + + def test_relative_link_itself(self): + self.make_escape() + self.assertBashAllowed(["rm escape", "rm -rf escape", "unlink escape", "mv escape other"], cwd=self.temp) + + def test_wildcard_matching_links(self): + self.make_escape() + self.make_filelink() + self.assertBashAllowed([f"rm {self.t}/*", f"rm -rf {self.t}/*"]) + + +class TestRestrictTempWithoutEscapeAllowed(TempLinkSandboxMixin, unittest.TestCase): + """外へのリンクが関わらない一時ディレクトリの操作は,どの OS でも許可のまま.""" + + def test_delete_and_overwrite_without_link(self): + t, r = self.t, self.r + self.assertBashAllowed([ + f"rm {t}/file.txt", + f"rm -rf {t}/realdir", + f"rm -rf {t}/realdir/", + f"echo y > {t}/file.txt", + f"cp {r}/file.txt {t}/file.txt", + f"mv {t}/file.txt {t}/moved", + f"sed -i s/x/y/ {t}/file.txt", + f"truncate -s 0 {t}/file.txt", + f"shred {t}/file.txt", + ]) + + def test_through_link_to_inside_temp(self): + self.make_innerlink() + t, r = self.t, self.r + self.assertBashAllowed([ + f"rm {t}/innerlink/f.txt", + f"rm -rf {t}/innerlink/", + f"echo y > {t}/innerlink/f.txt", + f"cp {r}/file.txt {t}/innerlink/f.txt", + ]) + + def test_create_with_missing_parents(self): + t, r = self.t, self.r + self.assertBashAllowed([ + f"touch {t}/new.txt", + f"echo y > {t}/no/such/parent/new.txt", + f"mkdir -p {t}/no/such/parent", + f"cp {r}/file.txt {t}/no/such/parent/new.txt", + f"rm -rf {t}/no/such/parent", + ]) + self.assertAllowed(self.tool("Write", {"file_path": os.path.join(self.temp, "no", "such", "new.txt"), "content": "y"})) + + +class TestRestrictTempSkillCommandShapes(TempLinkSandboxMixin, unittest.TestCase): + """/sync-template・/set-mode が mktemp -d の配下で実行するコマンドの形.""" + + def shapes(self, root: str) -> list: + r = self.r + return [ + f'git clone --depth 1 https://example.invalid/t.git "{root}/tpl"', + f': > "{root}/overrides.tsv"', + f'mkdir -p "{root}/3way/.claude" "{root}/merged/.claude"', + f'cp "{r}/file.txt" "{root}/3way/ours"', + f'cp "{root}/tpl/file.txt" "{r}/file.txt"', + f"sed 's/\\r$//' \"{r}/file.txt\" > \"{root}/3way/ours\"", + f'rm -rf "{root}/tpl" "{root}"', + f'rm -rf "{root}"', + ] + + def test_shapes_on_existing_files(self): + root = os.path.join(self.temp, "work") + for name in ("overrides.tsv", os.path.join("3way", "ours"), os.path.join("tpl", "file.txt")): + self.touch(root, name) + self.assertBashAllowed(self.shapes(_fwd(root))) + + @unittest.skipIf(os.name == "nt", "mktemp コマンドの実体を直接呼べるのは Linux / macOS だけのため(Windows は Git Bash 経由)") + def test_shapes_under_real_mktemp(self): + if shutil.which("mktemp") is None: + self.skipTest("mktemp コマンドが無い") + root = subprocess.check_output(["mktemp", "-d"], universal_newlines=True).strip() + self.addCleanup(shutil.rmtree, root, True) + for name in ("overrides.tsv", os.path.join("3way", "ours"), os.path.join("tpl", "file.txt")): + self.touch(root, name) + self.assertBashAllowed(self.shapes(root)) + + def test_shapes_with_shell_variables(self): + self.assertBashAllowed([ + 'TEMP_DIR=$(mktemp -d)\ngit clone --depth 1 "$U" "$TEMP_DIR"\ncp "$TEMP_DIR/$f" "$f"\nrm -rf "$TEMP_DIR"', + 'WORK_DIR=$(mktemp -d)\n: > "$WORK_DIR/overrides.tsv"\nmkdir -p "$WORK_DIR/3way"\nrm -rf "$WORK_DIR"', + ]) + + +@unittest.skipIf(os.name == "nt", "基準の /tmp を実パスに解決できるのは Linux / macOS だけのため(Windows の /tmp は Git Bash の仮想パス)") +class TestRestrictTempLinkUnderSlashTmp(TempLinkSandboxMixin, unittest.TestCase): + """基準の一方である /tmp を直接使う(gettempdir が別の場所の macOS 等でも /tmp を判定できること).""" + + temp_parent = "/tmp" + + def setUp(self) -> None: + if not (os.path.isdir("/tmp") and os.access("/tmp", os.W_OK)): + self.skipTest("/tmp が存在しないか書き込めない") + super().setUp() + + def test_escape_is_denied(self): + self.make_escape() + self.make_filelink() + t = self.t + self.assertBashDenied([f"rm {t}/escape/file.txt", f"echo y > {t}/filelink", f"rm /tmp/..{_fwd(self.existing)}"]) + + def test_without_escape_is_allowed(self): + self.make_escape() + t = self.t + name = os.path.basename(self.temp) + self.assertBashAllowed([f"rm {t}/escape", f"rm {t}/file.txt", f"echo y > {t}/no/such/parent/new.txt", + f"rm -rf {t}/no/such/parent", f"rm /tmp/{name}/file.txt"]) + + def test_is_temp_path(self): + self.make_escape() + self.assertTrue(self.rra.is_temp_path("/tmp")) + self.assertTrue(self.rra.is_temp_path(f"/tmp/{os.path.basename(self.temp)}/no/such/file")) + self.assertFalse(self.rra.is_temp_path(f"{self.t}/escape/file.txt")) + self.assertTrue(self.rra.is_temp_path(f"{self.t}/escape", True)) + self.assertFalse(self.rra.is_temp_path(f"{self.t}/escape")) + self.assertFalse(self.rra.is_temp_path("/tmp/../etc")) + + +@unittest.skipUnless(os.name == "nt", "Git Bash 形式の /tmp は Windows にしか存在しないため") +class TestRestrictGitBashTmpOnWindows(RestrictSandboxMixin, unittest.TestCase): + """Windows の /tmp は実パスに解決できないので,今までどおり文字列で許可する.""" + + def test_is_temp_path(self): + for path in ("/tmp", "/tmp/x", "/tmp/x/y.txt", "/tmp/tmp.AbCdEf/tpl", "\\tmp\\x"): + with self.subTest(path): + self.assertTrue(self.rra.is_temp_path(path)) + self.assertTrue(self.rra.is_temp_path(path, True), "keep_final_link は Windows では効かない") + for path in ("/tmp/../etc", "/tmpfoo/x", "/etc/hosts"): + with self.subTest(path): + self.assertFalse(self.rra.is_temp_path(path)) + + def test_commands(self): + for cmd in ("rm /tmp/x", "rm -rf /tmp/x", "echo y > /tmp/x/y.txt", "cp file.txt /tmp/x", "mkdir -p /tmp/x/y", + 'git clone --depth 1 https://example.invalid/t.git "/tmp/tmp.AbCdEf"', ': > "/tmp/tmp.AbCdEf/o.tsv"'): + with self.subTest(cmd): + self.assertAllowed(self.bash(cmd), cmd) + + +class TestContainedDeniedEntryInTemp(TempLinkSandboxMixin, unittest.TestCase): + """再帰読み取りの起点の配下にある禁止パスの検出(Policy.contained_denied_entry).""" + + def setUp(self) -> None: + super().setUp() + self.secret = os.path.join(self.out, "dir") + self.deny = [self.secret] + + def policy(self): + return self.rra.Policy(self.repo, self.deny) + + @unittest.skipIf(os.name == "nt", REAL_PATH_TEMP_REASON) + def test_link_to_outside_detects_denied_entry(self): + link = os.path.join(self.temp, "toout") + self.link_dir(self.out, link) + self.assertEqual(self.policy().contained_denied_entry(link), self.secret) + self.assertDenied(self.bash(f"grep -r x {_fwd(link)}")) + self.assertDenied(self.tool("Grep", {"pattern": "x", "path": link})) + self.assertDenied(self.tool("Glob", {"pattern": "*", "path": link})) + + def test_temp_without_link_detects_nothing(self): + self.assertIsNone(self.policy().contained_denied_entry(self.temp)) + self.assertAllowed(self.bash(f"grep -r x {self.t}")) + + def test_denied_entry_inside_temp_is_not_contained(self): + """一時ディレクトリは対象外なので,配下に禁止パスがあっても検出しない(検出の条件が効いていること).""" + self.deny = [os.path.join(self.temp, "realdir")] + self.assertIsNone(self.policy().contained_denied_entry(self.temp)) + + +MACOS_TEMPDIR = "/var/folders/ab/cd/T" + + +def _fake_macos_realpath(path, **_): + """macOS のリンク(/tmp → /private/tmp,/var → /private/var)と,/tmp/x/escape → /Users/me/data を模擬する.""" + path = posixpath.normpath(path) + for link, target in (("/tmp/x/escape", "/Users/me/data"), ("/tmp", "/private/tmp"), ("/var", "/private/var")): + if path == link or path.startswith(link + "/"): + return _fake_macos_realpath(target + path[len(link):]) + return path + + +@contextlib.contextmanager +def _simulate_macos_paths(module): + """module から見える os を POSIX 相当にし,posixpath.realpath と tempfile.gettempdir を macOS 相当にする. + + with を抜けると(例外時も)mock.patch が元に戻すので,他のテストには影響しない. + """ + with _simulate_posix_host(module), \ + mock.patch.object(posixpath, "realpath", _fake_macos_realpath), \ + mock.patch.object(tempfile, "gettempdir", lambda: MACOS_TEMPDIR): + yield + + +class TestIsTempPathMacOSSimulation(unittest.TestCase): + """macOS のパス構成を差し替えで模擬する(実機は PR の CI で確認する). + + os.name と os.path も POSIX 相当に差し替えるので,ホスト OS によらず実行できる. + """ + + @classmethod + def setUpClass(cls) -> None: + cls.rra = _load_restrict() + + def test_temp_paths_are_allowed(self): + cases = ("/tmp", "/tmp/new/file", "/private/tmp", "/private/tmp/new/file", + MACOS_TEMPDIR, MACOS_TEMPDIR + "/tmp.abc/file", + "/private" + MACOS_TEMPDIR, "/private" + MACOS_TEMPDIR + "/tmp.abc/file") + with _simulate_macos_paths(self.rra): + for path in cases: + with self.subTest(path): + self.assertTrue(self.rra.is_temp_path(path)) + + def test_link_itself_keeps_final_component(self): + with _simulate_macos_paths(self.rra): + for path in ("/tmp/x/escape", MACOS_TEMPDIR + "/tmp.abc", "/tmp/tmp.abc"): + with self.subTest(path): + self.assertTrue(self.rra.is_temp_path(path, True)) + + def test_outside_paths_are_not_temp(self): + cases = ("/tmp/x/escape", "/tmp/x/escape/file.txt", "/tmp/../etc", "/private/etc/hosts", "/var/log/x", + "/private/tmpfoo/x", "/tmpfoo/x", MACOS_TEMPDIR + "foo/x", "/private/var/folders") + with _simulate_macos_paths(self.rra): + for path in cases: + with self.subTest(path): + self.assertFalse(self.rra.is_temp_path(path)) + + def test_keep_final_link_does_not_hide_parent_link(self): + with _simulate_macos_paths(self.rra): + self.assertFalse(self.rra.is_temp_path("/tmp/x/escape/file.txt", True)) + + def test_commands(self): + repo = "/work/repo" + with _simulate_macos_paths(self.rra): + for cmd in ("rm /tmp/tmp.abc/file", f"rm -rf {MACOS_TEMPDIR}/tmp.abc", "rm -rf /tmp/x/escape", + "rm /private/tmp/tmp.abc/file"): + with self.subTest(cmd): + self.assertIsNone(self.rra.check_bash_command(cmd, repo, repo, [])) + for cmd in ("rm /tmp/x/escape/file.txt", "rm /private/etc/hosts", "rm /tmp/../etc/hosts"): + with self.subTest(cmd): + self.assertIsNotNone(self.rra.check_bash_command(cmd, repo, repo, [])) + + def test_simulation_is_restored(self): + real_realpath = posixpath.realpath + real_gettempdir = tempfile.gettempdir + with self.assertRaises(RuntimeError): + with _simulate_macos_paths(self.rra): + self.assertEqual(self.rra.os.path.realpath("/tmp"), "/private/tmp") + self.assertEqual(tempfile.gettempdir(), MACOS_TEMPDIR) + raise RuntimeError("x") + self.assertIs(posixpath.realpath, real_realpath) + self.assertIs(tempfile.gettempdir, real_gettempdir) + self.assertIs(self.rra.os, os) + + +# --------------------------------------------------------------------------- +# restrict_repo_access.py: 想定外の例外・壊れた入力の拒否(Issue #62) +# --------------------------------------------------------------------------- +# 判定の結果は標準入力・標準出力・終了コードで見る(フックの入出力の仕様そのものなので). +# 例外を起こすテストは,本物のプロセスの終了コードを見るために subprocess の中で関数を差し替える. +HOOK_DRIVER = ( + "import io, os, sys\n" + "sys.path.insert(0, sys.argv[1])\n" + "import restrict_repo_access as rra\n" + "exec(sys.argv[2])\n" + "rra.main()\n" +) +HOOK_RAISE = ( + "class ZzBoom(Exception):\n" + " pass\n" + "def boom(*args, **kwargs):\n" + " raise ZzBoom('SECRET_MESSAGE')\n" + "{target} = boom\n" +) +UNEXPECTED_PREFIX = "想定外の例外(" +NUL_REASON = "NUL 文字" +WRAPPER_COMMAND = [BASH, ".claude/hooks/run_python.sh", "--fail-closed", ".claude/hooks/restrict_repo_access.py"] + + +class HookIOMixin(RestrictSandboxMixin): + """main に標準入力でバイト列を渡し,拒否の JSON・終了コード・stderr を確かめる.""" + + def hook_env(self, project_dir: bool = True, **extra) -> dict: + env = dict(os.environ) + env.pop("CLAUDE_PROJECT_DIR", None) + if project_dir: + env["CLAUDE_PROJECT_DIR"] = self.repo + env.update(extra) + return env + + @staticmethod + def raw(data) -> bytes: + """Claude Code と同じ,ASCII エスケープしない生の UTF-8 の JSON.""" + return json.dumps(data, ensure_ascii=False).encode("utf-8") + + def feed(self, payload: bytes, env: dict | None = None, stdout=subprocess.PIPE, stderr=subprocess.PIPE): + return subprocess.run([sys.executable, "-B", RESTRICT], input=payload, stdout=stdout, stderr=stderr, + env=self.hook_env() if env is None else env, cwd=self.repo, timeout=TIMEOUT) + + def feed_tool(self, tool_name, tool_input, env: dict | None = None, **extra): + data = dict({"tool_name": tool_name, "tool_input": tool_input, "cwd": self.repo}, **extra) + return self.feed(self.raw(data), env) + + def feed_driver(self, setup: str, payload: bytes, stdout=subprocess.PIPE, stderr=subprocess.PIPE): + """フックの一部を差し替えてから main を実行する(setup は rra を名前で参照できる).""" + return subprocess.run([sys.executable, "-B", "-c", HOOK_DRIVER, HOOKS_DIR, setup], input=payload, + stdout=stdout, stderr=stderr, env=self.hook_env(), cwd=self.repo, timeout=TIMEOUT) + + def feed_wrapper(self, payload: bytes, stdout=subprocess.PIPE): + """settings.json と同じコマンド(run_python.sh --fail-closed 経由)で起動する.""" + return subprocess.run(WRAPPER_COMMAND, input=payload, stdout=stdout, stderr=subprocess.PIPE, + env=self.hook_env(), cwd=REPO_ROOT, timeout=TIMEOUT) + + def assertHookDenies(self, result, label="") -> str: + """通常の拒否と同じ形の JSON(1 個だけ)と終了コード 0 を確かめ,理由を返す.""" + self.assertEqual(result.returncode, 0, (label, result.stdout, result.stderr)) + self.assertTrue(result.stdout.strip(), ("拒否の JSON が出力されていない(許可された)", label)) + output = json.loads(result.stdout.decode("utf-8"))["hookSpecificOutput"] + self.assertEqual(output["hookEventName"], "PreToolUse", label) + self.assertEqual(output["permissionDecision"], "deny", label) + self.assertTrue(output["permissionDecisionReason"], label) + return output["permissionDecisionReason"] + + def assertHookDeniesUnexpected(self, result, label="") -> str: + reason = self.assertHookDenies(result, label) + self.assertIn(UNEXPECTED_PREFIX, reason, label) + return reason + + def assertHookAllows(self, result, label="") -> None: + self.assertEqual(result.returncode, 0, (label, result.stdout, result.stderr)) + self.assertEqual(result.stdout.strip(), b"", label) + self.assertEqual(result.stderr.strip(), b"", label) + + @contextlib.contextmanager + def unwritable(self, kind: str): + """書き込みに失敗する標準出力・標準エラー用のファイル記述子を用意する.""" + if kind == "read-only file": + path = os.path.join(self.base, "readonly.txt") + with open(path, "wb"): + pass + with open(path, "rb") as f: + yield f + else: # 読み手のいないパイプ + read_end, write_end = os.pipe() + os.close(read_end) + try: + yield write_end + finally: + os.close(write_end) + + UNWRITABLE_KINDS = ("read-only file", "closed pipe") + + +class TestHookUnexpectedException(HookIOMixin, unittest.TestCase): + """判定中の想定外の例外は拒否になる(理由は型名だけで,コマンドや例外メッセージを含まない).""" + + def payload(self, tool_name="Bash", tool_input=None): + if tool_input is None: + tool_input = {"command": "echo SECRET_COMMAND"} + return self.raw({"tool_name": tool_name, "tool_input": tool_input, "cwd": self.repo}) + + def test_exception_is_denied_with_type_name(self): + cases = { + "shell check": ("rra.check_shell_command", "Bash", None), + "powershell check": ("rra.check_shell_command", "PowerShell", None), + "file check": ("rra.check_file_tool", "Read", {"file_path": "SECRET_COMMAND"}), + "config": ("rra.load_deny_read", "Bash", None), + "repo root": ("rra.get_repo_root", "Read", {"file_path": "SECRET_COMMAND"}), + "realpath": ("os.path.realpath", "Bash", {"command": "rm ./SECRET_COMMAND"}), + } + for label, (target, tool_name, tool_input) in cases.items(): + with self.subTest(label): + result = self.feed_driver(HOOK_RAISE.format(target=target), self.payload(tool_name, tool_input)) + reason = self.assertHookDenies(result, label) + self.assertIn("想定外の例外(ZzBoom)", reason) + self.assertNotIn("SECRET_COMMAND", reason) + self.assertNotIn("SECRET_MESSAGE", reason) + + def test_traceback_goes_to_stderr(self): + result = self.feed_driver(HOOK_RAISE.format(target="rra.check_shell_command"), self.payload()) + stderr = result.stderr.decode("utf-8", "replace") + self.assertIn("Traceback", stderr) + self.assertIn("ZzBoom", stderr) + self.assertIn("SECRET_MESSAGE", stderr) + + def test_reason_points_to_the_hook(self): + """全操作が止まる不具合のときに対処できるよう,理由にフックの場所が書かれている.""" + result = self.feed_driver(HOOK_RAISE.format(target="rra.check_shell_command"), self.payload()) + self.assertIn("restrict_repo_access.py", self.assertHookDenies(result)) + + def test_exception_with_broken_str_is_denied(self): + setup = ("class ZzBoom(Exception):\n" + " def __str__(self):\n" + " raise RuntimeError('broken')\n" + "def boom(*args, **kwargs):\n" + " raise ZzBoom()\n" + "rra.check_shell_command = boom\n") + self.assertIn("想定外の例外(ZzBoom)", self.assertHookDenies(self.feed_driver(setup, self.payload()))) + + def test_via_wrapper(self): + """settings.json と同じ起動方法でも拒否の JSON が届く.""" + reason = self.assertHookDeniesUnexpected(self.feed_wrapper(b"{")) + self.assertIn("JSONDecodeError", reason) + + +class TestHookBrokenInput(HookIOMixin, unittest.TestCase): + """壊れた入力は拒否になる.""" + + def test_broken_json(self): + cases = (b"{", b"}", b"not json", b'{"tool_name": "Bash"', b"{'tool_name': 'Bash'}", + b'{"tool_name": "Bash", "tool_input": {"command": "SECRET_COMMAND') + for payload in cases: + with self.subTest(payload): + reason = self.assertHookDeniesUnexpected(self.feed(payload)) + self.assertIn("JSONDecodeError", reason) + self.assertNotIn("SECRET_COMMAND", reason) + + def test_empty_input(self): + for payload in (b"", b" ", b"\n", b"\r\n"): + with self.subTest(payload): + self.assertHookDeniesUnexpected(self.feed(payload)) + + def test_json_that_is_not_an_object(self): + for payload in (b"[]", b"[1]", b'[{"tool_name": "Bash"}]', b"123", b"1.5", b'"text"', b"null", b"true", b"false"): + with self.subTest(payload): + self.assertHookDeniesUnexpected(self.feed(payload)) + + def test_undecodable_bytes(self): + cases = (b"\xff", b"\x80abc", b"\xff\xfe\x00", b"\xc3", + b'{"tool_name": "Bash", "tool_input": {"command": "echo \xff"}}', + b'{"tool_name": "Bash", "tool_input": {"command": "echo \x82\xa0"}}') # cp932 の「あ」 + for payload in cases: + with self.subTest(payload): + self.assertHookDeniesUnexpected(self.feed(payload)) + + def test_too_deeply_nested_json(self): + """RecursionError も Exception なので拒否になる.""" + self.assertHookDeniesUnexpected(self.feed(b"[" * 200000)) + + def test_stdin_without_binary_buffer(self): + for label, setup in (("StringIO", "sys.stdin = io.StringIO('{}')\n"), ("None", "sys.stdin = None\n")): + with self.subTest(label): + self.assertHookDeniesUnexpected(self.feed_driver(setup, b"{}"), label) + + def test_invalid_tool_input_type(self): + for tool_name in ("Bash", "PowerShell", "Read", "Edit", "Write"): + for tool_input in ("rm x", ["rm x"], [{"command": "rm x"}], 123, 1.5, True): + with self.subTest(tool=tool_name, tool_input=tool_input): + self.assertHookDeniesUnexpected(self.feed_tool(tool_name, tool_input)) + + def test_invalid_tool_input_type_holding_the_key_name(self): + """文字列やリストの tool_input に項目名と同じ値があっても,tool_input の型不正として拒否する.""" + cases = (("Bash", "command"), ("Bash", ["command"]), ("PowerShell", "command"), ("Write", "file_path"), + ("Edit", ["file_path"]), ("NotebookEdit", "notebook_path"), ("NotebookEdit", ["notebook_path"])) + for tool_name, tool_input in cases: + with self.subTest(tool=tool_name, tool_input=tool_input): + self.assertHookDeniesUnexpected(self.feed_tool(tool_name, tool_input)) + + def test_invalid_tool_input_reason_has_no_command(self): + reason = self.assertHookDeniesUnexpected(self.feed_tool("Bash", "rm SECRET_COMMAND")) + self.assertNotIn("SECRET_COMMAND", reason) + + def bad_cwd_inputs(self): + return { + "Bash echo": ("Bash", {"command": "echo hi"}), + "Bash rm": ("Bash", {"command": "rm ./a"}), + "Read relative": ("Read", {"file_path": "file.txt"}), + "Edit relative": ("Edit", {"file_path": "file.txt", "old_string": "x", "new_string": "y"}), + } + + def bad_cwd_absolute_inputs(self): + target = os.path.join(self.repo, "file.txt") + return { + "Read absolute": ("Read", {"file_path": target}), + "Edit absolute": ("Edit", {"file_path": target, "old_string": "x", "new_string": "y"}), + } + + def test_invalid_cwd_type_with_absolute_path(self): + """不正な型の cwd を拒否するのは cwd を使う判定だけ.CLAUDE_PROJECT_DIR と絶対パスで判定できれば影響しない.""" + for label, (tool_name, tool_input) in self.bad_cwd_absolute_inputs().items(): + for cwd in (123, 1.5, True, ["x"], {"a": 1}): + with self.subTest(label, cwd=cwd): + data = {"tool_name": tool_name, "tool_input": tool_input, "cwd": cwd} + self.assertHookAllows(self.feed(self.raw(data)), label) + + def test_invalid_cwd_type_keeps_decision_for_outside_absolute_path(self): + """cwd を使わない判定なので,リポジトリ外の判定も cwd の型によらず変わらない.""" + edit = {"file_path": self.existing, "old_string": "x", "new_string": "y"} + for cwd in (123, ["x"]): + with self.subTest(cwd=cwd): + reason = self.assertHookDenies(self.feed(self.raw({"tool_name": "Edit", "tool_input": edit, "cwd": cwd}))) + self.assertNotIn(UNEXPECTED_PREFIX, reason) + read = {"tool_name": "Read", "tool_input": {"file_path": self.existing}, "cwd": cwd} + self.assertHookAllows(self.feed(self.raw(read))) + + def test_invalid_cwd_type(self): + for label, (tool_name, tool_input) in self.bad_cwd_inputs().items(): + for cwd in (123, 1.5, True, ["x"], {"a": 1}): + with self.subTest(label, cwd=cwd): + data = {"tool_name": tool_name, "tool_input": tool_input, "cwd": cwd} + self.assertHookDeniesUnexpected(self.feed(self.raw(data)), label) + + def test_invalid_cwd_type_without_project_dir(self): + inputs = dict(self.bad_cwd_inputs(), **self.bad_cwd_absolute_inputs()) + for label, (tool_name, tool_input) in inputs.items(): + for cwd in (123, ["x"]): + with self.subTest(label, cwd=cwd): + data = {"tool_name": tool_name, "tool_input": tool_input, "cwd": cwd} + self.assertHookDeniesUnexpected(self.feed(self.raw(data), self.hook_env(project_dir=False)), label) + + +class TestHookInvalidValueType(HookIOMixin, unittest.TestCase): + """判定の対象の値(コマンド・書き込み先のパス)が文字列でなければ拒否する.""" + + INVALID_REASON = "型が不正" + TARGETS = (("Bash", "command"), ("PowerShell", "command"), ("Write", "file_path"), ("Edit", "file_path"), + ("MultiEdit", "file_path"), ("NotebookEdit", "notebook_path")) + + def outside_marker(self) -> str: + return os.path.join(self.out, "zz_marker_in_list") + + def invalid_values(self): + marker = self.outside_marker() + return ([marker], ["rm", marker], ["rm -rf " + _fwd(marker)], [], 0, False, {}, None, 123, True) + + def test_invalid_type_is_denied(self): + for tool_name, key in self.TARGETS: + for value in self.invalid_values(): + with self.subTest(tool=tool_name, value=value): + result = self.feed_tool(tool_name, {key: value}) + reason = self.assertHookDenies(result) + self.assertIn(self.INVALID_REASON, reason) + self.assertNotIn(UNEXPECTED_PREFIX, reason) + self.assertNotIn("zz_marker_in_list", reason) + self.assertEqual(result.stderr, b"") + + def test_invalid_type_is_denied_with_extra_fields(self): + """他の項目が正常でも結果は同じ(Edit の old_string 等).""" + edit = {"file_path": [self.outside_marker()], "old_string": "x", "new_string": "y"} + self.assertIn(self.INVALID_REASON, self.assertHookDenies(self.feed_tool("Edit", edit))) + write = {"file_path": 0, "content": "x"} + self.assertIn(self.INVALID_REASON, self.assertHookDenies(self.feed_tool("Write", write))) + + def test_invalid_type_is_denied_without_project_dir(self): + for tool_name, key in self.TARGETS: + with self.subTest(tool_name): + reason = self.assertHookDenies(self.feed_tool(tool_name, {key: []}, self.hook_env(project_dir=False))) + self.assertIn(self.INVALID_REASON, reason) + + def test_invalid_type_is_denied_via_wrapper(self): + payload = self.raw({"tool_name": "Bash", "tool_input": {"command": ["rm", self.outside_marker()]}, + "cwd": self.repo}) + self.assertIn(self.INVALID_REASON, self.assertHookDenies(self.feed_wrapper(payload))) + + def test_invalid_type_with_unwritable_stdout_exits_2(self): + for kind in self.UNWRITABLE_KINDS: + with self.subTest(kind), self.unwritable(kind) as stdout: + payload = self.raw({"tool_name": "Bash", "tool_input": {"command": []}, "cwd": self.repo}) + self.assertEqual(self.feed(payload, stdout=stdout).returncode, 2) + + def test_missing_key_or_empty_string_is_allowed(self): + for tool_name, key in self.TARGETS: + with self.subTest(tool=tool_name, value="missing"): + self.assertHookAllows(self.feed_tool(tool_name, {"other": "x"})) + with self.subTest(tool=tool_name, value="empty"): + self.assertHookAllows(self.feed_tool(tool_name, {key: ""})) + + def test_read_side_paths_are_not_judged_by_type(self): + cases = (("Read", "file_path", {}), ("Grep", "path", {"pattern": "x"}), ("Glob", "path", {"pattern": "*.py"})) + for tool_name, key, others in cases: + for value in self.invalid_values(): + with self.subTest(tool=tool_name, value=value): + self.assertHookAllows(self.feed_tool(tool_name, dict(others, **{key: value}))) + + def test_other_tools_are_not_judged_by_type(self): + marker = self.outside_marker() + for tool_input in ({"command": ["rm", marker]}, {"file_path": [marker]}, {"notebook_path": [marker]}): + with self.subTest(tool_input=tool_input): + self.assertHookAllows(self.feed_tool("TodoWrite", tool_input)) + + def test_keys_of_other_tools_are_not_judged(self): + """見るのはそのツールの項目だけ(Bash の file_path や Write の command は判定の対象でない).""" + self.assertHookAllows(self.feed_tool("Bash", {"command": "echo hi", "file_path": ["x"]})) + self.assertHookAllows(self.feed_tool("Write", {"file_path": os.path.join(self.repo, "n.txt"), "command": ["x"]})) + + +class TestHookBrokenConfig(HookIOMixin, unittest.TestCase): + """repo-access.json が壊れていて警告を出せないときの動作.""" + + BROKEN_CONFIGS = ("{broken", json.dumps({"deny_read": [1, 2]})) + + def write_config(self, text: str) -> None: + with open(os.path.join(self.repo, ".claude", "repo-access.json"), "w", encoding="utf-8") as fh: + fh.write(text) + + def rm_payload(self, target: str) -> bytes: + return self.raw({"tool_name": "Bash", "tool_input": {"command": f'rm "{target}"'}, "cwd": self.repo}) + + def test_rm_in_repo_is_denied_when_warning_cannot_be_written(self): + """禁止リストを読めず警告も出せないので,判定できないものとして想定外の例外で拒否する.""" + for text in self.BROKEN_CONFIGS: + self.write_config(text) + for kind in self.UNWRITABLE_KINDS: + with self.subTest(config=text, kind=kind), self.unwritable(kind) as stderr: + self.assertHookDeniesUnexpected(self.feed(self.rm_payload("file.txt"), stderr=stderr), kind) + + def test_rm_outside_is_denied_when_warning_cannot_be_written(self): + target = _fwd(self.existing) + for kind in self.UNWRITABLE_KINDS: + self.write_config("{broken") + with self.subTest(kind), self.unwritable(kind) as stderr: + self.assertHookDenies(self.feed(self.rm_payload(target), stderr=stderr), kind) + + def test_rm_outside_with_stderr_none_outputs_only_deny_json(self): + """sys.stderr が None のとき警告が stdout に混ざると,拒否の JSON が壊れて素通りする.""" + self.write_config("{broken") + self.assertHookDenies(self.feed_driver("sys.stderr = None\n", self.rm_payload(_fwd(self.existing)))) + + def test_rm_in_repo_with_stderr_none_keeps_stdout_clean(self): + """許可のときも stdout に判定以外のものを出さない.""" + self.write_config("{broken") + result = self.feed_driver("sys.stderr = None\n", self.rm_payload("file.txt")) + if result.stdout.strip(): + self.assertHookDeniesUnexpected(result) + else: + self.assertEqual(result.returncode, 0) + + def test_rm_in_repo_is_allowed_when_warning_can_be_written(self): + """stderr に書ければ従来どおり,禁止リストを空として扱って判定を続ける.""" + for text in self.BROKEN_CONFIGS: + self.write_config(text) + with self.subTest(config=text): + result = self.feed(self.rm_payload("file.txt")) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(result.stdout.strip(), b"") + self.assertTrue(result.stderr.strip(), "stderr に警告が出ること") + + +@unittest.skipUnless(os.path.exists("/dev/full"), "/dev/full は Linux 固有のデバイス(書き込みが必ず ENOSPC になる)のため." + "他の OS でも書き込みの失敗は TestHookOutputFailure の閉じたパイプ等で確認している") +class TestHookDevFull(HookIOMixin, unittest.TestCase): + """本物の書き込み失敗(ディスクフル相当)でも終了コードが 120 にならない.""" + + def test_stdout_full_exits_2(self): + with open("/dev/full", "wb") as stdout: + self.assertEqual(self.feed(b"{", stdout=stdout).returncode, 2) + payload = self.raw({"tool_name": "Bash", "tool_input": {"command": f'rm "{_fwd(self.existing)}"'}, + "cwd": self.repo}) + self.assertEqual(self.feed(payload, stdout=stdout).returncode, 2) + + def test_stderr_full_still_denies(self): + with open("/dev/full", "wb") as stderr: + self.assertHookDeniesUnexpected(self.feed(b"{", stderr=stderr)) + + +class TestHookToolInputNotJudged(HookIOMixin, unittest.TestCase): + """判定しないツールの tool_input の型は問わず,空の tool_input は入力なしとして扱う.""" + + def test_string_tool_input_of_other_tools(self): + for tool_name in ("TodoWrite", "WebSearch"): + with self.subTest(tool_name): + self.assertHookAllows(self.feed_tool(tool_name, "text")) + + def test_empty_list_tool_input(self): + for tool_name in ("Bash", "PowerShell", "Read", "Edit", "Write", "TodoWrite"): + with self.subTest(tool_name): + self.assertHookAllows(self.feed_tool(tool_name, [])) + + +class TestHookOutputFailure(HookIOMixin, unittest.TestCase): + """stdout に書けなければ終了コード 2 でブロックし,stderr に書けなくても拒否は続く.""" + + BROKEN_WRITE = ("class Broken(io.StringIO):\n" + " def write(self, text):\n" + " raise OSError('broken')\n" + "{stream} = Broken()\n") + BROKEN_FLUSH = ("class Broken(io.StringIO):\n" + " def flush(self):\n" + " raise OSError('broken')\n" + "{stream} = Broken()\n") + + def deny_payloads(self): + rm_outside = {"tool_name": "Bash", "tool_input": {"command": f'rm "{_fwd(self.existing)}"'}, "cwd": self.repo} + nul = {"tool_name": "Bash", "tool_input": {"command": "echo a\0b"}, "cwd": self.repo} + return {"normal deny": self.raw(rm_outside), "NUL deny": self.raw(nul), "broken json": b"{", "empty": b""} + + def test_stdout_unwritable_exits_2(self): + for kind in self.UNWRITABLE_KINDS: + for label, payload in self.deny_payloads().items(): + with self.subTest(kind=kind, payload=label), self.unwritable(kind) as stdout: + self.assertEqual(self.feed(payload, stdout=stdout).returncode, 2) + + def test_stdout_replaced_with_broken_stream_exits_2(self): + setups = {"None": "sys.stdout = None\n", "write": self.BROKEN_WRITE.format(stream="sys.stdout"), + "flush": self.BROKEN_FLUSH.format(stream="sys.stdout")} + for label, setup in setups.items(): + for name, payload in self.deny_payloads().items(): + with self.subTest(stream=label, payload=name): + self.assertEqual(self.feed_driver(setup, payload).returncode, 2) + + def test_stdout_unwritable_via_wrapper_exits_2(self): + for kind in self.UNWRITABLE_KINDS: + with self.subTest(kind), self.unwritable(kind) as stdout: + self.assertEqual(self.feed_wrapper(b"{", stdout=stdout).returncode, 2) + + def test_allowed_input_does_not_need_stdout(self): + data = {"tool_name": "Read", "tool_input": {"file_path": "file.txt"}, "cwd": self.repo} + for kind in self.UNWRITABLE_KINDS: + with self.subTest(kind), self.unwritable(kind) as stdout: + self.assertEqual(self.feed(self.raw(data), stdout=stdout).returncode, 0) + + def test_stderr_unwritable_still_denies(self): + for kind in self.UNWRITABLE_KINDS: + with self.subTest(kind), self.unwritable(kind) as stderr: + self.assertHookDeniesUnexpected(self.feed(b"{", stderr=stderr), kind) + + def test_stderr_unwritable_keeps_normal_deny(self): + """stderr に何も書かない通常の拒否も,stderr の状態に影響されない.""" + data = {"tool_name": "Bash", "tool_input": {"command": f'rm "{_fwd(self.existing)}"'}, "cwd": self.repo} + for kind in self.UNWRITABLE_KINDS: + with self.subTest(kind), self.unwritable(kind) as stderr: + self.assertHookDenies(self.feed(self.raw(data), stderr=stderr), kind) + + def test_stderr_unwritable_with_injected_exception_still_denies(self): + setup = HOOK_RAISE.format(target="rra.check_shell_command") + payload = self.raw({"tool_name": "Bash", "tool_input": {"command": "echo hi"}, "cwd": self.repo}) + for kind in self.UNWRITABLE_KINDS: + with self.subTest(kind), self.unwritable(kind) as stderr: + self.assertHookDeniesUnexpected(self.feed_driver(setup, payload, stderr=stderr), kind) + + def test_stderr_replaced_with_broken_stream_still_denies(self): + setups = {"None": "sys.stderr = None\n", "write": self.BROKEN_WRITE.format(stream="sys.stderr")} + for label, setup in setups.items(): + with self.subTest(label): + self.assertHookDeniesUnexpected(self.feed_driver(setup, b"{"), label) + + def test_both_unwritable_exits_2(self): + for kind in self.UNWRITABLE_KINDS: + with self.subTest(kind), self.unwritable(kind) as stream: + self.assertEqual(self.feed(b"{", stdout=stream, stderr=stream).returncode, 2) + + +class TestHookDoesNotCatchExit(HookIOMixin, unittest.TestCase): + """SystemExit・KeyboardInterrupt は捕捉しない(拒否に変えない).""" + + def run_main_with(self, target: str, tool_name: str, tool_input: dict, error: BaseException): + payload = self.raw({"tool_name": tool_name, "tool_input": tool_input, "cwd": self.repo}) + stdout = io.StringIO() + with mock.patch.dict(os.environ, {"CLAUDE_PROJECT_DIR": self.repo}), \ + mock.patch.object(self.rra, target, side_effect=error), \ + mock.patch.object(sys, "stdin", io.TextIOWrapper(io.BytesIO(payload))), \ + mock.patch.object(sys, "stdout", stdout): + try: + self.rra.main() + finally: + self.captured_stdout = stdout.getvalue() + + def cases(self): + return (("check_shell_command", "Bash", {"command": "echo hi"}), + ("check_file_tool", "Read", {"file_path": "file.txt"})) + + def test_keyboard_interrupt_propagates(self): + for target, tool_name, tool_input in self.cases(): + with self.subTest(target): + with self.assertRaises(KeyboardInterrupt): + self.run_main_with(target, tool_name, tool_input, KeyboardInterrupt()) + self.assertEqual(self.captured_stdout, "") + + def test_system_exit_keeps_its_code(self): + for target, tool_name, tool_input in self.cases(): + with self.subTest(target): + with self.assertRaises(SystemExit) as caught: + self.run_main_with(target, tool_name, tool_input, SystemExit(7)) + self.assertEqual(caught.exception.code, 7) + self.assertEqual(self.captured_stdout, "") + + def test_exit_code_of_real_process(self): + setup = ("def leave(*args, **kwargs):\n" + " raise SystemExit(7)\n" + "rra.check_shell_command = leave\n") + payload = self.raw({"tool_name": "Bash", "tool_input": {"command": "echo hi"}, "cwd": self.repo}) + result = self.feed_driver(setup, payload) + self.assertEqual(result.returncode, 7, result.stderr) + self.assertEqual(result.stdout, b"") + + +class TestHookNulCommand(HookIOMixin, unittest.TestCase): + """Bash / PowerShell のコマンドの NUL は OS・対象によらず拒否する(main を通す).""" + + def assertNulDenied(self, result, label=""): + reason = self.assertHookDenies(result, label) + self.assertIn(NUL_REASON, reason, label) + self.assertNotIn(UNEXPECTED_PREFIX, reason, label) + self.assertEqual(result.stderr, b"", label) + + def commands(self): + outside = _fwd(self.out) + return (("Bash", "rm /tmp/a\0b"), ("Bash", "rm ./a\0b"), ("Bash", f"rm {outside}/zz/a\0b"), + ("Bash", "echo a\0b"), ("PowerShell", "Remove-Item ./a\0b"), ("PowerShell", "Write-Output a\0b"), + ("Bash", "\0"), ("Bash", "\0echo a"), ("Bash", "echo a\0"), ("Bash", "rm ./a\0"), + ("Bash", "echo 日本語\0"), ("PowerShell", f'Remove-Item "{self.existing}\0"')) + + def test_denied_with_escaped_json(self): + for tool_name, command in self.commands(): + with self.subTest(tool=tool_name, command=command): + self.assertNulDenied(self.run_main({"tool_name": tool_name, "tool_input": {"command": command}, + "cwd": self.repo}, self.hook_env())) + + def test_denied_with_raw_utf8_json(self): + for tool_name, command in self.commands(): + with self.subTest(tool=tool_name, command=command): + self.assertNulDenied(self.feed_tool(tool_name, {"command": command})) + + def test_denied_without_project_dir(self): + for tool_name, command in self.commands(): + with self.subTest(tool=tool_name, command=command): + self.assertNulDenied(self.feed_tool(tool_name, {"command": command}, self.hook_env(project_dir=False))) + + def test_denied_via_wrapper(self): + payload = self.raw({"tool_name": "Bash", "tool_input": {"command": "rm ./a\0b"}, "cwd": self.repo}) + self.assertNulDenied(self.feed_wrapper(payload)) + + def test_raw_nul_byte_in_json_text_is_denied(self): + """JSON の文字列に生の NUL は書けない(壊れた JSON).どちらの理由でも拒否される.""" + self.assertHookDenies(self.feed(b'{"tool_name": "Bash", "tool_input": {"command": "echo a\x00b"}}')) + + def test_nul_outside_command_is_not_judged(self): + """NUL の拒否の対象はコマンド文字列だけ(Write の内容や説明文は判定しない).""" + self.assertHookAllows(self.feed_tool("Bash", {"command": "echo hi", "description": "a\0b"})) + self.assertHookAllows(self.feed_tool("Write", {"file_path": os.path.join(self.repo, "n.txt"), "content": "a\0b"})) + + +class TestHookReadsUtf8Bytes(HookIOMixin, unittest.TestCase): + """入力はロケールの文字コードによらず UTF-8 の JSON として読む.""" + + # None はロケールの既定(日本語の Windows なら cp932)のまま起動する + ENCODINGS = ("cp932", "utf-8", "ascii", "latin-1", None) + + def setUp(self) -> None: + super().setUp() + self.named_existing = os.path.join(self.out, "既存語.txt") + with open(self.named_existing, "w", encoding="utf-8") as fh: + fh.write("x") + with open(os.path.join(self.repo, "日本語.txt"), "w", encoding="utf-8") as fh: + fh.write("x") + + def encoding_env(self, encoding) -> dict: + env = self.hook_env() + for key in ("PYTHONIOENCODING", "PYTHONUTF8"): + env.pop(key, None) + if encoding is not None: + env["PYTHONIOENCODING"] = encoding + return env + + def each_encoding(self): + for encoding in self.ENCODINGS: + yield encoding, self.encoding_env(encoding) + + def test_premise_cp932_text_mode_breaks_this_input(self): + """再現の前提: `語` の直後の `\\"` は,cp932 のテキストモードで読むと JSON として壊れる.""" + payload = self.raw({"tool_name": "Bash", "tool_input": {"command": 'echo "日本語"'}, "cwd": self.repo}) + self.assertIn(b'\xe8\xaa\x9e\\"', payload) + result = subprocess.run([sys.executable, "-B", "-c", "import json, sys; json.load(sys.stdin)"], input=payload, + capture_output=True, env=self.encoding_env("cp932"), timeout=TIMEOUT) + self.assertNotEqual(result.returncode, 0) + self.assertIn(b"JSONDecodeError", result.stderr) + + def test_quote_right_after_japanese_is_allowed(self): + repo_file = os.path.join(self.repo, "日本語.txt") + cases = { + "echo": ("Bash", {"command": 'echo "日本語"'}), + "escaped quote": ("Bash", {"command": 'echo "語\\"語"'}), + "commit": ("Bash", {"command": 'git commit -m "[fix] 日本語"'}), + "rm in repo": ("Bash", {"command": 'rm "./語"'}), + "PowerShell": ("PowerShell", {"command": 'Write-Output "日本語"'}), + "Write in repo": ("Write", {"file_path": repo_file, "content": '"日本語"'}), + "Write new outside": ("Write", {"file_path": os.path.join(self.out, "新規語.txt"), "content": '"語"'}), + "Edit in repo": ("Edit", {"file_path": repo_file, "old_string": '"語"', "new_string": '"日本語"'}), + } + for label, (tool_name, tool_input) in cases.items(): + for encoding, env in self.each_encoding(): + with self.subTest(label, encoding=encoding): + payload = self.raw({"tool_name": tool_name, "tool_input": tool_input, "cwd": self.repo}) + self.assertIn(b"\xe8\xaa\x9e", payload) + self.assertHookAllows(self.feed(payload, env), label) + + def test_japanese_without_quote_is_allowed(self): + for encoding, env in self.each_encoding(): + with self.subTest(encoding=encoding): + self.assertHookAllows(self.feed_tool("Bash", {"command": "echo 日本語"}, env)) + self.assertHookAllows(self.feed_tool("Read", {"file_path": self.named_existing}, env)) + + def test_japanese_outside_is_denied(self): + outside = _fwd(self.out) + named = _fwd(self.named_existing) + cases = { + "rm": ("Bash", {"command": f'rm "{outside}/日本語"'}, "日本語"), + "rm -rf": ("Bash", {"command": f'rm -rf "{outside}/語"'}, "語"), + "rm unquoted": ("Bash", {"command": f"rm {outside}/日本語"}, "日本語"), + "redirect": ("Bash", {"command": f'echo 語 > "{named}"'}, "既存語"), + "Remove-Item": ("PowerShell", {"command": f'Remove-Item "{outside}/日本語"'}, "日本語"), + "Edit": ("Edit", {"file_path": self.named_existing, "old_string": "語", "new_string": "語"}, "既存語"), + } + for label, (tool_name, tool_input, shown) in cases.items(): + for encoding, env in self.each_encoding(): + with self.subTest(label, encoding=encoding): + reason = self.assertHookDenies(self.feed_tool(tool_name, tool_input, env), label) + self.assertNotIn(UNEXPECTED_PREFIX, reason, label) + self.assertIn(shown, reason, "文字化けせずに読めている") + + def test_write_over_existing_japanese_file_is_denied(self): + """既存ファイルかどうかの判定は,名前を正しく読めていないと許可に倒れる.""" + for encoding, env in self.each_encoding(): + with self.subTest(encoding=encoding): + tool_input = {"file_path": self.named_existing, "content": "語"} + reason = self.assertHookDenies(self.feed_tool("Write", tool_input, env)) + self.assertNotIn(UNEXPECTED_PREFIX, reason) + + def test_via_wrapper(self): + allow = self.raw({"tool_name": "Bash", "tool_input": {"command": 'echo "日本語"'}, "cwd": self.repo}) + self.assertHookAllows(self.feed_wrapper(allow)) + target = _fwd(os.path.join(self.out, "日本語")) + denied = self.raw({"tool_name": "Bash", "tool_input": {"command": f'rm "{target}"'}, "cwd": self.repo}) + self.assertNotIn(UNEXPECTED_PREFIX, self.assertHookDenies(self.feed_wrapper(denied))) + + def test_reason_is_ascii_safe_under_any_output_encoding(self): + """拒否の JSON は stdout の文字コードによらず UTF-8 として読める(assertHookDenies が読む).""" + for encoding, env in self.each_encoding(): + with self.subTest(encoding=encoding): + self.assertIn("JSONDecodeError", self.assertHookDeniesUnexpected(self.feed(b"{", env))) + + +class TestHookNormalDecisionsViaMain(HookIOMixin, unittest.TestCase): + """例外の捕捉で,正常な入力の判定は変わらない.""" + + def test_read(self): + self.assertHookAllows(self.feed_tool("Read", {"file_path": os.path.join(self.repo, "file.txt")})) + self.assertHookAllows(self.feed_tool("Read", {"file_path": self.existing})) + + def test_edit(self): + edit = {"old_string": "x", "new_string": "y"} + self.assertHookAllows(self.feed_tool("Edit", dict(edit, file_path=os.path.join(self.repo, "file.txt")))) + reason = self.assertHookDenies(self.feed_tool("Edit", dict(edit, file_path=self.existing))) + self.assertNotIn(UNEXPECTED_PREFIX, reason) + + def test_bash_rm(self): + self.assertHookAllows(self.feed_tool("Bash", {"command": "rm file.txt"})) + reason = self.assertHookDenies(self.feed_tool("Bash", {"command": f'rm "{_fwd(self.existing)}"'})) + self.assertNotIn(UNEXPECTED_PREFIX, reason) + + def test_powershell_remove_item(self): + reason = self.assertHookDenies(self.feed_tool("PowerShell", {"command": f'Remove-Item "{self.existing}"'})) + self.assertNotIn(UNEXPECTED_PREFIX, reason) + + def test_no_tool_name(self): + self.assertHookAllows(self.feed(b"{}")) + self.assertHookAllows(self.feed(self.raw({"tool_input": {"command": "echo hi"}, "cwd": self.repo}))) + + def test_missing_or_null_tool_input(self): + for tool_name in ("Bash", "Read", "Edit"): + with self.subTest(tool_name): + self.assertHookAllows(self.feed(self.raw({"tool_name": tool_name, "cwd": self.repo}))) + self.assertHookAllows(self.feed_tool(tool_name, None)) + + def test_ascii_escaped_json_is_read_the_same(self): + data = {"tool_name": "Bash", "tool_input": {"command": 'echo "日本語"'}, "cwd": self.repo} + self.assertHookAllows(self.run_main(data, self.hook_env())) + + def test_nul_in_transcript_path_does_not_deny_other_decisions(self): + """使えない transcript_path は無いものとして扱う(どのパスの判定でも拒否にはしない).""" + transcript = {"transcript_path": os.path.join(self.base, "session\0.jsonl")} + self.assertHookAllows(self.feed_tool("Read", {"file_path": "file.txt"}, **transcript)) + self.assertHookAllows(self.feed_tool("Bash", {"command": "rm file.txt"}, **transcript)) + reason = self.assertHookDenies(self.feed_tool("Bash", {"command": f'rm "{_fwd(self.existing)}"'}, **transcript)) + self.assertNotIn(UNEXPECTED_PREFIX, reason) + + +# --------------------------------------------------------------------------- +# restrict_repo_access.py: 書き込み許可ディレクトリ allow_write(Issue #64) +# --------------------------------------------------------------------------- +# サンドボックス(一時ディレクトリの外)に repo と並べて sib/ を置き,repo-access.json の +# allow_write に "../sib" を書いて判定する.設定は load_allow_write(main と同じ読み込み)で読む. +class AllowWriteSandboxMixin(Issue59SandboxMixin): + """sandbox/ + repo/ 仮のリポジトリ + sib/ 書き込み許可ディレクトリ(allow_write: ../sib) + file.txt・sub/deep.txt・secret/key.txt + sib2/file.txt 名前が前方一致する別のディレクトリ(許可しない) + outside/ リポジトリ外(許可しない) + """ + + def setUp(self) -> None: + super().setUp() + self.sib = os.path.join(self.base, "sib") + self.sib_file = self.touch(self.sib, "file.txt") + self.sib_deep = self.touch(self.sib, "sub", "deep.txt") + self.sib_secret = self.touch(self.sib, "secret", "key.txt") + self.sib2_file = self.touch(self.base, "sib2", "file.txt") + self.s = _fwd(self.sib) + self.allow = [] + + def write_config(self, config) -> None: + text = config if isinstance(config, str) else json.dumps(config) + with open(os.path.join(self.repo, ".claude", "repo-access.json"), "w", encoding="utf-8") as fh: + fh.write(text) + + def load(self, config) -> tuple: + """設定を書いて(仮のホームで)load_allow_write・load_deny_read を呼び,結果と stderr を返す.""" + self.write_config(config) + err = io.StringIO() + with self.fake_home(), contextlib.redirect_stderr(err): + allow = self.rra.load_allow_write(self.repo) + deny = self.rra.load_deny_read(self.repo) + return allow, deny, err.getvalue() + + def use(self, config) -> str: + """設定を読み込んで判定に使う(以降の bash・ps・tool に効く).""" + self.allow, self.deny, err = self.load(config) + return err + + def bash(self, command: str, cwd: str | None = None): + return self.rra.check_bash_command(command, cwd or self.repo, repo_root=self.repo, deny_read=self.deny, + transcript_path=self.transcript_path, allow_write=self.allow) + + def ps(self, command: str, cwd: str | None = None): + return self.rra.check_powershell_command(command, cwd or self.repo, repo_root=self.repo, deny_read=self.deny, + transcript_path=self.transcript_path, allow_write=self.allow) + + def tool(self, name: str, tool_input: dict, cwd: str | None = None): + policy = self.rra.Policy(self.repo, self.deny, self.transcript_path, self.allow) + return self.rra.check_file_tool(name, tool_input, cwd or self.repo, policy) + + def assertSame(self, loaded: list, expected: list) -> None: + normed = [os.path.normcase(os.path.realpath(p)) for p in expected] + self.assertEqual([os.path.normcase(p) for p in loaded], normed) + + +class TestAllowWriteLoad(AllowWriteSandboxMixin, unittest.TestCase): + """設定の書き方(deny_read と同じ)と,危険・無効な指定の無視と警告.""" + + def test_relative_sibling_entry(self): + allow, _, err = self.load({"allow_write": ["../sib"]}) + self.assertSame(allow, [self.sib]) + self.assertEqual(err, "") + + def test_absolute_entries(self): + for entry in (self.sib, _fwd(self.sib), _fwd(self.sib) + "/"): + with self.subTest(entry): + allow, _, err = self.load({"allow_write": [entry]}) + self.assertSame(allow, [self.sib]) + self.assertEqual(err, "") + + def test_home_entry(self): + work = os.path.join(self.home, "work") + os.makedirs(work) + allow, _, err = self.load({"allow_write": ["~/work"]}) + self.assertSame(allow, [work]) + self.assertEqual(err, "") + + def test_repo_root_relative_entry(self): + """リポジトリルート相対で解決する.""" + allow, _, _ = self.load({"allow_write": ["../outside/dir"]}) + self.assertSame(allow, [os.path.join(self.out, "dir")]) + + @unittest.skipUnless(os.name == "nt", "Git Bash 形式のパス(/c/...)は Windows 固有のため") + def test_gitbash_form_entry(self): + allow, _, _ = self.load({"allow_write": [_gitbash(self.sib)]}) + self.assertSame(allow, [self.sib]) + + def test_missing_config_or_key_is_empty_without_warning(self): + err = io.StringIO() + with contextlib.redirect_stderr(err): + self.assertEqual(self.rra.load_allow_write(self.repo), []) + self.assertEqual(err.getvalue(), "") + allow, _, err = self.load({"deny_read": ["~/.ssh"]}) + self.assertEqual(allow, []) + self.assertEqual(err, "") + + def test_broken_config_is_empty_with_warning(self): + """壊れた設定は空扱い(許可側に倒れない).deny_read が不正なときも allow_write を空にする.""" + configs = ["{broken", json.dumps(["../sib"]), json.dumps("../sib"), + json.dumps({"deny_read": "~/.ssh", "allow_write": ["../sib"]}), + json.dumps({"deny_read": [1], "allow_write": ["../sib"]}), + json.dumps({"deny_read": None, "allow_write": ["../sib"]})] + for text in configs: + with self.subTest(text): + allow, _, err = self.load(text) + self.assertEqual(allow, []) + self.assertTrue(err.strip(), "stderr に警告が出ること") + + def test_non_list_allow_write_is_ignored_with_warning(self): + for value in ("../sib", {"a": "../sib"}, 1, True, None): + with self.subTest(repr(value)): + allow, _, err = self.load({"allow_write": value}) + self.assertEqual(allow, []) + self.assertTrue(err.strip(), "stderr に警告が出ること") + + def test_non_string_element_is_ignored_but_others_kept(self): + allow, _, err = self.load({"allow_write": [1, None, ["../sib"], "../sib"]}) + self.assertSame(allow, [self.sib]) + self.assertTrue(err.strip(), "stderr に警告が出ること") + + def assertIgnored(self, entries) -> None: + """危険な指定は無視して警告し,同時に書いた正しい指定(../sib)は効くこと.""" + for entry in entries: + with self.subTest(entry=entry): + allow, _, err = self.load({"allow_write": [entry, "../sib"]}) + self.assertSame(allow, [self.sib]) + self.assertTrue(err.strip(), f"stderr に警告が出ること: {entry}") + + def test_filesystem_root_is_ignored(self): + self.assertIgnored(["/", os.path.abspath(os.sep), _fwd(os.path.abspath(os.sep))]) + + def test_home_itself_and_ancestors_are_ignored(self): + self.assertIgnored(["~", "~/", self.home, _fwd(self.home) + "/", "~/.."]) + + def test_dir_containing_home_is_ignored(self): + """ホームの祖先(allow_write に書いたディレクトリの中にホームがある)は無視する.""" + home = os.path.join(self.sib, "userhome") + os.makedirs(home) + self.write_config({"allow_write": ["../sib"]}) + err = io.StringIO() + with mock.patch.dict(os.environ, {"HOME": home, "USERPROFILE": home}), contextlib.redirect_stderr(err): + self.assertEqual(self.rra.load_allow_write(self.repo), []) + self.assertTrue(err.getvalue().strip()) + + def test_repo_itself_and_ancestors_are_ignored(self): + self.assertIgnored(["..", "../", ".", "./", "../..", self.repo, self.base, _fwd(self.base), "../sib/.."]) + + def test_nonexistent_or_file_is_ignored(self): + self.assertIgnored(["../no_such_dir", os.path.join(self.base, "no_such_dir"), "../sib/file.txt", + self.existing]) + + def test_claude_config_folder_is_ignored(self): + os.makedirs(os.path.join(self.home, ".claude", "projects"), exist_ok=True) + self.assertIgnored(["~/.claude", "~/.claude/projects", os.path.join(self.home, ".claude")]) + + def test_wildcard_brace_and_user_home_are_ignored(self): + self.assertIgnored(["../si*", "../si?", "../s[i]b", "../{sib,outside}", "../sib{,2}", "~nosuchuser_x/dir"]) + + def test_empty_string_is_ignored(self): + allow, _, _ = self.load({"allow_write": ["", " ", "../sib"]}) + self.assertSame(allow, [self.sib]) + + def test_symlinked_allow_dir_is_resolved(self): + link = os.path.join(self.base, "siblink") + self.link_dir(self.sib, link) + allow, _, _ = self.load({"allow_write": ["../siblink"]}) + self.assertSame(allow, [self.sib]) + + def test_link_to_dangerous_dir_is_ignored(self): + """リンク経由で書いてもリンク先(リポジトリの親)で判定する.""" + link = os.path.join(self.out, "to_base") + self.link_dir(self.base, link) + allow, _, err = self.load({"allow_write": ["../outside/to_base"]}) + self.assertEqual(allow, []) + self.assertTrue(err.strip()) + + +class TestAllowWriteOperations(AllowWriteSandboxMixin, unittest.TestCase): + """allow_write の配下はリポジトリ外でも上書き・Edit・削除・移動を許可する.""" + + def setUp(self) -> None: + super().setUp() + self.use({"allow_write": ["../sib"]}) + self.assertTrue(self.allow) + + def test_all_write_ops_allowed_inside(self): + self.assertAllWriteOpsAllowed(self.sib_file) + self.assertAllWriteOpsAllowed(self.sib_deep) + + def test_notebook_edit_allowed_inside(self): + self.assertAllowed(self.tool("NotebookEdit", {"notebook_path": self.sib_file})) + + def test_delete_and_move_subdirectory(self): + sub = _fwd(os.path.join(self.sib, "sub")) + self.assertBashAllowed([f'rm -rf "{sub}"', f'mv "{sub}" "{self.s}/sub2"', f'rm -r "{self.s}/sub/"', + f'cp -r "{self.r}/sub" "{self.s}/sub"']) + self.assertPsAllowed([f'Remove-Item "{os.path.join(self.sib, "sub")}" -Recurse -Force', + f'Move-Item "{os.path.join(self.sib, "sub")}" "{os.path.join(self.sib, "sub2")}"']) + + def test_cd_into_allow_dir_then_relative(self): + self.assertBashAllowed([f'cd "{self.s}" && rm file.txt', f'cd "{self.s}" && rm -rf sub', + f'cd "{self.s}" && echo y > file.txt']) + self.assertBashAllowed(["rm file.txt", "rm -rf sub", "sed -i s/x/y/ sub/deep.txt"], cwd=self.sib) + self.assertPsAllowed([f'Set-Location "{self.sib}"; Remove-Item file.txt']) + + def test_allow_dir_itself_is_not_deletable(self): + self.assertBashDenied([f'rm -rf "{self.s}"', f'rm -rf "{self.s}/"', f'rm -rf "{self.s}/."', + f'mv "{self.s}" "{self.o}/moved"', f'cd "{self.s}" && rm -rf .']) + self.assertPsDenied([f'Remove-Item "{self.sib}" -Recurse -Force', + f'Move-Item "{self.sib}" "{os.path.join(self.out, "moved")}"']) + + def test_move_or_copy_onto_existing_outside_is_denied(self): + self.assertBashDenied([f'mv "{_fwd(self.sib_file)}" "{_fwd(self.existing)}"', + f'cp "{_fwd(self.sib_file)}" "{_fwd(self.existing)}"']) + + def test_outside_and_similar_names_still_denied(self): + self.assertAllWriteOpsDenied(self.existing) + self.assertAllWriteOpsDenied(self.sib2_file) + + def test_ambiguous_paths_are_denied(self): + s = self.s + self.assertBashDenied([ + f'rm "{s}"/{{file.txt,sub/deep.txt}}', + f'rm {s}/{{file.txt,x}}', + f'rm "{s}/sub/../file.txt"', + f'rm {s}/*/deep.txt', + f'echo y > "{s}/sub/../file.txt"', + f'cd {s}/* && rm deep.txt', + f'cd "{s}/sub/.." && rm file.txt', + ]) + self.assertDenied(self.tool("Edit", {"file_path": os.path.join(self.sib, "sub", "..", "file.txt")})) + + def test_relative_dotdot_in_command_is_denied(self): + """コマンド中の `..`(../sib/...)は文字列から対象を確定できないとして許可しない(Issue #64).""" + self.assertBashDenied(["rm ../sib/file.txt", "echo y > ../sib/file.txt"]) + self.assertPsDenied(["Remove-Item ../sib/file.txt"]) + + def test_link_escaping_allow_dir_is_denied(self): + link = os.path.join(self.sib, "escape") + self.link_dir(os.path.join(self.out, "dir"), link) + self.assertAllWriteOpsDenied(os.path.join(link, "file.txt")) + self.assertBashDenied([f'rm -rf "{_fwd(link)}/"']) + + @unittest.skipIf(os.name == "nt", "リンク自体を消すだけかの判定は POSIX のシンボリックリンクで確かめる" + "(Windows はシンボリックリンク作成に権限が要り,ジャンクションでは rm の挙動が異なるため)") + def test_removing_link_itself_is_allowed(self): + link = os.path.join(self.sib, "escape") + os.symlink(os.path.join(self.out, "dir"), link, target_is_directory=True) + self.assertBashAllowed([f'rm "{_fwd(link)}"', f'rm -f "{_fwd(link)}"', "rm escape"], cwd=self.sib) + filelink = os.path.join(self.sib, "filelink") + os.symlink(self.existing, filelink) + self.assertBashAllowed([f'rm "{_fwd(filelink)}"']) + self.assertBashDenied([f'echo y > "{_fwd(filelink)}"', f'sed -i s/x/y/ "{_fwd(filelink)}"']) + self.assertDenied(self.tool("Edit", {"file_path": filelink})) + + def test_access_via_link_to_allow_dir_is_allowed(self): + """実パスで判定するので,許可ディレクトリを指すリンク経由の操作は許可する.""" + link = os.path.join(self.out, "to_sib") + self.link_dir(self.sib, link) + self.assertAllowed(self.tool("Edit", {"file_path": os.path.join(link, "file.txt")})) + self.assertAllowed(self.bash(f'rm "{_fwd(link)}/file.txt"')) + + def test_deny_read_takes_precedence(self): + self.use({"deny_read": ["../sib/secret"], "allow_write": ["../sib"]}) + self.assertAllWriteOpsDenied(self.sib_secret) + self.assertBashDenied([f'rm -rf "{self.s}/secret"', f'cat "{_fwd(self.sib_secret)}"']) + self.assertAllWriteOpsAllowed(self.sib_file) + + def test_without_allow_write_behavior_unchanged(self): + for config in ({"deny_read": []}, {}, {"allow_write": []}): + with self.subTest(config=config): + self.use(config) + self.assertAllWriteOpsDenied(self.sib_file) + self.assertAllowed(self.tool("Write", {"file_path": os.path.join(self.sib, "new.txt")})) + self.assertAllowed(self.tool("Read", {"file_path": self.sib_file})) + self.assertAllowed(self.bash("rm -rf sub")) + + def test_invalid_deny_read_disables_allow_write(self): + self.use({"deny_read": [1], "allow_write": ["../sib"]}) + self.assertAllWriteOpsDenied(self.sib_file) + + def test_ignored_entries_grant_nothing(self): + self.use({"allow_write": ["..", "~", "/", "../si*", "../{sib,outside}"]}) + self.assertEqual(self.allow, []) + self.assertAllWriteOpsDenied(self.sib_file) + self.assertAllWriteOpsDenied(self.existing) + + def test_does_not_extend_to_other_zones(self): + """allow_write は他プロジェクトのメモ・~/.claude の判定を変えない.""" + self.assertAllWriteOpsDenied(self.other_note) + self.assertAllWriteOpsDenied(self.settings) + + +@unittest.skipUnless(os.name == "nt", "パスの大文字小文字の同一視・Git Bash 形式は Windows 固有のため") +class TestAllowWriteWindowsCase(AllowWriteSandboxMixin, unittest.TestCase): + def test_case_difference_in_config_and_command(self): + self.use({"allow_write": ["../SIB"]}) + self.assertTrue(self.allow) + self.assertAllWriteOpsAllowed(os.path.join(self.base, "SIB", "FILE.TXT")) + self.assertAllWriteOpsAllowed(self.sib_file) + self.assertAllWriteOpsDenied(self.sib2_file) + self.assertBashDenied([f'rm -rf "{_fwd(os.path.join(self.base, "SIB"))}"']) + + def test_gitbash_form_in_command(self): + self.use({"allow_write": ["../sib"]}) + self.assertAllowed(self.bash(f'rm "{_gitbash(self.sib_file)}"')) + + +class TestAllowWriteViaMain(AllowWriteSandboxMixin, HookIOMixin, unittest.TestCase): + """main に標準入力で JSON を渡す経路で allow_write が読まれること.""" + + def inputs(self, path: str) -> dict: + f = _fwd(path) + return { + "Edit": ("Edit", {"file_path": path, "old_string": "x", "new_string": "y"}), + "Write": ("Write", {"file_path": path, "content": "y"}), + "Bash rm": ("Bash", {"command": f'rm "{f}"'}), + "Bash mv": ("Bash", {"command": f'mv "{f}" "{f}.moved"'}), + "Bash redirect": ("Bash", {"command": f'echo y > "{f}"'}), + "PowerShell Remove-Item": ("PowerShell", {"command": f'Remove-Item "{path}"'}), + } + + def assertAllAllowedViaMain(self, path: str) -> None: + for label, (name, tool_input) in self.inputs(path).items(): + with self.subTest(label, path=path): + self.assertHookAllows(self.feed_tool(name, tool_input), label) + + def assertAllDeniedViaMain(self, path: str) -> None: + for label, (name, tool_input) in self.inputs(path).items(): + with self.subTest(label, path=path): + self.assertHookDenies(self.feed_tool(name, tool_input), label) + + def test_allowed_with_config(self): + self.write_config({"allow_write": ["../sib"]}) + self.assertAllAllowedViaMain(self.sib_file) + self.assertAllDeniedViaMain(self.existing) + self.assertHookDenies(self.feed_tool("Bash", {"command": f'rm -rf "{self.s}"'})) + + def test_denied_without_allow_write(self): + self.write_config({"deny_read": []}) + self.assertAllDeniedViaMain(self.sib_file) + + def test_deny_read_wins_via_main(self): + self.write_config({"deny_read": ["../sib/secret"], "allow_write": ["../sib"]}) + self.assertAllDeniedViaMain(self.sib_secret) + self.assertAllAllowedViaMain(self.sib_file) + + def test_broken_deny_read_disables_allow_write_via_main(self): + self.write_config({"deny_read": "~/.ssh", "allow_write": ["../sib"]}) + self.assertAllDeniedViaMain(self.sib_file) + + def test_dangerous_entry_warns_and_valid_entry_still_works(self): + self.write_config({"allow_write": ["..", "../sib"]}) + result = self.feed_tool("Bash", {"command": f'rm "{_fwd(self.sib_file)}"'}) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(result.stdout.strip(), b"") + self.assertTrue(result.stderr.strip(), "stderr に警告が出ること") + self.assertHookDenies(self.feed_tool("Bash", {"command": f'rm "{_fwd(self.existing)}"'})) + + def test_parent_entry_does_not_allow_outside(self): + self.write_config({"allow_write": [".."]}) + self.assertAllDeniedViaMain(self.existing) + self.assertAllDeniedViaMain(self.sib_file) + + def test_warning_unwritable_is_denied(self): + """警告を書けないときは判定できないものとして拒否する(リポジトリ内の操作でも).""" + self.write_config({"allow_write": ["..", "../sib"]}) + payload = self.raw({"tool_name": "Bash", "tool_input": {"command": "rm file.txt"}, "cwd": self.repo}) + for kind in self.UNWRITABLE_KINDS: + with self.subTest(kind), self.unwritable(kind) as stderr: + self.assertHookDeniesUnexpected(self.feed(payload, stderr=stderr), kind) + self.assertHookDenies(self.feed_driver("sys.stderr = None\n", payload)) + + def test_via_wrapper_like_settings_json(self): + self.write_config({"allow_write": ["../sib"]}) + data = {"tool_name": "Edit", "tool_input": {"file_path": self.sib_file, "old_string": "x", "new_string": "y"}, + "cwd": self.repo} + result = self.feed_wrapper(self.raw(data)) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(result.stdout.strip(), b"") + data["tool_input"]["file_path"] = self.existing + self.assertHookDenies(self.feed_wrapper(self.raw(data))) + + if __name__ == "__main__": unittest.main() diff --git a/.claude/rules/hooks-cross-platform.md b/.claude/rules/hooks-cross-platform.md index b9c2d77..5ed511e 100644 --- a/.claude/rules/hooks-cross-platform.md +++ b/.claude/rules/hooks-cross-platform.md @@ -22,6 +22,7 @@ - 絶対パスの判定を `ntpath.isabs` の結果に直接依存させない.Python 3.13 で `ntpath.isabs` が変わり,ドライブ無しの root-relative パス(`/tmp/x`・`\tmp\x`)を False と判定するようになったため,そのまま使うと cwd と結合されて `D:\tmp\x` 等に化け,Python のバージョンで判定が変わる(フックでは `is_absolute` で Windows の `/`・`\` 始まりを常に絶対パスとして扱う) - Git Bash 形式のパス(`/c/Users/...`)・ドライブレター・UNC パス等の Windows 固有の変換は `os.name == "nt"` のときだけ行い,他 OS の挙動を変えない - シェルスクリプト(`*.sh`)は macOS 標準の bash 3.2 と BSD 版コマンドでも動く書き方にする(GNU 拡張のオプションや bash 4 以降の構文に頼らない) +- `settings.json` 等でフックを配線するときは,コマンド中のパスを `$CLAUDE_PROJECT_DIR` 起点にしてダブルクォートで囲む(例: `bash "$CLAUDE_PROJECT_DIR/.claude/hooks/run_python.sh" "$CLAUDE_PROJECT_DIR/.claude/hooks/notify.py"`).相対パスだと作業フォルダが移ったときにフックが見つからず,アクセス制限フックが素通りになる.ダブルクォートは Windows の `C:\Users\...` 形式やスペースを含むパスのため ## テストの書き方 (Writing Tests) diff --git a/.claude/rules/template-customization.md b/.claude/rules/template-customization.md index 3126e3d..43f6b18 100644 --- a/.claude/rules/template-customization.md +++ b/.claude/rules/template-customization.md @@ -13,7 +13,7 @@ - **対象外**: - プロジェクトが新規に作ったファイル(立ち上げ時に作成するコーディング規約 rule,プロジェクト独自の skill / agent 等).テンプレートに存在しないので同期で上書きされない - `.claude/verify-profile.md`(検証プロファイル).テンプレートが持つのは雛形(`.claude/skills/verify/profile-template.md`)だけであり,プロファイル本体はプロジェクト所有のため同期で触られない.台帳登録は不要 - - `.claude/repo-access.json`(リポジトリ外アクセス制限フックの禁止リスト).テンプレートには含まれないプロジェクト所有のファイルのため同期で触られない.台帳登録は不要 + - `.claude/repo-access.json`(リポジトリ外アクセス制限フックの設定.禁止リスト `deny_read`・書き込み許可ディレクトリ `allow_write`).テンプレートには含まれないプロジェクト所有のファイルのため同期で触られない.台帳登録は不要 - `.claude/project-board`(Project ボードの有効化と対象 Project の指定).テンプレートには含まれないプロジェクト所有のファイルのため同期で触られない.台帳登録は不要 - `CLAUDE.md`・`.gitignore`・`docs/PROGRESS.md`・`.gitattributes`・`.claude/settings.json`.これらは `/sync-template` の「マージ必須ファイル」として別途保護されており,台帳登録は不要 - テンプレート由来かどうか判断に迷う場合は**記録する側に倒す**.余計な記録は `/sync-template` が「テンプレート側に存在しないパス」として警告してくれるが,記録漏れは改変の消失につながる diff --git a/.claude/settings.json b/.claude/settings.json index 1801fd4..89f1699 100644 --- a/.claude/settings.json +++ b/.claude/settings.json @@ -11,7 +11,7 @@ "hooks": [ { "type": "command", - "command": "bash .claude/hooks/run_python.sh --fail-closed .claude/hooks/restrict_repo_access.py" + "command": "bash \"$CLAUDE_PROJECT_DIR/.claude/hooks/run_python.sh\" --fail-closed \"$CLAUDE_PROJECT_DIR/.claude/hooks/restrict_repo_access.py\"" } ] }, @@ -20,7 +20,7 @@ "hooks": [ { "type": "command", - "command": "bash .claude/hooks/run_python.sh .claude/hooks/notify.py", + "command": "bash \"$CLAUDE_PROJECT_DIR/.claude/hooks/run_python.sh\" \"$CLAUDE_PROJECT_DIR/.claude/hooks/notify.py\"", "async": true } ] @@ -32,7 +32,7 @@ "hooks": [ { "type": "command", - "command": "bash .claude/hooks/run_python.sh .claude/hooks/notify.py", + "command": "bash \"$CLAUDE_PROJECT_DIR/.claude/hooks/run_python.sh\" \"$CLAUDE_PROJECT_DIR/.claude/hooks/notify.py\"", "async": true } ] @@ -43,7 +43,7 @@ "hooks": [ { "type": "command", - "command": "bash .claude/hooks/run_python.sh .claude/hooks/notify.py", + "command": "bash \"$CLAUDE_PROJECT_DIR/.claude/hooks/run_python.sh\" \"$CLAUDE_PROJECT_DIR/.claude/hooks/notify.py\"", "async": true } ] diff --git a/.claude/skills/set-mode/SKILL.md b/.claude/skills/set-mode/SKILL.md index 484e430..47db846 100644 --- a/.claude/skills/set-mode/SKILL.md +++ b/.claude/skills/set-mode/SKILL.md @@ -69,13 +69,13 @@ ### 3-A.2 settings.json に SessionStart(check_sync) を配線 -`.claude/settings.json` を Read し,既存の `PreToolUse`(`restrict_repo_access.py`)を保持したまま,`SessionStart` フックを追加する(既に配線済みなら何もしない): +`.claude/settings.json` を Read し,既存の `PreToolUse`(`restrict_repo_access.py`)を保持したまま,`SessionStart` フックを追加する(既に配線済みなら何もしない.ただし相対パスの `bash .claude/hooks/check_sync.sh` で配線済みなら下記の `$CLAUDE_PROJECT_DIR` 起点の書き方に置き換える): ```json "SessionStart": [ { "hooks": [ - { "type": "command", "command": "bash .claude/hooks/check_sync.sh", "timeout": 10 } + { "type": "command", "command": "bash \"$CLAUDE_PROJECT_DIR/.claude/hooks/check_sync.sh\"", "timeout": 10 } ] } ] diff --git a/.claude/skills/setup/SKILL.md b/.claude/skills/setup/SKILL.md index ce60a18..e918e1e 100644 --- a/.claude/skills/setup/SKILL.md +++ b/.claude/skills/setup/SKILL.md @@ -66,7 +66,7 @@ "SessionStart": [ { "hooks": [ - { "type": "command", "command": "bash .claude/hooks/check_sync.sh", "timeout": 10 } + { "type": "command", "command": "bash \"$CLAUDE_PROJECT_DIR/.claude/hooks/check_sync.sh\"", "timeout": 10 } ] } ] diff --git a/.claude/skills/sync-template/SKILL.md b/.claude/skills/sync-template/SKILL.md index 4f455bf..4c15955 100644 --- a/.claude/skills/sync-template/SKILL.md +++ b/.claude/skills/sync-template/SKILL.md @@ -330,5 +330,5 @@ - 台帳への登録は必ず理由を添える(ユーザーから聞く).理由の無い登録は次回同期時の判断材料にならない.台帳の書式(パス列はバッククォート囲み,方針列は `keep` / `merge` / `ask`)を崩さない - 同期対象外ファイル(`README.md`)はテンプレート紹介用のためプロジェクトには反映しない.テンプレート側で追加・変更・削除があってもプロジェクトの該当ファイルは触らない - チーム層ファイル(`GUIDE_03`/`check_sync.sh`)は `.claude/project-mode` が `team` のプロジェクトにのみ同期する.`task-*` skill は共通層のためモードに関わらず同期する.`solo`(または未設定)のプロジェクトには配置・更新・削除いずれもしない.`/sync-template` は「版の追従」のみを行い,**モードの切り替えはしない**.solo↔team の切替は `/set-mode ` を使う(team 層ファイルの配置/削除・`settings.json` 配線・`CLAUDE.md` の team 化/solo 化・`project-mode` 更新を一括で行う).`.claude/project-mode` を手で書き換えるだけでは切り替わらない -- テンプレートが管理するのは `.claude/` 配下のうち `agents/`,`skills/`,`rules/`,`hooks/`,`settings.json`,`template-sync-sha`,`template-overrides.md`(雛形のみ.登録内容はプロジェクト固有)のみ.`.claude/plans/`・`.claude/commit-context.md`・`.claude/verify-profile.md`(検証プロファイル.テンプレートが持つのは雛形 `.claude/skills/verify/profile-template.md` のみ)・`.claude/repo-access.json`(リポジトリ外アクセス制限フックの禁止リスト.GUIDE_01「環境構築」)・`.claude/project-mode`・`.claude/project-board`(Project ボードの有効化と対象 Project の指定.`.claude/skills/task-start/reference.md`「ボード設定の判定」)等のプロジェクト固有ファイルはテンプレートに含まれないため同期対象外(`$CHANGED_ENTRIES` に現れず,コピー・上書き・削除のいずれも起きない) +- テンプレートが管理するのは `.claude/` 配下のうち `agents/`,`skills/`,`rules/`,`hooks/`,`settings.json`,`template-sync-sha`,`template-overrides.md`(雛形のみ.登録内容はプロジェクト固有)のみ.`.claude/plans/`・`.claude/commit-context.md`・`.claude/verify-profile.md`(検証プロファイル.テンプレートが持つのは雛形 `.claude/skills/verify/profile-template.md` のみ)・`.claude/repo-access.json`(リポジトリ外アクセス制限フックの設定(禁止リスト `deny_read`・書き込み許可ディレクトリ `allow_write`).GUIDE_01「環境構築」)・`.claude/project-mode`・`.claude/project-board`(Project ボードの有効化と対象 Project の指定.`.claude/skills/task-start/reference.md`「ボード設定の判定」)等のプロジェクト固有ファイルはテンプレートに含まれないため同期対象外(`$CHANGED_ENTRIES` に現れず,コピー・上書き・削除のいずれも起きない) - `chore/sync-template` ブランチは他の作業ブランチと混ぜず,作成後は速やかにマージすること.複数の作業ブランチで `/sync-template` を実行すると `.claude/template-sync-sha` がコンフリクトする.コンフリクト時は新しい(HEAD 側の)SHA を採用すること. diff --git a/.claude/skills/sync-template/reference.md b/.claude/skills/sync-template/reference.md index 4460ddc..0494a10 100644 --- a/.claude/skills/sync-template/reference.md +++ b/.claude/skills/sync-template/reference.md @@ -337,7 +337,7 @@ 3. **既存の hooks を保持したまま**,テンプレート側で追加・変更された hook(イベント・matcher・command)のみを統合する: - 既存に無いイベント/hook はテンプレート版から追加する - プロジェクト固有の hook(team の SessionStart `check_sync.sh` 等)は残す - - 同一 hook の command 変更(例: `restrict_repo_access.py` の起動方法変更)はテンプレート版に合わせる.旧形式の `python .claude/hooks/<名前>.py` は `bash .claude/hooks/run_python.sh [--fail-closed] .claude/hooks/<名前>.py` に置き換える(`--fail-closed` はテンプレート版と同じく `restrict_repo_access.py` にのみ付ける).`run_python.sh` が同期で配置済みであることも確認する + - 同一 hook の command 変更(例: `restrict_repo_access.py` の起動方法変更)はテンプレート版に合わせる.旧形式の `python .claude/hooks/<名前>.py` や相対パスの `bash .claude/hooks/run_python.sh [--fail-closed] .claude/hooks/<名前>.py` は `bash "$CLAUDE_PROJECT_DIR/.claude/hooks/run_python.sh" [--fail-closed] "$CLAUDE_PROJECT_DIR/.claude/hooks/<名前>.py"`(JSON 内では `"` を `\"` にエスケープ)に置き換える(`--fail-closed` はテンプレート版と同じく `restrict_repo_access.py` にのみ付ける).`run_python.sh` が同期で配置済みであることも確認する.team の SessionStart の `bash .claude/hooks/check_sync.sh` も同様に `bash "$CLAUDE_PROJECT_DIR/.claude/hooks/check_sync.sh"` に置き換える(相対パスだと作業フォルダが移ったときにフックが見つからない) - 同一 hook の matcher 変更(例: `restrict_repo_access.py` の対象ツールに `NotebookEdit`・`PowerShell` を追加)もテンプレート版に合わせる.プロジェクトが独自に足したツール名があれば残す - solo モードで SessionStart(check_sync) が無い場合は,team 専用の配線を勝手に追加しない 4. `hooks` 以外のキーも同じ方針でマージする.特に `permissions.allow` は,テンプレート側に追加されたルール(`Bash(gh pr merge:*)` 等.auto mode で ops-runner にマージを実行させるために必要)を既存へ追加し,プロジェクトが独自に足したルールは残す(削除しない) diff --git a/.claude/skills/task-create/SKILL.md b/.claude/skills/task-create/SKILL.md index 5bd357e..3969895 100644 --- a/.claude/skills/task-create/SKILL.md +++ b/.claude/skills/task-create/SKILL.md @@ -39,7 +39,7 @@ - **Issue**: 番号・タイトル・URL - **ボード**: Todo(`.claude/project-board` が無い場合は「未追加(ボード未使用)」と表記する) -- **次の手順**: 「このタスクに着手する場合は `/task-start ` を実行してください.」 +- **次の手順**: 「このタスクに着手する場合は `/task-start ` を実行してください(人間の判断が要らなければそのまま `/implement` に進みます).」 ## 注意事項 (Notes) diff --git a/.claude/skills/task-start/SKILL.md b/.claude/skills/task-start/SKILL.md index 547b72a..baf5fb1 100644 --- a/.claude/skills/task-start/SKILL.md +++ b/.claude/skills/task-start/SKILL.md @@ -1,11 +1,11 @@ --- name: task-start model: inherit -description: "既存 Issue を拾って作業を開始する(アサイン・ボード In Progress・作業ブランチ作成).solo / team 両モードで使用できる." -argument-hint: "" +description: "既存 Issue を拾って作業を開始する(アサイン・ボード In Progress・作業ブランチ作成).Issue の内容から人間の判断が要るかを見極め,不要(または数問の質問で解消できる)ならそのまま /implement に進む.solo / team 両モードで使用できる." +argument-hint: " [--prep-only]" --- -あなたはタスク着手の司令塔です.着手準備(アサイン・ボード操作・作業ブランチ作成)の実行は **ops-runner エージェント**(軽量モデル)に委譲し,あなた自身はユーザー確認の仲介と結果の報告だけを行います(使用量節約のため,git・gh 操作を自分では行わない). +あなたはタスク着手の司令塔です.着手準備(アサイン・ボード操作・作業ブランチ作成)の実行は **ops-runner エージェント**(軽量モデル)に委譲し,あなた自身はユーザー確認の仲介・Issue 内容の見極め・`/implement` への引き継ぎを行います(使用量節約のため,git・gh 操作を自分では行わない). 本スキルは **solo / team 両モードで使用できる**.team モードでは GUIDE_03(チーム開発ルール)にも従うこと.solo モードでは GUIDE_03 は存在しないため,本スキルと本スキルの `reference.md` の記述を基準とする. @@ -13,7 +13,10 @@ ## ステップ 1: 前提確認 (Pre-check) -$ARGUMENTS を確認する.Issue 番号(数値または `#数値`)が指定されていなければ「対象の Issue 番号を指定してください.新規 Issue を立てる場合は `/task-create` を使います」と伝えて終了する. +$ARGUMENTS を確認する. + +- Issue 番号(数値または `#数値`)が指定されていなければ「対象の Issue 番号を指定してください.新規 Issue を立てる場合は `/task-create` を使います」と伝えて終了する +- `--prep-only` が指定されていれば,着手準備(ステップ 2〜3)だけを行い,ステップ 4 の見極めと `/implement` への移行はせずにステップ 5 の完了サマリーで終了する ## ステップ 2: 委譲 (Delegate) @@ -23,19 +26,51 @@ - 対象の Issue 番号 - **ブランチ名**: Issue の内容を把握している場合(同セッションで `/task-create` した直後等)は `.claude/rules/git-conventions.md` の命名規則で決めて渡す.把握していなければ ops-runner に規約どおり提案・作成させ,報告で名前を確認する - 確認が必要な事態(未コミット変更・未マージブランチ・進行中タスクあり・他人アサイン等)では,該当項目をまとめて停止・報告すること +- 報告には Issue の本文とコメント(`/task-handoff` の引継ぎメモを含む)を**要約せずそのまま**含めること ## ステップ 3: 確認の仲介 (Confirm) エージェントが確認事項で停止した場合は,状況をユーザーに提示して判断を仰ぎ,承認された項目を「ユーザー承認済み」と明示して再委譲する. -## ステップ 4: 完了サマリー (Summary) +## ステップ 4: 着手判定 (Readiness Check) -エージェントの報告をもとに以下を提示する: +ops-runner の報告に含まれる Issue の本文・コメントを読み,関連する仕様・設計ドキュメント(`docs/` 配下等)を必要な範囲で確認したうえで,**実装に入る前に人間の判断が必要な点**を洗い出す.洗い出した結果により,以下の 3 つに分岐する. + +| 判定 | 基準 | 動作 | +| --- | --- | --- | +| A. そのまま実装可 | 目的・完了条件・実装方針が Issue と既存ドキュメントから読み取れる.細部はコードベースの慣習や妥当な既定で決められる | 確認せずに `/implement` へ進む | +| B. 数問の質問で解消 | 未決事項が少数(目安 4 問以内)で,それぞれ選択肢を示して答えられる粒度である(例: 2 案のどちらで実装するか,表示文言,対象範囲の線引き) | `AskUserQuestion` で 1 回にまとめて質問し,回答を反映して `/implement` へ進む | +| C. 会話で詰める必要あり | 要件・目的そのものが曖昧,複数の設計方針に大きなトレードオフがあり議論が要る,Issue に「要検討」「相談」等の記載がある,不可逆な判断(スキーマ・公開 API・外部サービスの選定等)を含む,質問が 4 問を超える | 停止する(下記) | + +判定の注意: + +- 迷ったら B に倒す(推測で実装に入って手戻りするより,数問聞く方が安い).ただし規約・既存ドキュメントで既に決まっている事項,すぐ決まる二択で推奨が明確な事項は質問しない(推奨を採用し,`/implement` へ渡すタスク内容に「採用した前提」として明記する) +- B の質問は,各問に推奨案を先頭(`(Recommended)` 付き)に置き,Issue の該当箇所を引用して単独で読めるようにする.回答で新たな大きな論点が出てきた場合は C に切り替える +- C で停止する場合は,ステップ 5 の完了サマリーに続けて「決める必要がある論点」(論点・背景・考えられる選択肢と推奨)を提示し,会話で方針を詰める.合意できたら,ユーザーの「進めて」等の指示を受けて合意内容を反映した `/implement` に進む(ユーザーの再入力は不要) +- 不可逆な設計判断で自信が持てない場合は,C で停止する前に `/consult` の利用を検討してよい(`consult` skill の利用条件に従う) + +## ステップ 5: 完了サマリー (Summary) + +ops-runner の報告をもとに以下を提示する(A・B では `/implement` に進む直前に簡潔に提示する): - **Issue**: 番号・タイトル・URL - **ボード**: In Progress(`.claude/project-board` が無い場合は「アサインのみ(ボード未使用)」と表記する) - **ブランチ**: 作成したブランチ名 -- **次の手順**: 「`/implement` に対象 Issue の内容を渡して実装を開始してください(`gh issue view ` で取得できます).」 +- **着手判定**: A / B / C と,その理由 1 行(B の場合は質問と回答の要約,`--prep-only` の場合は「着手準備のみ」) +- **次の手順**: + - A・B: 「`/implement` を開始します.」 + - C: 「上記の論点を決めたら `/implement` に進みます.」 + - `--prep-only`: 「`/implement` に対象 Issue の内容を渡して実装を開始してください(`gh issue view ` で取得できます).」 + +## ステップ 6: 実装への移行 (Hand Off to Implement) + +A・B(および C で合意した後)は,Skill ツールで `implement` skill を起動する.引数(タスク内容)には以下を含める: + +- Issue 番号・タイトル・URL +- Issue の本文(コメントに仕様の追記・引継ぎメモがあればその要点も) +- B の質問への回答・C で合意した内容・判定時に採用した前提(「確定事項」として明記する) + +以降は `implement` skill の手順(Phase 1 後の人間による動作確認等)に従う.`/implement` の完了後もコミットは行わず,`/commit` を案内するだけにする(CLAUDE.md「Git 運用」). ## 注意事項 (Notes) @@ -43,3 +78,4 @@ - Projects(ボード)は既定では使わず,`.claude/project-board` があるときだけ操作する(`reference.md`「ボード設定の判定」) - `.claude/project-board` がある場合に限り `project` スコープが必要.スコープエラーの停止報告が来たら `gh auth refresh -s project` をユーザーに案内する(`reference.md`「必要なスコープ」) - 新規 Issue を立てる場合は `/task-create`,Issue 無しで進める場合は本コマンドを使わず直接 `/implement` 等へ +- 着手準備だけ行い実装は後で始めたい場合は `--prep-only` を付ける diff --git a/.claude/skills/task-start/reference.md b/.claude/skills/task-start/reference.md index 5db4346..b597554 100644 --- a/.claude/skills/task-start/reference.md +++ b/.claude/skills/task-start/reference.md @@ -63,10 +63,10 @@ 1. **前提確認**: `git status` を確認し,未コミットの変更があれば停止して報告する.`git branch --show-current` を確認し,`main` 以外にいる場合は `git log main..HEAD --oneline` で未マージコミットを確認し,残っていれば停止して報告する(直列運用の原則) 2. **直列運用チェック**: 「ボード設定の判定」に従い `.claude/project-board` の有無を確認する.進行中の作業を数える(`.claude/project-board` があればその Project の `item-list` で Status が `In Progress` のもの,無ければ `gh issue list --assignee @me --state open`).対象 Issue 以外に 1 件以上あれば,該当タスクの一覧を添えて停止して報告する(禁止ではなく原則) -3. **対象 Issue の確認・アサイン**: `gh issue view ` で内容を確認する(存在しない・クローズ済み・他人がアサイン済みの場合は停止して報告する).`gh issue edit --add-assignee @me` で自分をアサインする +3. **対象 Issue の確認・アサイン**: `gh issue view --json number,title,url,state,assignees,body,comments` で本文とコメントを確認する(存在しない・クローズ済み・他人がアサイン済みの場合は停止して報告する).`gh issue edit --add-assignee @me` で自分をアサインする 4. **ボードを In Progress へ**(`.claude/project-board` がある場合のみ): 「Projects の操作」に従い,未追加なら `item-add` → Status を `In Progress` に変更 → `item-list` で結果を確認する 5. **作業ブランチ作成**: `git checkout main && git pull origin main` で `main` を最新化し,`git checkout -b <ブランチ名>` する.ブランチ名は司令塔から渡されていればそれを使い,無ければ Issue タイトルから規約どおり(プレフィックス+英単語 2〜4 語.Issue 番号は含めない)決めて,決めた名前とプレフィックスの選択理由を報告に含める -6. **報告**: Issue 番号・タイトル・URL・ボード状態(`.claude/project-board` が無ければ「ボード未使用」)・作成したブランチ名を返す +6. **報告**: Issue 番号・タイトル・URL・ボード状態(`.claude/project-board` が無ければ「ボード未使用」)・作成したブランチ名に加え,Issue の本文とコメントを**要約せずそのまま**返す(司令塔が着手判定と `/implement` への引き継ぎに使う) ※ ステップ 1〜3 の停止条件に複数該当する場合は,まとめて 1 回の報告で返す(司令塔との往復を減らす).司令塔から「ユーザー承認済み」と明示された項目では停止しない. diff --git a/.claude/template-sync-sha b/.claude/template-sync-sha index 9c5d6ac..30d687c 100644 --- a/.claude/template-sync-sha +++ b/.claude/template-sync-sha @@ -1 +1 @@ -f3164fcaa5298f2a8fc869e376597f6e23501e76 +7874ae3acc7c0bbc3ae69f24f82bf6e7051dbec0 diff --git a/CLAUDE.md b/CLAUDE.md index 053fef6..79c2942 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -37,7 +37,7 @@ ### タスク管理(任意) -- やるべきことを GitHub Issues で管理してよい(solo / team 共通).`/task-create`(起票・事前計画)→ `/task-start `(着手準備)→ `/task-handoff`(中断時の引継ぎメモ投稿)を使う +- やるべきことを GitHub Issues で管理してよい(solo / team 共通).`/task-create`(起票・事前計画)→ `/task-start `(着手準備.人間の判断が要らなければそのまま `/implement` に進む)→ `/task-handoff`(中断時の引継ぎメモ投稿)を使う - Issue は必須ではない.小さい変更や試験的作業は Issue 無しで進めてよい - solo モードでは進捗記録(`.claude/rules/progress-log.md`)は従来どおり運用し,Issue はタスクの管理・引継ぎの補助として使う @@ -62,6 +62,8 @@ - 例外: `gh` CLI で操作できる GitHub リポジトリ設定(Dependabot alerts / security updates の有効化)は Claude が `gh api` で行う(手順は `.claude/skills/setup/reference.md`,背景は GUIDE_01「環境構築」) - リポジトリ外のファイルの削除・上書き(既存ファイルの移動を含む) - フックが検出できない書き方であっても Claude は自分で実行しない(変数・スクリプトファイル・`python -c` 等による迂回も禁止).必要な操作であれば,実行するコマンドをそのまま提示し,ユーザーにプロンプトで `! <コマンド>` として実行するよう依頼する + - 例外: 今のプロジェクトの Claude メモのフォルダ(`~/.claude/projects/<プロジェクト>/memory/`)の配下は Claude が修正・削除してよい.他のプロジェクトのメモ,`memory` フォルダ自体,会話の記録,`~/.claude` のその他のファイル(`settings.json` 等)は対象外 + - 例外: `.claude/repo-access.json` の `allow_write` に書いたディレクトリの配下は Claude が修正・削除してよい(指定したディレクトリ自体の削除・移動は対象外.書き方と無視される指定は GUIDE_01「リポジトリ外アクセス制限フック」) - 実機・ブラウザでの動作確認(`verifier` による自動検証は前段であり,これを置き換えない) - ストアへのアップロード・リリース作業 diff --git "a/docs/01_GUIDE/GUIDE_01_\343\203\227\343\203\255\343\202\270\343\202\247\343\202\257\343\203\210\347\253\213\343\201\241\344\270\212\343\201\222\343\203\225\343\203\255\343\203\274.md" "b/docs/01_GUIDE/GUIDE_01_\343\203\227\343\203\255\343\202\270\343\202\247\343\202\257\343\203\210\347\253\213\343\201\241\344\270\212\343\201\222\343\203\225\343\203\255\343\203\274.md" index 798046d..7a89792 100644 --- "a/docs/01_GUIDE/GUIDE_01_\343\203\227\343\203\255\343\202\270\343\202\247\343\202\257\343\203\210\347\253\213\343\201\241\344\270\212\343\201\222\343\203\225\343\203\255\343\203\274.md" +++ "b/docs/01_GUIDE/GUIDE_01_\343\203\227\343\203\255\343\202\270\343\202\247\343\202\257\343\203\210\347\253\213\343\201\241\344\270\212\343\201\222\343\203\225\343\203\255\343\203\274.md" @@ -62,7 +62,7 @@ - **前提条件**: 以下のツールは全プロジェクト共通で導入する. - `git` — バージョン管理(運用ルールは `.claude/rules/git-conventions.md` で定義) - `gh` — GitHub CLI(PR 作成・マージ等に使用) - - Python 3.7 以上と `bash` — `.claude/settings.json` のフック(リポジトリ外アクセス制限・通知)の実行に使用.フックは `bash .claude/hooks/run_python.sh` 経由で起動し,`python3` → `python` → `py` の順に実際に起動できるものを使う(いずれか 1 つで起動できればよい.Windows では Git for Windows 付属の `bash` を使う).※ Python が見つからないとアクセス制限フックが対象ツール(Read・Write・Edit・NotebookEdit・Glob・Grep・Bash・PowerShell)を**すべてブロックする**(通知フックは何もせず素通りする) + - Python 3.7 以上と `bash` — `.claude/settings.json` のフック(リポジトリ外アクセス制限・通知)の実行に使用.フックは `bash "$CLAUDE_PROJECT_DIR/.claude/hooks/run_python.sh"` 経由で起動し(作業フォルダが移っても見つかるよう,パスはリポジトリのルート `$CLAUDE_PROJECT_DIR` 起点で書く),`python3` → `python` → `py` の順に実際に起動できるものを使う(いずれか 1 つで起動できればよい.Windows では Git for Windows 付属の `bash` を使う).※ Python が見つからないとアクセス制限フックが対象ツール(Read・Write・Edit・NotebookEdit・Glob・Grep・Bash・PowerShell)を**すべてブロックする**(通知フックは何もせず素通りする) - **基本方針**: 環境の再現性を重視し,手順書だけに頼らず構築を自動化・コード化できる方法を優先する(例: Docker,Dev Containers,Windows Sandbox,IaC ツール等). - **人間が決めること**: 開発マシンの選定,クラウドサービスのアカウント作成,環境構築方法の選択 - **実際の構築まで行う**: 手順書を書いて終わりにせず,`/setup` がその手順に従って実際に環境を構築し,実行して分かった誤り・前提の抜けを手順書に反映してから人間のレビューを受ける(未検証の手順書は誤りを含みやすく,最初に詰まるのがその場のユーザーになるため).区分は次の 3 つ(詳細は `.claude/skills/setup/reference.md`「環境構築の実行」) @@ -78,19 +78,35 @@ - 削除(常に拒否): Bash の `rm`・`rmdir`・`unlink`・`shred`・`truncate`・`find -delete`/`-exec rm`・`mv` の移動元・`rsync --delete` の書き込み先,PowerShell の `Remove-Item` とそのエイリアス・`Clear-Content`・`Move-Item`/`Rename-Item` の移動元・`[IO.File]::Delete` 等,`cmd /c del` 等.`python -c`・`node -e`・ヒアドキュメント等のインライン実行は,削除系の呼び出し(`rmtree`・`os.remove`・`unlink`・`fs.rm` 等)があり,かつコード中にリポジトリ外のパスがある場合に拒否する.Edit・NotebookEdit(既存ファイルの書き換え)も拒否する - 上書き(書き込み先が既に存在する場合だけ拒否.無ければ新規作成として許可): `>`・`>|`・`&>`,`cp`・`mv`・`install`・`rsync`・`scp`・`ln -f`・`Copy-Item`・`Move-Item` の書き込み先(既存ディレクトリへのコピー・移動は `<ディレクトリ>/<コピー元の名前>` で判定),`sed -i`・`perl -i`,`tee`(`-a` 無し)・`Set-Content`・`Out-File`/`Tee-Object`/`Export-Csv`(`-Append` 無し)・`New-Item -Force`,`dd of=`,`curl -o`・`wget -O`・`Invoke-WebRequest -OutFile` 等の保存先,`Expand-Archive -Force`・`Compress-Archive -Force`,Write ツール,インライン実行の `open(..., 'w')`・`writeFile` 等 - 許可: 新規作成・ダウンロード・`mkdir`/`New-Item -ItemType Directory`・`touch`・追記(`>>`・`tee -a`・`Add-Content`・`Out-File -Append`).`chmod`・`chown`・`Set-Acl` も中身が失われないため許可する - - `cd`・`pushd`・`Set-Location` を追跡し,`~` と `$HOME` を展開してから判定する.基準はリポジトリのルート(`CLAUDE_PROJECT_DIR`)で,システム一時ディレクトリ(`/tmp`・`%TEMP%`.スクラッチパッドを含む)と `/dev/null`・`$null` 等は削除・上書きも許可する - - 読み取り: Read・Glob・Grep,Bash・PowerShell の読み取りはリポジトリ外も許可する.**読んだファイルの内容は Claude の API に送信される**ため,リポジトリ外を読ませることの是非はプロジェクトごとに判断する.読ませたくない場所(`~/.ssh`・`~/.aws`・他案件のフォルダ等)は禁止リスト `.claude/repo-access.json` に書く(任意.無ければ禁止リストは空).禁止リストに該当するパスは読み取り・書き込みとも拒否する.Glob・Grep・再帰的に読むコマンド(`grep -r`・`find`・`Get-ChildItem` 等)は,リポジトリ外の検索起点の配下に禁止パスがある場合も拒否する + - パスの展開と解決: Bash の波括弧(PowerShell・`cmd` は展開しないので対象外)と,Bash・PowerShell のワイルドカードを実際に展開し,展開後の各パスも判定する.`..` はリンク・ジャンクションを解決しながらたどった先でも判定する.波括弧の展開数が上限を超えた語が削除・上書きの対象なら拒否する.`rm` 等の最後の要素に一致したリンクはリンク自体が消えるだけなのでリンク先を判定しないが,Bash で末尾に `/` がある場合はリンク先の中身が消えるので判定する + - `cd`・`pushd`・`Set-Location` を追跡し(`cd -`・`pushd -`・`Set-Location -`・`Push-Location -` は同じコマンド内で追跡できる場合だけ),`~` と `$HOME` を展開してから判定する.基準はリポジトリのルート(`CLAUDE_PROJECT_DIR`)で,システム一時ディレクトリ(`/tmp`・`%TEMP%`.スクラッチパッドを含む)と `/dev/null`・`$null` 等は削除・上書きも許可する.Linux・macOS の一時ディレクトリはリンクを解決した実パスで判定するので,外へのリンク越しの操作は許可しない + - 今のプロジェクトの Claude メモのフォルダも削除・上書きを許可する(`MEMORY.md` の更新や古いメモの修正・削除は Claude の通常の作業のため).許可先はフック入力の `transcript_path` の親フォルダ直下の `memory` の配下だけで,`transcript_path` が無い場合は許可しない + - 許可しないもの: 他のプロジェクトのメモ,`memory` フォルダ自体の削除・移動,`memory` がリンクの場合,会話の記録,`~/.claude` のその他のファイル(`settings.json` 等) + - 実際の対象を文字列から確定できないパスも許可しない: 波括弧を含む,`..` を含む(`memory` の中に留まる場合も),途中の階層にワイルドカードを含む,コマンド内の `cd` 等の移動先がこれらやワイルドカードを含む.ただし最後の要素だけのワイルドカード(`memory/*` 等)は許可する.メモは git の管理外なので,消すと戻せない + - 既知の制限: `transcript_path` の親の階層(ホームフォルダ名等)に `[` や `{` があると,メモのフォルダの許可が効かず拒否される(安全側) + - `.claude/repo-access.json` の禁止リストは本許可より優先する + - `.claude/repo-access.json` の `allow_write` に書いたディレクトリの配下も削除・上書き・Edit・移動を許可する(任意.隣のリポジトリ等,リポジトリ外でも Claude に編集させたい場所を指定する.`permissions.additionalDirectories` で作業ディレクトリを追加してもフックはそれを見ないので,書き換えさせたい場合はここにも書く) + - 隣のリポジトリを編集させるには次の 2 つを設定する(`allow_write` だけでは Claude Code 本体がセッション外として許可を求めるか止めるため,効かないように見える): ① 作業場所に加える: 各自の `.claude/settings.local.json` の `permissions.additionalDirectories` に絶対パスで書く(そのセッションだけなら `/add-dir <パス>`.詳細は [公式ドキュメント「Working directories」](https://code.claude.com/docs/en/permissions#working-directories)),② 書き換えを許可する: `allow_write` に書く + - ① はパソコンごとにパスが違うので git の対象外の `settings.local.json` に,② はリポジトリに入れて共有する(相対パスで書ける).読ませるだけなら ① だけでよい + - 許可するのは配下だけで,指定したディレクトリ自体の削除・移動は許可しない.禁止リスト(`deny_read`)に当たるパスは `allow_write` より優先して拒否する + - 許可ディレクトリ・操作対象ともリンクを解決した実パスで判定するので,許可ディレクトリの外へのリンク越しの操作は許可しない.実際の対象を文字列から確定できないパス(波括弧・`..` を含む,途中の階層にワイルドカードを含む等)はメモのフォルダと同じく許可しない.最後の要素だけのワイルドカード(`<許可ディレクトリ>/*` 等)は許可する + - 設定では `../sibling-repo` と書けるが,コマンド中で `../sibling-repo/...` と書くと `..` を含むため拒否される.Claude に操作させるときは絶対パスで書くか,`cd` で許可ディレクトリに移動してから相対パスで操作する + - 次の指定は無視して警告を出す: 配列でない(`allow_write` 全体)・文字列でない要素,ワイルドカード・波括弧を含む,`~user` 形式,存在しない・ディレクトリでない,ファイルシステムのルート,ホームディレクトリそのもの・その祖先,リポジトリ自身・その祖先(`..` だけの指定等),`~/.claude` の中.`deny_read` が不正な場合や設定ファイルが壊れている場合は `allow_write` も空として扱う + - 読み取り: Read・Glob・Grep,Bash・PowerShell の読み取りはリポジトリ外も許可する.**読んだファイルの内容は Claude の API に送信される**ため,リポジトリ外を読ませることの是非はプロジェクトごとに判断する.読ませたくない場所(`~/.ssh`・`~/.aws`・他案件のフォルダ等)は `.claude/repo-access.json` の禁止リスト `deny_read` に書く(任意.無ければ禁止リストは空).禁止リストに該当するパスは読み取り・書き込みとも拒否する.Glob・Grep・再帰的に読むコマンド(`grep -r`・`find`・`Get-ChildItem` 等)は,リポジトリ外の検索起点の配下に禁止パスがある場合も拒否する ```json { - "deny_read": ["~/.ssh", "~/.aws", "C:/Users/me/source/other-project", "secrets"] + "deny_read": ["~/.ssh", "~/.aws", "C:/Users/me/source/other-project", "secrets"], + "allow_write": ["../sibling-repo", "~/work/data-repo"] } ``` - - パスは絶対パス・`~` 始まり・リポジトリルート相対で書く.ファイルが壊れている(JSON として読めない等)場合は禁止リストを空として扱い,警告を出す + - `deny_read`・`allow_write` とも,パスは絶対パス・`~` 始まり・リポジトリルート相対(`../` で隣のフォルダを指せる)で書く.ファイルが壊れている(JSON として読めない等)場合は禁止リストを空として扱い,警告を出す(警告を書けないときは後述の想定外の例外として拒否する) - プロジェクト所有のファイルであり,テンプレートには含まれないため `/sync-template` で上書きされない.人によって守りたい場所が違う場合は各自の場所も含めて書くか,各自が後述の `permissions.deny` を `.claude/settings.local.json` に書く - - **限界**: コマンド文字列の静的解析のため原理的に完全には防げない.変数展開(`$DIR` 等.`~`・`$HOME`・`$env:USERPROFILE`・一時ディレクトリ系以外は解決しない),スクリプトファイル経由の操作,`xargs` 等パイプで渡したパス,エイリアス・関数,エンコードされたコマンド,未対応コマンドによる削除・上書き,インライン実行中の未対応の書き方(変数に入れたパス・Perl の `open` 等)は検出できない.既存かどうかはフック実行時点で判定するため,同じコマンド内で先に作ったファイルを上書きする場合等は許可される.逆に,インライン実行で削除系の呼び出しとリポジトリ外のパス(文字列やコメント中のものも含む)が同時に現れると,削除対象でなくても拒否されることがある.`cmd /c` の引数のうち `/opt` のように `/` の後に要素が 1 つだけのパスは,スイッチ(`/mir` 等)と区別できないため判定の対象外になる.また Glob・Grep を省略した検索起点(リポジトリ内)では,リポジトリ内の禁止パスを含む検索までは止めない - - **拒否されたときの運用**: リポジトリ外の削除・上書きの最終判断は人間が持つ.フックに拒否されても,Claude は別の書き方(変数経由・スクリプトファイル経由・`python -c` 等)で迂回しない.必要な操作であれば,Claude は実行するコマンドをそのまま提示して依頼するので,ユーザーが内容を確認し,プロンプトで `! <コマンド>` として自分で実行する.フックが検出できない書き方であっても,リポジトリ外のファイルの削除・上書き(既存ファイルの移動を含む)は同じ扱いとする(`CLAUDE.md`「手動確認が必要な作業」).禁止リストによる読み取りの拒否は「読ませたくない場所」の指定なので,Claude は迂回して読まず,`!` での実行依頼もしない + - 判定できないときは拒否する: 判定中の想定外の例外,JSON として読めない入力,オブジェクトでない JSON,Bash・PowerShell のコマンド文字列に NUL がある場合,コマンドや書き込み先のパスが文字列でない場合.想定外の例外の拒否理由には例外の種類を示し,トレースバックは stderr に出す.フックの不具合の可能性があるので,拒否が続くときは `.claude/hooks/restrict_repo_access.py` を確認する.この拒否でも別の書き方で迂回しない + - **フック自体が動けないとき**: 判定の前の失敗(フックの構文エラー・import 時の例外)とフックのタイムアウトでは,ツールの実行を止められない.Claude Code は終了コード 2 以外の失敗をブロックとして扱わないため.Python が見つからない場合は `run_python.sh --fail-closed` が拒否する + - **限界**: コマンド文字列の静的解析のため原理的に完全には防げない.Write・Edit 等のパスに NUL がある場合は OS で結果が分かれる(Windows は通常どおり判定して許可されることがあり,Linux・macOS は例外として拒否する).変数展開(`$DIR` 等.`~`・`$HOME`・`$env:USERPROFILE`・一時ディレクトリ系以外は解決しない),スクリプトファイル経由の操作,`xargs` 等パイプで渡したパス,エイリアス・関数,エンコードされたコマンド,未対応コマンドによる削除・上書き,インライン実行中の未対応の書き方(変数に入れたパス・Perl の `open` 等)は検出できない.既存かどうかはフック実行時点で判定するため,同じコマンド内で先に作ったファイルを上書きする場合等は許可される.`cmd /c` のコマンドとインライン実行のコードは波括弧・ワイルドカード・リンクの展開の対象外で,`**` は 1 階層のワイルドカードとして扱う.ワイルドカードの一致が多すぎると残りは調べず,基点がリポジトリ内・一時ディレクトリならそのまま許可する.`pushd -n `(実際には移動しないが移動として扱う),サブシェル内の `pushd`/`popd`,PowerShell 5.1 の `Push-Location -`(7 系の挙動で追跡する)では実際の対象とずれることがある.クォート内の波括弧・ワイルドカードも展開するので,実害のない操作が拒否されることがある.逆に,インライン実行で削除系の呼び出しとリポジトリ外のパス(文字列やコメント中のものも含む)が同時に現れると,削除対象でなくても拒否されることがある.`cmd /c` の引数のうち `/opt` のように `/` の後に要素が 1 つだけのパスは,スイッチ(`/mir` 等)と区別できないため判定の対象外になる.また Glob・Grep を省略した検索起点(リポジトリ内)では,リポジトリ内の禁止パスを含む検索までは止めない + - **拒否されたときの運用**: リポジトリ外の削除・上書きの最終判断は人間が持つ.フックに拒否されても,Claude は別の書き方(変数経由・スクリプトファイル経由・`python -c` 等)で迂回しない.必要な操作であれば,Claude は実行するコマンドをそのまま提示して依頼するので,ユーザーが内容を確認し,プロンプトで `! <コマンド>` として自分で実行する.フックが検出できない書き方であっても,リポジトリ外のファイルの削除・上書き(既存ファイルの移動を含む)は同じ扱いとする(`CLAUDE.md`「手動確認が必要な作業」.今のプロジェクトの Claude メモのフォルダの配下と `allow_write` に書いたディレクトリの配下は例外).禁止リストによる読み取りの拒否は「読ませたくない場所」の指定なので,Claude は迂回して読まず,`!` での実行依頼もしない - **`!` で実行したコマンドにはこのフックはかからない**(実機で確認済み).Claude が提示したコマンドは,削除・上書きの対象が意図どおりかを確認してから実行する - 確実性が必要な場合は以下を併用する - OS のフォルダ権限(Claude Code を実行するユーザーに守りたいフォルダの書き込み権限を与えない.dev container ならリポジトリだけをマウントする)