From ed2a1661650c80c03ffef18873cb8480a2f311c0 Mon Sep 17 00:00:00 2001 From: mnovak Date: Sat, 7 Nov 2026 16:33:13 +0100 Subject: [PATCH] [repo] Hygiene: batched hook (300 files 1.7 s), narrower build/ and JWK rules, more key forms, bash-4 check --- .githooks/pre-commit | 165 +++++++++++++++++++++++++---------- .githooks/test-pre-commit.sh | 73 +++++++++++++++- 2 files changed, 191 insertions(+), 47 deletions(-) diff --git a/.githooks/pre-commit b/.githooks/pre-commit index 2f90534..969166c 100755 --- a/.githooks/pre-commit +++ b/.githooks/pre-commit @@ -4,31 +4,45 @@ # Ianitor pre-commit hook. Rejects staged files that must never be in git: # - binaries: any NUL byte anywhere in the staged blob (git attributes do not matter) # - private keys: PEM/PKCS#8/OpenSSH/PGP blocks, SSH2 (RFC 4716) keys, PuTTY .ppk, -# age secret keys, JWK private keys, WireGuard PrivateKey lines, and key-store file names +# age secret keys, JWK private keys (an object with "kty" RSA/EC/OKP and "d"), +# WireGuard private keys (wg-quick `PrivateKey =` or YAML `private_key:`), and +# key-store file names # - files over 5 MB (5,000,000 bytes, as CLAUDE.md says) -# - build output and dependencies: target/, node_modules/, dist/, build/, .svelte-kit/ +# - build output and dependencies: target/, node_modules/, dist/, .svelte-kit/ anywhere; +# build/ at the repository root, in apps//, or next to a package.json # Name checks are case-insensitive. Paths are read NUL-separated, so quotes, tabs, -# backslashes or newlines in file names cannot slip past. A staged file that cannot be read -# blocks the commit. +# backslashes or newlines in file names cannot slip past. A staged file that cannot be read, +# or any git command that fails, blocks the commit. +# +# Contents are checked in a few batch passes over the index (one `git cat-file`, two +# `git grep`), not with processes per file. # # Enable once per clone: git config core.hooksPath .githooks # Test it: bash .githooks/test-pre-commit.sh -# Needs bash 4+ (Git Bash on Windows, any Linux). + +if [ -z "${BASH_VERSINFO:-}" ] || [ "${BASH_VERSINFO[0]}" -lt 4 ]; then + echo "pre-commit: needs bash 4 or newer (this is ${BASH_VERSION:-not bash}); commit blocked." >&2 + echo "pre-commit: use Git Bash on Windows, any Linux, or a newer bash on macOS." >&2 + exit 1 +fi set -u LIMIT=5000000 -# Patterns are written so that this file does not match them itself. +# Patterns are written so that this file does not match them itself. They are matched +# case-insensitively. KEY_PATTERNS=( '-----BEGIN [A-Z0-9 ]*PRIVATE KEY( BLOCK)?-----' '---- BEGIN SSH2 ENCRYPTED PRIVATE KEY[ ]----' '---- BEGIN SSH2 PRIVATE KEY[ ]----' 'PuTTY-User-Key-File-[0-9]+:' 'AGE-SECRET-KEY-[1][0-9A-Z]+' - '^[[:space:]]*PrivateKey[[:space:]]*=[[:space:]]*[A-Za-z0-9+/]{42,43}=?[[:space:]]*$' + '^[[:space:]]*(-[[:space:]]*)?["'\'']?private_?key["'\'']?[[:space:]]*[:=][[:space:]]*["'\'']?[A-Za-z0-9+/]{42,43}=?["'\'']?[[:space:]]*,?[[:space:]]*$' ) -JWK_KTY='"kt[y]"[[:space:]]*:' -JWK_D='"d"[[:space:]]*:[[:space:]]*"' +# One flat JSON object (JWK members are flat) holding a private-key parameter set. +JWK_OBJECT='\{[^{}]*\}' +JWK_KTY='"kt[y]"[[:space:]]*:[[:space:]]*"(RSA|EC|OKP)"' +JWK_D='"[d]"[[:space:]]*:[[:space:]]*"' failed=0 reject() { @@ -36,25 +50,59 @@ reject() { printf 'pre-commit: rejected %q: %s\n' "$1" "$2" >&2 failed=1 } - -list=$(mktemp 2>/dev/null || echo "${TMPDIR:-/tmp}/ianitor-pre-commit.$$") -blob=$(mktemp 2>/dev/null || echo "${TMPDIR:-/tmp}/ianitor-pre-commit-blob.$$") -trap 'rm -f "$list" "$blob"' EXIT - -if ! git diff --cached --raw -z --no-abbrev --no-renames --diff-filter=ACMT >"$list"; then - echo 'pre-commit: cannot list the staged files; commit blocked.' >&2 +die() { + echo "pre-commit: $1; commit blocked." >&2 exit 1 -fi +} + +tmp=$(mktemp -d 2>/dev/null || { d="${TMPDIR:-/tmp}/ianitor-pre-commit.$$"; mkdir -p "$d" && echo "$d"; }) || + die "cannot create a temporary directory" +trap 'rm -rf "$tmp"' EXIT + +git diff --cached --raw -z --no-abbrev --no-renames --diff-filter=ACMT >"$tmp/list" || + die "cannot list the staged files" +git ls-files -z -- ':(glob)**/package.json' >"$tmp/packages" || + die "cannot list package.json files" + +declare -A staged=() pkgdir=() +paths=() shas=() + +while IFS= read -r -d '' p; do + d=${p%package.json} + d=${d%/} + # The root package.json needs no entry: build/ at the root is always output. + [ -n "$d" ] && pkgdir[${d,,}]=1 +done <"$tmp/packages" + +# build/ is output only at the root, in apps// or beside a package.json. +is_build_output() { + local lower=$1 prefix= + [[ $lower == build/* || $lower =~ ^apps/[^/]+/build/ ]] && return 0 + local rest=$lower part + while [[ $rest == */* ]]; do + part=${rest%%/*} + rest=${rest#*/} + if [[ $part == build && -n $prefix && -n ${pkgdir[${prefix%/}]+x} ]]; then + return 0 + fi + prefix+="$part/" + done + return 1 +} # --raw -z gives ": " NUL "" NUL. while IFS= read -r -d '' meta && IFS= read -r -d '' path; do - read -r _ mode _ sha _ <<<"${meta#:}" + read -r -a f <<<"${meta#:}" + mode=${f[1]} sha=${f[3]} lower=${path,,} case "/$lower" in - */target/*|*/node_modules/*|*/dist/*|*/build/*|*/.svelte-kit/*) + */target/*|*/node_modules/*|*/dist/*|*/.svelte-kit/*) reject "$path" "build output or dependency directory" ;; esac + if is_build_output "$lower"; then + reject "$path" "build output directory" + fi base=${lower##*/} case "$base" in @@ -65,35 +113,60 @@ while IFS= read -r -d '' meta && IFS= read -r -d '' path; do # Submodule entries have no blob to inspect. [ "$mode" = 160000 ] && continue + staged[$path]=$sha + paths+=("$path") + shas+=("$sha") +done <"$tmp/list" - if ! git cat-file blob "$sha" >"$blob" 2>/dev/null; then - reject "$path" "the staged content cannot be read" - continue - fi - size=$(wc -c <"$blob" | tr -d '[:space:]') - if ! [[ $size =~ ^[0-9]+$ ]]; then - reject "$path" "the staged size cannot be determined" - continue - fi - if (( size > LIMIT )); then - reject "$path" "$size bytes is over the 5 MB limit (5,000,000 bytes)" - fi - - textsize=$(tr -d '\000' <"$blob" | wc -c | tr -d '[:space:]') - if [ "$textsize" != "$size" ]; then - reject "$path" "binary file (contains NUL bytes)" - fi - - for pattern in "${KEY_PATTERNS[@]}"; do - if LC_ALL=C grep -a -E -q -e "$pattern" "$blob"; then - reject "$path" "contains a private key" - break +if [ "${#paths[@]}" -gt 0 ]; then + # Sizes: one batch for every blob, in order. + printf '%s\n' "${shas[@]}" | git cat-file --batch-check='%(objectname) %(objecttype) %(objectsize)' >"$tmp/sizes" || + die "cannot read the staged blobs" + i=0 + while read -r _ type size; do + p=${paths[$i]} + if [ "$type" != blob ] || ! [[ $size =~ ^[0-9]+$ ]]; then + reject "$p" "the staged content cannot be read" + elif (( size > LIMIT )); then + reject "$p" "$size bytes is over the 5 MB limit (5,000,000 bytes)" fi - done - if LC_ALL=C grep -a -E -q -e "$JWK_KTY" "$blob" && LC_ALL=C grep -a -E -q -e "$JWK_D" "$blob"; then - reject "$path" "contains a JWK private key" - fi -done <"$list" + i=$((i + 1)) + done <"$tmp/sizes" + [ "$i" -eq "${#paths[@]}" ] || die "cannot read the size of every staged blob" + + # Contents: git grep over the index, every file read as text (-a), names NUL-separated, + # then kept only when staged. Exit 1 means no match; anything above blocks the commit. + search() { + local out=$1 rc + shift + git -c grep.fullName=true -c color.grep=never grep --cached --no-recurse-submodules \ + -a -l -z "$@" >"$out" + rc=$? + [ "$rc" -le 1 ] || die "git grep failed (exit $rc)" + } + + search "$tmp/nul" -P '\x00' + while IFS= read -r -d '' p; do + [ -n "${staged[$p]+x}" ] && reject "$p" "binary file (contains NUL bytes)" + done <"$tmp/nul" + + args=() + for pattern in "${KEY_PATTERNS[@]}"; do args+=(-e "$pattern"); done + search "$tmp/keys" -i -E "${args[@]}" + while IFS= read -r -d '' p; do + [ -n "${staged[$p]+x}" ] && reject "$p" "contains a private key" + done <"$tmp/keys" + + # JWK members may span lines, so candidates are flattened and split into objects. + search "$tmp/jwk" -F -e '"kt''y"' + while IFS= read -r -d '' p; do + [ -n "${staged[$p]+x}" ] || continue + if git cat-file blob "${staged[$p]}" | tr '\r\n\t' ' ' | grep -a -o -E "$JWK_OBJECT" | + grep -a -E "$JWK_KTY" | grep -a -q -E "$JWK_D"; then + reject "$p" "contains a JWK private key" + fi + done <"$tmp/jwk" +fi if [ "$failed" -ne 0 ]; then echo 'pre-commit: commit blocked. Unstage the files above (git rm --cached ).' >&2 diff --git a/.githooks/test-pre-commit.sh b/.githooks/test-pre-commit.sh index 8cbbd33..a7a239c 100755 --- a/.githooks/test-pre-commit.sh +++ b/.githooks/test-pre-commit.sh @@ -111,6 +111,9 @@ expect reject "PuTTY private key content" putty.txt printf 'not really a key\n' > me.ppk expect reject "*.ppk file name" me.ppk +printf '# created: 2026\nage-secret-key-%s\n' 1qyz8xrfk3w6j9p2m4n5l7kxqzj5s8tvh3r2w6y9 > lower.txt +expect reject "age secret key in lower case" lower.txt + printf '# created: 2026\nAGE-SECRET-KEY-%s\n' 1QYZ8XRFK3W6J9P2M4N5L7KXQZJ5S8TVH3R2W6Y9 > identity.txt expect reject "age secret key" identity.txt @@ -120,9 +123,33 @@ expect reject "JWK private key" key.json printf '{"k%s":"EC","crv":"P-256","x":"f83O","y":"x_FE"}\n' ty > pub.json expect accept "JWK public key" pub.json +printf '{\n "k%s"\n : "RSA",\n "n": "0vx7",\n "e": "AQAB",\n "d"\n :\n "X4cT"\n}\n' ty > rsa.json +expect reject "JWK private key across lines, newline before the colon" rsa.json + +printf '{"keys":[{"k%s":"OKP","crv":"Ed25519","x":"11qY","d":"nWGx"}]}\n' ty > jwks.json +expect reject "OKP private key inside a JWKS" jwks.json + +printf '{"jwk":{"k%s":"EC","x":"f83O","y":"x_FE"},"meta":{"d":"2026-11-07"}}\n' ty > mixed.json +expect accept "JWK public key with an unrelated \"d\" in another object" mixed.json + +printf '{"k%s":"oct","k":"GawgguFy","d":"not a private-key parameter"}\n' ty > oct.json +expect accept "\"d\" with kty oct is not an RSA/EC/OKP private key" oct.json + printf '[Interface]\nPrivate%s = %s\nAddress = 10.0.0.2/32\n' Key yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk= > wg0.conf expect reject "WireGuard private key" wg0.conf +printf 'wireguard:\n interface:\n private_%s: yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk=\n' key > wg.yaml +expect reject "WireGuard private_key in YAML" wg.yaml + +printf 'peers:\n - private_%s: "yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk="\n' key > wg2.yml +expect reject "WireGuard private_key in a YAML list, quoted" wg2.yml + +printf 'private_%s_file: /run/secrets/wg\n' key > wg3.yaml +expect accept "WireGuard private_key_file path (no key)" wg3.yaml + +printf '*.txt binary\n' > .gitattributes && cp "$SRC/pem" attr.txt && git add .gitattributes +expect reject "PEM key in a file .gitattributes marks binary" attr.txt + printf 'not really a key\n' > server.key expect reject "*.key file name" server.key @@ -163,7 +190,23 @@ mkdir -p apps/web/dist && printf 'x\n' > apps/web/dist/index.html expect reject "file under dist/" apps/web/dist/index.html mkdir -p apps/web/build && printf 'x\n' > apps/web/build/index.html -expect reject "file under build/" apps/web/build/index.html +expect reject "file under apps//build/" apps/web/build/index.html + +mkdir -p build && printf 'x\n' > build/out.js +expect reject "file under build/ at the root" build/out.js + +mkdir -p crates/x/src/build && printf 'pub mod x;\n' > crates/x/src/build/mod.rs +expect accept "source module named build (crates/x/src/build/mod.rs)" crates/x/src/build/mod.rs + +mkdir -p apps/web/src/build && printf 'x\n' > apps/web/src/build/x.ts +expect accept "apps/web/src/build/ is not output" apps/web/src/build/x.ts + +mkdir -p packages/ui/build && printf '{}\n' > packages/ui/package.json && printf 'x\n' > packages/ui/build/ui.js +git add packages/ui/package.json +expect reject "build/ next to a package.json" packages/ui/build/ui.js + +mkdir -p docs/build && printf 'x\n' > docs/build/notes.md +expect accept "build/ with no package.json beside it" docs/build/notes.md mkdir -p apps/web/.svelte-kit && printf 'x\n' > apps/web/.svelte-kit/env.js expect reject "file under .svelte-kit/" apps/web/.svelte-kit/env.js @@ -177,5 +220,33 @@ expect_staged reject "PEM key in a file named with a newline" "$(printf 'new\nli printf 'fine\n' > "$SRC/fine" expect_staged accept "harmless file named with a double quote" 'say"hi".txt' "$SRC/fine" +# Bash 3 or a POSIX sh: the hook refuses with a clear message. Only testable where sh is +# not bash (dash on Debian); Git Bash's sh is bash. +if [ -z "$(sh -c 'echo "${BASH_VERSION:-}"')" ]; then + printf 'x\n' > shtest.txt && git add shtest.txt + if sh "$HOOKS/pre-commit" 2>"$WORK/.err"; then + fail=$((fail + 1)); echo "FAIL the hook ran under a shell that is not bash 4" + elif grep -q 'needs bash 4' "$WORK/.err"; then + pass=$((pass + 1)); echo "ok reject run by sh (not bash): clear message" + else + fail=$((fail + 1)); echo "FAIL no clear message under sh:"; cat "$WORK/.err" + fi + git reset -q --hard HEAD; git clean -q -fdx -e .err +else + echo "skip sh is bash here; the bash-4 check is exercised where sh is dash" +fi + +# Speed: 300 ordinary files in one commit. +mkdir -p many +for n in $(seq 1 300); do printf 'line %d\n' "$n" > "many/f$n.txt"; done +git add many +start=$(date +%s%N) +commit_and_check accept "300 ordinary files in one commit" +ms=$(( ($(date +%s%N) - start) / 1000000 )) +printf ' (300 files: %d ms)\n' "$ms" +if [ "$ms" -gt 10000 ]; then + fail=$((fail + 1)); echo "FAIL 300 files took over 10 s" +fi + printf '\nhook: %d passed, %d failed\n' "$pass" "$fail" [ "$fail" -eq 0 ]