git pre-commit 检测敏感信息

项目中如果填写了一些密钥、账号、密码等敏感信息,我们一般不希望把这些数据上传到git仓库中,避免隐私泄露。

以下是一种通过 pre-commit 实现的敏感数据检测方案:

利用 .git/hooks/pre-commit 来实现一个 shell 脚本,检测指定 token ,即敏感信息,然后将拒绝提交,并给出报错信息。

  1. 找到项目中的 .git/hooks 文件夹,在里面创建一个 pre-commit 文件(没有任何后缀名),通过 git 提交前,会自动执行这个脚本;

  2. pre-commit 中写入:

    #!/bin/bash
    
    # 定义敏感信息模式
    sensitive_patterns=("password" "api_key" "secret" "token")
    
    # 扫描所有已暂存的文件
    files=$(git diff --cached --name-only)
    found_sensitive_info=false
    
    for file in $files; do
        if [ -f "$file" ]; then
            for pattern in "${sensitive_patterns[@]}"; do
                if grep -q "$pattern" "$file"; then
                    echo "Sensitive information detected in file: $file"
                    echo "Pattern: $pattern"
                    found_sensitive_info=true
                fi
            done
        fi
    done
    
    # 如果发现敏感信息,拒绝提交
    if [ "$found_sensitive_info" = true ]; then
        echo "Commit rejected due to sensitive information."
        exit 1
    fi
    

    sensitive_patterns 中就是字符串形式的敏感信息;

  3. 然后通过 git commit 提交时,如果存在上述信息,就会报错并拒绝提交:

    20:48:07.752: [demo] git -c credential.helper= -c core.quotepath=false -c log.showSignature=false add --ignore-errors -A -f -- src/main/resources/application.yml src/main/java/cn/comradexy/demo/config/DemoConfig.java .gitignore
    20:48:07.809: [demo] git -c credential.helper= -c core.quotepath=false -c log.showSignature=false commit -F C:\Users\71969\AppData\Local\Temp\git-commit-msg-.txt --
    Sensitive information detected in file: src/main/resources/application.yml
    Pattern: password
    Commit rejected due to sensitive information.
    
  4. 手动修改后,重新提交,就可以避免敏感信息的泄露。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值