SAST with the GitLab template

Find bugs in your own code, and make the findings fail the pipeline.

Intermediate13 min · lesson 11 of 17
Lesson files
The scripts, test data and local test servers this lesson uses, exactly as they ran on the lab machine (18 files, 7 KB): sast.tar.gz. The lab VM shares no folders with your computer, so fetch them inside the VM: cd ~/lab && curl -fsSLO https://secopslog.com/lab-files/ci-gitlab/sast.tar.gz && tar -xzf sast.tar.gz, which creates ~/lab/sast/. SHA-256: 1977caff9b24f5020544bf726ccaf12241b15ec25693d492382f83330c74fd66

Static analysis reads source code without running it and looks for patterns that are often bugs: user input reaching a shell, a weak hash, a disabled certificate check. It's cheap to run on every push, and it catches the routine mistakes that slip past code review. GitLab ships it as a template that works on the Free tier, with one catch this lesson is about: on Free, a finding never fails anything by itself.

One include line

app/.gitlab-ci.yml
# GitLab's SAST template adds a Semgrep-based job. On the Free tier it produces a report, and
# nothing blocks on it, so the gate job below is what turns findings into a red pipeline.
include:
- template: Jobs/SAST.gitlab-ci.yml
stages: [test, gate]
sast-gate:
stage: gate
image: secopslog-py:3.15
needs:
- job: semgrep-sast
artifacts: true
script:
- python gate.py gl-sast-report.json High Critical

The template adds the scanning jobs, and sast-gate is ours. The code to scan is a small script with two classic mistakes:

app/report.py
"""Builds a small report for a customer. It has the kind of bugs SAST is good at finding."""
import hashlib
import subprocess
import sys
def archive(name):
# The customer name goes straight into a shell command.
subprocess.run(f"tar -czf /tmp/{name}.tgz report.txt", shell=True, check=True)
def fingerprint(data):
return hashlib.md5(data).hexdigest()
if __name__ == "__main__":
archive(sys.argv[1])

Look at what the template brings in before running it:

ubuntu@secopslog-cicd:~/lab/sast · GitLab 19.5.3
$ ./up.sh
runner lab-runner: online (tags: lab,docker) GitLab 19.5.3 is up on http://127.0.0.1:8929
$ ./seed.sh app app/
pushed app: 7099b6f first commit
$ ./gl.sh '/projects/root%2Fapp/ci/lint' | jq -r '.merged_yaml' > /tmp/merged.yml && grep -oE '^[a-z0-9-]+-sast:' /tmp/merged.yml | tr -d : | paste -sd' ' && grep -m2 -E '^ +(SAST_ANALYZER_IMAGE_TAG|SECURE_ANALYZERS_PREFIX):' /tmp/merged.yml; rm -f /tmp/merged.yml
gitlab-advanced-sast bandit-sast brakeman-sast eslint-sast flawfinder-sast kubesec-sast gosec-sast mobsf-android-sast mobsf-ios-sast nodejs-scan-sast phpcs-security-audit-sast pmd-apex-sast security-code-scan-sast semgrep-sast sobelow-sast spotbugs-sast SECURE_ANALYZERS_PREFIX: "$CI_TEMPLATE_REGISTRY_HOST/security-products" SAST_ANALYZER_IMAGE_TAG: '2'

The template defines a job for each analyzer, from gitlab-advanced-sast to semgrep-sast, and each job has rules that check which languages the repository contains. Only analyzers that find their file types join the pipeline, which here means semgrep-sast for Python. The images come from GitLab's registry under SECURE_ANALYZERS_PREFIX, by major-version tag: gitlab-advanced-sast, the first job in the file, uses tag 2, and semgrep-sast pulls semgrep:6, as the hands-on shows. Of all the jobs listed, bandit-sast included, only semgrep-sast joined this pipeline.

A scan with findings

