使用 Git Hooks 防止敏感信息泄露

欢迎关注公众号:冬瓜白

在日常开发中,我们可能会不小心将敏感信息提交到 Git。为了防止这种情况,可以利用 Git Hooks 编写一个简单的脚本,当发现提交中包含敏感词时,给出提示。

以下是一个基于 pre-commit 钩子的示例脚本:

bash 复制代码
#!/bin/bash
# pre-commit.sh

FILES_PATTERN='\.(java|js|ts)(\..+)?$'
FORBIDDEN_WORDS=("PASSWORD" "SECRET" "TOKEN")  # 添加更多的敏感词
FILES=$(git diff --cached --name-only --diff-filter=ACMR HEAD | grep -E $FILES_PATTERN)

ERRORS=""

for FILE in $FILES
do
  for WORD in "${FORBIDDEN_WORDS[@]}"
  do
    if grep -q $WORD $FILE
    then
      ERRORS="${ERRORS}ERROR: Found '$WORD' references in $FILE. Please check them.\n"
    fi
  done
done

if [ -n "$ERRORS" ]; then
  echo -e $ERRORS
  exit 1
fi

exit 0

在这个脚本中定义了三个敏感词:PASSWORDSECRETTOKEN。你可以根据需要添加更多的敏感词。

将这个脚本保存在 .git/hooks/pre-commit

同时设置脚本可执行:

bash 复制代码
➜  z-sharding git:(master) chmod +x .git/hooks/pre-commit

这时候当尝试提交包含敏感词的代码时,Git 会给出提示,并精确指出具体的文件,这里我修改了一段包含敏感词的代码:

java 复制代码
    private static final String SECRET = "";

Git 提交会弹出提示,并且精确到具体的文件:

bash 复制代码
➜  z-sharding git:(master) ✗ git add .
➜  z-sharding git:(master) ✗ git commit -m 'feat:test2'
ERROR: Found 'SECRET' references in src/main/java/com/mi/maf/sharding/core/ConnectionWrapper.java. Please check them.

通过这种方式,可以有效地防止敏感信息的泄露。

相关推荐
小龙5 小时前
[Git 报错解决]本地分支落后于远程分支(`non-fast-forward`)
大数据·git·elasticsearch·github
爱敲代码的婷婷婷.6 小时前
git 指定版本回退、临时保存 等操作
git
闲云一鹤7 小时前
Git 焚决!一个绝招助你找回丢失的代码文件!
前端·git
DKunYu7 小时前
2.分支管理
大数据·git·elasticsearch·搜索引擎·gitee
DKunYu8 小时前
1.基本操作
git·gitee
小龙8 小时前
【Git 报错解决】SSH 公钥认证失败(`Permission denied (publickey)`)
运维·git·ssh
哆啦code梦9 小时前
Git Flow架构图解:分支策略全解析
git·git flow·分支策略
Albert Edison9 小时前
【Git】远程操作
git·svn·github
脾气有点小暴10 小时前
Git指令大全(常见版)
前端·git
DKunYu12 小时前
3.远程操作
大数据·git·elasticsearch·搜索引擎·gitee