Static, Dependency and Secret Scanning in CI
Run the three scanners a pull-request pipeline needs on a small sample repository: Semgrep for your own code, pip-audit for dependencies and Gitleaks for secrets. Combine them into one gate script that fails the build, fix what it finds with a test first, and wire it into a pinned GitHub Actions workflow.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: Create the sample repository
- Step 2: Static analysis with Semgrep
- Step 3: Dependency scanning with pip-audit
- Step 4: Secret scanning with Gitleaks
- Step 5: One gate script for CI
- Step 6: Fix with a test first, then re-run the gate
- Check your understanding
- Apply it
- Review prompt
Lessons of Secure Coding & Code Review
- Where Security Review Fits in Delivery Concept · 15 min
- Tracing Untrusted Input from Source to Sink Worked example · 25 min
- Static, Dependency and Secret Scanning in CI Lab · 30 min
- Triaging and Tuning Scanner Results Worked example · 20 min
- Fixes That Stay Fixed Lab · 25 min
- Secure Code Review Check Knowledge check · 6 questions
What you will learn
- Configure static analysis, dependency scanning and secret scanning in CI, triage results into true and false positives, and tune rules to reduce noise.
Prerequisites: Web Application Security
01. Goal and setup
Manual review is good at logic and design flaws, but it is slow and inconsistent at spotting the same small mistakes again and again. Automated scanners cover those, on every pull request, before a human looks. Three kinds work together:
- Static analysis (SAST, static application security testing) reads your own source code without running it and matches patterns or data flows, such as request data reaching SQL text.
- Dependency scanning (SCA, software composition analysis) compares the exact versions of the libraries you use with databases of published advisories.
- Secret scanning looks for credentials such as API tokens and private keys in files and history, using known token formats plus checks on how random a string looks.
In this lab you run all three on a small sample repository, combine them into one gate script that exits non-zero when something must block the merge, fix what they find, and see the gate pass. The same script is what the CI job runs.
You need: Python 3.10 or later, curl, and a Linux x86-64 shell (on macOS, download the darwin Gitleaks archive instead). Versions used: Semgrep 1.185.0, pip-audit 2.10.1, pytest 9.2.0, Gitleaks 8.30.1. pip-audit needs internet access to query the advisory database.
mkdir -p scan-lab/bin && cd scan-lab
python3 -m venv .venv && source .venv/bin/activate
python -m pip install "semgrep==1.185.0" "pip-audit==2.10.1" "pytest==9.2.0"
cd bin
base=https://github.com/gitleaks/gitleaks/releases/download/v8.30.1
curl -sSLO "$base/gitleaks_8.30.1_linux_x64.tar.gz"
curl -sSLO "$base/gitleaks_8.30.1_checksums.txt"
sha256sum --check --ignore-missing gitleaks_8.30.1_checksums.txt
tar -xzf gitleaks_8.30.1_linux_x64.tar.gz gitleaks && cd ..
export PATH="$PWD/bin:$PATH"
gitleaks versiongitleaks_8.30.1_linux_x64.tar.gz: OK
8.30.1The checksum check matters: a scanner runs with access to your whole repository, so verify that the archive is the one the project published before you run it. Keep this shell open, or run source .venv/bin/activate and the export PATH line again in a new one.
02. Step 1: Create the sample repository
The sample is the data layer of a notes service. It has one real flaw, one pattern that only looks dangerous, and an old dependency. Create the folders and files below inside scan-lab.
mkdir -p notes_api rules tools tests && touch notes_api/__init__.py
printf 'flask==3.1.3\nrequests==2.31.0\n' > requirements.txt"""Data access for a small notes service (lab sample: one deliberate flaw)."""
import sqlite3
import subprocess
def connect():
return sqlite3.connect("notes.db")
def notes_by_tag(conn, tag):
# FLAW: the tag from the request is pasted into the SQL text
return conn.execute(f"SELECT id, title FROM notes WHERE tag = '{tag}'").fetchall()
def note_by_id(conn, note_id):
row = conn.execute("SELECT id, title FROM notes WHERE id = ?", (note_id,))
return row.fetchone()
def backup():
# constant command, no request data involved
subprocess.run("sqlite3 notes.db .dump > backup.sql", shell=True, check=True)import os
DATABASE = os.environ.get("NOTES_DB", "notes.db")
GITHUB_TOKEN = os.environ["GITHUB_TOKEN"] # read from the environment, never committedRead db.py as a reviewer first. notes_by_tag builds SQL by pasting tag into the text, so the database parses whatever the caller sends as part of the query. note_by_id passes its value separately as a bound parameter (the ?), so the database treats it only as data. backup uses shell=True, which hands a string to /bin/sh; that is dangerous when untrusted text reaches it, but here the string is a constant.
Check that the layout is right before you scan it. The empty folders are filled in the next steps.
find notes_api rules tools tests | LC_ALL=C sortnotes_api
notes_api/__init__.py
notes_api/db.py
notes_api/settings.py
rules
tests
tools03. Step 2: Static analysis with Semgrep
Semgrep rules are YAML files with patterns written in the syntax of the target language. Projects often start with a published ruleset (--config p/python downloads one from the Semgrep registry), but registry rules change over time, so this lab uses two local rules to keep the output stable. CodeQL, the SAST engine behind GitHub code scanning, works differently: it first extracts the code into a database and then runs queries that follow data through the program, which suits deeper data-flow questions but needs more setup than a Semgrep pattern. Each rule has a severity; you will use it to decide what blocks a merge. Save the rules as scan-lab/rules/python-security.yml, and a small report printer as scan-lab/tools/findings.py.
rules:
- id: sql-built-from-string
languages: [python]
severity: ERROR
message: SQL text built from a variable; pass values as ? parameters
pattern-either:
- pattern: $CONN.execute(f"...")
- pattern: $CONN.execute("..." % ...)
- pattern: $CONN.execute("..." + ...)
- id: subprocess-shell-true
languages: [python]
severity: WARNING
message: shell=True runs the string through /bin/sh; check what reaches it
pattern: subprocess.run(..., shell=True, ...)"""Print one line per finding from a Semgrep or Gitleaks JSON report."""
import json
import sys
data = json.load(open(sys.argv[1]))
if isinstance(data, dict): # Semgrep: {"results": [...]}
for r in data["results"]:
rule = r["check_id"].split(".")[-1]
print(f"{r['path']}:{r['start']['line']} {r['extra']['severity']} {rule}")
print(f"{len(data['results'])} Semgrep finding(s)")
else: # Gitleaks: [...]
for r in data:
print(f"{r['File']}:{r['StartLine']} {r['RuleID']} {r['Secret']}")
print(f"{len(data)} Gitleaks finding(s)")semgrep scan --metrics=off --disable-version-check --quiet --config rules/ \
--json -o semgrep.json notes_api/
echo "exit=$?"
python3 tools/findings.py semgrep.jsonexit=0
notes_api/db.py:12 ERROR sql-built-from-string
notes_api/db.py:22 WARNING subprocess-shell-true
2 Semgrep finding(s)Both findings are reported, but the exit code is 0: without --error, Semgrep reports and does not fail. The ERROR finding is a true positive, a real flaw. The WARNING is a candidate that a human must judge; lesson 4 shows how to triage it and record the decision. A pipeline that blocks on every warning teaches developers to ignore it, so the gate in step 5 blocks only on ERROR rules.
04. Step 3: Dependency scanning with pip-audit
pip-audit reads requirements.txt, looks up each pinned version in PyPI's vulnerability data, which comes from the Python Packaging Advisory Database (-s osv queries OSV instead), and reports known vulnerabilities with the versions that fix them. --no-deps audits exactly the pins you list; it needs every line pinned with ==. Real projects audit a lock file that pins transitive dependencies too. The tool can list one advisory twice, so this printer removes duplicates. Save it as scan-lab/tools/deps.py.
"""Summarise a pip-audit JSON report: one line per package and advisory."""
import json
import sys
report = json.load(open(sys.argv[1]))
seen = set()
for dep in report["dependencies"]:
for vuln in dep.get("vulns", []):
key = (dep["name"], vuln["id"])
if key in seen:
continue # the same advisory can be listed more than once
seen.add(key)
cve = next((a for a in vuln["aliases"] if a.startswith("CVE-")), "-")
fix = ", ".join(vuln["fix_versions"]) or "no fix yet"
print(f"{dep['name']} {dep['version']} {cve:<15} fixed in {fix}")
print(f"{len(seen)} advisory(ies)")pip-audit -r requirements.txt --no-deps --disable-pip --progress-spinner off \
-f json -o deps.json 2>/dev/null
echo "exit=$?"
python3 tools/deps.py deps.jsonexit=1
requests 2.31.0 CVE-2024-35195 fixed in 2.32.0
requests 2.31.0 CVE-2024-47081 fixed in 2.32.4
requests 2.31.0 CVE-2026-25645 fixed in 2.33.0
3 advisory(ies)pip-audit exits 1 when it finds anything. Your list may be longer than this one, because new advisories are published all the time; that is the point of scanning on every build. Not every advisory affects you. Whether your code calls the vulnerable function, and whether the package runs in production or only in development, both change the priority. Lesson 4 covers that triage.
05. Step 4: Secret scanning with Gitleaks
To give the scanner something to find without putting a real-looking token in this lesson, a script generates a fake one in GitHub's personal-token format. Save it as scan-lab/tools/make_leak.py and run it, then scan.
"""Write a file with a fake token in GitHub's format, so the scanner has a target.
The token is random and fake; generating it keeps it out of the lesson text."""
import random
import string
rng = random.Random(2026)
fake = "ghp_" + "".join(rng.choices(string.ascii_letters + string.digits, k=36))
with open("notes_api/legacy_config.py", "w") as out:
out.write(f'GITHUB_TOKEN = "{fake}" # pasted while debugging\n')
print("wrote notes_api/legacy_config.py")python3 tools/make_leak.py
gitleaks dir notes_api --no-banner --redact --log-level error \
--report-format json --report-path leaks.json
echo "exit=$?"
python3 tools/findings.py leaks.jsonwrote notes_api/legacy_config.py
exit=1
notes_api/legacy_config.py:1 github-pat REDACTED
1 Gitleaks finding(s)--redact keeps the secret out of the report and the CI log, which matters because CI logs are widely readable. Note that settings.py is not reported: it names an environment variable but holds no value, which is the safe pattern.
If a scanner finds a real credential that has been pushed, deleting the line is not enough. Copies may already sit in forks, clones, CI logs and caches. The first action is to revoke the credential and issue a new one, then check the provider's logs for use you do not recognise; cleaning history comes later. gitleaks dir scans only the files as they are now. gitleaks git scans the commit history, which is how you find a token that was committed and then deleted. GitHub also offers secret scanning and push protection on the server side.
06. Step 5: One gate script for CI
CI needs one command that runs every scanner, shows what each found, and fails if any gate fails. The script keeps going after a failure so that the developer sees all problems in one run. Save it as scan-lab/ci.sh, make it executable and run it.
#!/usr/bin/env bash
# Run the three security gates the way the CI job does; exit 1 if any gate fails.
set -u
status=0
echo "== SAST (Semgrep, blocking rules only)"
semgrep scan --metrics=off --disable-version-check --quiet --error --severity ERROR \
--config rules/ --json -o semgrep.json notes_api/ || status=1
python3 tools/findings.py semgrep.json
echo "== Dependencies (pip-audit)"
pip-audit -r requirements.txt --no-deps --disable-pip --progress-spinner off \
-f json -o deps.json 2>/dev/null || status=1
python3 tools/deps.py deps.json
echo "== Secrets (Gitleaks)"
gitleaks dir notes_api --no-banner --redact --log-level error \
--report-format json --report-path leaks.json || status=1
python3 tools/findings.py leaks.json
echo "security gates: $([ "$status" -eq 0 ] && echo PASS || echo FAIL)"
exit "$status"chmod +x ci.sh && ./ci.sh; echo "exit=$?"== SAST (Semgrep, blocking rules only)
notes_api/db.py:12 ERROR sql-built-from-string
1 Semgrep finding(s)
== Dependencies (pip-audit)
requests 2.31.0 CVE-2024-35195 fixed in 2.32.0
requests 2.31.0 CVE-2024-47081 fixed in 2.32.4
requests 2.31.0 CVE-2026-25645 fixed in 2.33.0
3 advisory(ies)
== Secrets (Gitleaks)
notes_api/legacy_config.py:1 github-pat REDACTED
1 Gitleaks finding(s)
security gates: FAIL
exit=107. Step 6: Fix with a test first, then re-run the gate
Start with a test that shows the SQL flaw as a plain bug: a tag containing an apostrophe, such as mum's, breaks the query, because the apostrophe ends the SQL string early. With a bound parameter the same tag is just data. Save the test as scan-lab/tests/test_db.py and run it on the current code.
import sqlite3
from notes_api.db import notes_by_tag
def make_db():
conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE notes (id INTEGER, title TEXT, tag TEXT)")
conn.executemany("INSERT INTO notes VALUES (?, ?, ?)",
[(1, "Recipes", "mum's"), (2, "Diary", "private")])
return conn
def test_quote_in_tag_is_treated_as_data():
assert notes_by_tag(make_db(), "mum's") == [(1, "Recipes")]python -m pytest -q -p no:cacheprovider 2>&1 | tail -n 2 | sed -E 's/ in [0-9.]+s//'FAILED tests/test_db.py::test_quote_in_tag_is_treated_as_data - sqlite3.Opera...
1 failedNow fix all three findings. Replace notes_api/db.py with the version below, delete the file with the leaked token (in real life: revoke it first), and move requests to a fixed release.
"""Data access for a small notes service (lab sample)."""
import sqlite3
import subprocess
def connect():
return sqlite3.connect("notes.db")
def notes_by_tag(conn, tag):
# the tag travels as a bound parameter, never as part of the SQL text
return conn.execute("SELECT id, title FROM notes WHERE tag = ?", (tag,)).fetchall()
def note_by_id(conn, note_id):
row = conn.execute("SELECT id, title FROM notes WHERE id = ?", (note_id,))
return row.fetchone()
def backup():
# constant command, no request data involved
subprocess.run("sqlite3 notes.db .dump > backup.sql", shell=True, check=True)rm notes_api/legacy_config.py
sed -i 's/requests==2.31.0/requests==2.34.2/' requirements.txt
python -m pytest -q -p no:cacheprovider 2>&1 | tail -n 1 | sed -E 's/ in [0-9.]+s//'1 passed./ci.sh; echo "exit=$?"== SAST (Semgrep, blocking rules only)
0 Semgrep finding(s)
== Dependencies (pip-audit)
0 advisory(ies)
== Secrets (Gitleaks)
0 Gitleaks finding(s)
security gates: PASS
exit=0The WARNING about shell=True is still in the code but does not block, because the gate only fails on ERROR rules; you will triage it in lesson 4. The test you added now runs in CI too, so the SQL flaw cannot quietly return.
The workflow below runs the same steps on every pull request. It is shown for reference and was not run here. Actions are pinned to full commit SHAs with the tag in a comment, because a tag can be moved to different code; the job token is read-only and the checkout does not keep credentials, which limits what a compromised step could do. GitHub's security hardening guide for Actions explains both.
# .github/workflows/security.yml
name: security
on: pull_request
permissions:
contents: read
jobs:
gates:
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
with:
python-version: "3.12"
- name: Install scanners
run: |
python -m pip install "semgrep==1.185.0" "pip-audit==2.10.1" "pytest==9.2.0"
mkdir -p bin && cd bin
base=https://github.com/gitleaks/gitleaks/releases/download/v8.30.1
curl -sSLO "$base/gitleaks_8.30.1_linux_x64.tar.gz"
curl -sSLO "$base/gitleaks_8.30.1_checksums.txt"
sha256sum --check --ignore-missing gitleaks_8.30.1_checksums.txt
tar -xzf gitleaks_8.30.1_linux_x64.tar.gz gitleaks
- name: Tests
run: python -m pytest -q
- name: Security gates
run: PATH="$PWD/bin:$PATH" ./ci.sh08. Check your understanding
09. Apply it
For the skill project, add these three gates to the CI of the intentionally vulnerable sample repository you are reviewing. Start from a published Semgrep ruleset, scan the lock file with pip-audit (or npm audit for a Node project), and run gitleaks git once over the full history. Save each tool's JSON report; you will triage every finding in lesson 4.
10. Review prompt
From memory, say what SAST, SCA and secret scanning each look at, and give one kind of problem each would miss. Then explain why the gate blocks only on ERROR rules, and what you do first when a scanner finds a real, pushed credential.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.