Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
97 changes: 84 additions & 13 deletions .claude/hooks/guard-public-text.sh
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@
# fleet. Unset, the hook does nothing. Set, any failure blocks: a scanner
# that cannot run, or a body file the hook cannot read, never lets text out.
#
# A `gh api` call with no body and a GET or HEAD method only reads and passes
# unscanned. The address a command sends to (endpoint, -R) is never scanned.
#
# Usage: Configured in .claude/settings.json as a PreToolUse hook (Bash)
# Platforms: macOS, Linux, Windows (Git Bash)

Expand Down Expand Up @@ -79,6 +82,28 @@ literal_path() {
printf '%s' "${path}"
}

# Whether the `gh api` call in $1 only reads. A field or --input sends a body
# and makes gh POST; an explicit -X/--method wins. graphql always POSTs, so
# there only a query with no mutation reads.
gh_api_reads() {
local call="${1#*gh api}" method=""
# -X takes its value attached too (-XPOST), as pflag allows.
[[ "${call}" =~ (^|[[:space:]])(-X|--method)([[:space:]]+|=)?([A-Za-z]+) ]] \
&& method=$(printf '%s' "${BASH_REMATCH[4]}" | tr '[:lower:]' '[:upper:]')
if [[ "${call}" =~ (^|[[:space:]])graphql([[:space:]]|$) ]]; then
[[ "$(printf '%s' "${call}" | tr '[:upper:]' '[:lower:]')" == *mutation* ]] && return 1
[[ "${call}" =~ (--input|=@) ]] && return 1
return 0
fi
case "${method}" in
GET | HEAD) return 0 ;;
"") ;;
*) return 1 ;;
esac
# A short field flag sends a body with its value attached as well (-ftitle=x).
! [[ "${call}" =~ (^|[[:space:]])(-[fF]|--field([[:space:]]|=)|--raw-field([[:space:]]|=)|--input([[:space:]]|=)) ]]
}

