tools: pii-scan guard with a private pattern list, tag-release gate and pre-push hook

tools/pii-scan.sh scans the tree, a commit range (added lines and messages) or a push
(pre-push protocol, incl. annotated tag messages). Generic shapes stay in the script; the
proper nouns move to the operator's private list ($FLY_PII_PATTERNS), which can also name
env files whose values are matched as literals and never printed. lint.sh section 5 now
runs it (a missing list is a note, so public CI still passes) and no longer spells the
names with one bracketed character. tag-release.sh fails closed without the list and scans
the tree and every line since the previous tag. tools/install-hooks.sh installs a pre-push
hook that scans pushes to github. Tests in infra/tests/pii-scan-test.sh.
This commit is contained in:
acamilo 2026-09-29 15:52:35 +00:00
parent 49a00bc84a
commit 05324293ee
8 changed files with 607 additions and 106 deletions

View file

@ -32,6 +32,8 @@ Read `docs/architecture-tour.md` first. Then `docs/stream-mvp-plan.md` for decis
LAN addresses, container ids, host paths, account ids, channel names, people's names, `pass`
entry names or forge URLs. Say "the host", "the release container", "the dev container", "the
channel", "the operator"; put the real values in the operator's infra repo. Real values belong
in an env file outside the checkout — see `infra/env/README.md`. `infra/tests/lint.sh` refuses
the patterns; the rules live in the operator's infra repo and
`infra/tests/de-pii-allow.txt` the few legitimate mentions.
in an env file outside the checkout — see `infra/env/README.md`. `tools/pii-scan.sh` refuses
the patterns (run by `infra/tests/lint.sh`, `infra/build/tag-release.sh` and the pre-push hook
from `tools/install-hooks.sh`); the proper nouns it looks for live in the operator's private
pattern list (`$FLY_PII_PATTERNS`), never here, and `infra/tests/de-pii-allow.txt` lists the few
legitimate mentions. Run `tools/install-hooks.sh` once per clone.

View file

@ -38,6 +38,19 @@ branch="$(git rev-parse --abbrev-ref HEAD)"
if git rev-parse -q --verify "refs/tags/${TAG}" >/dev/null; then
die "refusing to tag: ${TAG} already exists (git tag -l ${TAG})"
fi
# A tag is published with its whole history, so the privacy scan runs first and fails
# closed: without the operator's private pattern list ($FLY_PII_PATTERNS) it cannot see
# host names, people's names, the channel or pass entry names, and a tag is not cut blind.
# It checks the tree being tagged and every line added since the previous tag.
log "running tools/pii-scan.sh (private pattern list required)"
"${REPO_DIR}/tools/pii-scan.sh" --require-private --tree HEAD \
|| die "refusing to tag: tools/pii-scan.sh found identifying strings in the tree (or its private pattern list is missing) — see above"
prev_tag="$(git describe --tags --abbrev=0 --match 'v[0-9]*' HEAD 2>/dev/null || true)"
pii_range="HEAD"
[ -z "$prev_tag" ] || pii_range="${prev_tag}..HEAD"
"${REPO_DIR}/tools/pii-scan.sh" --require-private --range "$pii_range" \
|| die "refusing to tag: tools/pii-scan.sh found identifying strings in commits since ${prev_tag:-the root} (a tag publishes them even if a later commit removed them) — see above"
git fetch --tags >/dev/null 2>&1 \
&& log "fetched tags from the remote" \
|| log "WARNING: git fetch --tags failed (no remote configured, or offline) — checking only against local tag state"

View file

@ -1,33 +1,32 @@
# infra/tests/de-pii-allow.txt — the mentions infra/tests/lint.sh's de-PII
# guard (section 5) is allowed to find.
# infra/tests/de-pii-allow.txt — the mentions tools/pii-scan.sh (run by
# infra/tests/lint.sh section 5, infra/build/tag-release.sh and the pre-push hook)
# is allowed to find.
#
# Format, whitespace-separated:
#
# <path> <pattern-name> # reason
#
# <path> is a repo-relative path, a directory prefix ending in `/`, or a glob.
# <pattern-name> is one of the guard's own names (host-proxmox, host-backup,
# host-llm, operator-name, lan-address, container-id, host-root-path,
# home-path, twitch-account, claim-log-name, forge-name, infra-repo-name,
# mac-address, email-address, pass-entry-path), or `*` for every pattern.
# <pattern-name> is a pattern name: a generic one from tools/pii-scan.sh
# (`tools/pii-scan.sh --list`), one from the operator's private pattern list
# (operator-name, forge-name, ...), or `*` for every pattern.
#
# EVERY LINE NEEDS A REASON. The right fix is almost always to redact instead —
# the rules and the per-file verdicts live in the operator's infra repo.
# An entry here says "this string is not identifying", not "this is grandfathered".
#
# The literals in the comments below are spelled with one bracketed character, for
# the same reason lint.sh spells its patterns that way: an allowlist that carried the
# plaintext would be the leak it is meant to prevent.
# Comments below describe what a mention is, never the private string itself: an
# allowlist that carried the plaintext would be the leak it is meant to prevent.
# --- chat-username fixtures -------------------------------------------------
# Lowercase `"alex"` is the chat-username fixture the sanitizer, deny-list,
# A lowercase first name is the chat-username fixture the sanitizer, deny-list,
# rate-limiter, ticker and store tests are written against; the de-PII sprint
# leaves test fixture names alone. The guard's operator-name pattern is
# case-sensitive precisely so capitalised `Al[e]x` in prose still fails, and
# `al[e]x_camilo` (the real handle shape) was replaced with `fly_fan_42`. These
# entries exist only for the few places a fixture is lowercase-with-a-boundary
# that the case-sensitive pattern would still catch via another alternative.
# leaves test fixture names alone. The operator-name pattern is case-sensitive
# precisely so the capitalised name in prose still fails, and the real handle
# was replaced with `fly_fan_42`. These entries exist only for the few places a
# fixture is lowercase-with-a-boundary that the pattern would still catch via
# another alternative.
apps/stage/tests/unit/ operator-name # lowercase chat-username fixtures
services/flysim/crates/flysim/tests/ operator-name # lowercase chat-username fixtures
services/flysim/crates/flysim/src/chat.rs operator-name # sanitizer unit-test fixtures in the same file
@ -35,12 +34,12 @@ services/flysim/crates/flysim/src/eventlog.rs operator-name # ticker fixture in
services/bridge/tests/ operator-name # lowercase chat-username fixtures
# --- container-side paths ---------------------------------------------------
# `/ro[o]t/nvidia.run`, `/ro[o]t/virtualgl.deb` and `/ro[o]t/nv.run` are paths INSIDE
# `nvidia.run`, `virtualgl.deb` and `nv.run` under root's home are paths INSIDE
# a container: root's home on a stock Debian guest, not an operator-chosen
# location, and not specific to this network. Host-side staging paths are
# parameterised instead (HOST_STAGE_DIR / `<host-stage>`).
infra/02-base.sh host-root-path # /ro[o]t/nvidia.run and /ro[o]t/virtualgl.deb are inside the guest
docs/design/gpu.md host-root-path # same two paths, plus /proc/<pid>/ro[o]t/... which is procfs, not /root
infra/02-base.sh host-root-path # the two installer paths under root's home are inside the guest
docs/design/gpu.md host-root-path # same two paths, plus /proc/<pid>/ root links, which are procfs
# --- documentation examples -------------------------------------------------
# A made-up MAC in a worked example of the compatibility string. Real MACs are
@ -51,11 +50,16 @@ services/flysim/crates/flybrain-gb/src/compatibility.rs mac-address # aa:bb:...
# Third-party addresses and handles: upstream projects, not this network.
# (None currently; keep the section so the next one lands in the right place.)
apps/stage/public/fonts/ email-address # SIL OFL licence text from upstream font projects; not ours to edit
infra/tests/lint.sh email-address # `lint@ex[a]mple.invalid`, the git identity for the throwaway test repos
infra/tests/lint.sh email-address # the example.invalid git identity for the throwaway test repos
infra/tests/pii-scan-test.sh email-address # same example.invalid identity for the scanner's throwaway repos
# --- publish pack ------------------------------------------------------------
NOTICE operator-name # the copyright holder's legal name, chosen by the operator 2026-09-17; change here if an entity is preferred
LICENSES.md operator-name # same copyright line, mirrored
.forgejo/workflows/ci.yml forge-name # the product name of the CI runner (F[o]rgejo Actions), not the operator's forge
.github/workflows/ci.yml forge-name # a comment naming the F[o]rgejo copy of this workflow
.forgejo/workflows/ci.yml forge-name # the product name of the CI runner, not the operator's forge
.github/workflows/ci.yml forge-name # a comment naming the sibling copy of this workflow
infra/docs/secrets-history-scan.md forge-name # names the two workflow files by path
infra/tests/de-pii-allow.txt forge-name # this file names the .f[o]rgejo/ workflow directory in the two entries above
infra/tests/de-pii-allow.txt forge-name # this file names that workflow directory in the entry above
# --- fixtures ----------------------------------------------------------------
apps/stage/tests/unit/query.test.ts private-address # made-up address in a feed-URL parsing fixture
services/bridge/tests/ secret-assignment # fake client id/secret fixtures ("test-client-secret-DO-NOT-LOG")

View file