ubuntu@secopslog-cicd:~/lab/sast · GitLab 19.5.3
$ PIPE_WAIT=600 ./pipeline.sh app/ | grep -vE "^(\\[INFO\\]|Downloading|Pulling|Waiting)"; exit ${PIPESTATUS[0]}
--- job semgrep-sast (test): success $ /analyzer run [WARN] [Semgrep] [2026-11-10T22:41:55Z] ▶ /builds/root/app/.gitlab/sast-ruleset.toml not found, ruleset customization will be disabled. Uploading artifacts... gl-sast-report.json: found 1 matching artifact files and directories Uploading artifacts as "archive" to coordinator... 201 Created correlation_id=01M73T0GE9DXTTQHRFBWS6JMBW id=1 status=201 token=64_wFbU9Q Uploading artifacts... gl-sast-report.json: found 1 matching artifact files and directories Uploading artifacts as "sast" to coordinator... 201 Created correlation_id=01M73T0H0R0R8WTEEVGBGSJQMH id=1 status=201 token=64_wFbU9Q --- job sast-gate (gate): failed Removing .semgrepignore Removing gl-sast-report.json Removing semgrep.sarif $ python gate.py gl-sast-report.json High Critical High report.py:9 Improper neutralization of special elements used in an OS Command ('OS Medium report.py:13 Use of a broken or risky cryptographic algorithm 2 findings, 1 at Critical/High ERROR: Job failed: exit code 1 pipeline #1: failed

semgrep-sast succeeded. It found two problems and uploaded its report twice, as an artifact and as "sast", the security report GitLab understands, and reported success, because analyzer jobs never fail on findings, on any tier. Blocking a merge on findings is done by security policies, which are an Ultimate feature. sast-gate read the report and failed: a High for the shell command on line 9 and a Medium for MD5 on line 13. Without the gate, this pipeline would have been green.

app/gate.py
"""Fails when a GitLab security report has findings at the given severities.
Usage: python gate.py REPORT.json SEVERITY... (exit 1 if any finding matches)"""
import json
import sys
report, blocking = sys.argv[1], set(sys.argv[2:])
findings = json.load(open(report)).get("vulnerabilities", [])
for f in findings:
loc = f.get("location", {})
pkg = loc.get("dependency", {}).get("package", {}).get("name")
where = pkg or f"{loc.get('file', '?')}:{loc.get('start_line', '?')}"
print(f"{f.get('severity', '?'):8} {where:16} {f.get('name', '')[:70]}")
hits = [f for f in findings if f.get("severity") in blocking]
print(f"{len(findings)} findings, {len(hits)} at {'/'.join(sorted(blocking))}")
sys.exit(1 if hits else 0)

The gate is fifteen lines of Python because the report format is documented and stable: a JSON file with a vulnerabilities list, each with a severity, a location and identifiers. The same script gates the secret detection and container scanning lessons too. The report says which scanner produced it:

ubuntu@secopslog-cicd:~/lab/sast · GitLab 19.5.3
$ ./gl.sh "/projects/root%2Fapp/jobs/$(./gl.sh '/projects/root%2Fapp/jobs?per_page=10' | jq -r '[.[] | select(.name=="semgrep-sast")][0].id')/artifacts/gl-sast-report.json" | jq -r '(.scan | "\(.analyzer.name) \(.analyzer.version), scanner \(.scanner.name) \(.scanner.version), status \(.status)"), (.vulnerabilities[] | "\(.severity) \(.identifiers | map(.value) | join(" "))")'
Semgrep 6.31.1, scanner Semgrep 1.183.0, status success High bandit.B602 78 A03:2021 A05:2025 A1:2017 B602 Medium bandit.B303-1 327 A02:2021 A04:2025 A3:2017 B303

GitLab's Semgrep analyzer 6.31.1, running Semgrep 1.183.0. The findings carry the IDs of the rules that matched, here Bandit-compatible ones (B602, shell injection, and B303, weak hash), with their CWE numbers (78 and 327) and OWASP Top 10 categories. Those IDs are what you search for when you want to know why a rule fired. They name rules, not tools: no Bandit job ran.

Fix the code

The fix for both findings is the boring, correct version: an argument list, so the name is never parsed by a shell, and SHA-256 instead of MD5.

ubuntu@secopslog-cicd:~/lab/sast · GitLab 19.5.3
$ cp solutions/report.py app/ && ./commit.sh app/ "argument list, sha256" && PIPE_WAIT=600 ./pipeline.sh app/ | sed -n "/--- job sast-gate/,\$p"
pushed: 17f4f91 argument list, sha256 to main --- job sast-gate (gate): success Removing .semgrepignore Removing gl-sast-report.json Removing semgrep.sarif Downloading artifacts $ python gate.py gl-sast-report.json High Critical 0 findings, 0 at Critical/High pipeline #2: success

Both findings are gone and the gate passes. Note what changed: the code, not the gate, the severity list or a suppression comment.

SAST is good atSAST can't see
Dangerous calls: shell=True, eval, unsafe deserialisationWhether the input can actually reach them in production
Weak cryptography: MD5, SHA-1, ECB modeLogic bugs, such as a missing permission check
Hard-coded patterns it has a rule forVulnerable dependencies (that's dependency scanning)
Every push, in secondsConfiguration of the running system (that's DAST and reviews)
Watch out
The gate lives in the repository it checks. On the Free tier, one merge request can change the code and delete the gate job together, and the pipeline goes green. A gate in your own .gitlab-ci.yml stops honest mistakes, not a determined change, so review every change to CI files, or keep the gate job in a separate project pulled in with include: project: at a pinned ref. The gate also reads one report: if another analyzer joins later, give it its own gate, because the analyzers all name their report gl-sast-report.json.
Watch out
A finding is a pattern match, not a proof, and the usual way teams make a SAST gate pass is to suppress findings. Review suppressions like code: who added them, and why. And gate on the severities you will really fix. A gate that fails on every Medium gets switched off within a month.

Hands-on

The template runs the analyzer from a major-version tag, so a new analyzer release changes your results without any commit of yours. Find the digest the runner actually pulled. pipeline.sh hides the image lines, so read the raw job log through the API: ./gl.sh /projects/root%2Fapp/jobs/JOB_ID/trace | grep digest, with the semgrep-sast job's ID from ./gl.sh '/projects/root%2Fapp/jobs?per_page=10' | jq '.[] | {id, name}'. then pin it: add a semgrep-sast: job to .gitlab-ci.yml that only sets variables: SAST_ANALYZER_IMAGE: "<image>@sha256:<digest>", push, and check which image the next job used. Finish with ./down.sh.

What you should see: the first scan's log says Using docker image sha256:091d57c078a6... for registry.gitlab.com/security-products/semgrep:6 with digest registry.gitlab.com/security-products/semgrep@sha256:091d57c078a6..., the digest that tag pointed at that day. After the override, the job pulls semgrep@sha256:091d57c078a6... directly, and both jobs still pass. A new semgrep:6 release no longer changes your pipeline. You move the pin when you choose to, after reading what changed, so give the pin an owner and a schedule (a monthly bump, or a dependency bot), or the rules quietly stop improving. On self-managed GitLab you can also mirror the analyzer images into your own registry and point SECURE_ANALYZERS_PREFIX at it.

Remember

Include the SAST template, then add your own gate on the report, because on the Free tier nothing else fails the pipeline. Fix the code rather than the gate, and pin the analyzer by digest so results change only when you decide.

Quick check
01On the Free tier, semgrep-sast finds a High-severity command injection. What is the status of the semgrep-sast job?
Incorrect — The analyzer job reports findings. It does not fail on them.
Incorrect — There is no such step on the Free tier.
Correct — In the lab, semgrep-sast passed and only sast-gate failed.
Incorrect — The SAST template works on every tier.
02Why did the template add a semgrep-sast job, but no job for Go or Java?
Correct — Each analyzer job has rules that check which file types the project contains. Only analyzers for languages present in the repository join the pipeline.
Incorrect — The template defines several analyzers on every tier.
Incorrect — Several analyzers exist. They join the pipeline by rules.
Incorrect — The lab did not change the template's defaults.
03A team wants SAST results to change only when they decide. What do they pin?
Incorrect — That pins the job definitions, not the analyzer image they pull.
Correct — They set it through SAST_ANALYZER_IMAGE. A major-version tag moves with every analyzer release.
Incorrect — The runner does not decide which rules the analyzer applies.
Incorrect — Analyzer releases add and change rules regularly.

Related