Lab: scan a repository and an image for leaked credentials
Plant a generated token in Git history and in an image layer, find both with Gitleaks and Trivy, test your scanner configuration with negative cases, and remediate in the right order.
Contentsand lesson path
On this page
- Secret Detection Mechanics: Regex Signatures and Shannon Entropy
- Container Layer Inspection: Auditing OCI Image Blobs
- Lab Execution: Gitleaks Repository Scan and Trivy Image Audit
- Check your understanding
- Apply it
- Review prompt
Lessons of Secrets Management
- How secrets escape, and what to do when one does Concept · 20 min
- Lab: scan a repository and an image for leaked credentials Lab · 20 min
- Secret managers and the path from store to process Concept · 15 min
- Lab: sync a secret from a manager into Kubernetes Lab · 30 min
- Keyless CI and rotating credentials without an outage Worked example · 25 min
- Check: secrets design review Knowledge check · 6 questions
What you will learn
- Identify where secrets leak (repositories, images, CI logs, environment dumps) and respond to a leaked credential by revoking, rotating and scanning history.
01. Secret Detection Mechanics: Regex Signatures and Shannon Entropy
Secret scanners such as Gitleaks and Trivy combine two techniques:
-
Pattern Matching (Regular Expressions): Finds vendor credentials that have a fixed prefix and length. For example, long-term AWS access key IDs start with
AKIAand temporary (STS) ones withASIA, followed by 16 characters (Gitleaks' built-in rule covers several such prefixes), classic GitHub personal access tokens matchghp_[0-9a-zA-Z]{36}, and Stripe live secret keys start withsk_live_(Gitleaks accepts 10 to 99 letters and digits after it). Such signatures produce few false positives for the vendors they cover. -
Shannon Entropy Analysis: Finds secrets with no fixed format (custom passwords, hex-encoded or random keys). Shannon entropy measures how unpredictable the characters of a string are. Per-character entropy is capped by the alphabet: a random hex string can reach at most 4 bits per character (log2 of 16) and a random base64 string at most 6, and short strings score lower still. Measured on 1,000 random strings each, 40-character hex tokens averaged about 3.7 and 43-character base64url tokens about 4.9. Ordinary words and identifiers usually score lower than a random string of the same alphabet and length, but the gap is smaller than people expect, so thresholds must be tuned per character set. Gitleaks' built-in generic rule uses 3.5; a threshold of 4.3 would miss every hex key.
A configuration file such as the one below adds a rule. Three details matter. Rules are an array of tables ([[rules]], each with an id); a [rules.<name>] table is not a valid rule and Gitleaks refuses to load the file. secretGroup names the capture group that holds the secret, so the regex must actually capture the token. And a custom configuration replaces the built-in rules unless it says [extend] useDefault = true, which would silently switch off more than 200 detectors.
A repository audit must therefore scan history, not only the current checkout: every commit reachable from any branch or tag in the .git object database (gitleaks git scans all refs by default). Deleting a file in a new commit, or adding it to .gitignore, leaves every earlier commit, and the file inside it, untouched.
Many teams use three gates: a pre-commit hook on the developer's laptop blocks a commit before it leaves, GitHub secret scanning push protection rejects a push at the server, and a CI scan checks every pull request.
# Keep the ~200 built-in rules and add one of our own
[extend]
useDefault = true
[[rules]]
id = "internal-api-token"
description = "High-entropy token assigned to api_key or token"
regex = '''(?i)(?:api_key|token)\s*=\s*['"]?([A-Za-z0-9_\-]{24,})'''
secretGroup = 1
entropy = 3.5
keywords = ["api_key", "token"]02. Container Layer Inspection: Auditing OCI Image Blobs
Images leak secrets too. Each build step that changes files adds a layer, and every layer is stored as its own tarball. A key or credential file copied into a layer stays there for as long as the image exists.
A common mistake is to delete the file in a later instruction: COPY id_rsa /root/.ssh/ followed by RUN rm -f /root/.ssh/id_rsa. Each instruction that changes files creates an immutable, content-addressed layer. The rm only records a whiteout marker (.wh.id_rsa) in the top layer; the earlier layer still holds the private key, and anyone who can pull the image can extract it.
Scanners such as Trivy unpack each layer of the image separately (trivy image --scanners secret <image>), so a file deleted in a later layer is still found in the layer that added it. A clean result means no rule matched, not that no secret exists.
The fix is a BuildKit secret mount. Instead of COPY credentials.txt /root/ or ENV DB_PASSWORD=xyz, use: RUN --mount=type=secret,id=npmrc,target=/root/.npmrc npm install. BuildKit mounts the secret into an in-memory filesystem only while that one instruction runs, so it is not written into any image layer unless the command itself copies it somewhere.
03. Lab Execution: Gitleaks Repository Scan and Trivy Image Audit
You will plant a token in Git history and in an image layer, then find both. Nothing in this lab is a real credential: the token and the key are generated randomly on your machine.
What you need: Git, Python 3, Docker, Gitleaks 8.19 or later (the outputs below come from 8.30.1) and Trivy (0.76.2). Gitleaks 8.19 replaced gitleaks detect and gitleaks protect with gitleaks git (history) and gitleaks dir (files); Trivy deprecated --security-checks in favour of --scanners.
- Create a repository with a leaked token in its history. The first commit adds a staging config with a random token; the second commit deletes it, so the current checkout looks clean. A second file holds AWS's documentation key
AKIAIOSFODNN7EXAMPLE.
git init -q leak-lab && cd leak-lab
mkdir -p config
python3 -c 'import secrets; print("API_TOKEN=" + secrets.token_urlsafe(32))' \
> config/staging.env
printf 'AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE\n' > config/aws-docs-example.env
git add . && git commit -qm "add staging config"
git rm -q config/staging.env && git commit -qm "remove staging config"
git log --format='%s' # commit subjects, newest firstremove staging config
add staging config- Scan the whole history with the built-in rules. Gitleaks walks every commit, so it finds the deleted token.
--redactkeeps the secret out of the terminal and CI logs.
cd leak-lab
gitleaks git -v --redact .Finding: API_TOKEN=REDACTED
Secret: REDACTED
RuleID: generic-api-key
Entropy: 4.722435
File: config/staging.env
Line: 1
Commit: 351a0e8010f8d0528e647a381d4a55354eaa88eb
11:46PM INF 1 commits scanned.
11:46PM INF scanned ~93 bytes (93 bytes) in 451ms
11:46PM WRN leaks found: 1Notice what is not reported: config/aws-docs-example.env. Gitleaks' built-in aws-access-token rule allowlists keys that end in EXAMPLE, so planting AWS's documentation key teaches you nothing. The negative test in step 4 uses a random key instead.
- Add your own rule without losing the built-in ones. Save the configuration above as
.gitleaks.tomlinleak-laband scan again with--config .gitleaks.toml. The custom rule now reports the token under its own ID.
gitleaks git -v --redact --config .gitleaks.toml .Finding: API_TOKEN=REDACTED
RuleID: internal-api-token
File: config/staging.env
Commit: 351a0e8010f8d0528e647a381d4a55354eaa88eb
11:46PM WRN leaks found: 1- Negative tests. First, a key in the real AWS format (not ending in
EXAMPLE) must be found. Second, a configuration written as[rules.<name>]tables, a common mistake, must be rejected rather than silently ignored.
K="AKIA$(python3 -c 'import secrets; print("".join(secrets.choice(
"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567") for _ in range(16)))')"
printf 'AWS_ACCESS_KEY_ID=%s\n' "$K" > config/aws-real-looking.env
gitleaks dir -v --redact config
cat > broken.toml <<'EOF'
[rules.aws-access-key]
regex = 'AKIA[0-9A-Z]{16}'
EOF
gitleaks git --config broken.toml .Finding: AWS_ACCESS_KEY_ID=REDACTED
RuleID: aws-access-token
File: config/aws-real-looking.env
11:46PM WRN leaks found: 1
11:46PM FTL Failed to load config error="rule |id| is missing or empty"- Plant a key in an image layer and scan the image. In an empty directory, create the Dockerfile below and a
deploy.envholding a random key, build, and scan. TheRUN rmadds only a whiteout entry; Trivy reads every layer and reports the file from theCOPYlayer.
FROM alpine:3.22
WORKDIR /app
COPY deploy.env /app/deploy.env
RUN rm /app/deploy.env # too late: the COPY layer still holds the fileK="AKIA$(python3 -c 'import secrets; print("".join(secrets.choice(
"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567") for _ in range(16)))')"
printf 'AWS_ACCESS_KEY_ID=%s\n' "$K" > deploy.env
docker build -t app:lab .
trivy image --scanners secret app:lab
trivy image --scanners secret --exit-code 1 --quiet app:lab > /dev/null
echo "exit: $?"/app/deploy.env (secrets)
=========================
Total: 1 (UNKNOWN: 0, LOW: 0, MEDIUM: 0, HIGH: 0, CRITICAL: 1)
CRITICAL: AWS (aws-access-key-id)
════════════════════════════════════════
AWS Access Key ID
────────────────────────────────────────
/app/deploy.env:1 (offset: 18 bytes) (added by 'COPY deploy.env /app/deploy.env')
────────────────────────────────────────
1 [ AWS_ACCESS_KEY_ID=********************
exit: 1- Remediate in the right order, then prove the history is clean. For a real leak, revoke the credential first (lesson 01): rewriting history does not take the token back from anyone who already has a copy. Then rebuild the image without the file (with a BuildKit secret mount if the build needs it) and delete the old tags. Rewrite Git history last.
Try the rewrite on leak-lab. Install git-filter-repo with brew install git-filter-repo, pipx install git-filter-repo, or sudo apt install git-filter-repo on Debian 13 or Ubuntu 25.04 and later (Debian 12 and Ubuntu 24.04 ship version 2.38, which lacks the --sensitive-data-removal option below). A plain pip install fails on Ubuntu 24.04 and Debian 12 or 13, which protect the system Python (PEP 668).
filter-repo refuses to rewrite a repository that does not look like a fresh clone. On leak-lab the first check to fail is the reflog (Git's local record of where each branch pointed): a fresh clone has one entry, and your two commits wrote two. Later checks would also fail (untracked files from steps 3 and 4; the branch was never pushed to origin). --force skips all of these checks, which is acceptable only on a throwaway repository. filter-repo then drops the commit that became empty, expires the reflog and runs git gc --prune=now.
git filter-repo --invert-paths --path config/staging.env --force
git log --format='%s' --all -- config/staging.env # no commit has the file
git log --format='%s'
gitleaks git -v --redact .add staging config
6:35PM INF 1 commits scanned.
6:35PM INF scanned ~39 bytes (39 bytes) in 434ms
6:35PM INF no leaks foundThe remove staging config commit is gone because it became empty, and Gitleaks finds no leak in any commit. On a shared repository (this lab has no remote) the rewrite counts only once the server has it: run filter-repo in a fresh clone with --sensitive-data-removal instead of --force, push with the command it prints (git push --force --mirror origin), have everyone delete old clones and clone again, and ask your Git host to purge cached views and pull-request refs.
04. Check your understanding
05. Apply it
Put secret scanning into your pipelines:
- Embed Gitleaks in CI Pull Requests: Run
gitleaks git --log-opts="--all"(Gitleaks 8.19 and later; older versions usegitleaks detect) in pull request workflows so that a new secret fails the build. - Scan Images in Container Registries: Automate Trivy scans on every Docker image build (
trivy image --scanners secret --exit-code 1) before pushing to production registries. - Tune Entropy Thresholds: Give each custom
.gitleaks.tomlrule an entropy threshold that fits its token's alphabet. - Purge History with git-filter-repo: When historical cleanup is required, use
git-filter-reporather than deprecatedgit filter-branchfor speed and safety. - Mandate Repository Re-Clones: After any history rewrite, ask everyone to delete old clones and clone again.
- Automate Pre-Commit Scanning: Give developers a
pre-commithook that catches secrets before a commit exists.
06. Review prompt
Explain how secret scanners combine regex signatures with Shannon entropy to find credentials. Describe why scanning each image layer catches a secret that a later layer deleted, and why everyone must clone again after a history purge with git-filter-repo.
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.