@ -31,6 +31,9 @@ mapfile -t SHELL_SCRIPTS < <(
# nothing else ever exercises it before it runs as root, at boot,
# against /etc/pve.
find "$INFRA_DIR/host" -name '*.sh' -type f
# the privacy guard lives in tools/ because the pre-push hook and
# tag-release run it too.
find "$INFRA_DIR/../tools" -maxdepth 1 -name '*.sh' -type f
} | sort -u
)
@ -1386,16 +1389,13 @@ fi
# forge URLs. The rules, and the keep/move/redact verdict behind every file
# that was touched, live in the operator's infra repo.
#
# Two things about the patterns below are deliberate:
#
# * Each proper noun is spelled with ONE bracketed character — `sp[i]cy`,
# `chonk[e]rs`, `Al[e]x`. The regex still matches the real string exactly,
# but the literal token does not appear in this file, so the guard does not
# itself become the last copy of what it refuses. Do not "tidy" the
# brackets away.
# * `operator-name` is the only case-SENSITIVE pattern. Capitalised `Al[e]x` in
# prose is the operator; lowercase quoted `"al[e]x"` is a chat-username
# fixture all through the tests, which the sprint explicitly leaves alone.
# The scan is tools/pii-scan.sh. It carries only GENERIC shapes (addresses,
# container ids, host paths, e-mail, credential shapes); the proper nouns are
# loaded at run time from the operator's private pattern list
# ($FLY_PII_PATTERNS), so the guard is not itself a list of what it refuses.
# Here a missing private list is a NOTE (public CI has none, by design);
# infra/build/tag-release.sh and the pre-push hook (tools/install-hooks.sh)
# fail closed instead.
#
# Legitimate mentions are listed in infra/tests/de-pii-allow.txt, one
# `path pattern-name # reason` per line. Add to it only with a reason; the
@ -1406,81 +1406,29 @@ echo "--- de-PII guard ---"
REPO_ROOT="$(cd "$INFRA_DIR/.." && pwd)"
DEPII_ALLOW="$INFRA_DIR/tests/de-pii-allow.txt"
DEPII_NAMES=(); DEPII_FLAGS=(); DEPII_RES=()
depii() { DEPII_NAMES+=("$1"); DEPII_FLAGS+=("$2"); DEPII_RES+=("$3"); }
# name grep flags regex (one bracketed char per proper noun)
depii host-proxmox '-i' 'sp[i]cy'
depii host-backup '-i' 'chonk[e]rs'
depii host-llm '-i' '\bsl[o]th\b'
depii operator-name '' '\bAl[e]x\b|al[e]x_camilo|al[e]x\.camilo|al[e]x-(copy|ui)-taste'
depii lan-address '-i' '192\.168\.[0-9]{1,3}\.[0-9]{1,3}|\b2600:[0-9a-f]'
depii container-id '-i' '\b(ct|vm)[ _-]?[12][0-9][0-9]\b|\bpct +[a-z-]+ +[0-9]{2,4}\b|subvol-[12][0-9][0-9]-disk|/lxc/[12][0-9][0-9]\.conf'
depii host-root-path '' '/ro[o]t/'
depii home-path '' '/ho[m]e/[a-z]'
depii twitch-account '-i' '15412[6]9693|aflyplayspok[e]mon'
depii claim-log-name '' 'AGENTS[_]LOG'
depii forge-name '-i' 'forg[e]jo|git[e]a'
depii infra-repo-name '-i' 'trik[i]lli'
depii mac-address '' '\b([0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}\b'
depii email-address '' '[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+\.[A-Za-z]{2,}'
depii pass-entry-path '' '\bpass +(show|insert) +[A-Za-z0-9._-]+/'
# depii_allowed PATH PATTERN_NAME — true when de-pii-allow.txt excuses this
# pair. A path entry may end in `/` (directory prefix) or `*` (glob).
depii_allowed() {
local path="$1" name="$2" a_path a_name rest
[ -f "$DEPII_ALLOW" ] || return 1
while read -r a_path a_name rest; do
case "$a_path" in ''|'#'*) continue ;; esac
[ "$a_name" = "$name" ] || [ "$a_name" = '*' ] || continue
case "$a_path" in
*/) case "$path" in "$a_path"*) return 0 ;; esac ;;
*\**) # shellcheck disable=SC2254
case "$path" in $a_path) return 0 ;; esac ;;
*) [ "$path" = "$a_path" ] && return 0 ;;
esac
done < "$DEPII_ALLOW"
return 1
}
# The tree, minus what the sprint deliberately excludes: the connectome data
# (neuron ids and column CSVs, no house strings), the npm lockfile, and
# .local/ (untracked anyway). Prefer `git grep` — it honours .gitignore and is
# an order of magnitude faster — and fall back to grep -r for a checkout that
# is not a git repo (a release tarball unpacked on the host).
depii_scan() {
local flags="$1" re="$2"
if git -C "$REPO_ROOT" rev-parse --git-dir >/dev/null 2>&1; then
# shellcheck disable=SC2086
git -C "$REPO_ROOT" grep -nI $flags -E -e "$re" -- \
. ':!data' ':!package-lock.json' 2>/dev/null || true
else
# shellcheck disable=SC2086
grep -rnI $flags -E -e "$re" "$REPO_ROOT" \
--exclude-dir=data --exclude-dir=.git --exclude-dir=node_modules \
--exclude-dir=.local --exclude-dir=target --exclude=package-lock.json \
2>/dev/null | sed "s|^${REPO_ROOT}/||" || true
fi
}
DEPII_OUT="$("$REPO_ROOT/tools/pii-scan.sh" --allow "$DEPII_ALLOW" --tree 2>&1)" && DEPII_RC=0 || DEPII_RC=$?
DEPII_HITS=0
for i in "${!DEPII_NAMES[@]}"; do
name="${DEPII_NAMES[$i]}"
while IFS= read -r line; do
[ -n "$line" ] || continue
hit_path="${line%%:*}"
depii_allowed "$hit_path" "$name" && continue
fail "de-PII: ${name}: ${line}"
DEPII_HITS=$((DEPII_HITS + 1))
done < <(depii_scan "${DEPII_FLAGS[$i]}" "${DEPII_RES[$i]}")
done
case "$line" in
"pii-scan: NOTE:"*) echo "$line" ;;
"pii-scan: clean"*|"pii-scan: "*" finding(s) "*|"") ;;
"pii-scan: "*) fail "de-PII: ${line#pii-scan: }"; DEPII_HITS=$((DEPII_HITS + 1)) ;;
esac
done <<<"$DEPII_OUT"
if [ "$DEPII_HITS" -eq 0 ]; then
pass "de-PII guard: no identifying strings outside tests/de-pii-allow.txt (${#DEPII_NAMES[@]} patterns)"
else
if [ "$DEPII_RC" -eq 0 ] && [ "$DEPII_HITS" -eq 0 ]; then
pass "de-PII guard: $(printf '%s\n' "$DEPII_OUT" | grep -o 'clean.*' | tail -1)"
elif [ "$DEPII_HITS" -gt 0 ]; then
echo " ^ redact these (rules in the operator's infra repo), or, if the" >&2
echo " mention is genuinely legitimate, add it to infra/tests/de-pii-allow.txt with a reason." >&2
else
fail "de-PII guard: tools/pii-scan.sh exited ${DEPII_RC}: ${DEPII_OUT}"
fi
if "$INFRA_DIR/tests/pii-scan-test.sh" >/dev/null 2>&1; then
pass "pii-scan tests: tree, range, commit message, value needles, allowlist, fail-closed, pre-push hook"
else
fail "pii-scan tests failed; run infra/tests/pii-scan-test.sh"
fi
echo "--- loop recovery tests ---"

172
infra/tests/pii-scan-test.sh Executable file
View file

