diff --git a/.claude/hooks/restrict_repo_access.py b/.claude/hooks/restrict_repo_access.py
index 218d408..5d0bdbb 100644
--- a/.claude/hooks/restrict_repo_access.py
+++ b/.claude/hooks/restrict_repo_access.py
@@ -30,8 +30,28 @@
許可ゾーン(リポジトリ外でも削除・上書きを許可する):
- システム一時ディレクトリ(/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 の親の階層に [ や { があると,メモのフォルダの許可は効かない(安全側の制限)
+
+パスの展開と解決(削除・上書き・作成の対象について):
+- 波括弧は Bash 系の方言でだけ展開して,元の文字列のままの判定に加えて展開後の各パスも判定する
+ (PowerShell・cmd.exe は波括弧を展開しない).展開数が上限を超えた語が削除・上書きの対象なら拒否する
+- ワイルドカードはフック実行時に実際に展開して,一致した各パスも判定する(Bash・PowerShell.
+ 一致が無ければ文字列のままの判定だけ)
+- `..` は文字列の正規化に加え,OS と同じ順に要素をたどる解決(リンク・ジャンクションを解決してから
+ 親に上がる)でも判定する.どちらかでリポジトリ外や既存ファイルに当たれば拒否・上書き扱いにする
+- cd - / pushd - / Set-Location - / + / Push-Location - / + は,同じコマンド内で追跡できる場合だけ移動先を解決する
限界(重要):
本フックはコマンド文字列の静的解析であり,原理的に完全には防げない.変数展開
@@ -40,6 +60,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,10 +79,12 @@
from __future__ import annotations
+import fnmatch
import json
import os
import posixpath
import re
+import stat
import sys
import tempfile
@@ -93,6 +123,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 +288,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 +394,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 +427,281 @@
if cwd is None:
return UNKNOWN
token = os.path.join(cwd, token)
- return os.path.normpath(token)
+ return token
+
+
+def is_ambiguous_for_memory(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 +715,10 @@
# 判定コンテキスト
# ---------------------------------------------------------------------------
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) -> None:
self.repo_root = repo_root
self.deny_read = deny_read
+ self.transcript_path = transcript_path
def denied_entry(self, path: str) -> str | None:
"""path が禁止リストのいずれかの配下なら,その禁止エントリを返す."""
@@ -387,8 +739,31 @@
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_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_for_memory(path) or (raw is not None and is_ambiguous_for_memory(raw)):
+ return False
+ return self.is_inside_memory(path)
def deny_read_message(target: str, entry: str) -> str:
@@ -701,6 +1076,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_for_memory(dest + "/"): # 末尾に区切りを足して最後の要素も途中の階層として見る
+ self.ambiguous_cd = True
def normalize_literal(literal: str) -> str:
@@ -891,15 +1274,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 +1314,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 +1424,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 +1438,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 +1465,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 +1494,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 +1649,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 +1717,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 +1736,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 +1751,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 +1788,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 +1811,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 +1838,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 +1858,22 @@
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) -> 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))
-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) -> 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))
def glob_base(pattern: str) -> str:
@@ -1415,17 +1903,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
@@ -1455,7 +1944,7 @@
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"))
if tool_name in ("Bash", "PowerShell"):
analyzer = analyze_bash if tool_name == "Bash" else analyze_powershell
diff --git a/.claude/hooks/tests/test_hooks.py b/.claude/hooks/tests/test_hooks.py
index 85b42c9..f4f9c21 100644
--- a/.claude/hooks/tests/test_hooks.py
+++ b/.claude/hooks/tests/test_hooks.py
@@ -846,19 +846,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 +1744,2036 @@
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)
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/.claude/template-sync-sha b/.claude/template-sync-sha
index 9c5d6ac..a3de4a2 100644
--- a/.claude/template-sync-sha
+++ b/.claude/template-sync-sha
@@ -1 +1 @@
-f3164fcaa5298f2a8fc869e376597f6e23501e76
+524d2b57b2da8a5caa5c8041941e1f23e02ae671
diff --git a/CLAUDE.md b/CLAUDE.md
index f3c13c5..9a5a5b5 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -61,6 +61,7 @@
- 例外: `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` 等)は対象外
- 実機・ブラウザでの動作確認(`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..5099cc7 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"
@@ -78,7 +78,13 @@
- 削除(常に拒否): 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` 等は削除・上書きも許可する
+ - パスの展開と解決: 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` の禁止リストは本許可より優先する
- 読み取り: Read・Glob・Grep,Bash・PowerShell の読み取りはリポジトリ外も許可する.**読んだファイルの内容は Claude の API に送信される**ため,リポジトリ外を読ませることの是非はプロジェクトごとに判断する.読ませたくない場所(`~/.ssh`・`~/.aws`・他案件のフォルダ等)は禁止リスト `.claude/repo-access.json` に書く(任意.無ければ禁止リストは空).禁止リストに該当するパスは読み取り・書き込みとも拒否する.Glob・Grep・再帰的に読むコマンド(`grep -r`・`find`・`Get-ChildItem` 等)は,リポジトリ外の検索起点の配下に禁止パスがある場合も拒否する
```json
@@ -89,8 +95,8 @@
- パスは絶対パス・`~` 始まり・リポジトリルート相対で書く.ファイルが壊れている(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 は迂回して読まず,`!` での実行依頼もしない
+ - **限界**: コマンド文字列の静的解析のため原理的に完全には防げない.変数展開(`$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 メモのフォルダの配下は例外).禁止リストによる読み取りの拒否は「読ませたくない場所」の指定なので,Claude は迂回して読まず,`!` での実行依頼もしない
- **`!` で実行したコマンドにはこのフックはかからない**(実機で確認済み).Claude が提示したコマンドは,削除・上書きの対象が意図どおりかを確認してから実行する
- 確実性が必要な場合は以下を併用する
- OS のフォルダ権限(Claude Code を実行するユーザーに守りたいフォルダの書き込み権限を与えない.dev container ならリポジトリだけをマウントする)