Skip to content

feat(hooks): judge shell function bodies instead of asking for every function - #200

Closed
furedea-agent[bot] wants to merge 45 commits into
mainfrom
feat/allow-dynamic-syntax-inside-sandbox
Closed

furedea-agent[bot] wants to merge 45 commits into
mainfrom
feat/allow-dynamic-syntax-inside-sandbox

Conversation

@furedea-agent

@furedea-agent furedea-agent Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

シェル関数を定義しただけで一律「要確認」にしていたのをやめ,関数本体の各コマンドを定義した位置で判定する.あわせて,文字列を後でコードとして実行する,またはコマンド名の実体を差し替える構文(trap・alias・builtin eval・hash -p・aliases[...] などの特殊パラメータ)を閉じる.
判断事項:ADR-0015 の規則 2(同じコマンドで定義した関数・エイリアスは確認)と食い違う.関数の部分は adr レーンの新 ADR で置き換える想定.エイリアスは引き続き確認とする.

flowchart TD
  C[コマンド] --> P{shfmt で解析できる?}
  P -- いいえ --> ASK[確認]
  P -- はい --> Z{エイリアス・関数・コマンドパスを定義する?<br/>alias x=…, aliases[..]=, hash -p, set -A functions …}
  Z -- はい --> ASK
  Z -- いいえ --> B[関数本体・ループ・置換の中も含めて全 CallExpr を列挙]
  B --> T{trap / eval の文字列}
  T -- 動的 --> ASK
  T -- リテラル --> B
  B --> I{関数本体のシェルが呼び出し側の入力を読む?<br/>後で別ディレクトリで動く相対スクリプト?}
  I -- はい --> ASK
  I -- いいえ --> R[禁止ルール・許可ルールで各コマンドを判定]
  B --> D{コマンド名が実行時まで不明?}
  D -- はい --> ASKG[guard_git が確認(既存)]
Loading

方針変更:単純な関数本体だけを判定する(985a3a3)

関数本体の抜け道を個別に塞ぐ対策は収束しなかった.塞ぐたびに,レビューが新しい抜け道を見つけた(eval・trap の文字列,heredoc,unset の添字評価,算術式,名前参照,zsh の修飾子,入れ子の定義など).そこで個別の対策をやめ,許可する範囲を絞って安全側に倒す.

  • 関数本体の中身を各コマンドとして判定して許可するのは,本体が許可リストに収まる場合だけにする.許可リストに入るものは次のとおり.
    • コマンド,&&・||・パイプ,if・case・for・while,サブシェル
    • 算術比較を含まない [[ ]]
    • オプションなしでリテラル名の local
    • 引用と単純な展開からなる語
  • 次のどれかを含む本体は,この PR より前と同じく関数ごと確認になる.
    • heredoc,入れ子の関数定義
    • 算術式($(( ))・(( ))・let・算術比較の [[ ]]),添字やスライス(${a[i]}・${x:0:1}・a[i]=)
    • 追記代入(+=)
    • local 以外の宣言,オプション付きの local
    • 値を再評価する組込みや,名前で代入する組込み:unset・eval・trap・source/.・alias・builtin・command・hash・read 系・printf -v・getopts・exec・zsh の noglob/nocorrect や setopt など
  • 許可リストで不要になった個別の対策は消した.消したのは,算術の文脈での引数参照,heredoc での引数展開,名前で代入する組込みへの引数のコピー,宣言の属性,eval・trap の文字列に対する引数変更の検査である.
  • 単純な本体のうち引数の書き直しで追えない形(修飾子付きの展開,置換の中での引数参照,コピーの再代入など)は,これまでどおり確認になる.
形 変更前 変更後
mk() { mkdir -p "$1"; cat > "$1/rule.yml"; }; mk a <<EOF …(11/14 の実例 2 件) 確認 許可
f() { gh pr merge 1; }; f 確認 確認(関数本体は provider から見えない扱いにして ask 接頭辞を適用)
f() { git commit --no-verify -m x; }; f 確認 禁止
f(){ find . "$@"; }; f -delete(呼び出しの引数で本体に禁止オプションを渡す) 確認 禁止(本体を各呼び出しの引数で書き直して再判定)
f() { "$@"; }; f gh pr merge 1 確認 確認(guard_git:コマンド名が実行時まで不明)
f(){ sh; }; f <<EOF … / echo … | f 確認 確認(関数本体のシェルが呼び出し側の入力を受け継ぐ)
set -- "gh pr merge 1"; builtin eval "$1" 許可(既存の穴) 確認
trap "$X" EXIT / trap 'gh pr merge 1' EXIT / zsh の trap '-x; gh pr merge 1' EXIT 許可(既存の穴) 確認
trap 'git commit --no-verify -m x' EXIT 許可(既存の穴) 禁止
alias g=gh の次の行で g pr merge 1 許可(既存の穴) 確認(エイリアス定義はすべて確認)
aliases[g]=gh / BASH_ALIASES[g]=gh / commands[gh]=./evil / hash -p ./evil gh / printf -vBASH_ALIASES[g] gh / declare -n x=BASH_ALIASES 許可(既存の穴) 確認
ループ・関数・trap・eval の中の cd の後で相対パスのスクリプトを sh < で読む 一部 許可(既存の穴) 確認
trap 'echo done' EXIT / alias / hash -r / for f in *.py; do ruff check "$f"; done 許可 許可
for i in …; do eval "echo \$K_$i"; done(11/14 の実例) 確認 確認(eval の動的スクリプト)

検証

  • uv run pytest:6071 passed, 1 skipped(985a3a3 でのローカル実行)
  • ruff check / ruff format --check / ty check / deptry / vulture:成功(lefthook の pre-commit も成功)
  • 新規 tests/hooks/test_dynamic_syntax.py(208 件):関数本体を呼び出しの引数で再判定($@・$1・${1}・$*・引用・shift・eval・trap・関数からの呼び出し・再定義・引用した関数名・id=$1 のコピー),追えない形(演算子付きの展開・for a;・set --・getopts・argv)の確認,関数・ループ・置換の許可,関数内の外部効果のある呼び出しの確認,実行時に決まるコマンド名の確認(guard_git),trap/alias/builtin eval/hash/特殊パラメータの確認と禁止,関数・ループ・trap・eval と cd の組み合わせ,関数本体による入力の継承,2026-11-14 のログにある 3 件(関数 2 件は許可,eval 1 件は確認のまま)
  • 既存のすり抜け対策テストはすべて通過.関数を一律確認と想定していた既存テストは新しい判定に合わせて移動した(test_allowed_command.py・test_forbidden_command.py・test_guard_git.py).f(){ git reset --hard; } は確認から禁止に変わる(より厳しくなる方向)
  • 変更した判定条件に手動で変異を約 40 個入れた:生き残った変異は等価なもの(trap の動作 - の判定と -- 後の打ち切りで,実行され得ない形にしか影響しない)だけ.等価でない生き残りはテストを追加するか条件を簡素化して解消した.プロジェクトに mutmut が入っていないため手動で実施した
  • Red→Green:追加した 48 件のテスト(後述の未解決スレッド 8 件,以前フォローアップに回したセキュリティ項目,自動セキュリティレビューの 2 件)は,修正前に失敗することを確認してから修正した
  • 共有の verify(verification_session.py verify)は,サンドボックスが記録ディレクトリの .lock への書き込みを拒否したため実行できなかった.代わりに上記のチェックを個別に実行した

