diff --git a/CLAUDE.md b/CLAUDE.md index e30bb93..4777198 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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. diff --git a/docs/design/infra.md b/docs/design/infra.md index e6aea86..33a21b5 100644 --- a/docs/design/infra.md +++ b/docs/design/infra.md @@ -555,7 +555,7 @@ into this project. | What | Where | Mode | |---|---|---| -| source of truth | `pass twitch/-key`, `twitch/-key`, `twitch/helix-client-id`, `twitch/helix-client-secret`, `twitch/fly-pokemon-bot-token` | WSL box only | +| source of truth | `pass twitch/-key`, `twitch/-key`, `twitch/-client-id`, `twitch/-client-secret`, `twitch/-token` | WSL box only | | stream key, in CT | `/etc/fly/creds/twitch-key.cred` | `root:root 0400`, dir `0700` | | bridge app creds, in CT | `/etc/fly/creds/twitch-app.cred` | `root:root 0400` | | bridge refresh tokens | `/var/lib/fly/bridge/tokens.json` | `fly:fly 0600` | diff --git a/docs/design/stage-bridge.md b/docs/design/stage-bridge.md index c05aa44..782231e 100644 --- a/docs/design/stage-bridge.md +++ b/docs/design/stage-bridge.md @@ -177,7 +177,7 @@ Node 22, TypeScript, `tsx` for dev, `node --test` for tests. Deps: `@twurple/aut One-time interactive authorization in `tools/authorize.mts`, run by hand on the WSL box, producing a refresh token. Primary path: authorization-code flow with a temporary `http://localhost:3000/callback` listener (Twitch permits `http://localhost` redirects) and `exchangeCode` from `@twurple/auth`. Device-code grant against `https://id.twitch.tv/oauth2/device` is the fallback for headless authorization; twurple's first-class support for it is **unverified**, so if used it is 30 lines of hand-rolled polling rather than a library claim. -Runtime uses `RefreshingAuthProvider` with `onRefresh` persisting to `/var/lib/flybridge/tokens.json`, written `0600` by an atomic temp-file rename, owned by the service user, never in git (`.gitignore` plus a repo-level check). `TWITCH_CLIENT_ID` and `TWITCH_CLIENT_SECRET` arrive via systemd `LoadCredentialEncrypted=`, sourced from `pass` on the WSL box under `twitch/fly-pokemon-client-{id,secret}`, matching the stream-key posture already documented. +Runtime uses `RefreshingAuthProvider` with `onRefresh` persisting to `/var/lib/flybridge/tokens.json`, written `0600` by an atomic temp-file rename, owned by the service user, never in git (`.gitignore` plus a repo-level check). `TWITCH_CLIENT_ID` and `TWITCH_CLIENT_SECRET` arrive via systemd `LoadCredentialEncrypted=`, sourced from `pass` on the WSL box under `twitch/-client-{id,secret}`, matching the stream-key posture already documented. Two identities, both registered on the provider: the **bot account** (chat send) and the **broadcaster account** (redemptions, predictions, markers). Scopes to request, with the intent recorded per scope: diff --git a/infra/06-secrets.sh b/infra/06-secrets.sh index f6d27b8..7a571c6 100755 --- a/infra/06-secrets.sh +++ b/infra/06-secrets.sh @@ -26,7 +26,7 @@ # docs/design/stage-bridge.md section B1 has flybridge read # TWITCH_CLIENT_ID and TWITCH_CLIENT_SECRET as two separate # LoadCredentialEncrypted= values sourced from -# twitch/fly-pokemon-client-{id,secret}. This script follows infra.md (the +# twitch/-client-{id,secret}. This script follows infra.md (the # doc this task implements) and writes ONE twitch-app.cred containing both # values as two lines ("\n\n"); flybridge's own # implementation (out of scope here, not yet written) will need to parse @@ -118,9 +118,14 @@ fi # docs/stream-mvp-plan.md's rollout order) — install only if both pass # entries already exist, so running this before the Twitch app is # registered is a clean no-op rather than a hard failure. -BRIDGE_ID_KEY="${BRIDGE_ID_KEY:-twitch/helix-client-id}" -BRIDGE_SECRET_KEY="${BRIDGE_SECRET_KEY:-twitch/helix-client-secret}" -if command -v pass >/dev/null 2>&1 \ +# The two entry NAMES come from the env file (BRIDGE_ID_KEY, BRIDGE_SECRET_KEY): a +# `pass` entry name identifies the operator's store, so it is not spelled here. +BRIDGE_ID_KEY="${BRIDGE_ID_KEY:-}" +BRIDGE_SECRET_KEY="${BRIDGE_SECRET_KEY:-}" +if [ -z "$BRIDGE_ID_KEY" ] || [ -z "$BRIDGE_SECRET_KEY" ]; then + log "06-secrets: WARNING: BRIDGE_ID_KEY / BRIDGE_SECRET_KEY are not set in the env file, skipping twitch-app." \ + "Set both to the pass entry names of the Twitch app id and secret (infra/env/example.env) to install it." +elif command -v pass >/dev/null 2>&1 \ && pass show "$BRIDGE_ID_KEY" >/dev/null 2>&1 \ && pass show "$BRIDGE_SECRET_KEY" >/dev/null 2>&1; then log "06-secrets: installing twitch-app from pass:${BRIDGE_ID_KEY} + pass:${BRIDGE_SECRET_KEY}" diff --git a/infra/build/tag-release.sh b/infra/build/tag-release.sh index dd4365c..2bccc3c 100755 --- a/infra/build/tag-release.sh +++ b/infra/build/tag-release.sh @@ -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" diff --git a/infra/docs/secrets-history-scan.md b/infra/docs/secrets-history-scan.md index 6e5e257..dbe137b 100644 --- a/infra/docs/secrets-history-scan.md +++ b/infra/docs/secrets-history-scan.md @@ -49,7 +49,7 @@ a credential. Full list: | # | shape matched | path | commits (first → last touching) | verdict | | --- | --- | --- | --- | --- | -| 1 | `pass show "$PASS_KEY"` shell pipelines, 4 blobs | `infra/06-secrets.sh` | `0d1a762` → `69816e6` | **False positive.** The script's whole job is to pipe `pass show` into `systemd-creds` on the container; the value never lands in a file and never in git. `PASS_KEY` holds a pass *entry name* (`twitch/fly-pokemon-key`), not a secret. | +| 1 | `pass show "$PASS_KEY"` shell pipelines, 4 blobs | `infra/06-secrets.sh` | `0d1a762` → `69816e6` | **False positive.** The script's whole job is to pipe `pass show` into `systemd-creds` on the container; the value never lands in a file and never in git. `PASS_KEY` holds a pass *entry name* (`twitch/-key`), not a secret. | | 2 | `pass show … \| head -c8` in a verify helper, 6 blobs | `infra/verify.sh` | `0d1a762` → `57276d4` | **False positive.** Reads the first 8 bytes of the stored key to compare a prefix against what the container holds. The prefix is computed at run time and printed nowhere that is committed. | | 3 | `accessToken:` / `refreshToken:` struct fields, 3 blobs | `services/bridge/src/auth.ts` | `d9f00b6` → `48cd40a` | **False positive.** Twurple `AccessToken` field names in code (`accessToken: token.accessToken`). No literal values. | | 4 | `accessToken:` / `refreshToken:` struct fields, 1 blob | `services/bridge/tools/authorize.mts` | `77f5892` | **False positive.** Same: the interactive authorize tool writes the token it just fetched to a path outside the repo. | diff --git a/infra/env/README.md b/infra/env/README.md index 0210427..0536f12 100644 --- a/infra/env/README.md +++ b/infra/env/README.md @@ -53,6 +53,8 @@ requires `CTID`, `HOSTNAME`, `IP`, `GAME` and `PUSH_TARGET`; `ROLE` defaults to Secrets. `PASS_KEY` holds the **name** of a `pass` entry, never a key. The Twitch app id/secret arrive as the systemd credential `twitch-app`, installed by -`infra/06-secrets.sh` from `pass` on the operator box; the OAuth tokens live in the +`infra/06-secrets.sh` from `pass` on the operator box, reading the two entry **names** from +`BRIDGE_ID_KEY` and `BRIDGE_SECRET_KEY` in the real env file (it skips `twitch-app` with a +warning when they are unset); the OAuth tokens live in the container as `/var/lib/flybridge/tokens.json`, mode 0600. `ROM_SHA256` is a digest, and the ROM it describes is never committed, copied into the repo, or shown on stream. diff --git a/infra/env/example.env b/infra/env/example.env index 4dae070..b4a9604 100644 --- a/infra/env/example.env +++ b/infra/env/example.env @@ -216,6 +216,11 @@ TWITCH_CHANNEL= # never is. 06-secrets.sh reads it on the operator box and installs it as a # systemd credential. PASS_KEY=twitch/-key +# The `pass` entries holding the Twitch app client id and secret (names only). +# 06-secrets.sh installs them together as the twitch-app credential; unset means +# it skips twitch-app with a warning. +BRIDGE_ID_KEY=twitch/-client-id +BRIDGE_SECRET_KEY=twitch/-client-secret # --- flybridge (services/bridge/src/config.ts) ------------------------------ # 05-deploy.sh writes these into /etc/fly/fly.env, which flybridge.service reads diff --git a/infra/tests/de-pii-allow.txt b/infra/tests/de-pii-allow.txt index 9328c05..8b437b0 100644 --- a/infra/tests/de-pii-allow.txt +++ b/infra/tests/de-pii-allow.txt @@ -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: # # # reason # # is a repo-relative path, a directory prefix ending in `/`, or a glob. -# 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. +# 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 / ``). -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//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// 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") diff --git a/infra/tests/lint.sh b/infra/tests/lint.sh index 82e9897..4cb3ab7 100755 --- a/infra/tests/lint.sh +++ b/infra/tests/lint.sh @@ -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 +while IFS= read -r line; do + 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 ---" diff --git a/infra/tests/pii-scan-test.sh b/infra/tests/pii-scan-test.sh new file mode 100755 index 0000000..672b6a0 --- /dev/null +++ b/infra/tests/pii-scan-test.sh @@ -0,0 +1,180 @@ +#!/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" < "$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 ":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 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" + +# --- review-pii-guard N2/N3 (2026-09-29) ---------------------------------------------- +printf 'broken - (unclosed\n' > "$T/private/bad-patterns.txt" +expect 2 "an invalid private regex refuses to scan (never 'clean')" -- env FLY_PII_PATTERNS="$T/private/bad-patterns.txt" "$SCAN" --tree +printf '++ %s\n' "$LAN" > "$W/src/plusplus.txt" +git -C "$W" add -A && git -C "$W" commit -qm "a line that starts with ++" +expect 1 "an added line starting '++ ' is still scanned" -- "$SCAN" --range HEAD~1..HEAD +git -C "$W" rm -qf src/plusplus.txt && git -C "$W" commit -qm "drop it" + +echo "===" +if [ "$FAILS" -eq 0 ]; then echo "pii-scan-test: ALL PASSED"; else echo "pii-scan-test: ${FAILS} FAILED"; exit 1; fi diff --git a/services/bridge/README.md b/services/bridge/README.md index 7d9d638..8f5c960 100644 --- a/services/bridge/README.md +++ b/services/bridge/README.md @@ -244,7 +244,7 @@ The unit itself lives in `infra/`, not here (W4 in `docs/stream-mvp-plan.md`). W provide: - `LoadCredentialEncrypted=twitch-client-id:...` and `...twitch-client-secret:...`, sourced from - `pass` (`twitch/fly-pokemon-client-{id,secret}`), giving `$CREDENTIALS_DIRECTORY` the two files + `pass` (`twitch/-client-{id,secret}`), giving `$CREDENTIALS_DIRECTORY` the two files `src/config.ts` reads. - A writable, persistent directory for `TOKENS_FILE`, `REDEMPTION_STATE_FILE` and `NOTICE_STATE_FILE` (default `/var/lib/flybridge/`), owned by the service user. diff --git a/tools/README.md b/tools/README.md index a0db3f8..f35b975 100644 --- a/tools/README.md +++ b/tools/README.md @@ -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`. diff --git a/tools/install-hooks.sh b/tools/install-hooks.sh new file mode 100755 index 0000000..c347d31 --- /dev/null +++ b/tools/install-hooks.sh @@ -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)" diff --git a/tools/pii-scan.sh b/tools/pii-scan.sh new file mode 100755 index 0000000..ca5c095 --- /dev/null +++ b/tools/pii-scan.sh @@ -0,0 +1,306 @@ +#!/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 +# (" " 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): +# flags: -i (ignore case) or - (case-sensitive) +# @values each KEY=VALUE value of 8+ chars in that file becomes a +# literal needle, reported as secret-value:, with +# the matched text never printed +# +# Findings print as `pii-scan: : : `; 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=() +# Every pattern is compiled once up front: grep exits 2 on a bad regex, and a scan that +# silently skipped a broken private pattern would report "clean" (fail open). +pat() { + local rc=0 f=-E + [ "$2" = -i ] && f=-iE + grep $f -e "$3" /dev/null 2>&1 || rc=$? + [ "$rc" -le 1 ] || die "pattern '$1' is not a valid extended regex; refusing to scan" + 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 ' '" + 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: ` # 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="" ;; + *) 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 = ""; hdr = 0; next } + /^--- / { hdr = 1; next } + /^\+\+\+ / && hdr { path = substr($0, 5); sub(/^b\//, "", path); if (path == "/dev/null") path = ""; hdr = 0; next } + /^@@ / { hdr = 0; 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\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\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 ' # 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