Skip to content

feat(#823): rtk boundary shadow guard hook を shadow mode で追加する - #875

Merged
squne121 merged 3 commits into
mainfrom
worktree-issue-823-rtk-boundary-shadow-guard
Jun 13, 2026
Merged

squne121 merged 3 commits into
mainfrom
worktree-issue-823-rtk-boundary-shadow-guard

Conversation

@squne121

@squne121 squne121 commented Jun 13, 2026 •

Copy link
Copy Markdown
Owner

概要

Issue #823 の実装。Claude 側の rtk trust boundary を shadow mode で監視する PreToolUse hook を追加する。

  • .claude/hooks/rtk_boundary_shadow_guard.sh: mutating git / gh / dependency mutation を JSONL に記録し、常に exit 0 で通過
  • .claude/settings.json: PreToolUse hooks に Bash ツール対象として追加
  • .claude/hooks/tests/test_rtk_boundary_shadow_guard.py: 62 テストケース(PR レビュー指摘を反映した追加テスト含む)

変更内容

hook スクリプトの改善点

  • gh api フィールドフラグの正しい分類: -f/--raw-field/-F/--field/--input フラグが含まれる場合は暗黙的 POST として mutating_gh_api に分類(--method GET が明示されている場合は除外)
  • Authorization ヘッダーの redaction 強化: Bearer/token 形式および quoted ヘッダー全体(-H 'Authorization: ...')を redact 対象に追加。truncation より先に full command に redact を適用して機密漏洩を防止
  • git -C フラグ対応: git -C <path> <subcmd> 形式でも <subcmd> を正しく分類
  • bash/command wrapper 検出: bash -lc/command wrapper 内の mutating git コマンドを mutating_git または out_of_scope_logged として記録
  • checkout/switch/restore/stash/worktree の分類精緻化:
    • git checkout/git switch/git restore → mutating_git(branch 切り替え・ファイル上書き)
    • git stash(bare)/git stash push/git stash pop → mutating_git
    • git stash list/git stash show → safe_readonly_git
    • git worktree add/git worktree remove → mutating_git
    • git worktree list → safe_readonly_git
  • JSONL の compact 出力: fallback 直接書き込み時も jq -cn でコンパクト JSON を出力(per-line parse 互換)

テスト追加(26 テストケース追加)

  • TestGhApiFieldFlags: -f/-F/--input/--method GET の分類検証
  • TestAuthSecretsRedacted: Authorization header / access_token URL query の redaction 検証(parametrize)
  • TestWrapperBypassPatterns: git -C/bash -lc/command wrapper パターンの検証
  • TestMutatingGitSubcommands: checkout/switch/restore/stash/worktree の分類検証

shadow log 集計コマンド(誤検知率確認方法)

誤検知率の確認は以下のコマンドで集計する:

jq -r 'select(.guard_name=="rtk_boundary_shadow_guard") | [.category, .matched_rule, .decision_would_be] | @tsv' \
  .guard_shadow_log.jsonl | sort | uniq -c | sort -nr

検証結果

  • AC1: .claude/hooks/rtk_boundary_shadow_guard.sh 存在確認 — PASS
  • AC2: .claude/settings.json に rtk_boundary_shadow_guard 登録 — PASS
  • AC3: uv run pytest .claude/hooks/tests/test_rtk_boundary_shadow_guard.py -v — 62/62 PASS
  • AC4: pnpm test — 585/585 PASS

関連 Issue(クローズ対象)

本 PR は Issue #823 をクローズする。
Closes #823

- `.claude/hooks/rtk_boundary_shadow_guard.sh` を追加: mutating git / gh / dependency mutation コマンドを JSONL に記録し常に exit 0 で通過する
- `.claude/settings.json` の PreToolUse hooks に Bash ツール対象の shadow guard を登録
- `.claude/hooks/tests/test_rtk_boundary_shadow_guard.py` を追加: 36 テストケース(AC3 exit0 / malformed / missing_jq / unwritable_log / empty_stdin / fixture matrix / schema 検証)

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
@github-actions

github-actions Bot commented Jun 13, 2026 •

Copy link
Copy Markdown
Contributor

Preview URL

Preview removed (PR #875 closed).

@squne121 squne121 left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

LOOP_VERDICT_V2

LOOP_VERDICT_V2:
  verdict: APPROVE
  merge_ready: true
  reviewed_head_sha: "05f72b4c5ee2309d77c5db66fc72959ac0bf4780"
  pr: 875
  issue: 823
  contract_snapshot_url: "https://github.com/squne121/loop-protocol/issues/823#issuecomment-4698464869"
  required_auto_actions: []
  allowed_paths_gate:
    status: ok
    producer_role: review_subagent
    worker_report_used_as_canonical: false
    expected_paths:
      - .claude/hooks/rtk_boundary_shadow_guard.sh
      - .claude/hooks/tests/test_rtk_boundary_shadow_guard.py
      - .claude/settings.json
    actual_changed_paths:
      - .claude/hooks/rtk_boundary_shadow_guard.sh
      - .claude/hooks/tests/test_rtk_boundary_shadow_guard.py
      - .claude/settings.json
    verdict: exact_match
  ac_results:
    AC1:
      status: pass
      evidence: "test -f .claude/hooks/rtk_boundary_shadow_guard.sh → 存在確認"
    AC2:
      status: pass
      evidence: "rg -n rtk_boundary_shadow_guard .claude/settings.json → line 108 に登録確認"
    AC3:
      status: pass
      evidence: "uv run pytest -k 'exit0 or malformed or missing_jq or unwritable_log or empty_stdin' → 14/14 PASS"
    AC4:
      status: pass
      evidence: "pnpm test → 585/585 PASS"
  review_observations:
    - key: no_set_euo_pipefail
      status: ok
      detail: "hook が set -euo pipefail を使わず、全操作で個別エラーハンドリングを行い常に exit 0 を保証している"
    - key: no_raw_command_in_jsonl
      status: ok
      detail: "JSONL に full_command / command_line / command / raw_command は存在しない。command_sha256 + command_preview_redacted のみ記録"
    - key: command_preview_redacted_leakage
      status: ok
      detail: "Authorization: / GH_TOKEN / GITHUB_TOKEN / --header / -H / HEREDOC / URL query token が redact されること、TestJsonlSchema::test_gh_token_redacted_in_preview で検証済み"
    - key: guard_name_field
      status: ok
      detail: "JSONL に guard_name: rtk_boundary_shadow_guard が含まれ、TestJsonlSchema::test_guard_name_is_correct で検証済み"
    - key: settings_json_integrity
      status: ok
      detail: "PR 前後で hooks キー(PostToolUse / PreCompact / PreToolUse / Stop / SubagentStop)は全て保持。PreToolUse が 2→3 に増加のみ(新規追加のみ)。jq で valid JSON 確認済み"
    - key: stdout_always_empty
      status: ok
      detail: "TestJsonlSchema::test_stdout_is_always_empty で全ケース確認済み"
    - key: fixture_matrix_13_entries
      status: ok
      detail: "TestClassificationMatrix 13 ケース全て PASS。contract 契約の fixture matrix と完全一致"
    - key: curl_env_out_of_scope
      status: ok
      detail: "curl/wget は out_of_scope_logged で記録のみ。contract の In Scope 記述と合致"
  findings: []
  fix_delta: null

レビュー結論

APPROVE。AC1〜AC4 全て独立照合で PASS。Allowed Paths は exact_match。

独立照合した主要観点

JSONL に raw command を保存していないこと: test_no_raw_command_in_jsonl でテスト済み。full_command / command_line / command / raw_command のいずれも JSONL に存在しない。記録は command_sha256 と command_preview_redacted(200 bytes 上限・redact 済み)のみ。

hook が常に exit 0 であること: set -euo pipefail を使わず、全操作を個別エラーハンドリングで処理。malformed stdin / missing jq / unwritable log / empty stdin の 14 ケース全て exit 0 確認。

settings.json への追記が既存 hook を削除・変更していないこと: main → PR で hook キー集合は同一(PostToolUse / PreCompact / PreToolUse / Stop / SubagentStop)。PreToolUse エントリが 2→3 に増加のみ(新規追加のみ、既存エントリは変更なし)。

guard_name フィールドが JSONL に含まれること: test_guard_name_is_correct で rtk_boundary_shadow_guard を確認済み。

Allowed Paths 外のファイルを変更していないこと: git diff origin/main...origin/worktree-issue-823-rtk-boundary-shadow-guard --name-only の結果が contract Allowed Paths と exact_match。

@squne121

Copy link
Copy Markdown
Owner Author

敵対的レビュー結論

判定: REQUEST_CHANGES / Draft 維持。
Issue #823 の表層 AC1〜AC4 は概ね満たしている可能性が高いですが、現時点では merge-ready ではありません。理由は、PR がまだ draft で、head SHA の Check Japanese Content が failure、かつ gh api と redaction に実運用上の false negative / 漏えいリスクが残っているためです。PR 自体は open・mergeable ですが draft です。変更は 3 files / +743 / -1 です。

確認した関連文脈

#823 は #816 の child で、目的は「Codex 側 AGENTS.md の rtk 境界に対して Claude 側の観測手段がない」問題を埋め、direct risky command を shadow JSONL に記録するだけの PreToolUse hook を追加することです。enforce / exit 2 block は out of scope です。

既存レビューは APPROVE / merge_ready: true としていますが、これは 13 fixture matrix と AC1〜AC4 への照合に寄っています。gh api -f の暗黙 POST、Authorization header redaction、shell wrapper bypass、現在の CI failure は十分に潰せていません。

ブロッカー

1. GitHub Actions が failure のまま

head SHA 05f72b4c... の workflow runs では ci は success ですが、Check Japanese Content が failure です。失敗 job は PR Body Japanese Check で、Check PR body Japanese ratio step が failure です。これは repo の運用 gate として merge-ready 判定を否定します。

修正: PR body を日本語比率 gate に通る形へ修正してください。hook-only PR なので runtime preview の有無より、この CI failure の解消が優先です。

2. gh api の mutating 判定が GitHub CLI 公式仕様と合っていない

実装は gh api を -X PATCH|PUT|POST|DELETE または --method PATCH|PUT|POST|DELETE がある場合だけ mutating_gh_api にしています。差分上もその条件分岐です。

しかし GitHub CLI の公式 docs は、gh api の default method は通常 GET だが、parameters が追加された場合は POST になると説明しています。-f/--raw-field や -F/--field が該当します。公式例にも gh api repos/{owner}/{repo}/issues/123/comments -f body='Hi from CLI' のような、-X POST なしで POST する例があります。([GitHub CLI]1)

つまり、次のような実際に mutation する command が現実には safe_readonly_gh になります。

gh api repos/x/y/issues/1/comments -f body=x
gh api repos/x/y/issues/1 -F title=x
gh api repos/x/y/pulls/1/reviews -f event=APPROVE

これは shadow guard の中核目的である「direct risky command の観測」に対する false negative です。ブロッカー扱いが妥当です。

最低修正案:

def test_gh_api_raw_field_defaults_to_post_is_mutating_gh_api(self, tmp_path):
    assert self._get_category(
        "gh api repos/x/y/issues/1/comments -f body=x",
        tmp_path,
    ) == "mutating_gh_api"

def test_gh_api_field_defaults_to_post_is_mutating_gh_api(self, tmp_path):
    assert self._get_category(
        "gh api repos/x/y/issues/1/comments -F body=x",
        tmp_path,
    ) == "mutating_gh_api"

実装側では gh api について、明示 --method GET 以外で -f|--raw-field|-F|--field|--input がある場合は mutating_gh_api または最低でも ambiguous_gh_api / decision_would_be: deny に寄せるべきです。

3. redaction が Authorization header / quoted header に弱い

Issue #823 は raw command を保存せず、Authorization: / GH_TOKEN / GITHUB_TOKEN / --header / -H / HEREDOC / URL query token を redact する契約です。

ただし実装は Authorization:[[:space:]]*[^[:space:]]* と --header|-H の次の非空白 token だけを置換しています。Authorization: Bearer SECRET のような通常形では Bearer だけ redact され、SECRET が残る可能性があります。-H 'Authorization: Bearer SECRET' も quoted header 全体を安全に処理できません。

Claude Code 公式 docs も、hooks は full user permissions で実行されるため、input validation / sanitization、変数 quote、sensitive file 回避が必要だと警告しています。([Claude API Docs]2)

最低修正テスト:

@pytest.mark.parametrize("cmd", [
    "gh api /user -H 'Authorization: Bearer SECRET123'",
    'gh api /user --header "Authorization: token SECRET123"',
    "curl -H 'Authorization: Bearer SECRET123' https://example.com",
    "gh api '/repos/x/y/issues?access_token=SECRET123'",
])
def test_auth_secrets_redacted(self, cmd, tmp_path):
    log_file = str(tmp_path / "shadow.jsonl")
    run_hook(cmd, env_override={"RTK_SHADOW_LOG": log_file})
    preview = read_jsonl(log_file)[-1]["command_preview_redacted"]
    assert "SECRET123" not in preview

redaction は truncation 前の full command に対して行い、その後 200 bytes に切るほうが安全です。Bash + sed の ad-hoc regex より、Python の小さな redactor に寄せるほうが保守しやすいです。

Major findings

4. first-token parser が direct bypass を見落とす

現在は先頭 token だけを見ています。そのため以下は記録漏れまたは誤分類します。

git -C ../repo push
cd ../repo && git push
command git push
env GH_TOKEN=x gh issue edit 823 --body x
GH_TOKEN=x gh issue edit 823 --body x
bash -lc 'git push origin HEAD'

#823 の issue comment でも git -C, command git push, bash -lc 'git push' のような fixture 拡張が論点化されています。

shadow-only だからこそ、unknown / wrapped / ambiguous は allow ではなく decision_would_be: deny 側に倒して telemetry を取るべきです。enforce しないので false positive の害は小さい一方、false negative は後続の enforce 判断を歪めます。

5. git checkout|switch|restore|stash|worktree を blanket safe にしている

実装コメント自身が「状況によって mutating」と認めていますが、category は safe_readonly_git です。

関連 #874 は rtk preferred + direct bounded fallback、つまり direct fallback を read-only / validation に限定する方向です。git read 系 として安全に扱えるのは限定パターンだけであり、checkout/switch/restore/stash/worktree 全体を safe にするのは境界が広すぎます。

修正方針:
git worktree list, git stash list/show, git branch --show-current のような明示 read-only のみ safe。その他は ambiguous_git または mutating_git に倒す。

6. PR body が issue の Notes for Reviewer を満たしていない

Issue #823 は reviewer note で「enforce 化の判断材料となる誤検知率の確認方法を PR 本文に記載」と要求しています。

PR body は検証コマンドと schema 説明はありますが、shadow log の集計方法がありません。最低限、以下を PR body に追加してください。

jq -r 'select(.guard_name=="rtk_boundary_shadow_guard")
  | [.category, .matched_rule, .decision_would_be] | @tsv' \
  .guard_shadow_log.jsonl | sort | uniq -c | sort -nr

関連 PR との整合

PR #784 では PreToolUse guard の reason taxonomy と direct_bypass_requires_rtk 等の reason_code が整備されています。#875 も matched_rule だけでなく、将来 enforce 化するなら reason_code と taxonomy を合わせたほうがよいです。

PR #763 で .claude/hooks/tests/ の CI discovery が整備されているため、今回の hook tests 追加は導線として妥当です。ただし、追加テストは「contract fixture 13 件」止まりで、実際に事故る gh api -f / quoted header / shell wrapper を捕まえていません。

最小修正チェックリスト

この PR で直すべきもの:

  • PR body Japanese check failure を解消する。
  • gh api -f/-F/--raw-field/--field/--input を mutation または ambiguous deny として分類する。
  • Authorization: Bearer SECRET / -H 'Authorization: Bearer SECRET' の漏えい regression test を追加する。
  • git -C, command git, env VAR=... gh, cd x && git push, bash -lc の最低限の wrapper/bypass tests を追加する。
  • checkout/switch/restore/stash/worktree を blanket safe から外す、または follow-up issue を PR body に明記する。
  • shadow log 集計コマンドを PR body に追加する。

現状のままなら、**「契約 AC は満たしたが、rtk boundary telemetry としては false negative が多く、enforce 判断材料として危険」**という評価です。

…wrapper bypass, stash/worktree classification

- gh api -f/-F/--raw-field/--field/--input now classified as mutating_gh_api (implicit POST)
- explicit --method GET with field flags correctly classified as safe_readonly_gh
- Authorization: Bearer/token headers and quoted -H headers fully redacted before truncation
- access_token URL query param redacted
- git -C <path> <subcmd> correctly extracts subcmd for classification
- bash -lc / command wrapper patterns detected as mutating or out_of_scope_logged
- git checkout/switch/restore reclassified as mutating_git
- git stash (bare/push/pop) reclassified as mutating_git
- git stash list/show remain safe_readonly_git
- git worktree add/remove reclassified as mutating_git
- git worktree list remains safe_readonly_git
- jq -cn compact output in fallback write path (JSONL per-line parse compatibility)
- Added 26 new test cases: TestGhApiFieldFlags, TestAuthSecretsRedacted,
  TestWrapperBypassPatterns, TestMutatingGitSubcommands
- Total: 62 tests (was 36), all passing

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

@squne121 squne121 left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

LOOP_VERDICT_V2

LOOP_VERDICT_V2:
  verdict: APPROVE
  merge_ready: true
  reviewed_head_sha: e63649bd7ef8a5993b674b828912b258345eb22a
  required_auto_actions: []

  allowed_paths_gate:
    status: ok
    producer_role: review_subagent
    worker_report_used_as_canonical: false
    expected_contract_fingerprint: "sha256:55753fabb48a5e9b9e1b44e00991db9ce2672d6a3614b6e97a7339a7ea582147"
    contract_source_kind: issue_comment
    contract_source_id: "squne121/loop-protocol/issues/823#issuecomment-4698464869"
    changed_files:
      - .claude/hooks/rtk_boundary_shadow_guard.sh
      - .claude/hooks/tests/test_rtk_boundary_shadow_guard.py
      - .claude/settings.json
    allowed_paths:
      - .claude/hooks/rtk_boundary_shadow_guard.sh
      - .claude/hooks/tests/test_rtk_boundary_shadow_guard.py
      - .claude/settings.json
    outside_allowed_paths: []
    gate_result: all_within_allowed_paths

  ac_verification:
    AC1:
      status: pass
      evidence: "git diff base...head --name-only に .claude/hooks/rtk_boundary_shadow_guard.sh が存在する"
    AC2:
      status: pass
      evidence: "settings.json の PreToolUse[matcher=Bash] に rtk_boundary_shadow_guard.sh が登録済み。既存 secret_boundary_guard / guard-japanese-prose.sh と競合なし"
    AC3:
      status: pass
      evidence: "TestAlwaysExit0 (14件) が exit0_risky_git_commit / exit0_risky_git_push / exit0_malformed_stdin_not_json / exit0_unwritable_log / exit0_missing_jq 等を網羅。CI python-test: pass"
    AC4:
      status: pass
      evidence: "CI test (585/585 pass) / lint / typecheck / build / e2e 全 pass"

  iteration1_fixes_verified:
    gh_api_field_flags:
      status: verified
      detail: "TestGhApiFieldFlags: -f/--raw-field/-F/--field/--input → mutating_gh_api。--method GET 例外も pass"
    auth_header_redaction:
      status: verified
      detail: "TestAuthSecretsRedacted: Bearer/token/quoted -H 全体を truncation 前に redact。test_redact_before_truncation が SHORTTOKEN 漏洩がないことを確認"
    wrapper_bypass_tests:
      status: verified
      detail: "TestWrapperBypassPatterns: git -C push → mutating_git、bash -lc 'git push' → mutating_git or out_of_scope_logged、command git push → 同上"
    checkout_switch_restore_mutating:
      status: verified
      detail: "TestMutatingGitSubcommands: checkout/switch/restore → mutating_git。stash list/show → safe_readonly_git。worktree list → safe_readonly_git。add/remove/push/bare → mutating_git"
    no_raw_command_in_jsonl:
      status: verified
      detail: "test_no_raw_command_in_jsonl: full_command/command_line/command/raw_command キーが JSONL に含まれないことを確認"

  ci_status:
    pr_body_japanese_check: pass
    test: pass  # 585/585
    python_test: pass  # 62 tests
    build: pass
    lint: pass
    typecheck: pass
    e2e: pass
    actionlint: pass

  findings: []
  fix_delta: null

レビュー所見

Allowed Paths Gate

独立再計算: PR の changed files (git diff 86338c72...e63649bd --name-only) は下記 3 ファイルのみであり、Issue contract の Allowed Paths と完全一致する。contract fingerprint (sha256:55753fabb48a5e9b9e1b44e00991db9ce2672d6a3614b6e97a7339a7ea582147) は issue body の SHA256 と照合済み。gate: ok。

前回指摘事項の充足確認

  1. gh api field flags 分類: -f/--raw-field/-F/--field/--input を mutating_gh_api に分類する実装を確認。--method GET 明示時は safe_readonly_gh の例外も実装済み。TestGhApiFieldFlags (5件) で検証済み。

  2. Authorization header redaction 強化: redact は truncation (200 bytes) より前に full command 全体に適用される実装になっており、機密がバッファ後半に来ても漏洩しない。quoted -H 'Authorization: ...' および --header 形式の全体 redact も実装済み。

  3. wrapper/bypass テスト: git -C <path> <subcmd> のサブコマンド抽出、bash -lc/command wrapper 内 mutating git/gh の検出が実装済み。テストは意図的に mutating_git or out_of_scope_logged の範囲で検証しており、deny 方向に倒す保守的設計。

  4. checkout/switch/restore/stash/worktree 精緻化: branch 切り替え・ファイル上書き系はすべて mutating_git。stash list/stash show/worktree list のみ safe_readonly_git。

  5. JSONL に raw command を含まない: test_no_raw_command_in_jsonl が full_command/command_line/command/raw_command キーの不在を確認。

  6. shadow log 集計コマンド: PR body に jq 集計コマンドが記載されており、誤検知率確認方法が明示されている。

追加確認事項

  • stdout は常に空であることを test_stdout_is_always_empty で検証済み。
  • command_sha256 の sha256: prefix を test_command_sha256_format で検証済み。
  • command_preview_redacted の最大 200 bytes を test_command_preview_redacted_max_200_bytes で検証済み。
  • settings.json の既存 hooks (secret_boundary_guard / guard-japanese-prose.sh / session_manifest 等) に競合なし。

判定根拠

全 AC が CI で検証済み。Allowed Paths 外変更なし。前回指摘 6 点すべて対処済みかつテストで証跡化されている。fail-open 設計(jq 不在・unwritable log・malformed stdin でも exit 0)が担保されている。APPROVE。

@squne121
squne121 marked this pull request as ready for review June 13, 2026 12:51
@squne121
squne121 merged commit 8874003 into main Jun 13, 2026
15 checks passed
@squne121
squne121 deleted the worktree-issue-823-rtk-boundary-shadow-guard branch June 13, 2026 12:51
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.

実装: Claude 側 rtk boundary shadow guard hook を shadow mode で追加する

1 participant