レビュー対応

  • 未解決スレッド 8 件(b44f532 で全件修正):

    • builtin / command / eval を経由した shift・set
    • 関数宣言に付いたリダイレクト
    • eval --
    • コピー変数の再代入と連鎖コピー
    • for a in "$@"
    • 本体のリダイレクト先の書き直し(呼び出し側で展開したチルダを保つ)
    • 組込みやラッパーを上書きする関数名
    • eval・trap の中のシェルが受け継ぐ標準入力
  • 以前フォローアップに回したセキュリティ項目もすべて修正し,フォローアップ節は削除した:

    • BASH_FUNC_ で始まる語を確認にした
    • IFS について,引用・エスケープ・ブレース・$'...' の綴り,宣言の glob 名,名前参照で変える形を確認にした
    • 引用なしの引数を持つ関数がある場合,算術式・read 系・printf -v・source・eval・trap があれば確認にした
  • 自動セキュリティレビュー(b44f532 の前):eval 本体の名前を利用者が騙れる問題を,実行ごとの nonce で塞いだ.$'I\x46S' の綴りも確認にした

  • claude-review(P2):接頭辞だけのエイリアスがすり抜ける → エイリアス定義はすべて確認にした

  • codex-review(P1×3):関数呼び出し時の作業ディレクトリ,関数本体による標準入力の継承,trap 実行時のディレクトリ → いずれも修正し,テストを追加した

  • 2 回目の再レビュー(df65653):zsh の trap '-x; …'(P2),関数の引数経由で禁止オプションを渡す形(P1)→ 修正し,テストを追加した

  • 3 回目の再レビュー(9cd9dc1):trap の件は 2 回目と同じ指摘で,上の修正で解消した.関数宣言に付いたリダイレクト(P1)は新しい指摘だったため,上限ルールに従いフォローアップに回した(下記)

  • 4・5 回目(42719a7・60e5ee6.2 回目の指摘への修正をプッシュしたことで走った):set のオペランドと ${1:--delete} は 60e5ee6 で修正済み."$@" の引数境界は 60e5ee6 では再現しない(deny になる).それ以外は上限ルールに従いフォローアップに回した(下記)

  • 自動セキュリティレビュー(60e5ee6 の後):id=$1 の後に同じ変数へ再代入する形と,builtin set / command set 経由での位置パラメータの置き換え → フォローアップに回した(下記).同じ式内の変数代入を追わないのは ADR-0015 の既知の穴と同じ種類

  • 自動セキュリティレビュー:ループ本体・trap・eval の中の cd,alias -- -g=…,zsh/bash の特殊パラメータ(属性付きオプション・名前参照・実行時に決まる名前を含む),hash -rp,関数本体のシェルが本体の外から受け取る入力 → 修正し,テストを追加した

Limits

安全側の誤検知(不要な確認).すり抜けではないので直さず,ここに記録する.

  • 許可リストの外の構文を含む関数本体は,中身が安全でも関数ごと確認になる.例:
    • heredoc を使う f(){ sh <<'EOF' … EOF }
    • f(){ . ./script.sh; },builtin・command を使う本体,本体内の trap 'echo done' EXIT
    • 算術比較の [[ $n -eq 0 ]],local -r,export・declare を使う本体
  • 関数本体が引数(またはそのコピー)を,コマンド置換・プロセス置換・算術式・ヒアドキュメント・修飾子付きの展開・zsh の展開フラグや修飾子($1:l,$@[2])の中で読むと,出力を評価できないため一律に確認になる.例:f(){ find . <(printf %s "$1"); }.プロセス置換は /dev/fd/N のパスにしかならず無害だが,それでも確認になる
  • 引数を読む関数があるソースに,次のどれかがあると確認になる:
    • フック変数名(PROMPT_COMMAND など)
    • 実行時に決まるプログラム名
    • コールバックを取る組込み(mapfile -C など)に渡した,実行時に決まる語
    • 関数名をコマンド以外の語として使う箇所(関数名と同じ短い単語を,無関係なコマンドの引数に使った場合も含む)
  • コピー変数の名前が関数本体の外で $name として現れる場合,また export・set -a・setopt などがソースのどこかにある場合は,コピーが漏れ得るとみなして確認になる
  • コピーを持つ本体が 2 回以上 shift する場合,またはループの中で shift する場合は確認になる
  • 引数を読む関数があり,引数を引用なしで展開する本体がある場合,ソースに算術式・read 系・printf -v・source・eval・trap があれば,IFS が変わり得るとして確認になる
  • 本体にシェルの呼び出しがあり,引数をパイプやリダイレクトで流す場合は確認になる.呼び出しの語のどれかがシェル名であれば,シェルとみなす(grep bash のような無関係な語でも)
  • sh -c '…' _ 引数 や sh -s -- 引数 のように,渡した引数をスクリプトが読み得る場合(スクリプトに $ があるだけでも)は,禁止の判定を済ませたうえで確認になる
  • 1 つのコマンドの再判定は,入れ子の解析 400 回までとし,それを超えると確認になる
  • ループ・関数・trap の本体で,ソースのどこかに cd・pushd・popd・chdir・zsh の auto_cd・setopt・emulate,または実行時に決まるプログラム名があると,相対パスのスクリプトを読む形が確認になる
  • 引用した "$1" などの代わりに,呼び出し側で展開され得る語(glob・brace・実行時の値)を渡すと確認になる
範囲・前提・フォローアップ
  • 共有モジュールの変更(最小限):agents/hooks/lib/shell_syntax.py(FuncDecl の受理,関数本体を provider から見えない扱いにする,遅延実行される本体のディレクトリ),shell_wrappers.py(builtin をラッパーとして追加),shell_input.py(関数本体のシェルの入力の継承,input_scripts の移動).新規の code_text.py(eval/trap/alias/hash と特殊パラメータ)と function_calls.py(関数本体を呼び出しの引数で書き直す)は,shell_syntax.py の 500 行上限に収めるために切り出したもの.pyproject.toml には deptry 用にこの 2 モジュールを登録した.gh の分類と command_permissions.json には触れていない
  • $CMD のような動的なコマンド名は,guard_git が既に一律確認にしている(既存テスト「run-time program names, which the Git guard judges」).guard_command で重複して確認することはしない
  • source / . のスクリプトファイルは,bash script.sh がファイルを読まないのと同じ既存の設計に揃え,対象外とした
  • 関数内の rm は,rm が確認の接頭辞であるため(bash -c 'rm …' と同じく)確認のまま.rm の扱いは prefixes レーンが担当する
  • ADR-0015 の規則 2 の置き換えは adr レーンが担当する

Refs #197

🤖 Generated with Claude Code

@furedea

furedea commented Nov 14, 2026

Copy link
Copy Markdown
Owner

@codex review

