-
-
Notifications
You must be signed in to change notification settings - Fork 3
263 lines (225 loc) · 8.54 KB
/
secret-scan-gitleaks.yml
File metadata and controls
263 lines (225 loc) · 8.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
# .github/workflows/secret-scan-gitleaks.yml
name: Secret Scan (Gitleaks) [Report-Only]
on:
pull_request:
branches: [main, develop]
push:
branches: [main]
workflow_dispatch:
concurrency:
group: secret-scan-${{ github.ref }}
cancel-in-progress: true
permissions:
contents: read
security-events: write
jobs:
gitleaks:
name: Gitleaks Scan (PR-fast / Main-full) [Report-Only]
runs-on: ubuntu-latest
timeout-minutes: 15
env:
GITLEAKS_VERSION: "8.30.0"
OUT_DIR: "secret-scan-reports"
OUT_SARIF: "gitleaks.sarif"
OUT_JSON: "gitleaks.json"
OUT_LOG: "gitleaks.log"
OUT_MD: "gitleaks-report.md"
CONFIG_FILE: ".gitleaks.toml"
steps:
- name: Checkout (PR-fast / Main-full)
uses: actions/checkout@v4
with:
# PR: shallow checkout for speed. Push to main: full history for maximum coverage.
fetch-depth: ${{ github.event_name == 'push' && github.ref == 'refs/heads/main' && 0 || 2 }}
- name: Ensure output folder exists + baselines
shell: bash
run: |
set -euo pipefail
mkdir -p "${OUT_DIR}"
# Always create JSON baseline (empty array)
echo "[]" > "${OUT_DIR}/${OUT_JSON}"
# Always create SARIF baseline
cat > "${OUT_DIR}/${OUT_SARIF}" << 'EOF'
{
"$schema": "https://json.schemastore.org/sarif-2.1.0.json",
"version": "2.1.0",
"runs": [
{ "tool": { "driver": { "name": "gitleaks", "version": "0" } }, "results": [] }
]
}
EOF
# Always create MD baseline
cat > "${OUT_DIR}/${OUT_MD}" << 'EOF'
# Gitleaks Secret Scan (Report-Only)
Status: Not executed yet.
EOF
- name: Install Gitleaks (pinned)
shell: bash
run: |
set -euo pipefail
VER="${GITLEAKS_VERSION}"
curl -sSL -o /tmp/gitleaks.tar.gz "https://github.com/gitleaks/gitleaks/releases/download/v${VER}/gitleaks_${VER}_linux_x64.tar.gz"
tar -xzf /tmp/gitleaks.tar.gz -C /tmp gitleaks
sudo mv /tmp/gitleaks /usr/local/bin/gitleaks
gitleaks version
- name: Run Gitleaks (PR-fast / Main-full) [Report-Only]
if: always()
shell: bash
run: |
# Report-only: never fail the job
set +e
CFG=()
if [ -f "${CONFIG_FILE}" ]; then
CFG=(--config="${CONFIG_FILE}")
fi
EXTRA=()
if [ "${{ github.event_name }}" = "pull_request" ]; then
# PR-fast: scan working tree only (no git history)
EXTRA=(--no-git)
fi
gitleaks detect \
--source="." \
--redact \
"${CFG[@]}" \
"${EXTRA[@]}" \
--report-format="json" \
--report-path="${OUT_DIR}/${OUT_JSON}" \
2>&1 | tee "${OUT_DIR}/${OUT_LOG}"
exit 0
- name: Build SARIF + Markdown report (from JSON/log)
if: always()
shell: bash
run: |
set -euo pipefail
python3 - << 'PY'
import json, os, re
out_dir = os.environ["OUT_DIR"]
json_path = os.path.join(out_dir, os.environ["OUT_JSON"])
sarif_path = os.path.join(out_dir, os.environ["OUT_SARIF"])
log_path = os.path.join(out_dir, os.environ["OUT_LOG"])
md_path = os.path.join(out_dir, os.environ["OUT_MD"])
ver = os.environ.get("GITLEAKS_VERSION","0")
# Read log (for error context)
log_text = ""
try:
with open(log_path, "r", encoding="utf-8", errors="replace") as f:
log_text = f.read()
except Exception:
pass
# Load findings JSON (fallback to empty list)
findings = []
try:
with open(json_path, "r", encoding="utf-8") as f:
data = json.load(f)
if isinstance(data, list):
findings = data
except Exception:
findings = []
# --- SARIF ---
sarif = {
"$schema": "https://json.schemastore.org/sarif-2.1.0.json",
"version": "2.1.0",
"runs": [{
"tool": {"driver": {"name": "gitleaks", "version": ver}},
"results": []
}]
}
def pick(d, *keys, default=None):
for k in keys:
if k in d and d[k] is not None:
return d[k]
return default
for item in findings:
file_path = pick(item, "File", "file", "Path", "path", default="")
start_line = pick(item, "StartLine", "startLine", "Line", "line", default=1)
rule_id = pick(item, "RuleID", "ruleID", "Rule", "rule", default="gitleaks")
desc = pick(item, "Description", "description", default="Potential secret detected")
try:
start_line = int(start_line)
except Exception:
start_line = 1
sarif["runs"][0]["results"].append({
"ruleId": str(rule_id),
"level": "error",
"message": {"text": f"{desc} (rule: {rule_id})"},
"locations": [{
"physicalLocation": {
"artifactLocation": {"uri": file_path},
"region": {"startLine": start_line}
}
}]
})
with open(sarif_path, "w", encoding="utf-8") as f:
json.dump(sarif, f, ensure_ascii=False, indent=2)
# --- Markdown report ---
status = "OK"
if re.search(r"\bFTL\b|\bFailed to load config\b", log_text, re.IGNORECASE):
status = "ERROR (see log)"
mode = "Main (full history)"
if os.environ.get("GITHUB_EVENT_NAME","") == "pull_request":
mode = "PR-fast (working tree only)"
md = []
md.append("# Gitleaks Secret Scan (Report-Only)")
md.append("")
md.append(f"**Status:** {status}")
md.append(f"**Mode:** {mode}")
md.append(f"**Findings:** {len(findings)}")
md.append("")
if len(findings) == 0:
md.append("No secrets detected (or scan produced no findings).")
else:
counts = {}
for x in findings:
rid = pick(x, "RuleID", "ruleID", "Rule", "rule", default="gitleaks")
counts[rid] = counts.get(rid, 0) + 1
md.append("## Top Rules")
for rid, c in sorted(counts.items(), key=lambda kv: kv[1], reverse=True)[:15]:
md.append(f"- `{rid}`: {c}")
md.append("")
md.append("> Artifacts: `gitleaks.json`, `gitleaks.sarif`, `gitleaks.log`, `gitleaks-report.md`")
with open(md_path, "w", encoding="utf-8") as f:
f.write("\n".join(md) + "\n")
PY
- name: Publish report to Run Summary (View Runs)
if: always()
shell: bash
run: |
set -euo pipefail
COUNT="$(python3 -c 'import json; import sys; print(len(json.load(open(sys.argv[1]))))' "${OUT_DIR}/${OUT_JSON}" 2>/dev/null || echo 0)"
{
echo "## 🔐 Gitleaks Secret Scan (Report-Only)"
echo ""
echo "**Workflow:** PR-fast / Main-full"
echo "**Event:** \`${{ github.event_name }}\`"
echo "**Ref:** \`${{ github.ref }}\`"
echo "**Findings:** ${COUNT}"
echo ""
echo "### Report"
echo ""
if [ -f "${OUT_DIR}/${OUT_MD}" ]; then
cat "${OUT_DIR}/${OUT_MD}"
else
echo "_No markdown report file found:_ \`${OUT_DIR}/${OUT_MD}\`"
fi
echo ""
echo "### Artifacts"
echo ""
echo "- \`${OUT_DIR}/${OUT_JSON}\`"
echo "- \`${OUT_DIR}/${OUT_SARIF}\`"
echo "- \`${OUT_DIR}/${OUT_LOG}\`"
echo "- \`${OUT_DIR}/${OUT_MD}\`"
} >> "$GITHUB_STEP_SUMMARY"
- name: Upload artifacts (reports)
if: always()
uses: actions/upload-artifact@v4
with:
name: secret-scan-reports
path: ${{ env.OUT_DIR }}/**
if-no-files-found: warn
retention-days: 30
- name: Upload SARIF to GitHub Code Scanning
if: always() && hashFiles(format('{0}/{1}', env.OUT_DIR, env.OUT_SARIF)) != ''
uses: github/codeql-action/upload-sarif@v4
with:
sarif_file: ${{ env.OUT_DIR }}/${{ env.OUT_SARIF }}
category: secrets/gitleaks