@ -0,0 +1,172 @@
#!/usr/bin/env bash
# infra/tests/pii-scan-test.sh — tests for tools/pii-scan.sh and tools/install-hooks.sh.
#
# Everything runs in throwaway repos under a temp dir, against a throwaway private pattern
# list. The fake identifying values are assembled at run time from pieces, so no complete
# fake value (and no real one) appears in this file for the tree scan to trip over.
set -euo pipefail
REPO="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
T="$(mktemp -d)"
trap 'rm -rf "$T"' EXIT
FAILS=0
ok() { echo "ok - $*"; }
bad() { echo "FAIL - $*"; FAILS=$((FAILS + 1)); }
# expect RC DESC -- CMD...: run CMD, capture output in $OUT, check the exit code
# the tree scan covers TRACKED files (git grep), like the guard it replaced
track() { git -C "$W" add -A; }
expect() {
local want="$1" desc="$2"; shift 3
local rc=0
OUT="$("$@" 2>&1)" || rc=$?
if [ "$rc" -eq "$want" ]; then ok "$desc"; else bad "$desc (exit $rc, wanted $want)"; printf '%s\n' "$OUT" | sed 's/^/ /'; fi
}
contains() { case "$OUT" in *"$1"*) ok "$2" ;; *) bad "$2 (missing '$1')"; printf '%s\n' "$OUT" | sed 's/^/ /' ;; esac; }
not_contains() { case "$OUT" in *"$1"*) bad "$2 (output leaks '$1')" ;; *) ok "$2" ;; esac; }
# --- fake private values, built from pieces -------------------------------------------
HOST="zorb""lequin" # a "host name"
PERSON="Quen""tavius" # a "person"
SECRET="fk""Q7pL2xV9""mZ4rT8wY""1nB6" # a "router key"
LAN="192.168"".77.21"
MAIL="someone""@""example.org"
mkdir -p "$T/private"
printf 'FAKE_ROUTER_KEY=%s\nSHORT=abc\n' "$SECRET" > "$T/private/router.env"
cat > "$T/private/patterns.txt" <<EOF
# test list
house-host -i ${HOST}
operator-name - \\b${PERSON}\\b
@values $T/private/router.env
EOF
export FLY_PII_PATTERNS="$T/private/patterns.txt"
# --- a throwaway repo with the scanner in it ------------------------------------------
W="$T/work"
git init -q -b main "$W"
git -C "$W" config user.name lint
git -C "$W" config user.email lint@example.invalid
mkdir -p "$W/tools" "$W/infra/tests" "$W/src"
cp "$REPO/tools/pii-scan.sh" "$REPO/tools/install-hooks.sh" "$W/tools/"
printf '# allowlist\n' > "$W/infra/tests/de-pii-allow.txt"
echo "hello" > "$W/src/a.txt"
git -C "$W" add -A && git -C "$W" commit -qm "init"
SCAN="$W/tools/pii-scan.sh"
expect 0 "clean tree passes" -- "$SCAN" --tree
contains "private list loaded" "private list is reported loaded"
expect 0 "--list prints names" -- "$SCAN" --list
contains "house-host" "--list includes private names"
not_contains "$HOST" "--list never prints a private regex"
# generic pattern
echo "feed at ws://${LAN}:7400" > "$W/src/b.txt"
track
expect 1 "LAN address in the tree fails" -- "$SCAN" --tree
contains "lan-address: src/b.txt:1:" "finding names the pattern and the location"
not_contains "$LAN" "the address itself is not echoed"
git -C "$W" rm -qf src/b.txt
# private noun, case-insensitive
echo "ssh root@$(echo "$HOST" | tr a-z A-Z).example" > "$W/src/c.txt"
track
expect 1 "private host name fails" -- "$SCAN" --tree
contains "house-host: src/c.txt:1:" "private name reported by its pattern name"
not_contains "$HOST" "private host name is not echoed"
git -C "$W" rm -qf src/c.txt
# case-sensitive private pattern: lowercase fixture passes, capitalised fails
echo "user: $(echo "$PERSON" | tr A-Z a-z)" > "$W/src/d.txt"
track
expect 0 "case-sensitive pattern ignores the lowercase fixture" -- "$SCAN" --tree
echo "by ${PERSON}" > "$W/src/d.txt"
track
expect 1 "case-sensitive pattern catches the capitalised name" -- "$SCAN" --tree
git -C "$W" rm -qf src/d.txt
# literal secret value from @values
echo "KEY=${SECRET}" > "$W/src/e.env"
track
expect 1 "a literal secret value fails" -- "$SCAN" --tree
contains "secret-value:FAKE_ROUTER_KEY: src/e.env:1:" "value finding names the env KEY"
not_contains "${SECRET:0:6}" "secret value is fully redacted"
git -C "$W" rm -qf src/e.env
# credential shape
echo "export STREAM_KEY=\"live_123456""7_abcdefghijABCDEFGHIJ123\"" > "$W/src/f.sh"
track
expect 1 "stream-key shape fails" -- "$SCAN" --tree
contains "secret-twitch" "stream key reported as secret-twitch"
git -C "$W" rm -qf src/f.sh
# allowlist
echo "contact ${MAIL}" > "$W/src/g.txt"
track
expect 1 "e-mail address fails" -- "$SCAN" --tree
printf 'src/g.txt email-address # upstream licence contact\n' >> "$W/infra/tests/de-pii-allow.txt"
expect 0 "allowlisted path/name pair passes" -- "$SCAN" --tree
printf 'src/ house-host # a different name does not excuse\n' >> "$W/infra/tests/de-pii-allow.txt"
echo "${LAN}" > "$W/src/g2.txt"
track
expect 1 "an allow entry excuses only its own pattern name" -- "$SCAN" --tree
git -C "$W" rm -qf src/g.txt src/g2.txt
printf '# allowlist\n' > "$W/infra/tests/de-pii-allow.txt"
# fail closed / open
expect 2 "--require-private without the list exits 2" -- env FLY_PII_PATTERNS="$T/nope" "$SCAN" --require-private --tree
contains "private pattern list not found" "missing list is named"
expect 0 "without --require-private a missing list is a NOTE" -- env FLY_PII_PATTERNS="$T/nope" "$SCAN" --tree
contains "NOTE: no private pattern list" "NOTE printed"
printf 'broken-line\n' > "$T/private/broken.txt"
expect 2 "a malformed private list is an error, not a silent pass" -- env FLY_PII_PATTERNS="$T/private/broken.txt" "$SCAN" --tree
# range: added then removed is still published history
base="$(git -C "$W" rev-parse HEAD)"
echo "on ${HOST} today" > "$W/src/h.txt"; git -C "$W" add -A; git -C "$W" commit -qm "add h"
git -C "$W" rm -q src/h.txt; git -C "$W" commit -qm "remove h"
expect 0 "tree is clean after the removal" -- "$SCAN" --tree
expect 1 "range still finds the line a commit added" -- "$SCAN" --range "${base}..HEAD"
contains "house-host:" "range finding names the pattern"
contains "src/h.txt:1" "range finding names path and line"
git -C "$W" commit -q --allow-empty -m "deploy to ${HOST}"
expect 1 "range scans commit messages" -- "$SCAN" --range "HEAD~1..HEAD"
contains "<commit-message>:1" "message finding is marked"
git -C "$W" reset -q --hard "$base"
git -C "$W" status --porcelain | grep -q . && bad "work repo not clean before the hook tests" || true
# --- pre-push hook ---------------------------------------------------------------------
git init -q --bare "$T/pub.git"
git init -q --bare "$T/priv.git"
git -C "$W" remote add github "$T/pub.git"
git -C "$W" remote add origin "$T/priv.git"
expect 0 "install-hooks installs" -- "$W/tools/install-hooks.sh"
[ -x "$W/.git/hooks/pre-push" ] && ok "hook is executable" || bad "hook missing"
expect 0 "install-hooks is idempotent" -- "$W/tools/install-hooks.sh"
expect 0 "clean push to github is accepted" -- git -C "$W" push -q github main
echo "at ${LAN}" > "$W/src/i.txt"; git -C "$W" add -A; git -C "$W" commit -qm "i"
expect 1 "push with PII to github is refused" -- git -C "$W" push -q github main
contains "refusing to publish" "hook explains the refusal"
expect 0 "push to a private remote is not scanned" -- git -C "$W" push -q origin main
git -C "$W" rm -q src/i.txt; git -C "$W" commit -qm "rm i"
expect 1 "removing it in a later commit does not unblock the push" -- git -C "$W" push -q github main
git -C "$W" reset -q --hard github/main
git -C "$W" tag -a v9.9.9 -m "release for ${HOST}"
expect 1 "annotated tag message is scanned" -- git -C "$W" push -q github v9.9.9
contains "<tag-message>" "tag finding is marked"
git -C "$W" tag -d v9.9.9 >/dev/null
git -C "$W" tag -a v9.9.8 -m "release"
expect 0 "clean annotated tag is accepted" -- git -C "$W" push -q github v9.9.8
git -C "$W" commit -q --allow-empty -m "clean"
expect 1 "push is refused when the private list is missing" -- env FLY_PII_PATTERNS="$T/nope" git -C "$W" push -q github main
git -C "$W" checkout -q -b old "$base"
rm -f "$W/tools/pii-scan.sh"
echo "x ${HOST}" > "$W/src/j.txt"; git -C "$W" add -A; git -C "$W" commit -qm "j"
expect 1 "a branch without tools/pii-scan.sh is scanned by the hook's own copy" -- git -C "$W" push -q github old
printf 'exit 0\n' > "$T/other-hook"
git -C "$W" checkout -q main
cp "$T/other-hook" "$W/.git/hooks/pre-push"
expect 1 "install-hooks refuses to clobber a foreign hook" -- "$W/tools/install-hooks.sh"
echo "==="
if [ "$FAILS" -eq 0 ]; then echo "pii-scan-test: ALL PASSED"; else echo "pii-scan-test: ${FAILS} FAILED"; exit 1; fi