@chatgpt-codex-connector

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

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-17T04:09:12.703672Z 423d11a Manual request
ℹ️ About Codex in GitHub

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

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

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

Comment thread agents/hooks/lib/code_text.py Resolved
@github-actions

Copy link
Copy Markdown

レビュー概要

ブロッキング(P0/P1)の指摘はなし.P2 が 1 件.

  • P2 agents/hooks/lib/code_text.py:alias の値を単体のスクリプトとして判定しているため,接頭辞だけの alias(alias g=gh の次の行に g pr merge 1)では許可ルールも禁止ルールもすり抜ける.以前からある穴で,この PR が塞いだのは値が完結した alias だけ.

確認した点:関数本体を provider から見えない扱いにすると ask 接頭辞が適用される."$@" や $1 は spreading・dynamic として扱われる.関数内の git commit "$@" は guard_git の OPTION_VERBS 判定で確認になる.trap と alias のオプション読み飛ばし,builtin のラッパー化も問題なし.

注:サンドボックスの制約でプローブのスクリプトを実行できなかったため,コードを読んで静的にレビューした.

🤖 Generated with Claude Code

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 36773d0e42

ℹ️ About Codex in GitHub

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

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

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread agents/hooks/lib/shell_syntax.py Resolved
@furedea

furedea commented Nov 14, 2026

Copy link
Copy Markdown
Owner

@codex review

Comment thread agents/hooks/lib/shell_syntax.py Resolved
@github-actions

Copy link
Copy Markdown

Review summary

Blocking (1):

  • P1: A function body's bare `sh`/`bash` reads stdin that comes from the call site, which the hook doesn't inspect. Examples: `f(){ sh; }; f <<EOF … EOF`, `echo '…' | f`, `f < script.sh`. Before this PR these asked because every function did; now they appear to pass, deny rules included (e.g. `git commit --no-verify`). See the inline comment.

Checked and found OK:

  • `cd`/`pushd` shadowed by a function, or a `cd` inside a function body: directory tracking keeps earlier directories reachable, so relative script reads still see the original directory.
  • `trap` operand parsing (`--`, `-p`, `-`, single operand, computed action), `alias` definitions vs lookups, and `builtin eval` through the new `builtin` wrapper.
  • Function arguments forwarded through `"$@"` work the same as a top-level variable: guard_git asks, and `gh` with run-time arguments asks.

I couldn't run probe tests in this sandbox, so the finding comes from reading the code.

🤖 Generated with Claude Code

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 889eb21437

ℹ️ About Codex in GitHub

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

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

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread agents/hooks/lib/shell_syntax.py Resolved
Comment thread agents/hooks/lib/code_text.py Resolved
@furedea

furedea commented Nov 14, 2026

Copy link
Copy Markdown
Owner

@codex review

Comment thread agents/hooks/lib/code_text.py Resolved
@github-actions

Copy link
Copy Markdown

レビュー概要

関数本体を定義位置で判定する変更と,trap / alias / builtin eval の中身を解析する変更を読んだ.ディレクトリの追跡は和集合を保つため,呼ばれない関数内の cd も問題にならない.deferred_calls は関数とループの本体を対象にしており,相対パスのスクリプトの読み込みは確認になる.builtin をラッパーに加えた変更と,zsh のコード定義パラメータの拒否も意図どおりに見える.

指摘は 1 件(ブロッカーなし):

  • P2 code_text._trap_scripts:先頭が - の単語をすべてオプションとして読み飛ばしている.zsh の trap はオプションを解釈しないため,trap '-x; gh pr merge 1' EXIT が許可されてしまう(bash でも trap -"$X" ... と X=- の組み合わせで同じことが起きる).詳しくはインラインコメントを参照.

🤖 Generated with Claude Code

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: df656531d1

ℹ️ About Codex in GitHub

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

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

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread agents/hooks/lib/shell_syntax.py Resolved
@furedea

furedea commented Nov 14, 2026

Copy link
Copy Markdown
Owner

@codex review

Comment thread agents/hooks/lib/code_text.py Resolved
@github-actions

Copy link
Copy Markdown

Review summary

1 blocking finding (P1)

  • P1 agents/hooks/lib/code_text.py:59: _trap_scripts skips any first word that starts with - as if it were an option. So trap '-x; gh pr merge 1' EXIT returns no script and is allowed. bash rejects this form, but zsh runs it as the trap action, so it gets past both the ask rules and the deny rules (for example trap '-x; git commit --no-verify -m x' EXIT).

I also looked at these and found no problems:

  • Function bodies are hidden from provider rules.
  • A shell inside a function body reading the caller's input (in_functions) asks.
  • A directory change inside a loop, function, trap, or eval adds an unknown directory, so later relative scripts ask.
  • builtin is unwrapped, so builtin eval, builtin trap and builtin alias are judged like the plain forms.
  • CODE_PARAMETERS catches assignments to and expansions of alias and function tables.

The new tests cover the changed behavior well, apart from the trap case above.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 9cd9dc10ee

ℹ️ About Codex in GitHub

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

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

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread agents/hooks/lib/shell_syntax.py Resolved
@furedea

furedea commented Nov 14, 2026

Copy link
Copy Markdown
Owner

@codex review

Comment thread agents/hooks/lib/shell_syntax.py Resolved
Comment thread agents/hooks/lib/code_text.py Resolved
@github-actions

Copy link
Copy Markdown

レビュー要約

ブロッキングな指摘(P0/P1)はありません.

  • P2(agents/hooks/lib/shell_syntax.py):eval・trap のスクリプトは単独のソースとして解析されます.そのため中のシェルが呼び出し側の標準入力(サブシェルのリダイレクトやパイプ)を読む形がすり抜けます.例:( trap sh EXIT; : ) <<EOF や echo ... | builtin eval sh.関数本体で追加した入力の継承の扱いを,eval・trap にも広げることを提案します.
  • P3(agents/hooks/lib/code_text.py):BASH_FUNC_<name>%% 環境変数による関数の取り込み(既存の穴)が,コマンド名の差し替えの検査対象に入っていません.

確認したが問題なしと判断した点:

  • 関数本体の判定位置と,provider から見えない扱いによる ask 接頭辞の適用
  • $@ の言い換え:引用内では隠れたオプションとして扱われ,ask になる
  • 再帰関数:深さの上限で確認に倒れる
  • 関数定義へのリダイレクト
  • 遅延実行時の cd によるディレクトリの扱い

なお,実行環境の制約でガードを実際に動かす検証はできていません.指摘はコードを読んで追ったものです.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 42719a7d63

ℹ️ About Codex in GitHub

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

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

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread agents/hooks/lib/function_calls.py Resolved
Comment thread agents/hooks/lib/function_calls.py Resolved
@furedea

furedea commented Nov 14, 2026

Copy link
Copy Markdown
Owner

@codex review

Comment thread agents/hooks/lib/shell_syntax.py Resolved
@github-actions

Copy link
Copy Markdown

Review summary

