#!/bin/sh
# Refuse commits that would put credentials, state files or the gold set
# into the history.
#
# Enable once per clone:  git config core.hooksPath .githooks
# Deliberate bypass:      git commit --no-verify
# Example in a doc/test:  end the line with "pragma: allowlist secret"
#
# Checks the staged content, not the working tree.

set -eu

fail=0
note() {
    printf 'pre-commit: %s\n' "$1" >&2
    fail=1
}

staged=$(git diff --cached --name-only --diff-filter=ACMR)
[ -n "$staged" ] || exit 0

# 1. Files that never belong in the repository: anything in a folder
#    secrets/, a .env other than the example, anything under data/ but
#    .gitkeep, and SQLite files anywhere.
forbidden=$(
    printf '%s\n' "$staged" | while IFS= read -r file; do
        case "$file" in
            secrets/* | */secrets/*) printf '%s\n' "$file" ;;
            *.env.example) ;;
            .env | */.env | .env.* | */.env.*) printf '%s\n' "$file" ;;
            data/*/.gitkeep | data/.gitkeep) ;;
            data/*) printf '%s\n' "$file" ;;
            *.db | *.db-journal | *.db-wal | *.db-shm | *.sqlite | *.sqlite3)
                printf '%s\n' "$file" ;;
        esac
    done
)
if [ -n "$forbidden" ]; then
    note "these files hold configuration, state or real mail ids:"
    printf '%s\n' "$forbidden" | sed 's/^/  /' >&2
fi

# 2. Credentials inside the staged lines, whatever the file is called.
# tests/test_repo_content.py holds the same patterns for every tracked
# file. A change to one changes the other.
patterns='sk-ant-[A-Za-z0-9_-]{16,}'
patterns="$patterns|sk-[A-Za-z0-9_-]{20,}"
patterns="$patterns|mbx_[A-Za-z0-9_-]{16,}"
patterns="$patterns|Bearer [A-Za-z0-9._-]{16,}"
patterns="$patterns|gh[pousr]_[A-Za-z0-9]{16,}"
patterns="$patterns|glpat-[A-Za-z0-9_-]{16,}"
patterns="$patterns|AKIA[0-9A-Z]{16}"
patterns="$patterns|BEGIN (RSA |OPENSSH |EC |DSA |PGP )?PRIVATE KEY"
# A name that ends in TOKEN, SECRET, PASSWORD or _KEY, maybe with more
# parts such as _FILE, then = or :, maybe a quote, then the value.
# _KEYWORD is no such name. A value that starts with / is a path, as a
# *_FILE setting names one.
patterns="$patterns|(TOKEN|SECRET|PASSWORD|_KEY)(_[A-Z]+)*[[:space:]]*[:=][[:space:]]*[\"']?[A-Za-z0-9+_-][A-Za-z0-9+/_.-]{11,}"
# The same in any case, as JSON and YAML write it: a name that ends in
# token, secret, password or _key, then = or :, then a quoted value, or a
# bare one that ends the line or a word. A bare value with a dot or a
# bracket is code, such as token = base64.b64encode(raw).
named="(^|[^a-z0-9])[\"']?[a-z0-9_]*(token|secret|password|passwd|_key)[\"']?"
named="$named[[:space:]]*[:=][[:space:]]*"
named="$named([\"'][A-Za-z0-9+_-][A-Za-z0-9+/_.-]{11,}|[A-Za-z0-9+_-][A-Za-z0-9+/_-]{11,}([[:space:]]|\$))"

added=$(git diff --cached -U0 | grep '^+' || true)
hits=$(
    {
        printf '%s\n' "$added" | grep -E "$patterns" || true
        printf '%s\n' "$added" | grep -iE "$named" || true
    } \
        | awk '!seen[$0]++' \
        | grep -v 'pragma: allowlist secret' \
        || true
)
if [ -n "$hits" ]; then
    note "staged lines look like a credential:"
    printf '%s\n' "$hits" | cut -c 1-120 | sed 's/^/  /' >&2
fi

if [ "$fail" -ne 0 ]; then
    printf 'pre-commit: nothing was committed (override with --no-verify).\n' >&2
    exit 1
fi