View file

@ -104,3 +104,17 @@ files, so `packages/brain/tests/dataset.test.ts` is the end-to-end check that th
during extraction from the `fly-plays-pokemon` prototype. The circuit roles are now accumulated
in the same pass over the sorted `root_id` list that builds `meta.json`, which is what made the
two scripts agree on neuron indices in the first place.
# Privacy guard
`pii-scan.sh` refuses identifying strings and credentials in what this public repo publishes:
the tree (`--tree [REV]`), the lines and messages of a commit range (`--range`), or everything a
push would publish (`--push REMOTE`, the pre-push hook's mode). The generic shapes live in the
script; the proper nouns are loaded from the operator's private pattern list
(`$FLY_PII_PATTERNS`, default `~/.config/flybrain/pii-patterns.txt`), so the guard never spells
out what it refuses. `infra/tests/lint.sh` runs it and treats a missing list as a note;
`infra/build/tag-release.sh` and the pre-push hook fail closed without it.
`install-hooks.sh` installs the pre-push hook for this clone and all its worktrees; it scans
pushes to the `github` remote (and any github.com URL, or names in `$FLY_PII_PUBLIC_REMOTES`).
Tests: `infra/tests/pii-scan-test.sh`.

51
tools/install-hooks.sh Executable file
View file

@ -0,0 +1,51 @@
#!/usr/bin/env bash
# tools/install-hooks.sh [--force]
#
# Installs the flybrain pre-push hook into this clone's hooks directory (shared by every
# worktree). On a push to a PUBLIC remote — the remote named `github`, any name listed in
# $FLY_PII_PUBLIC_REMOTES, or any github.com URL — the hook runs tools/pii-scan.sh --push
# over every commit the push would publish (added lines and messages), annotated tag
# messages, and each pushed tip's tree. It fails closed: without the operator's private
# pattern list ($FLY_PII_PATTERNS, default ~/.config/flybrain/pii-patterns.txt) the push is
# refused. Pushes to other remotes are not scanned.
#
# A copy of the scanner is installed next to the hook so branches that predate
# tools/pii-scan.sh are still scanned; re-run this script after the scanner changes.
# `git push --no-verify` skips the hook, as for any git hook; do not.
set -euo pipefail
FORCE=0
[ "${1:-}" != --force ] || FORCE=1
SELF_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
hooks_dir="$(git -C "$SELF_DIR" rev-parse --path-format=absolute --git-path hooks)"
mkdir -p "$hooks_dir"
hook="$hooks_dir/pre-push"
marker="# flybrain pii-guard pre-push hook"
if [ -e "$hook" ] && ! grep -qF "$marker" "$hook" && [ "$FORCE" -ne 1 ]; then
echo "install-hooks: $hook exists and is not ours; merge it by hand or re-run with --force" >&2
exit 1
fi
install -m 0755 "$SELF_DIR/pii-scan.sh" "$hooks_dir/flybrain-pii-scan.sh"
cat > "$hook" <<'HOOK'
#!/usr/bin/env bash
# flybrain pii-guard pre-push hook (installed by tools/install-hooks.sh; re-run it to update)
set -euo pipefail
remote="$1" url="${2:-}"
public=0
for r in github ${FLY_PII_PUBLIC_REMOTES:-}; do [ "$remote" = "$r" ] && public=1; done
case "$url" in *github.com[:/]*) public=1 ;; esac
[ "$public" -eq 1 ] || exit 0
top="$(git rev-parse --show-toplevel)"
scan="$top/tools/pii-scan.sh"
[ -x "$scan" ] || scan="$(dirname "${BASH_SOURCE[0]}")/flybrain-pii-scan.sh"
allow="$top/infra/tests/de-pii-allow.txt"
if ! FLY_PII_REPO="$top" "$scan" --require-private --allow "$allow" --push "$remote"; then
echo "pre-push: refusing to publish to '${remote}': fix the findings above (or restore the private pattern list)." >&2
exit 1
fi
HOOK
chmod 0755 "$hook"
echo "install-hooks: installed $hook (public remotes: github ${FLY_PII_PUBLIC_REMOTES:-}, and github.com URLs)"

297
tools/pii-scan.sh Executable file
View file

@ -0,0 +1,297 @@
#!/usr/bin/env bash
# tools/pii-scan.sh — refuse identifying strings and secrets in what this public repo publishes.
#
# tools/pii-scan.sh [options] --tree [REV] tracked files at REV (default: the checkout)
# tools/pii-scan.sh [options] --range REVS... lines ADDED by those commits, plus their
# messages (git rev-list syntax: A..B, X --not Y)
# tools/pii-scan.sh [options] --push REMOTE pre-push mode: reads git's pre-push stdin
# ("<lref> <lsha> <rref> <rsha>" lines) and scans
# every commit the push would publish, their
# messages, annotated tag messages, and each tip
# tools/pii-scan.sh --list pattern names in force (never the regexes)
#
# Options:
# --patterns FILE the PRIVATE pattern list (default $FLY_PII_PATTERNS, else
# ${XDG_CONFIG_HOME:-~/.config}/flybrain/pii-patterns.txt)
# --require-private exit 2 when that file is missing (tag-release and pre-push use this:
# fail closed). Without it a missing file is a NOTE and only the generic
# patterns below run (public CI has no private list, by design).
# --allow FILE allowlist (default infra/tests/de-pii-allow.txt)
#
# Exit: 0 clean, 1 findings, 2 usage or configuration error.
#
# Why two pattern sets. The generic shapes below (LAN addresses, container ids, host paths,
# e-mail addresses, credential shapes) contain no proper noun, so they can live here. The
# proper nouns — host names, the operator's names and handles, the channel, account ids,
# `pass` entry names, the forge — are exactly what must not be published, so they live in a
# file outside this repo and are loaded at run time. A guard that spelled them out (even with
# one character bracketed) would itself be the leak.
#
# Private file format, one per line (`#` comments):
# <name> <flags> <extended regex> flags: -i (ignore case) or - (case-sensitive)
# @values <env-file> each KEY=VALUE value of 8+ chars in that file becomes a
# literal needle, reported as secret-value:<KEY>, with
# the matched text never printed
#
# Findings print as `pii-scan: <name>: <where>: <redacted match>`; the match is cut to its
# first three characters so a log of the scan does not republish what it found.
set -euo pipefail
SELF_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# FLY_PII_REPO: the checkout to scan. The pre-push hook sets it, because its fallback copy of
# this script lives in .git/hooks, outside any work tree.
REPO_ROOT="${FLY_PII_REPO:-$(git -C "$SELF_DIR" rev-parse --show-toplevel 2>/dev/null || (cd "$SELF_DIR/.." && pwd))}"
usage() { sed -n '2,20p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//' >&2; exit 2; }
die() { echo "pii-scan: $*" >&2; exit 2; }
PATTERNS_FILE="${FLY_PII_PATTERNS:-${XDG_CONFIG_HOME:-$HOME/.config}/flybrain/pii-patterns.txt}"
ALLOW_FILE="$REPO_ROOT/infra/tests/de-pii-allow.txt"
REQUIRE_PRIVATE=0
MODE=""
MODE_ARGS=()
while [ $# -gt 0 ]; do
case "$1" in
--patterns) PATTERNS_FILE="${2:?}"; shift 2 ;;
--allow) ALLOW_FILE="${2:?}"; shift 2 ;;
--require-private) REQUIRE_PRIVATE=1; shift ;;
--tree|--range|--push|--list) MODE="$1"; shift; MODE_ARGS=("$@"); break ;;
-h|--help) usage ;;
*) die "unknown argument: $1 (see --help)" ;;
esac
done
[ -n "$MODE" ] || usage
TMP="$(mktemp -d)"
chmod 700 "$TMP"
trap 'rm -rf "$TMP"' EXIT
# --------------------------------------------------------------------------------------
# Patterns. NAMES/FLAGS/RES are parallel arrays; KIND is `re` or `values` (a -F -f file).
# The two path patterns keep one bracketed character only so this file does not match
# itself; they are not proper nouns.
# --------------------------------------------------------------------------------------
NAMES=(); FLAGS=(); RES=(); KIND=()
pat() { NAMES+=("$1"); FLAGS+=("$2"); RES+=("$3"); KIND+=(re); }
# name flags extended regex
pat lan-address -i '\b192\.168\.[0-9]{1,3}\.[0-9]{1,3}\b|\b2600:[0-9a-f]'
pat private-address - '\b10\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\b|\b172\.(1[6-9]|2[0-9]|3[01])\.[0-9]{1,3}\.[0-9]{1,3}\b'
pat tailnet-address - '\b100\.(6[4-9]|[7-9][0-9]|1[01][0-9]|12[0-7])\.[0-9]{1,3}\.[0-9]{1,3}\b'
pat private-dns -i '(@|://)[a-z0-9.-]+\.(internal|lan|home\.arpa|ts\.net)\b|\b[a-z0-9-]+\.ts\.net\b|\bheadscale\b'
pat container-id -i '\b(ct|vm)[ _-]?[12][0-9][0-9]\b|\bpct +[a-z-]+ +[0-9]{2,4}\b|\bqm +[a-z-]+ +[0-9]{2,4}\b|subvol-[12][0-9][0-9]-disk|/lxc/[12][0-9][0-9]\.conf'
pat host-root-path - '/ro[o]t/'
pat home-path - '/ho[m]e/[a-z]'
pat claim-log-name - 'AGENTS[_]LOG'
pat mac-address - '\b([0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}\b'
pat email-address - '[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}'
pat pass-entry-path - '\bpass +(show|insert|edit|generate) +[A-Za-z0-9._-]+/'
pat secret-private-key - '-----BEGIN [A-Z ]*PRIVATE KEY-----'
pat secret-token-prefix - '\bsk-(or-v1-|proj-|ant-)?[A-Za-z0-9_-]{20,}|\bgh[pousr]_[A-Za-z0-9]{30,}|\bgithub_pat_[A-Za-z0-9_]{30,}|\bAKIA[0-9A-Z]{16}\b|\bxox[baprs]-[A-Za-z0-9-]{10,}|\bglpat-[A-Za-z0-9_-]{20,}'
pat secret-twitch - 'oauth:[a-z0-9]{20,}|\blive_[0-9]{6,}_[A-Za-z0-9]{20,}'
pat secret-client-id -i '(client[_-]?id|clientid)["'"'"' ]*[:=][ "'"'"']*[a-z0-9]{30}\b'
pat secret-bearer - '\b(Bearer|Basic) [A-Za-z0-9._~+/=-]{24,}'
pat secret-assignment - '(KEY|SECRET|TOKEN|PASSWORD|PASSWD)["'"'"']?[ ]*[:=][ ]*["'"'"']?[A-Za-z0-9][A-Za-z0-9_+/=-]{19,}'
PRIVATE_LOADED=0
if [ -r "$PATTERNS_FILE" ]; then
PRIVATE_LOADED=1
lineno=0
while IFS= read -r raw || [ -n "$raw" ]; do
lineno=$((lineno + 1))
line="${raw#"${raw%%[![:space:]]*}"}"
case "$line" in ''|'#'*) continue ;; esac
if [ "${line%% *}" = "@values" ]; then
vfile="${line#@values}"; vfile="${vfile#"${vfile%%[![:space:]]*}"}"
vfile="${vfile/#\~/$HOME}"
[ -r "$vfile" ] || die "$PATTERNS_FILE:$lineno: @values file is not readable: $vfile"
while IFS= read -r kv || [ -n "$kv" ]; do
case "$kv" in ''|'#'*) continue ;; esac
kv="${kv#export }"
case "$kv" in *=*) ;; *) continue ;; esac
key="${kv%%=*}"; val="${kv#*=}"
val="${val%\"}"; val="${val#\"}"; val="${val%\'}"; val="${val#\'}"
[ "${#val}" -ge 8 ] || continue
n=${#NAMES[@]}
printf '%s\n' "$val" > "$TMP/needle.$n"
NAMES+=("secret-value:${key}"); FLAGS+=(-); RES+=("$TMP/needle.$n"); KIND+=(values)
done < "$vfile"
continue
fi
read -r pname pflags pre <<<"$line"
[ -n "${pre:-}" ] || die "$PATTERNS_FILE:$lineno: expected '<name> <flags> <regex>'"
case "$pflags" in -i|-) ;; *) die "$PATTERNS_FILE:$lineno: flags must be -i or -, got '$pflags'" ;; esac
pat "$pname" "$pflags" "$pre"
done < "$PATTERNS_FILE"
elif [ "$REQUIRE_PRIVATE" -eq 1 ]; then
die "private pattern list not found: ${PATTERNS_FILE} (set FLY_PII_PATTERNS). Refusing: without it the scan cannot see host names, people's names, the channel or pass entry names."
else
echo "pii-scan: NOTE: no private pattern list (${PATTERNS_FILE}); generic patterns only" >&2
fi
if [ "$MODE" = "--list" ]; then
printf '%s\n' "${NAMES[@]}"
exit 0
fi
# --------------------------------------------------------------------------------------
# Allowlist: `<path> <pattern-name> # reason`; path may end in / (prefix) or hold a glob.
# --------------------------------------------------------------------------------------
ALLOW_PATHS=(); ALLOW_NAMES=()
if [ -r "$ALLOW_FILE" ]; then
while read -r a_path a_name _; do
case "$a_path" in ''|'#'*) continue ;; esac
ALLOW_PATHS+=("$a_path"); ALLOW_NAMES+=("$a_name")
done < "$ALLOW_FILE"
fi
allowed() {
local path="$1" name="$2" i a
for i in "${!ALLOW_PATHS[@]}"; do
a="${ALLOW_NAMES[$i]}"
[ "$a" = "$name" ] || [ "$a" = '*' ] || continue
a="${ALLOW_PATHS[$i]}"
case "$a" in
*/) case "$path" in "$a"*) return 0 ;; esac ;;
*\**) # shellcheck disable=SC2254
case "$path" in $a) return 0 ;; esac ;;
*) [ "$path" = "$a" ] && return 0 ;;
esac
done
return 1
}
HITS=0
# report NAME PATH WHERE MATCH
report() {
local name="$1" path="$2" where="$3" match="$4" shown
allowed "$path" "$name" && return 0
case "$name" in
secret-*) shown="<redacted ${#match} chars>" ;;
*) shown="${match:0:3}… (${#match} chars)" ;;
esac
echo "pii-scan: ${name}: ${where}: ${shown}"
HITS=$((HITS + 1))
}
grep_flags() { # INDEX -> grep flags for regex pattern i (value needles use -F -f)
local i="$1"
# printf, not echo: `echo -E` is echo's own option and prints nothing.
if [ "${FLAGS[$i]}" = -i ]; then printf '%s\n' "-i -E"; else printf '%s\n' "-E"; fi
}
# --------------------------------------------------------------------------------------
# --tree [REV]
# --------------------------------------------------------------------------------------
scan_tree() {
local rev="${1:-}" i flags line path rest lno match is_git=0
git -C "$REPO_ROOT" rev-parse --git-dir >/dev/null 2>&1 && is_git=1
[ -z "$rev" ] || [ "$is_git" -eq 1 ] || die "--tree $rev needs a git checkout"
for i in "${!NAMES[@]}"; do
flags="$(grep_flags "$i")"
while IFS= read -r line; do
[ -n "$line" ] || continue
[ -z "$rev" ] || line="${line#"$rev":}"
path="${line%%:*}"; rest="${line#*:}"; lno="${rest%%:*}"; match="${rest#*:}"
report "${NAMES[$i]}" "$path" "$path:$lno" "$match"
done < <(
if [ "${KIND[$i]}" = values ]; then set -- -F -f "${RES[$i]}"; else set -- $flags -e "${RES[$i]}"; fi
if [ "$is_git" -eq 1 ]; then
# shellcheck disable=SC2086
git -C "$REPO_ROOT" grep -noI "$@" ${rev:+"$rev"} -- . ':!data' ':!package-lock.json' 2>/dev/null || true
else
grep -rnoI "$@" "$REPO_ROOT" --exclude-dir=data --exclude-dir=.git \
--exclude-dir=node_modules --exclude-dir=.local --exclude-dir=target \
--exclude=package-lock.json 2>/dev/null | sed "s|^${REPO_ROOT}/||" || true
fi
)
done
}
# --------------------------------------------------------------------------------------
# --range REVS...: added lines (corpus + index "commit path line") and commit messages.
# --------------------------------------------------------------------------------------
scan_corpus() { # CORPUS INDEX
local corpus="$1" index="$2" i flags
[ -s "$corpus" ] || return 0
for i in "${!NAMES[@]}"; do
flags="$(grep_flags "$i")"
while IFS=$'\t' read -r commit path lno match; do
report "${NAMES[$i]}" "$path" "${commit:0:10} $path:$lno" "$match"
done < <(
# shellcheck disable=SC2086
if [ "${KIND[$i]}" = values ]; then grep -noa -F -f "${RES[$i]}" "$corpus" || true
else grep -noa $flags -e "${RES[$i]}" "$corpus" || true; fi \
| awk -F'\t' 'NR==FNR { idx[NR] = $0; next }
{ n = index($0, ":"); k = substr($0, 1, n - 1) + 0;
print idx[k] "\t" substr($0, n + 1) }' "$index" -
)
done
}
scan_range() {
local corpus="$TMP/added" index="$TMP/added.idx"
git -C "$REPO_ROOT" log -p --no-color --no-ext-diff --no-renames --unified=0 \
--format='PIISCAN-COMMIT %H' "$@" -- . ':!data' ':!package-lock.json' \
| awk -v corpus="$corpus" -v index_f="$index" '
/^PIISCAN-COMMIT / { commit = $2; path = ""; next }
/^\+\+\+ / { path = substr($0, 5); sub(/^b\//, "", path); if (path == "/dev/null") path = ""; next }
/^@@ / { if (match($0, /\+[0-9]+/)) ln = substr($0, RSTART + 1, RLENGTH - 1) + 0; next }
/^\+/ { if (path != "") { print substr($0, 2) > corpus; print commit "\t" path "\t" ln > index_f }; ln++; next }
'
touch "$corpus" "$index"
scan_corpus "$corpus" "$index"
local mcorpus="$TMP/msgs" mindex="$TMP/msgs.idx"
git -C "$REPO_ROOT" log --no-color --format='PIISCAN-COMMIT %H%n%B' "$@" \
| awk -v corpus="$mcorpus" -v index_f="$mindex" '
/^PIISCAN-COMMIT / { commit = $2; ln = 0; next }
{ ln++; print $0 > corpus; print commit "\t<commit-message>\t" ln > index_f }
'
touch "$mcorpus" "$mindex"
scan_corpus "$mcorpus" "$mindex"
}
scan_tag_message() { # TAG-OBJECT-SHA
local corpus="$TMP/tagmsg" index="$TMP/tagmsg.idx"
git -C "$REPO_ROOT" cat-file tag "$1" | sed '1,/^$/d' > "$corpus"
awk -v t="$1" '{ print t "\t<tag-message>\t" NR }' "$corpus" > "$index"
scan_corpus "$corpus" "$index"
}
# --------------------------------------------------------------------------------------
# --push REMOTE: git's pre-push protocol on stdin.
# --------------------------------------------------------------------------------------
ZERO=0000000000000000000000000000000000000000
scan_push() {
local remote="$1" lref lsha rref rsha
while read -r lref lsha rref rsha; do
[ -n "${lsha:-}" ] || continue
case "$lsha" in *[!0]*) ;; *) continue ;; esac # branch/tag deletion publishes nothing
echo "pii-scan: checking ${lref} -> ${remote} ${rref}" >&2
if [ "$(git -C "$REPO_ROOT" cat-file -t "$lsha")" = tag ]; then
scan_tag_message "$lsha"
fi
if [ "$rsha" != "$ZERO" ] && git -C "$REPO_ROOT" cat-file -e "${rsha}^{commit}" 2>/dev/null; then
scan_range "${rsha}..${lsha}"
else
scan_range "$lsha" --not --remotes="$remote"
fi
scan_tree "$(git -C "$REPO_ROOT" rev-parse "${lsha}^{commit}")"
done
}
case "$MODE" in
--tree) [ ${#MODE_ARGS[@]} -le 1 ] || die "--tree takes at most one REV"
scan_tree "${MODE_ARGS[0]:-}" ;;
--range) [ ${#MODE_ARGS[@]} -ge 1 ] || die "--range needs revisions"
scan_range "${MODE_ARGS[@]}" ;;
--push) [ ${#MODE_ARGS[@]} -eq 1 ] || die "--push takes the remote name"
scan_push "${MODE_ARGS[0]}" ;;
esac
if [ "$HITS" -gt 0 ]; then
echo "pii-scan: ${HITS} finding(s) (private list: $([ "$PRIVATE_LOADED" -eq 1 ] && echo loaded || echo absent)). Redact them — real values belong in the operator's infra repo — or, if a mention is genuinely not identifying, add '<path> <name> # reason' to infra/tests/de-pii-allow.txt." >&2
exit 1
fi
echo "pii-scan: clean (${#NAMES[@]} patterns, private list $([ "$PRIVATE_LOADED" -eq 1 ] && echo loaded || echo absent))" >&2