1 blocking finding (P1), posted inline:

  • P1 agents/hooks/lib/shell_syntax.py:27: redirections attached to a function declaration (f(){ cat; } < ~/.ssh/id_rsa; f, f(){ echo x; } > ~/.bashrc; f) are not passed to the body's calls, so the secret-path and write-target checks never see them. These commands used to ask; now they look like they would be allowed. The PR lists this as a follow-up, but this PR is what opens it, so it should be fixed (or such declarations should ask) before merge, with tests.

I also looked at how positional parameters are rewritten ($@, shift, copies, nested functions, functions called from eval or trap), the new code_text checks (eval, trap, alias, hash, special parameters), the stdin handling inside function bodies, and the directory tracking for deferred code. I found nothing else worth blocking on. A function can still hand an argument on through an array copy (local a=("$@")), but that becomes a run-time argument, which is the same existing limitation as a top-level a=(...), not something new here.

Note: the sandbox did not let me run the hook, so this finding comes from reading the code, not from a reproduction.

🤖 Generated with Claude Code

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 60e5ee64a0

ℹ️ About Codex in GitHub

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

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

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread agents/hooks/lib/function_calls.py Resolved
Comment thread agents/hooks/lib/function_calls.py Resolved
Comment thread agents/hooks/lib/function_calls.py Resolved
@furedea

furedea commented Nov 14, 2026

Copy link
Copy Markdown
Owner

@codex review

Comment thread agents/hooks/lib/function_calls.py Resolved
Comment thread agents/hooks/lib/shell_syntax.py Resolved
@github-actions

Copy link
Copy Markdown

Review summary

Two blocking findings (P1), both posted as inline comments:

  1. P1: a function can shift its arguments without the hook noticing (function_calls.py:42). The shift check only matches a call that starts with the word shift. builtin shift, command shift and eval shift get past it, as does eval 'set -- …' in _reassigns. Example: f(){ builtin shift; find . "$1"; }; f x -delete is allowed, but at run time it executes find . -delete.
  2. P1: redirections on a function declaration are not checked (shell_syntax.py:27). This is the regression the PR already lists as a follow-up. Now that FuncDecl is allowed, f(){ cat; } < ~/.ssh/id_rsa; f skips the secret-path check. It asked before this PR, so it should be fixed before merging.

The rest of the change (respelling function bodies with each call's arguments, the eval/trap/alias/hash handling, and inherited input for shells in function bodies) looks sound and is well tested. This was a static review: I couldn't run the tests in this environment.

@furedea

furedea commented Nov 16, 2026

Copy link
Copy Markdown
Owner

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7a5940327a

ℹ️ About Codex in GitHub

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

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

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread agents/hooks/lib/function_calls.py Resolved
Comment thread agents/hooks/lib/shell_input.py Resolved
@github-actions

Copy link
Copy Markdown

Review summary

Blocking findings (P0/P1): 0

  • P2 agents/hooks/lib/shell_input.py:273: unpassed raises before the nested script is parsed. So a deny inside sh -c '…$1…' _ args (for example bash -c 'git commit --no-verify -m "$1"' _ msg) is now only an ask, where it used to be denied. Nothing tests that this keeps being denied.

I read the changes to function_calls.py, respelling.py, code_text.py, variable_changes.py, body_calls.py, shell_input.py and shell_syntax.py. I looked for these bypasses and they all end in ask or deny:

  • function names built at run time or written with quotes
  • calls through noglob or -
  • "$*" and unquoted splitting in the rewritten calls
  • closing eval or trap text early
  • functions copied with functions -c
  • export -f with bash -c
  • function bodies that inherit stdin
  • a cd inside a function body or loop

I couldn't run the test suite here: shfmt isn't available in this environment, so this review is from reading the code only.

🤖 Generated with Claude Code

… special builtins

Judge a shell script that reads the arguments handed after it, then hold the
command for review, so a deny inside the script still stands. Track an
assignment before a special builtin such as export, which keeps its value, as
a copy that asks. Move pure helpers out of shell_syntax and function_calls to
stay under the file length limit.

Refs #197

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@furedea

furedea commented Nov 16, 2026

Copy link
Copy Markdown
Owner

@codex review

Comment thread agents/hooks/lib/function_calls.py Resolved
@github-actions

Copy link
Copy Markdown

レビュー結果(読み取りのみ)

P1 × 1

  • P1 agents/hooks/lib/function_calls.py with_definitions:関数定義のソース範囲は閉じ括弧 } で終わり,本体の中で始めたヒアドキュメントの本文が含まれない.そのため,eval・trap のテキストの前に定義を付けたとき,開いたままのヒアドキュメントが続く marker・CODE_BODY の包み・スクリプト本体を飲み込む.例えば f() { cat <<EOF; } を定義してから eval 'f⏎git commit --no-verify -m x⏎EOF⏎{ true' を実行すると,入れ子の判定に見えるのは cat と true だけになる.CODE_BODY の FuncDecl が消えるので,早期終了の検査も働かない.eval は許可リスト上で透過扱いのため,禁止・確認対象のコマンドが許可になり得る(この PR の前は FuncDecl があれば一律確認だった).

確認の範囲:このランナーには shfmt が無いため,上の例はコードと shfmt の構文木の End 位置の仕様から追ったもので,実際には実行していない.回帰テストを追加して確かめてほしい.

その他(関数本体の位置での判定,引数の書き直し,標準入力の継承,cd の扱い,trap・alias・hash・特殊パラメータの検出)は読んだ範囲で fail-closed になっており,ほかに指摘はない.

🤖 Generated with Claude Code

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 702065b7f5

ℹ️ About Codex in GitHub

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

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

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread agents/hooks/lib/function_calls.py Resolved
Comment thread agents/hooks/lib/function_calls.py Resolved
… one

Closing each way a body could hide what it runs did not converge, so a body is
judged command by command only when an allowlist accepts it: commands, lists,
pipes, branches, loops, subshells, tests without arithmetic, plain local
declarations, and words. A heredoc, a nested definition, arithmetic or a
subscript, an append, and any builtin that evaluates text again or assigns by
name make the body ask, as every function did before. Drop the per-case checks
the allowlist now covers.

Refs #197

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@furedea

furedea commented Nov 16, 2026

Copy link
Copy Markdown
Owner

@codex review

@github-actions

Copy link
Copy Markdown

レビュー結果(読み取りのみ)

ブロッキングな指摘はありません(P0: 0 / P1: 0 / P2: 0 / P3: 0).

確認した主な点:

  • 関数本体の判定:本体のコマンドを定義した位置で判定し,provider から見えない扱い(wrapper_depth + 1)にして ask 接頭辞が効くこと.RELIED_NAMES・シェルフック名・リダイレクト付き本体・単純でない本体は確認に倒れること.
  • 呼び出しの引数による書き直し:引用符の内側の "$1"/"$@"/"$*" は外側の引用符を閉じてから shlex で引用し直すため,引数の $(...) が生きたり,複数の語が 1 語にまとまったりしないこと.実行時の語や glob を渡すと確認になること.shift・コピー・$#・入れ子の関数呼び出し(g "$1" は呼び出し側で動的語として確認)も追えていること.
  • $"..." / $'...' は書き直されないが,関数がある場合は may_change_ifs で確認になること.
  • eval/trap のテキストを nonce 付きの関数で包む方式:テキストが関数を早く閉じる形(End != len(data))や関数定義を含む形は確認になること.定義を前に置いたテキストの呼び出しも書き直されること.
  • alias/hash -p/aliases[...]/BASH_CMDS/printf -v/nameref/BASH_FUNC_ を経由して名前の実体を差し替える形が確認になること.
  • 関数本体のシェルが呼び出し側の入力を受け継ぐ形(in_functions)が確認になること.
  • 削除・移動されたテストは,新しい期待値(許可・禁止)で test_allowed_command.py / test_guard_git.py / test_simple_function_bodies.py に移っていること.