main() {
[[ -n "${CLAUDE_LEAK_GUARD:-}" ]] || exit 0
command -v jq >/dev/null 2>&1 || block "jq is required to read the command"
Expand All @@ -88,25 +113,62 @@ main() {
cmd=$(printf '%s' "${input}" | jq -r '.tool_input.command // empty')
[[ -n "${cmd}" ]] || exit 0

# Each publishing verb is detected on its own, so a read chained to a
# write never lets the write through. git's global options may sit
# between git and its subcommand (git -c k=v commit).
local start='(^|[^[:alnum:]_-])'
local git_opts='([[:space:]]+(-[Cc][[:space:]]+[^[:space:]]+|--(git-dir|work-tree|namespace|config-env|exec-path)(=[^[:space:]]+|[[:space:]]+[^[:space:]]+)|-[pP]|--(no-pager|paginate|bare|no-replace-objects|no-optional-locks|no-advice|no-lazy-fetch)))*'
local gh_verbs='((pr|issue)[[:space:]]+(create|edit|comment|review|close|merge)|(release|repo|label)[[:space:]]+(create|edit)|gist[[:space:]]+(create|edit)|workflow[[:space:]]+run)'
local gh_text=0 gh_api=0 commit=0 push=0
[[ "${cmd}" =~ ${start}gh[[:space:]]+${gh_verbs}([[:space:]]|$) ]] && gh_text=1
[[ "${cmd}" =~ ${start}gh[[:space:]]+api[[:space:]] ]] && gh_api=1
[[ "${cmd}" =~ ${start}git${git_opts}[[:space:]]+commit([[:space:]]|$) ]] && commit=1
[[ "${cmd}" =~ ${start}git${git_opts}[[:space:]]+push([[:space:]]|$) ]] && push=1
# A gh api read publishes nothing, whatever its endpoint names.
((gh_api)) && gh_api_reads "${cmd}" && gh_api=0

local kind=""
if [[ "${cmd}" =~ (^|[^[:alnum:]_-])gh[[:space:]]+((pr|issue)[[:space:]]+(create|edit|comment|review)|release[[:space:]]+(create|edit)|gist[[:space:]]+create|api[[:space:]]) ]]; then
if ((gh_text || gh_api)); then
kind="gh"
elif [[ "${cmd}" =~ (^|[^[:alnum:]_-])git[[:space:]]+(-C[[:space:]]+[^[:space:]]+[[:space:]]+)?commit([[:space:]]|$) ]]; then
elif ((commit)); then
kind="commit"
elif [[ "${cmd}" =~ (^|[^[:alnum:]_-])git[[:space:]]+(-C[[:space:]]+[^[:space:]]+[[:space:]]+)?push([[:space:]]|$) ]]; then
elif ((push)); then
kind="push"
fi
[[ -n "${kind}" ]] || exit 0

local dir repo=""
local dir repo="" remote="origin"
dir=$(command_dir "${cmd}")
[[ "${cmd}" =~ git[[:space:]]+-C[[:space:]]+([^[:space:]]+) ]] && dir=$(literal_path "${BASH_REMATCH[1]}" "${dir}") || true
if [[ "${kind}" == "gh" && "${cmd}" =~ (-R|--repo)[[:space:]=]+([A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+) ]]; then
repo="${BASH_REMATCH[2]}"
[[ "${cmd}" =~ ${start}git([[:space:]]+-c[[:space:]]+[^[:space:]]+)*[[:space:]]+-C[[:space:]]+([^[:space:]]+) ]] \
&& dir=$(literal_path "${BASH_REMATCH[3]}" "${dir}") || true
# A push sends to the remote it names, not necessarily origin.
if ((push)) && [[ "${cmd}" =~ ${start}git${git_opts}[[:space:]]+push(([[:space:]]+-[^[:space:]]*)*)[[:space:]]+([^-\;\&\|[:space:]][^\;\&\|[:space:]]*) ]]; then
remote="${BASH_REMATCH[${#BASH_REMATCH[@]} - 1]}"
fi

# The address names the repository: -R, else a gh api repos/<owner>/<name>
# endpoint. Several different ones leave the repository unknown.
local -a addresses=() distinct=()
local unread="${cmd}" named
while [[ "${kind}" == "gh" && "${unread}" =~ ((-R|--repo)[[:space:]=]+|(^|[[:space:]/])repos/)([A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+) ]]; do
named="${BASH_REMATCH[4]}"
addresses+=("${BASH_REMATCH[0]#"${BASH_REMATCH[3]}"}")
[[ " ${distinct[*]-} " == *" ${named} "* ]] || distinct+=("${named}")
unread="${unread#*"${BASH_REMATCH[0]}"}"
done
if ((${#addresses[@]} > 0)); then
((${#distinct[@]} == 1)) && repo="${distinct[0]}"
else
repo=$(github_repo "$(git -C "${dir}" remote get-url origin 2>/dev/null)")
# Outside GitHub nothing is public.
[[ -n "${repo}" || "${kind}" == "gh" ]] || exit 0
local url known=0
url=$(git -C "${dir}" remote get-url "${remote}" 2>/dev/null) || known=1
((known == 0)) || url="${remote}"
repo=$(github_repo "${url}")
# Outside GitHub nothing is public. A word that is neither a remote nor
# a URL (say, a misread flag value) stays unknown and is checked.
if [[ -z "${repo}" && "${kind}" != "gh" ]]; then
((known == 0)) && exit 0
[[ "${url}" == *"://"* || "${url}" == *@*:* ]] && exit 0
fi
fi
if [[ -n "${repo}" ]]; then
case "$(visibility "${repo}")" in
Expand All @@ -122,6 +184,8 @@ main() {
local -a local_only=()
[[ "${cmd}" =~ (^|[;&|][[:space:]]*)cd[[:space:]]+([^;&|[:space:]]+)[[:space:]]*\&\& ]] && local_only+=("${BASH_REMATCH[2]}")
[[ "${cmd}" =~ git[[:space:]]+-C[[:space:]]+([^[:space:]]+) ]] && local_only+=("${BASH_REMATCH[1]}")
# Where the text goes is not the text: endpoints and -R values are left out.
local_only+=(${addresses[@]+"${addresses[@]}"})

# Text a flag reads from a file: gh --body-file/-F, git commit -F/--file.
local rest="${cmd}" arg path
Expand Down Expand Up @@ -152,10 +216,17 @@ main() {
published="${published//"${token}"/}"
done
printf '%s\n' "${published}" >"${work}/command.txt"
# A push sends every commit the remotes lack, with its message.
if [[ "${kind}" == "push" ]]; then
git -C "${dir}" log --format='%B' HEAD --not --remotes -n 200 >"${work}/pushed-messages.txt" 2>/dev/null \
# A push may send any local branch or tag the remote lacks, so every commit
# message the remote has not seen is checked, and annotated tag messages too.
if ((push)); then
local -a lacks=(--not --remotes)
git -C "${dir}" remote get-url "${remote}" >/dev/null 2>&1 && lacks=(--not "--remotes=${remote}")
git -C "${dir}" log --format='%B' --branches --tags "${lacks[@]}" -n 200 >"${work}/pushed-messages.txt" 2>/dev/null \
|| block "cannot list the commits this push sends"
if [[ "${cmd}" =~ (--tags|--follow-tags|refs/tags/) || "$(git -C "${dir}" config --bool push.followTags 2>/dev/null)" == "true" ]]; then
git -C "${dir}" for-each-ref --count=200 --format='%(contents)' refs/tags >>"${work}/pushed-messages.txt" 2>/dev/null \
|| block "cannot list the tags this push may send"
fi
files+=("${work}/pushed-messages.txt")
fi

Expand Down
26 changes: 18 additions & 8 deletions docs/hooks.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,16 @@ scanner exits non-zero:

| Command | What is checked |
|---------|-----------------|
| `gh pr`/`gh issue` `create`, `edit`, `comment`, `review`; `gh release create`/`edit`; `gh gist create` | The command's text, and every `--body-file`/`-F` file |
| `gh api` | The command's text, `--input` files, and `-F field=@file` files |
| `gh pr`/`gh issue` `create`, `edit`, `comment`, `review`, `close`, `merge`; `gh release`/`repo`/`label` `create`/`edit`; `gh gist create`/`edit`; `gh workflow run` | The command's text, and every `--body-file`/`-F` file |
| `gh api` that writes: a field, `--input`, a non-GET method, or a graphql `mutation` | The command's text, `--input` files, and `-F field=@file` files |
| `git commit` | The message, inline or from `-F`/`--file` |
| `git push` | The message of every commit the remotes do not have yet |
| `git push` | The message of every local commit the pushed-to remote lacks, on any branch, plus annotated tag messages when tags go too |

A `gh api` read (no field, no `--input`, GET or HEAD, or a graphql query)
publishes nothing and passes unscanned, whatever its endpoint names. Each verb is
detected separately, so a read chained to a write (`gh api … && git commit -m …`)
still has the write checked. git's global options (`git -c k=v commit`) do not
hide a commit or push.

The scanner is yours, so the list of what is private never enters a public
repository. `CLAUDE_LEAK_GUARD` holds its command; the hook appends the file
Expand All @@ -63,11 +69,15 @@ whose needles come from a private repository:
```

- **Opt-in:** with `CLAUDE_LEAK_GUARD` unset the hook does nothing.
- **Public only:** the repository comes from `-R`/`--repo`, a leading
`cd <dir> &&`, `git -C <dir>`, or the working directory's `origin`. `gh repo
view` gives its visibility, cached for a day. Private and internal
repositories, and remotes outside GitHub, pass unchecked; an unknown
visibility is checked as public.
- **Public only:** the repository comes from `-R`/`--repo`, a `gh api
repos/<owner>/<name>` endpoint, the remote a `git push` names (else
`origin`), a leading `cd <dir> &&`, or `git -C <dir>`. `gh repo view` gives
its visibility, cached for a day. Private and internal repositories, and
remotes outside GitHub, pass unchecked. An unknown visibility is checked as
public, and so is a command naming two repositories, or a push to a word
that is neither a remote nor a URL.
- **Addresses are not text:** an endpoint or `-R` value says where text goes,
so it is left out of the scan; an owner a needle matches can be addressed.
- **Fails closed:** a scanner that cannot run, or a body file the hook cannot
read, blocks the call. A body file named through a variable (`--body-file
"$F"`) is refused: write the literal path.
Expand Down
176 changes: 176 additions & 0 deletions tests/guard-public-text.bats
Original file line number Diff line number Diff line change
Expand Up @@ -226,3 +226,179 @@ guard() {
[ "$(jq -r '.hooks.PreToolUse[1].matcher' "$SETTINGS_JSON")" = "Bash" ]
[ "$(jq -r '.hooks.PreToolUse[1].hooks[0].command' "$SETTINGS_JSON")" = "~/.claude/hooks/guard-public-text.sh" ]
}

commit_as() {
git -c user.name=t -c user.email=t@example.invalid commit -q --allow-empty -m "$1"
}

# A GET with no body publishes nothing, whatever its endpoint names. Before
# this, every read of an endpoint whose owner a needle matched was blocked.
# bats test_tags=unit
@test "a gh api read passes unscanned, even when its endpoint names a secret" {
visibility UNKNOWN
guard 'gh api repos/SECRETNAME/infra/rulesets --jq ".[].name"'
[ "$status" -eq 0 ]
guard 'gh api repos/SECRETNAME/infra/branches/main/protection --jq ".required_status_checks.contexts" | head -5'
[ "$status" -eq 0 ]
guard 'gh api -X GET search/issues -f q="repo:SECRETNAME/infra is:open"'
[ "$status" -eq 0 ]
guard 'gh api --method HEAD repos/SECRETNAME/infra'
[ "$status" -eq 0 ]
guard 'for id in $(gh api repos/SECRETNAME/x/rulesets --jq ".[].id"); do gh api repos/SECRETNAME/x/rulesets/$id; done'
[ "$status" -eq 0 ]
}

# A field makes gh POST by default, so a body still means a write.
# bats test_tags=unit
@test "a gh api call with a body or a writing method is scanned" {
guard 'gh api repos/acme/widgets/issues -f title=t -f body="SECRETNAME"'
[ "$status" -eq 2 ]
guard 'gh api repos/acme/widgets/issues --raw-field body=SECRETNAME'
[ "$status" -eq 2 ]
guard 'gh api -X DELETE repos/acme/widgets/issues/comments/1 && echo SECRETNAME'
[ "$status" -eq 2 ]
guard 'gh api --method=post repos/acme/widgets/issues -f body=SECRETNAME'
[ "$status" -eq 2 ]
}

# graphql always POSTs: a query only reads, a mutation publishes.
# bats test_tags=unit
@test "gh api graphql: a query passes, a mutation is scanned" {
guard 'gh api graphql -f query="{ repository(owner: \"SECRETNAME\", name: \"x\") { id } }"'
[ "$status" -eq 0 ]
guard 'gh api graphql -f query="mutation { addComment(input: {body: \"SECRETNAME\"}) { clientMutationId } }"'
[ "$status" -eq 2 ]
guard 'gh api graphql -f query="MUTATION { x(body: \"SECRETNAME\") }"'
[ "$status" -eq 2 ]
printf '{"query":"mutation { x(body: \\"SECRETNAME\\") }"}' >"$BATS_TEST_TMPDIR/m.json"
guard "gh api graphql --input $BATS_TEST_TMPDIR/m.json"
[ "$status" -eq 2 ]
}

# A read chained to a write must not carry the write through unscanned.
# bats test_tags=unit
@test "a gh api read chained to a write still checks the write" {
guard 'gh api repos/acme/widgets && git commit -m "add SECRETNAME"'
[ "$status" -eq 2 ]
guard 'gh api repos/acme/widgets; gh pr comment 3 --body "SECRETNAME"'
[ "$status" -eq 2 ]
commit_as "names SECRETNAME"
guard 'gh api repos/acme/widgets --jq .id && git push origin HEAD'
[ "$status" -eq 2 ]
}

# The endpoint names the repository, so its visibility decides, as -R does.
# bats test_tags=unit
@test "a gh api write takes its repository from the endpoint" {
visibility PRIVATE
guard 'gh api repos/acme/private/issues -f body="SECRETNAME"'
[ "$status" -eq 0 ]
visibility PUBLIC
guard 'gh api repos/acme/open/issues -f body="SECRETNAME"'
[ "$status" -eq 2 ]
[[ "$output" == *"acme/open"* ]]
}

# Two repositories in one command: the visibility of one cannot clear the other.
# bats test_tags=unit
@test "several repositories in one command are checked as unknown" {
visibility PRIVATE
guard 'gh api repos/acme/private/issues -f body=x; gh api repos/acme/open/issues -f body="SECRETNAME"'
[ "$status" -eq 2 ]
[[ "$output" == *"unknown visibility"* ]]
}

# Where the text goes is not the text: an owner a needle matches may be
# addressed, as long as nothing published names it.
# bats test_tags=unit
@test "the address is not scanned, only the text sent to it" {
guard 'gh api repos/SECRETNAME/widgets/issues -f body="all clean"'
[ "$status" -eq 0 ]
guard 'gh pr create -R SECRETNAME/widgets --title t --body "all clean"'
[ "$status" -eq 0 ]
guard 'gh pr create -R SECRETNAME/widgets --title t --body "hello SECRETNAME"'
[ "$status" -eq 2 ]
}

# Text these commands publish, missed before.
# bats test_tags=unit
@test "other gh commands that publish text are checked" {
local c
for c in 'gh pr merge 1 --subject "SECRETNAME"' 'gh pr close 1 --comment "SECRETNAME"' \
'gh issue close 1 --comment "SECRETNAME"' 'gh repo edit --description "SECRETNAME"' \
'gh repo create acme/new --public --description "SECRETNAME"' 'gh label create bug --description "SECRETNAME"' \
'gh gist edit 1 --desc "SECRETNAME"' 'gh workflow run ci.yml -f note="SECRETNAME"'; do
guard "$c"
[ "$status" -eq 2 ] || { echo "not checked: $c"; return 1; }
done
}

# git's global options between git and the subcommand hid the commit.
# bats test_tags=unit
@test "git global options before commit or push do not hide them" {
guard 'git -c commit.gpgsign=false commit -m "add SECRETNAME"'
[ "$status" -eq 2 ]
guard 'git --no-pager -c x=y commit -m "add SECRETNAME"'
[ "$status" -eq 2 ]
commit_as "names SECRETNAME"
guard 'git -c push.default=current push origin'
[ "$status" -eq 2 ]
}

# A repository can push to a GitHub remote that is not origin (a mirror).
# bats test_tags=unit
@test "a push to a named remote checks that remote, not origin" {
git remote set-url origin https://dev.azure.example/acme/_git/widgets
git remote add github https://github.com/acme/widgets.git
commit_as "names SECRETNAME"
guard 'git push origin HEAD'
[ "$status" -eq 0 ]
guard 'git push github HEAD'
[ "$status" -eq 2 ]
guard 'git push -u --force-with-lease github main'
[ "$status" -eq 2 ]
guard 'git push https://github.com/acme/widgets.git HEAD'
[ "$status" -eq 2 ]
}

# A word that is no remote (a misread flag value) must not read as "not GitHub".
# bats test_tags=unit
@test "a push to an unresolvable remote is checked, not waved through" {
git remote set-url origin https://dev.azure.example/acme/_git/widgets
commit_as "names SECRETNAME"
guard 'git push -o ci.skip github-mirror HEAD'
[ "$status" -eq 2 ]
}

# Pushing a branch other than HEAD sends that branch's messages.
# bats test_tags=unit
@test "a push checks every local branch the remote lacks, not only HEAD" {
commit_as "first"
git checkout -q -b other
commit_as "names SECRETNAME"
git checkout -q -
guard 'git push origin other'
[ "$status" -eq 2 ]
}

# Annotated tag messages travel with --tags and --follow-tags.
# bats test_tags=unit
@test "a push that sends tags checks annotated tag messages" {
commit_as "first"
git -c user.name=t -c user.email=t@example.invalid tag -a v1 -m "release SECRETNAME"
guard 'git push origin --follow-tags'
[ "$status" -eq 2 ]
guard 'git push origin v1 --tags'
[ "$status" -eq 2 ]
}

@test "gh api writes with attached short flags are still checked" {
guard 'gh api repos/acme/widgets/issues -ftitle=SECRETNAME'
[ "$status" -eq 2 ]
guard 'gh api repos/acme/widgets/issues -Fbody=SECRETNAME'
[ "$status" -eq 2 ]
guard 'gh api -XPATCH repos/acme/widgets/pulls/1 --input=- <<<"SECRETNAME"'
[ "$status" -eq 2 ]
guard 'gh api -XPOST repos/acme/widgets/dispatches -H "X: SECRETNAME"'
[ "$status" -eq 2 ]
}
Loading