summaryrefslogtreecommitdiff
path: root/scripts/leak-check
blob: fbbd5d5fb669485f77206a9780829e0cc9a209bb (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#!/bin/sh
# SPDX-License-Identifier: GPL-3.0-or-later
#
# leak-check: refuse personal data in the files git would commit.
#
# Scans every staged file (the index, not the working tree), and the names
# of staged files against the private list, for:
#   - the current user's home directory, e.g. /home/alice;
#   - email addresses (LICENSE is exempt);
#   - a private pattern list: one extended regular expression per line,
#     blank lines and lines starting with # ignored, matched ignoring case.
#     Its path is set per clone with:  git config krino.leakpatterns FILE
#     Keep that file outside the repository so the list is never published.
#
# A line matching the regex in `git config krino.leakallow` is never
# reported (for example a public contact address in the README).
#
# Prints file:line for each hit, never the matched text, so a hit on a
# private pattern does not echo the secret. Exits 0 when clean, 1 when
# something matched, 2 when the private list is configured but missing.

set -eu

cd "$(git rev-parse --show-toplevel)"

allow=$(git config --get krino.leakallow || true)
hits=0

# check LABEL GREP-ARGS...: report staged lines that match, as file:line.
check() {
	label=$1
	shift
	out=$(git grep --cached -n -I "$@" | { if [ -n "$allow" ]; then grep -v -E -i -e "$allow"; else cat; fi; } | cut -d: -f1,2 || true)
	if [ -n "$out" ]; then
		printf 'leak-check: %s:\n%s\n' "$label" "$out" | sed '2,$s/^/  /' >&2
		hits=1
	fi
}

home=${HOME%/} # a HOME of / becomes empty and is skipped
if [ -n "$home" ]; then
	check "your home directory ($home)" -F -e "$home" -- .
fi

check "an email address" -E -e '[[:alnum:]._%+-]+@[[:alnum:].-]+\.[[:alpha:]]{2,}' -- . ':(exclude)LICENSE'

list=$(git config --type=path --get krino.leakpatterns || true)
if [ -z "$list" ]; then
	echo "leak-check: no private pattern list (git config krino.leakpatterns FILE); built-in checks only" >&2
elif [ ! -r "$list" ]; then
	echo "leak-check: private pattern list $list is configured but cannot be read" >&2
	exit 2
else
	patterns=$(mktemp)
	trap 'rm -f "$patterns"' EXIT
	grep -v -e '^[[:space:]]*#' -e '^[[:space:]]*$' "$list" > "$patterns" || true
	if [ -s "$patterns" ]; then
		check "a private pattern from $list" -i -E -f "$patterns" -- .
		named=$(git ls-files --cached | grep -i -E -f "$patterns" || true)
		if [ -n "$named" ]; then
			printf 'leak-check: a file name matching a private pattern:\n%s\n' "$named" | sed '2,$s/^/  /' >&2
			hits=1
		fi
	fi
fi

if [ "$hits" -ne 0 ]; then
	echo "leak-check: remove the data above before committing; for a false positive, narrow the pattern or set krino.leakallow" >&2
	exit 1
fi