補足:この環境では shfmt と pytest を実行できなかったため,コードを読んで静的に確認しました.

🤖 Generated with Claude Code

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 985a3a385a

ℹ️ About Codex in GitHub

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

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

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread agents/hooks/lib/body_calls.py Resolved
… bodies

Refs #197

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@furedea

furedea commented Nov 17, 2026

Copy link
Copy Markdown
Owner

@codex review

None,
*(
"File CallExpr BinaryCmd Subshell Block TimeClause DeclClause "
"File CallExpr BinaryCmd Subshell Block TimeClause DeclClause FuncDecl "

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1: the secret-commit guard can check the wrong repository once function definitions parse

guard_file.commit_locations walks the commands that parse() returns, in order, and calls reached_directories on each one. Calls inside a function body now come back at the point where the function is defined, not where it is called. A cd between the definition and the call is therefore never applied to the body's git commit:

c(){ git commit -m x; }; cd ../other-repo && c
  1. commit_locations sees git commit -m x first, while directories == (cwd,).
  2. It lists staged files only in the current repository and finds nothing.
  3. At run time, the commit actually runs in ../other-repo, so a staged secret there is committed and the deny never fires.

Before this PR, FuncDecl raised UnsupportedSyntaxError. That sent the command to unparsed_commit_locations, which raises UnplacedCommitError, so the hook asked.

The deferred / reachable handling added in parse() only affects the scripts a shell reads from its input. It does not change the command list that guard_file (or shell_paths.command_paths for glob expansion) walks.

Possible fixes:

  • Mark deferred commands on Command, and have commit_locations add None for them when the source moves directory.
  • Or keep commit_locations failing closed when the source has a FuncDecl.

Also, no test covers a commit inside a function body in the guard_file tests.

@github-actions

Copy link
Copy Markdown

Review summary (read-only)

Blocking findings: 1 (P1)

  • P1 agents/hooks/lib/shell_syntax.py: function bodies now parse, and their commands are listed where the function is defined. guard_file.commit_locations follows cd through the commands in that order, so in c(){ git commit -m x; }; cd ../other && c it checks staged files in the current directory instead of ../other. The secret-commit deny can therefore miss a staged secret. Before this PR the hook asked (UnplacedCommitError). No test covers this case.

Static review only: shfmt was not available in the review environment, so I could not run the tests or try out attack strings.

I also traced the function-argument rewriting (function_calls.py, respelling.py, body_calls.py) and the eval/trap/alias/hash handling in code_text.py. In those paths I found no bypass I could confirm.

🤖 Generated with Claude Code

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 423d11a881

ℹ️ About Codex in GitHub

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

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

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +25 to +26
"unset eval trap let source . alias unalias builtin command hash read mapfile readarray vared getopts "
"zparseopts declare typeset export readonly enable emulate setopt unsetopt noglob nocorrect - exec".split()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge fc を再評価する組込みとして拒否する

fc を含む関数本体が単純と判定されるため,例えば bash --noprofile --norc -ic 'history -s "find . victim"; f(){ fc -s "victim=-delete" find; }; f' は検査上 history と fc の呼出ししか見えませんが,実行時には find . -delete を再実行して禁止規則を回避します.help fc も fc -s について「COMMAND is re-executed after the substitution」と明記しているため,fc を REEVALUATING に加えてこの本体を明示確認へ戻してください.

Useful? React with 👍 / 👎.

@furedea-agent

furedea-agent Bot commented Nov 17, 2026

Copy link
Copy Markdown
Contributor Author

閉じる.関数本体を組み立て直して判定する方式は,4 回直しても新しいすり抜け(fc の再実行,unset の添字評価,heredoc での隠蔽,cd による検査位置のずれ)が出て収束しなかった.文字列からは実行時の効果を確定できず,#181 の完成形(隔離環境+型付き Gateway で外部効果を通す)ではこの層自体がなくなるため,ここに投資しない.関数・ループの承認削減は,GitHub Gateway(credential を sandbox の外へ)と worktree の復元保証ができた後に,解析なしで実現する(#181 の子 Issue で扱う).

@furedea-agent furedea-agent Bot closed this Nov 17, 2026
furedea added a commit that referenced this pull request Nov 18, 2026
## 概要

hook・ast-grep・`adr-check` がすでに強制している規則を Skill の文章から削除した(#169 の
C).違反時のメッセージで直し方が分かる規則だけを対象にし,文章の書き換えはしていない.

## 対応表

| 規則 | 強制している仕組み | 削除した文章の場所 | 直し方が分かるメッセージ |
| --- | --- | --- | --- |
| `pip` を使わない | `command_permissions.json` の deny `pip` |
`python-style/references/tooling.md` の「don't use `pip`」 | `Use
project-managed package tooling instead of pip.` |
| `uv pip install` 禁止 | 同 deny `uv pip` | 同 `Prohibited:` 行の `uv pip
install` | 同上 |
| pytest-asyncio 禁止 | `py_no_pytest_asyncio`(error) |
`python-style/references/testing.md` の「do not use `asyncio`」 | note に
`@pytest.mark.anyio` への置換を明記 |
| `BaseModel` を直接継承しない |
`py_pydantic_base_model_only_in_frozen_base`(error) |
`python-style/references/models.md` の「only the class named
`FrozenBaseModel` may inherit ...」 | note に `FrozenBaseModel` への置換を明記 |
| `git push -u` 禁止 | `guard_git.py`(`git_safety.sandbox_form_reason`) |
`development-cycle/references/delivery.md` の段落 | `push with git push
origin <branch> and open the pull request with gh pr create --head
<branch>` |
| bare force push・`+refspec`・main/master への force push 禁止 |
`guard_git.py`(`git_safety.push_reason`) | `delivery.md` の「Never use
bare `--force` ...」,`development-cycle/SKILL.md` の「rewrite published
history only with the leased force push ...」 | `force-push flag
detected`,`push target is 'main'`(残した `--force-with-lease
--force-if-includes` の手順が正解を示す) |
| `-S` での署名禁止 | `guard_git.py`(`sandbox_form_reason`) |
`development-cycle/references/commits.md` の「`-S`」 | `agent commits and
tags are unsigned; drop the signing option ...` |
| subject 末尾にピリオドを付けない |
`commitlint`(`.commitlintrc.yml`,`config-conventional` の
`subject-full-stop`;lefthook の commit-msg) | `commits.md` の「No trailing
period.」 | commitlint が規則名を出力 |
| `herdr agent start` に余分な引数を渡さない | `forbidden_commands.json`(`herdr
agent start ... --`,例外は Sonnet・Opus の medium のみ) |
`development-cycle/references/branches.md` の「pass exactly ... other
agent arguments ask」(実際は ask ではなく deny で,文章が食い違っていた) | deny の
justification が許可する形を示す.コマンド例も残している |

## 文章を残したもの

| 文章 | 理由 |
| --- | --- |
| Jev の model rules(`hooks/lint/model-rules/`),#227 の ADR 規則 | advisory
のため.昇格するまで残す |
| #200 の shell 関数本体の判定 | 閉じていて強制していない |
| `bash_local_underscore_prefix`(severity が error
でない),`strict-mode-header` など model-rules | advisory |
| `bash-style` の shebang | 規則は shebang がある file だけを見るので,無い場合は検出されない |
|
`go_mutex_field_documented`,`go_iota_enum_typed`,`py_dataclass_slots`(`frozen=True`
の判断を含む行) | 強制は片方(コメントの有無・型の有無・`slots`)だけで,残りは判断基準 |
| `github-actions-style` の permissions・timeout |
強制は有無だけで,「必要な権限・適切な時間」は判断基準 |
| `rs_no_follow_links`,`rs_no_mocking_library` の周辺 |
「明示的に必要でテスト済みなら許す」「mock より fake を優先」という判断基準 |
| `herdr --group` 禁止,gh・herdr の ask の条件(`gh api` の変数の quote など) |
`--group` のメッセージは `Herdr ownership actions need one simple direct Herdr
call` で直し方が伝わらない.ask は block ではない |
| `uv`・`pnpm`・`go.sum`・`Cargo.lock` の手編集禁止,`@latest` | edit hook
が見ておらず,`@latest` は `go install` など一部しか拒否しない |
| commit の「Imperative mood」「72 文字」,subject の小文字(固有名詞の例外) | commitlint
の上限は 100 文字で,imperative は機械で判定できない |
| `ls-lint`・`shfmt`・`file-length`(pre-commit のみ,この repository 固有) |
skill は他の repository にも使われ,そこでは強制されない |
| default / protected branch への直接 push 禁止(`development-cycle/SKILL.md`)
| guard は `main` と `master` だけを知る(`PROTECTED_BRANCHES`).レビュー指摘で復元 |
| `uv add --dev` 禁止 | deny は prefix `uv add --dev` だけで,`uv add pkg
--dev` は ask.レビュー指摘で復元 |
| hook の迂回禁止(`commits.md`) | guard は `--no-verify` と `core.hooksPath`
だけを見て,`LEFTHOOK=0` は拒否しない.レビュー指摘で復元 |
| accepted ADR の本文を変えず `amended` に残す(`adr/SKILL.md`) | edit hook は
`--base` なしで走り,CI の `adr-lint` にしか効かない.レビュー指摘で復元 |
| ADR の置換手順(新 ADR の `supersedes`,旧 ADR の `superseded-by`) | 複数 file
にまたがる手順で,`adr-check` は事後にしか報告せず,他の repository では動かない.レビュー指摘で復元 |
| `verification_session.py verify` を実行しない | hook の block ではなく sandbox
の書き込み禁止 |

## 確認

- [x] `uv run --frozen pytest`: 6120 passed, 2 skipped(`tests/skills` の
skill command 検査を含む)
- [x] lefthook(shfmt,ls-lint,shellcheck,commitlint)が通る
- [x] `.github/workflows/` の変更なし

<details>
<summary>前提・範囲外</summary>

- 対象は block(deny・error)または CI 失敗の規則だけ.ask は対象外.
- 文章の書き換え・再構成,hook・CI・lint rule とメッセージの変更,advisory の規則,他の repository
は範囲外.

</details>

## レビュー指摘への対応

| 指摘 | 扱い |
| --- | --- |
| P2 `adr/SKILL.md`: 置換手順を消すと正の手順が無くなる | 修正.手順 4 の置換の一文を復元(後半の `amended`
だけ削除のまま) |
| P2 `python-style/references/tooling.md`: `uv add pkg --dev` は deny の
prefix に一致しない | 修正.`uv add --dev` を `Prohibited:` 行に復元 |
| P2 `commits.md`: `LEFTHOOK=0` で hook を無効化できる | 修正.「do not bypass the
repository hooks」を復元 |
| P2 `adr/SKILL.md`: accepted ADR の本文保護は CI にしか効かない | 修正.`amended` の文を復元
|
| P3・P1 `development-cycle/SKILL.md`: default / protected branch の push
禁止は `main`・`master` だけを guard が見る | 修正.「Do not push directly to the
default / protected branch.」を復元(force push の半分は強制済みなので削除のまま) |


Closes #230
Refs #169

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: furedea <132188853+furedea@users.noreply.github.com>
Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
furedea-agent Bot pushed a commit that referenced this pull request Nov 19, 2026
Emulating shell globbing in the hook does not converge (POSIX classes,
nocaseglob, walk bounds), the same lesson as #200. A glob stays a run-time
word and asks until #181. The removed still-ask tests are restored.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
furedea added a commit that referenced this pull request Nov 19, 2026
…nown at hook time (#254)

## 概要

hook の時点で確定できる事実がある `gh` 呼び出しが確認(ask)になり,lane
が承認待ちで止まっていた.文字列の解析を深くせず,確定できる 3 種類だけを allow 側に直す.

Closes #253
Refs #197, #181

## 変更

- 変更 1:`-R owner/repo`(`--repo`)で対象を明示した読み取りは,作業ディレクトリの remote
を理由に確認にしない(`gh_repository.names_repository_option`,`gh_invocation._classify_words`).host
は `-R` の値で決まり,host 部分が無ければ github.com.github.com 以外の host,run time の値,別の
option の値になりうる `-R`(直前が option)は従来どおり確認.
- **glob(Issue の受け入れ条件 3 つ目)は,この PR から外した.** ユーザーの決定:hook でシェルの glob
を再現する方式は収束しない(POSIX 文字クラス,`nocaseglob`,走査範囲と指摘が続いた.#200 と同じ教訓).未一致 glob
の「文字どおり扱い」とそのテストを削除し,glob を含む引数(`?ref=` など)は従来どおり確認.#181 で扱う.
- `-R` の許可は,行にほかのコマンドがあれば従来どおり確認(writable な PATH に git
を置きうるコマンドの検査を迂回しない).`GhCall.names_repository` を足し,`gh_policy._ungranted`
で行全体の検査を残した.
- 変更 2:1 コマンドだけの行で,hook の環境に設定済みの `$TMPDIR` / `$HOME` だけで書かれた body /
input ファイルの path は展開し,リテラルの path
と同じく存在・読み取り・サイズ・秘密のスキャンにかける(`gh_options.expand_environment`,`environment_files`).未設定の変数,`$TMPDIR`
/ `$HOME` 以外の変数,単独の `$f`,同じ行で代入した変数,ループ,コマンド置換は従来どおり確認.
- allow になる効果の区分は #201 の policy table のまま変えていない.`gh_policy.py` の変更は,`-R`
の許可に行全体の検査を残す 1 行とコメントだけ.`?ref=` を含む read は #181 まで確認のまま.

## テスト

- `tests/hooks/test_gh_known_at_hook_time.py`(新規):`-R` の 7 つの書き方が remote
に関わらず allow,host 違い・run time の値・option に食われうる `-R`・値なし・後続の別 host の `-R`
は ask,`GH_HOST` 違いは ask.glob を含む read endpoint(`?ref=`)と,`cp x
later/git; gh pr list -R …` は ask.
- `tests/hooks/test_gh_run_time_body_files.py`:`$TMPDIR` の body file が
allow,ほかの変数・未設定・単独変数・存在しないファイル・コマンド置換・同じ行の代入・ループ・stdin のリダイレクトは
ask,秘密を含むファイルは展開後に ask.
- 旧仕様(`-R` でも remote を見る,環境変数の body path は ask)を確かめていた既存テストを新しい仕様に合わせた.
- `uv run pytest tests`(6135 件),ruff,ty は通過.

## 記録(範囲外・前提)

- 判定と実行の間の変化(TOCTOU)は範囲外.hook が見たファイルや環境変数が gh の実行時に変わりうる.#181 で扱う.
- 環境変数の展開は,hook の環境の `TMPDIR` / `HOME`
がサンドボックス内のシェルと同じ値を持つことを前提にする(Issue
の決定).ほかの変数は値が違いうるので展開せず,確認のまま.セキュリティレビューの指摘(任意の変数を展開するとスキャン対象がずれる)はこの 2
変数への限定で対処した.
- Issue の実例 4 件目の確認理由(行が変数や環境を設定する)は,この実例だけでは再現できなかった(実際の理由は「run time の
file」).同じ行の代入は従来どおり確認.
- ループ・関数・同じ行での変数代入・コマンド置換は緩めていない(#200,#181).

- レビュー指摘(範囲外として回答・解決):フラグ直後の `-R`,`-R=値` の形,`HOME` のテスト不足.いずれも確認が 1
回増えるだけで誤った allow にはならず,read の option 表(#181)が必要.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: furedea <132188853+furedea@users.noreply.github.com>
Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
furedea added a commit that referenced this pull request Nov 20, 2026
…256)

## 概要

`gh` を読み取り専用のコマンドや `cd` とつないだ行は,「同じ行の別のコマンドが PATH の前の方に別の gh
を置けるかもしれない」として確認になっていた.hook の時点で分かる事実(各コマンドが何も書かず別のプログラムも走らせない,リダイレクト先が
PATH の要素でない,PATH に相対パスが無い)で判定し,この理由の確認をなくす.gh 自体の判定は #201 の policy table
のまま.

Closes #255
Refs #197, #253, #181

## 変更

- `read_only_commands.py`(新規):語だけで「ファイルを書かず,別のプログラムも走らせない」と言えるコマンドの判定.
- そのまま読み取り:`cat column cut echo false grep head jq ls nl printf pwd
sleep tail tr true wc`
- 語を見て判定:`awk`(`-F`/`-v` だけ,プログラムに `> | @ system getline` が無い),`sed`(`-n
-E -r -e` だけ,スクリプトは行番号・パターンの `p` か `w`/`e` フラグの無い
`s///`),`sort`(`-o`・`--compress-program` などを除く),`uniq`(オペランド 1
つまで),`base64`(`-d` だけ)
- run time に決まる語は,そのまま読み取りの組以外と `echo`/`printf`(`printf -v PATH`
になりうる)では確認.
  - **git の読み取りサブコマンドは入れていない**(下の「記録」参照).git を含む行は従来どおり確認.
- `gh_command_line.command_line`:
- `plants_nothing`:gh 以外がすべて上の読み取り(またはリテラルの `cd`)で,gh 呼び出しが 1 つ,gh
以外のリダイレクト先は `/dev/null` だけ,gh 自身の出力先は `/dev/null` か PATH
の要素でないディレクトリ(run time に決まる先・PATH に相対要素があるときは不可).このとき
`gh_environment._stand_in_problem` は PATH を理由に確認しない.
- `directories`:hook の cwd と,リテラルの `cd` が入りうる各ディレクトリ(それまでの各ディレクトリから,bash
が保つ論理パスと物理パスの両方).`cd` が失敗しても,サブシェル・パイプ内でも gh はこのどこかで動く.存在しない先,`-`
で始まる語(`cd -`,`-P`,`--` など),`pushd`/`popd`,run time の先,PATH
に相対・空の要素がある,`CDPATH` 下の相対の `cd`,環境の `cd` 関数は従来どおり確認.
- `{ }`,`( )`,`if`,ループなど CallExpr
以外の文にリダイレクトがある行は,中のコマンドに書き込みとして記録されないので確認.
- ヒアドキュメント・ヒアストリング・コマンド/プロセス/算術置換を含む行は,従来の判定(#200 の組の filter
だけ)に戻す.ループ・関数・代入は従来どおり `changes_environment` で確認.
- `command_objections.gh_objection`:gh 呼び出しを `directories`
の各ディレクトリで判定し,全部で allow のときだけ allow(作業リポジトリの
remote,設定,プログラムの所在をそれぞれのディレクトリで見る).`hook_input.working_directory`
を切り出した.
- `gh_environment`:`_stand_in_problem` の条件に `plants_nothing` を足しただけ(main
との差は 1 行).

