Skip to content

Instantly share code, notes, and snippets.

@nathanqthai
Last active April 23, 2023 18:07
Show Gist options
  • Save nathanqthai/0306c2b8b597e4e4bfab7755ebb7a2db to your computer and use it in GitHub Desktop.
Save nathanqthai/0306c2b8b597e4e4bfab7755ebb7a2db to your computer and use it in GitHub Desktop.
a git pre-commit hook to check for API keys
#!/bin/sh
# stash before we mess around
STASH_NAME="pre-commit-$(date +%s)"
git stash save -q --keep-index $STASH_NAME
# regexes to find keys
TWILIO_KEY="\bAC[a-z0-9]{32}\b"
TWILIO_SECRET="\b[a-z0-9]{32}\b"
API_REGEXPS=( $TWILIO_KEY $TWILIO_SECRET )
# search committed files for potential api keys
found_keys=() # list containing ponential matches
check_files=($(git diff --name-only --cached))
for file in ${check_files[@]}
do
# for each file check against regex
for key_regex in ${API_REGEXPS[@]}
do
found=$(grep --with-filename -r -n -E $key_regex $file | tr -d [:space:])
# append potential keys to list
if [ ! -z $file ]
then
found_keys+=($found)
git reset HEAD $file
fi
done
done
# if no keys, pop the stash and commit, otherwise show error
if [ ${#found_keys[@]} -eq 0 ];
then
STASHES=$(git stash list)
if [[ $STASHES == "$STASH_NAME" ]]; then
git stash pop -q
fi
exit 0
else
echo "\033[1;31;7mCOMMIT FAILED, FOUND POTENTIAL KEYS:\033[0m"
for key in ${found_keys[@]}
do
echo "\t\033[7m${key}\033[0m"
done
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment