在使用 Claude 時,Claude 建議我使用這工具搭配 gitleaks,可以在提交代碼前檢查是否有機敏資料會被提交到 git repository。
Claude 都這麼建議了,就試試吧。
在 Ubuntu 24.04 ,gitleaks 跟 pre-commit 都已經可以使用 apt 安裝。
sudo apt install gitleaks pre-commit
接下來就是配置。
目前我是先在一個 repository 測試,所以要先撰寫 .pre-commit-config.yaml
# See https://pre-commit.com for more information
# See https://pre-commit.com/hooks.html for more hooks
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v3.2.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
- id: check-yaml
- id: check-added-large-files
- repo: https://github.com/gitleaks/gitleaks
rev: v8.24.2
hooks:
- id: gitleaks
在這裡,我使用 pre-commit 所提供的範例,剛好也是我常會用的
- 檢查行末空白
- 末行的EOF
- yaml 格式
- 避免加入過大的檔案
再來是 gitleaks 的部份,這邊我有點猶豫的是語法,不確定我已經用 apt 安裝 gitleaks 了,是否還要加上 repo。後來想,先加上去再說,錯了再處理就好。但結果看起來是可以使用。
在編寫完成以後,執行以下指令安裝
pre-commit install
再來是 gitleaks 設定
# gitleaks 設定:沿用內建規則,再補上內建沒有的規則(#14)
[extend]
useDefault = true
# Tailscale key:tskey-<auth|client|api|scim|webhook>-<id>-<secret>
# 內建規則沒有涵蓋,見 work-diary/20261002-tailscale-oauth-secret.md
[[rules]]
id = "tailscale-key"
description = "Tailscale auth key / OAuth client secret / API key"
regex = '''\btskey-[a-z]+-[0-9A-Za-z]{6,}-[0-9A-Za-z]{16,}\b'''
keywords = ["tskey-"]
# Telegram bot token:<bot id>:AA<33 字元>(共約 46 字元)
# 內建的 telegram-bot-api-token 要求 token 前面有「telegr」,Alertmanager 的 `bot_token: <token>` 抓不到(#22)
[[rules]]
id = "telegram-bot-token-bare"
description = "Telegram bot token(不需要 telegram 關鍵字)"
regex = '''\b[0-9]{8,10}:AA[0-9A-Za-z_-]{33}\b'''
keywords = [":aa"]
然後就收工了。
pre-commit install 會把腳本寫到 .git/hooks/pre-commit ,讓 git commit 時,可以執行此腳本來檢查。