## 再生(2026-11-18 14:24〜11-19 15:13 JST の確認 390 件)

`issue255_replay.py` を本ブランチの hook と `origin/main` の hook
に向けて実行した(`XDG_STATE_HOME` を scratch に向け,実際の audit log には書かない).390 件のうち
command が無い 2 件を除く 388 件,guard_command 以外の hook による 16 件は対象外.再生環境の PATH
には書き込める要素が gh より前に無かったため,実際の hook 環境(PATH 理由 74 件)を近似する「書き込める要素を先頭に足した
PATH」でも測った.

| | 通常の PATH | 書き込める要素を先頭に足した PATH |
| --- | --- | --- |
| main で確認 → 本ブランチで allow | **36 件** | **19 件** |
| うち,消えた worktree への `cd` を既存チェックアウトに置き換えると追加で allow | +20 件 | +6 件 |

git 読み取りを入れていた段階(43 件 / 25 件)から 7 件 / 6 件減った.

確認のまま残る内訳(通常の PATH,388 件中 allow 49 件・他 hook 16 件を除く 323 件):

| 理由 | 件数 |
| --- | --- |
| 代入・ループ・wrapper・環境(#181) | 142 |
| 別のコマンドがディレクトリ/remote を変えうる(git 全般,`python3`,`jev-lint`,`mkdir`,消えた
worktree への `cd` 20 件など) | 64 |
| gh 呼び出しを分類できない(run time の値など) | 28 |
| 未対応の構文(`$'...'` など) | 28 |
| ほかのコマンド規則(cleanup_worktrees,agent-browser など) | 24 |
| rm guard | 16 |
| 書き込み先(class C/D) | 12 |
| 送るファイルの横に別コマンド | 9 |

書き込める PATH の場合は,確認のまま 260 件が PATH 理由で出る.その内訳(通常の PATH での理由)は,代入・ループ
129,別コマンド 64,gh 呼び出しが複数(通常の PATH なら allow)30,分類不可 24,class C/D 7,送るファイル
6.

新たに allow になった 36 件はすべて目視で確認した:gh 以外は `grep/head/tail/jq/awk '{print
...}'/sed -n/sort/uniq/ls/cat/sleep/echo/wc/base64 -d`,リテラルの
`cd`(`/tmp`,相対の `tests/hooks`→`../..`),`2>/dev/null` と `2>&1` だけ.gh
はすべて読み取り(`pr view/list/checks/diff`,`run view/list/watch`,`issue
view`,GET の `gh api`/`api graphql` query)で,#201 の policy table で許可される操作.

## テスト

- `tests/hooks/test_gh_joined_read_only_lines.py`(新規,書き込める PATH 要素を gh
より前に置いた状態で):
- allow:Issue の例 `gh pr checks 240 -R … 2>&1 | grep -c pass`,`/dev/null`
への出力,`awk | sort | uniq -c`,`sleep`/`echo`,`ls`/`wc`,`sed -n`
の行番号・パターン,`base64 -d`,PATH 外への gh の出力.
  - 作業リポジトリを読む gh は,読み取りだけの行でも remote が github.com 外なら確認.
- 確認のまま:`cp x later/gh`,`cp x later/git`(Issue
の例),`mv`,`ln`,`install`,`chmod`,`export PATH=`,PATH の要素へのリダイレクト(gh
自身の出力も),run time のリダイレクト先,ほかのコマンドの `echo x > notes.txt`・`>>
.git/config`,`sort -o`/`-uo`/`--compress-program`,`uniq` の出力ファイル,`awk`
の書き込み・`system`・`-f`,`sed w`/`-i`,`base64 -o`,`printf $OPT PATH
/tmp`,`echo $WORDS`,`{ echo x; } > later/gh`,`(echo x) > later/gh`,`if
…; fi > later/gh`,`{ echo x; } >> .git/config`,`git status`,`git
log`,`git commit`,`python3`.
- `cd`:github.com のチェックアウトへの `cd` は allow,github.com 外へは確認(`-R` 付きなら
allow),cwd 側が github.com 外なら確認,存在しない先・`$DIR`・`cd -`・`cd -P`・`pushd`・`cd
-- -foreign`・symlink 越しの `cd ..`・`CDPATH` 下の相対・環境の `cd` 関数・PATH
の相対要素(`.`,空)は確認.
  - ヒアドキュメント,ヒアストリング,`$(...)`,`<(...)`,ループ,関数,代入の行は確認.
- ゲートを外す・修正前のコードに戻すとこれらのテストが失敗することを確認した(ヒアドキュメント/置換,`cd
--`,symlink,`-P`,run time の `printf`/`echo`,まとまりへのリダイレクト).
- `tests/hooks/test_read_only_commands.py`(新規):`writes_nothing`
の単体テスト(`sort -t -o`,`sed -e p -e 'w out'`,`awk -v x=1 -F: …`,`git
log`/`git status` は読み取りに入らない,など).
- 既存の `test_gh_targets.py`(`gh … && gh …` は確認,`printf x > .git/config;
gh pr list` は確認など)は変更なしで通過.
- `uv run pytest tests`(6220 passed,2 skipped),`ruff check`,`ruff format
--check`,`ty check`,`deptry`,`vulture` を通過.

## 記録(範囲外・前提・限界)

- **git 読み取りは #181 に回した**(受け入れ条件 1 つ目の「読み取りの git
サブコマンドを含む」から外れる).レビューで,git
の読み取りがリポジトリ設定(textconv,`diff.external`,filter,fsmonitor,`gpg.program`,`hook.*`,`core.alternateRefsCommand`),`post-index-change`
フック,submodule(gitlink),環境(`GIT_PAGER`,`GIT_EXTERNAL_DIFF`,`GIT_CONFIG_*`),promisor
remote の遅延 fetch などからプログラムを走らせうる指摘が直すたびに続き,#200
と同じく収束しなかった.ユーザー判断(どちらでも可)を受けて親セッションが「外す」を選んだ.git
を含む行は従来どおり確認になり,そのための設定検査も削除した.減る件数は通常の PATH で 7 件,書き込める PATH で 6 件.
- Issue の受け入れ条件 3 つ目(リダイレクト先は `/dev/null` と PATH 外を許す)より厳しくした:PATH
外を許すのは gh 自身の出力だけで,gh 以外のコマンドは `/dev/null`
だけ.書いたファイルが同じ行の後のプログラムの設定になりうるため(自動セキュリティレビューの指摘).
- 判定と実行の間の変化(TOCTOU)は範囲外:hook が見た PATH の要素・`cd`
先・設定が実行時に変わりうる(同じ行のコマンドは書かないが,並行する別プロセスは書ける).#181 で扱う.
- `cd` は「gh が cwd と各 `cd` 先のどれで動いても allow」とした.`cd 先` だけで判定する Issue
の文言より厳しく,cwd の remote が github.com 外の場合は `cd` しても確認になる(構文から `cd`
の成否・サブシェルを読まずに済ませるため).
- gh 呼び出しが 2 つ以上の行は,PATH に書き込める要素がある環境では従来どおり確認(`gh repo clone`/`run
download` が後の gh の前に置きうるため).書き込める PATH の再生で 30 件がこれで残る.
- **レビュー最終回で出た指摘は直さずに残した(後続で扱う)**:
- P1:静的な `printf` の `%n` は引数名に文字数を代入する(`printf x%n PATH` で PATH が `1`
になる).書き込める PATH 要素がある環境では誤った allow になりうるので,最初に直す項目(対処案:`%n` を含む `printf`
を読み取りに数えない).
  - P2:zsh の 2 オペランドの `cd OLD NEW` を追跡していない(対処案:オペランドが 2 つ以上なら追わない).
- P2:gh のリダイレクト先のブレース展開(zsh の MULTIOS)と `~+`/`~-` を run time
の先として扱っていない(対処案:`literal_words.EXPANDING_TEXT` を再利用する).
- MEDIUM(ローカルの自動セキュリティレビュー):コマンドの無い文のリダイレクト(`> f`
単独)を,まとまりへのリダイレクトと同じく扱っていない(対処案:`Cmd` が引数のある CallExpr でない文の `Redirs`
をすべて書き込みとみなす).
- 誤検知として残るもの(確認が増えるだけで誤った allow にはならない):`awk` の比較 `>`,値を取る `uniq -f
N`,一覧に無い `sort` の option,`base64` のファイル入力,`cd -P`.
- レビュー対応:GitHub のスレッドはすべて返信して解決した(修正またはこの git
読み取りの除外で対処).ローカルの自動セキュリティレビューの指摘(他コマンドの書き込み,gitlink の submodule,promisor
の遅延 fetch)も,書き込みの制限と git 読み取りの除外で対処済み.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: furedea <132188853+furedea@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant