Hook pre-commit contra secretos en git: qué no protege (clone, --no-verify, permisos, git add -p) y cómo versionarlo con core.hooksPath (prueba)
con git 2.43.0, un clon no trajo el hook de .git/hooks y el commit de una clave de ejemplo AWS pasó; git commit --no-verify y -n también la dejaron pasar (el commit sin la opción salió con código 1). Con core.hooksPath apuntando a un directorio versionado el clon bloqueó el commit, pero solo después de ejecutar git config en ese clon; antes pasó. Un hook con modo 644 se ignoró con un aviso hint (y el commit con la clave se creó), un aviso que desaparece con advice.ignoredHook=false, tras lo cual la omisión es totalmente silenciosa. El hook se ejecutó siempre con el directorio actual en la raíz del árbol de trabajo, aunque el commit se lanzara desde sub/deep. Con la clave solo en el índice y el fichero limpio en disco, el hook que lee el disco dejó pasar el commit y la clave quedó en HEAD; el hook que lee git diff --cached lo bloqueó. Mismos resultados en 3 de 3 ejecuciones.
Este artículo no contiene enlaces de afiliado.
Un hook pre-commit que busca claves antes de cada commit es la defensa más barata contra subir un secreto a un repositorio. También es fácil de dar por hecho: vive donde git no lo versiona y se puede saltar con una opción. Aquí se mide qué pasa de verdad en cinco situaciones, con una clave falsa. Para copias de repositorios completos, mira git bundle y qué copia, donde el hook pre-commit aparece como algo que un git clone no trae.
Condiciones: git version 2.43.0, Ubuntu 24.04.5 LTS, Linux 7.0.0-1017-oracle, bash 5.2.21, LC_ALL=C.UTF-8, GIT_CONFIG_GLOBAL y GIT_CONFIG_SYSTEM a /dev/null, usuario normal. Todo ocurre en directorios de mktemp -d que el script borra al salir. El "secreto" es AKIAIOSFODNN7EXAMPLE, la clave de ejemplo de la documentación de AWS, no una credencial real, y el hook la detecta con la expresión AKIA[0-9A-Z]{16}. El script se ejecutó 3 veces y la salida fue idéntica en las 3 (comparada sin la cabecera de cada ejecución; las rutas temporales se sustituyen por TMP). No se probó git en Windows o macOS, hooks en otros lenguajes que sh, pre-push, commit-msg, herramientas como pre-commit (el framework), gitleaks o detect-secrets, el servidor remoto rechazando pushes, ni otras versiones de git. El texto lo redacté con ayuda de una IA a partir de la salida del script, y las cifras salen de esas ejecuciones.
Salida de la ejecución 1
Idéntica en las ejecuciones 2 y 3.
[1] hook in .git/hooks and git clone:
original has .git/hooks/pre-commit: yes; clone has it: no
git status in original lists the hook: 0
commit of a secret in the CLONE (no hook there):
exit=0, commit created: yes
> 1 file changed, 1 insertion(+)
> create mode 100644 cfg
[2] --no-verify against the hook (repo a):
git commit:
exit=1, commit created: no
> pre-commit: secret in staged changes, commit blocked
git commit --no-verify:
exit=0, commit created: yes
> 1 file changed, 1 insertion(+)
> create mode 100644 cfg
git commit -n (short form):
exit=0, commit created: yes
> 1 file changed, 1 insertion(+)
> create mode 100644 cfg
[3] core.hooksPath to a versioned directory:
clone has githooks/pre-commit (versioned): yes
clone, secret commit before setting hooksPath:
exit=0, commit created: yes
> 1 file changed, 1 insertion(+)
> create mode 100644 cfg
core.hooksPath in clone: githooks
clone, after git config core.hooksPath githooks:
exit=1, commit created: no
> pre-commit: secret in staged changes, commit blocked
core.hooksPath lives in .git/config of the clone: 1 line; in original repo c: (unset)
old .git/hooks/pre-commit (exit 1, prints OLD) once hooksPath is set; commit of a clean file:
exit=0, commit created: yes
> 1 file changed, 1 insertion(+)
> create mode 100644 ok
[4] hook without the executable bit:
mode 644, secret staged:
exit=0, commit created: yes
> hint: The '.git/hooks/pre-commit' hook was ignored because it's not set as executable.
> hint: You can disable this warning with `git config advice.ignoredHook false`.
> 1 file changed, 1 insertion(+)
> create mode 100644 cfg
mode 644, git -c advice.ignoredHook=false:
exit=0, commit created: yes
> 1 file changed, 1 insertion(+)
> create mode 100644 cfg
mode 755:
exit=1, commit created: no
> pre-commit: secret in staged changes, commit blocked
mode 755 but bad shebang (#!/nonexistent):
exit=1, commit created: no
> fatal: cannot exec '.git/hooks/pre-commit': No such file or directory
[5] working directory and environment seen by the hook:
commit launched from sub/deep:
cwd=TMP/f GIT_DIR=unset GIT_INDEX_FILE=.git/index
commit -a launched from sub/deep (temporary index):
cwd=TMP/f GIT_DIR=unset GIT_INDEX_FILE=TMP/f/.git/index.lock
commit with explicit path (git commit -m s sub/deep/h; --only mode):
cwd=TMP/f GIT_DIR=unset GIT_INDEX_FILE=TMP/f/.git/next-index-PID.lock
[6] staged content vs working tree (file partially staged):
--- hook checks: staged
A: secret only on disk (not staged): staged=0 on-disk=1
exit=0, commit created: yes
> 1 file changed, 1 insertion(+)
B: secret staged, disk is clean: staged=1 on-disk=0
exit=1, commit created: no
> pre-commit: secret in staged changes, commit blocked
secret inside HEAD after B: 0 line(s)
--- hook checks: disk
A: secret only on disk (not staged): staged=0 on-disk=1
exit=1, commit created: no
> pre-commit: secret in working-tree file, commit blocked
B: secret staged, disk is clean: staged=1 on-disk=0
exit=0, commit created: yes
> 1 file changed, 1 insertion(+)
secret inside HEAD after B: 1 line(s)
Lo que se ve
- El hook no viaja con el clon. El original tenía
.git/hooks/pre-commity el clon no;git statusno lo lista (0 coincidencias, incluso con--ignored). En el clon, el commit con la clave salió con código 0. Un hook en.git/hooksprotege solo ese directorio de trabajo. --no-verifyy-nlo saltan sin dejar rastro. Sin la opción, el commit salió con código 1 y no se creó; con--no-verifyy con-n, se creó. Esto no es un fallo: es el diseño. Quien quiera una barrera real necesita también un control en el servidor (no medido aquí).core.hooksPathversiona el hook, pero no se activa solo. El clon teníagithooks/pre-commit(versionado), y aun así el commit con la clave pasó hasta que se ejecutógit config core.hooksPath githooksen ese clon: la clave vive en.git/config, que no se copia. Con la ruta puesta, el commit se bloqueó. Concore.hooksPathactivo, el viejo.git/hooks/pre-commit(que habría dado exit 1 y escritoOLD) no se ejecutó: el commit de un fichero limpio pasó sin rastro deOLD.- Sin permiso de ejecución, el hook se ignora. Con modo 644, git 2.43.0 imprimió
hint: The '.git/hooks/pre-commit' hook was ignored because it's not set as executable.y creó el commit con la clave (exit 0). Con-c advice.ignoredHook=falseel mismo commit pasó sin ningún mensaje. Con modo 755 se bloqueó. Con modo 755 y un shebang inexistente,fatal: cannot exec '.git/hooks/pre-commit': No such file or directoryy exit 1: un hook roto bloquea, uno sin permiso solo avisa. Unhinten la terminal es fácil de no ver en un IDE o en una tubería. - Directorio de trabajo. El hook se ejecutó siempre en la raíz del árbol de trabajo (
TMP/f), aunquegit commitse lanzó desdesub/deep.GIT_DIRno estaba definido;GIT_INDEX_FILEapuntaba a.git/indexen el commit normal, a.git/index.lockcon-ay a unnext-index-PID.lockcon una ruta explícita. Concommit -ao con rutas, el índice que ve el hook no es el de siempre; por eso el hook debe usargit diff --cached(que respeta esa variable) y no leer.git/indexa mano. - Índice frente a disco. Con el fichero a medias (lo que deja
git add -p, aquí reproducido congit update-index --cacheinfo): en el caso A, la clave solo estaba en disco y lo staged estaba limpio; el hook que miragit diff --cacheddejó pasar el commit, y es correcto, porque la clave no entra en él; el hook que lee el fichero lo bloqueó, un falso positivo. En el caso B, la clave estaba en el índice y el disco ya estaba limpio: el hook de disco dejó pasar ygit show HEAD:app.confcontenía la clave (1 línea); el hook del índice bloqueó (0 líneas en HEAD). El fallo grave es el B, y es el que produce un hook que hacegrepsobre los ficheros.
Qué significa
- Escribe el hook sobre
git diff --cached, no sobre los ficheros en disco. En esta prueba fue el único que bloqueó el caso B. - Guarda el hook en un directorio versionado (
githooks/) y pongit config core.hooksPath githooksen un paso de instalación de cada clon; sin él, el clon no está protegido. Medido: el clon sin la configuración dejó pasar la clave. - Comprueba el modo con
git ls-files -s githooks(debe ser 100755). Un 644 se ignora con solo unhint. --no-verifyno se puede impedir en local. Si el secreto importa, la barrera tiene que repetirse fuera del ordenador del autor (no medido aquí).- Lo medido es git 2.43.0 en Ubuntu 24.04; otras versiones pueden cambiar los avisos.
Script completo
#!/bin/bash
# Git pre-commit hook for secrets hygiene, measured in throwaway repos (mktemp -d, removed on exit).
# 1 clone does not copy .git/hooks; 2 --no-verify bypasses; 3 core.hooksPath to a versioned dir;
# 4 non-executable hook: warning or silence; 5 hook cwd; 6 staged content vs working tree check.
# The "secret" is the AWS documentation example key, not a real credential. Usage: test-git-hooks.sh
set -u
export LC_ALL=C.UTF-8 GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_SYSTEM=/dev/null
export GIT_AUTHOR_NAME=t [email protected] GIT_COMMITTER_NAME=t [email protected]
T=$(mktemp -d /tmp/githooks.XXXXXX) || exit 1
trap 'rm -rf "$T"' EXIT
SECRET='AKIAIOSFODNN7EXAMPLE'
echo "$(git --version); $(. /etc/os-release; echo "$PRETTY_NAME"); $(uname -sr); bash ${BASH_VERSINFO[0]}.${BASH_VERSINFO[1]}.${BASH_VERSINFO[2]}"
# hook that checks the STAGED content (what will be committed)
STAGED_HOOK='#!/bin/sh
if git diff --cached -U0 | grep -E "^\+.*AKIA[0-9A-Z]{16}" >/dev/null; then
echo "pre-commit: secret in staged changes, commit blocked" >&2; exit 1
fi
exit 0'
# naive hook that checks the files on DISK
DISK_HOOK='#!/bin/sh
if git diff --cached --name-only | while read -r f; do grep -E "AKIA[0-9A-Z]{16}" "$f"; done | grep . >/dev/null; then
echo "pre-commit: secret in working-tree file, commit blocked" >&2; exit 1
fi
exit 0'
newrepo(){ rm -rf "$1"; git init -q -b main "$1"; ( cd "$1" && echo base > README && git add README && git commit -qm base ); }
try(){ # try LABEL: attempts a commit in cwd, prints exit code and whether HEAD moved
local before after out rc
before=$(git rev-parse HEAD); out=$("$@" 2>&1); rc=$?; after=$(git rev-parse HEAD)
printf ' exit=%d, commit created: %s\n' "$rc" "$([ "$before" != "$after" ] && echo yes || echo no)"
[ -n "$out" ] && printf '%s\n' "$out" | grep -v '^\[main' | sed 's/^/ > /'
}
for r in 1 2 3; do
echo "=== run $r ==="
echo "[1] hook in .git/hooks and git clone:"
newrepo "$T/a"; printf '%s\n' "$STAGED_HOOK" > "$T/a/.git/hooks/pre-commit"; chmod +x "$T/a/.git/hooks/pre-commit"
git clone -q "$T/a" "$T/b"
echo " original has .git/hooks/pre-commit: $([ -x "$T/a/.git/hooks/pre-commit" ] && echo yes || echo no); clone has it: $([ -e "$T/b/.git/hooks/pre-commit" ] && echo yes || echo no)"
echo " git status in original lists the hook: $(cd "$T/a" && git status --porcelain --ignored | grep -c hooks)"
echo " commit of a secret in the CLONE (no hook there):"
( cd "$T/b" && echo "key=$SECRET" > cfg && git add cfg && try git commit -m s )
rm -rf "$T/b"
echo "[2] --no-verify against the hook (repo a):"
cd "$T/a"; echo "key=$SECRET" > cfg; git add cfg
echo " git commit:"; try git commit -m s
echo " git commit --no-verify:"; try git commit --no-verify -m s
echo " git commit -n (short form):"; git reset -q --hard HEAD~1; echo "key=$SECRET" > cfg; git add cfg; try git commit -n -m s
echo "[3] core.hooksPath to a versioned directory:"
newrepo "$T/c"; cd "$T/c"; mkdir githooks; printf '%s\n' "$STAGED_HOOK" > githooks/pre-commit; chmod +x githooks/pre-commit
git add githooks; git commit -qm "add hooks"
rm -rf "$T/d"; git clone -q "$T/c" "$T/d"
echo " clone has githooks/pre-commit (versioned): $([ -x "$T/d/githooks/pre-commit" ] && echo yes || echo no)"
echo " clone, secret commit before setting hooksPath:"; ( cd "$T/d" && echo "key=$SECRET" > cfg && git add cfg && try git commit -m s )
( cd "$T/d" && git reset -q --hard HEAD~1 && git config core.hooksPath githooks && echo " core.hooksPath in clone: $(git config core.hooksPath)" )
echo " clone, after git config core.hooksPath githooks:"; ( cd "$T/d" && echo "key=$SECRET" > cfg && git add cfg && try git commit -m s )
echo " core.hooksPath lives in .git/config of the clone: $(grep -c hooksPath "$T/d/.git/config") line; in original repo c: $(git -C "$T/c" config --get core.hooksPath || echo '(unset)')"
echo " old .git/hooks/pre-commit (exit 1, prints OLD) once hooksPath is set; commit of a clean file:"
( cd "$T/d" && git reset -q --hard HEAD && printf '#!/bin/sh\necho OLD\nexit 1\n' > .git/hooks/pre-commit && chmod +x .git/hooks/pre-commit && echo clean > ok && git add ok && try git commit -m ok )
echo "[4] hook without the executable bit:"
mk4(){ newrepo "$T/e"; cd "$T/e"; printf '%s\n' "$STAGED_HOOK" > .git/hooks/pre-commit; chmod "$1" .git/hooks/pre-commit; echo "key=$SECRET" > cfg; git add cfg; }
echo " mode 644, secret staged:"; mk4 644; try git commit -m s
echo " mode 644, git -c advice.ignoredHook=false:"; mk4 644; try git -c advice.ignoredHook=false commit -m s
echo " mode 755:"; mk4 755; try git commit -m s
echo " mode 755 but bad shebang (#!/nonexistent):"; mk4 755; printf '#!/nonexistent\nexit 0\n' > .git/hooks/pre-commit; try git commit -m s
echo "[5] working directory and environment seen by the hook:"
newrepo "$T/f"; cd "$T/f"; mkdir -p sub/deep
printf '#!/bin/sh\necho "cwd=$(pwd | sed "s#^'"$T"'#TMP#") GIT_DIR=${GIT_DIR:-unset} GIT_INDEX_FILE=${GIT_INDEX_FILE:-unset}" >&2\nexit 0\n' > .git/hooks/pre-commit; chmod +x .git/hooks/pre-commit
echo x > sub/deep/f; git add sub/deep/f
echo " commit launched from sub/deep:"; ( cd sub/deep && git commit -m s 2>&1 | grep cwd | sed "s#$T#TMP#g; s/next-index-[0-9]*/next-index-PID/; s/^/ /" )
echo y > sub/deep/g; git add sub/deep/g
echo " commit -a launched from sub/deep (temporary index):"; echo z >> README; ( cd sub/deep && git commit -a -m s 2>&1 | grep cwd | sed "s#$T#TMP#g; s/next-index-[0-9]*/next-index-PID/; s/^/ /" )
echo w > sub/deep/h; git add sub/deep/h
echo " commit with explicit path (git commit -m s sub/deep/h; --only mode):"; ( git commit -m s sub/deep/h 2>&1 | grep cwd | sed "s#$T#TMP#g; s/next-index-[0-9]*/next-index-PID/; s/^/ /" )
echo "[6] staged content vs working tree (file partially staged):"
for kind in staged disk; do
newrepo "$T/g"; cd "$T/g"
[ $kind = staged ] && printf '%s\n' "$STAGED_HOOK" > .git/hooks/pre-commit || printf '%s\n' "$DISK_HOOK" > .git/hooks/pre-commit
chmod +x .git/hooks/pre-commit
printf 'line1\nline2\n' > app.conf; git add app.conf; git commit -qm conf
echo " --- hook checks: $kind"
# case A: secret only in the working tree, staged part is clean (what git add -p leaves behind)
printf 'line1\nline2\nkey=%s\nline4\n' "$SECRET" > app.conf
printf 'line1\nline2\nline4\n' > "$T/clean"; git update-index --cacheinfo 100644,"$(git hash-object -w "$T/clean")",app.conf
echo " A: secret only on disk (not staged): staged=$(git diff --cached | grep -c "$SECRET") on-disk=$(grep -c "$SECRET" app.conf)"
try git commit -m A
git reset -q --hard HEAD
# case B: secret staged, then removed from disk
printf 'line1\nline2\nkey=%s\n' "$SECRET" > app.conf; git add app.conf; printf 'line1\nline2\n' > app.conf
echo " B: secret staged, disk is clean: staged=$(git diff --cached | grep -c "$SECRET") on-disk=$(grep -c "$SECRET" app.conf)"
try git commit -m B
echo " secret inside HEAD after B: $(git show HEAD:app.conf | grep -c "$SECRET") line(s)"
done
done
Este artículo no contiene enlaces de afiliado.