SAST with the GitLab template
Find bugs in your own code, and make the findings fail the pipeline.
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: 1977caff9b24f5020544bf726ccaf12241b15ec25693d492382f83330c74fd66Static 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
# 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.ymlstages: [test, gate]sast-gate:stage: gateimage: secopslog-py:3.15needs:- job: semgrep-sastartifacts: truescript:- 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:
"""Builds a small report for a customer. It has the kind of bugs SAST is good at finding."""import hashlibimport subprocessimport sysdef 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:
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
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.
"""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 jsonimport sysreport, 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:
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.
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 at | SAST can't see |
|---|---|
Dangerous calls: shell=True, eval, unsafe deserialisation | Whether the input can actually reach them in production |
| Weak cryptography: MD5, SHA-1, ECB mode | Logic bugs, such as a missing permission check |
| Hard-coded patterns it has a rule for | Vulnerable dependencies (that's dependency scanning) |
| Every push, in seconds | Configuration of the running system (that's DAST and reviews) |
.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.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.
semgrep-sast finds a High-severity command injection. What is the status of the semgrep-sast job?semgrep-sast passed and only sast-gate failed.semgrep-sast job, but no job for Go or Java?SAST_ANALYZER_IMAGE. A major-version tag moves with every analyzer release.