GitLab Hour 6: Security and Governance in Practice
- Be able to state precisely each security capability's tier boundaries: SAST, Pipeline Secret Detection, and Container Scanning on Free the Free tier can run and produce JSON reports; new findings in MRs, the pipeline Security tab, vulnerability reports, security policies, Secret push protection, dependency scanning, DAST, and API security testing all require Ultimate.
- Use the official CI/CD components (
components/sast@3.5.0,secret-detection@2.4.0,dependency-scanning/main@2.1.1,container-scanning@5.2.0) to add scanning to myapp, and understand the report artifacts each job produces (gl-sast-report.json,gl-secret-detection-report.json,gl-sbom-*.cdx.json, etc.). - Try it yourself Secret push protection: a commit pushed with a fake token is
PUSH BLOCKEDrejected; understand the bypass methods (-o secret_push_protection.skip_all/[skip secret push protection]) leave audit events, and pipeline scanning and MR approval policies act as the backstop. - In security policy project, write scan execution, merge request approval, and pipeline execution policies, and link them to the group
mygroup-lab, so that all projects inherit them automatically. - Understand compliance frameworks (Premium) and requirements / controls (Ultimate), how deprecated compliance pipelines migrate to pipeline execution policies, and audit events (Premium) and audit event streaming (Ultimate).
- Design identity governance for a GitLab.com top-level group: SAML SSO + SCIM (Premium), maximum token lifetime and expiry reminders, service accounts, IP allowlists and domain restrictions, and complete an actionable governance architecture review.
1-hour time allocation
| # | Time | Module | Core content | Animation / interaction | Lab (mygroup-lab/myapp) |
|---|---|---|---|---|---|
| 0 | Before class | Security scanning sample project | Ultimate trial (30 days) or Free route, sample vulnerable branch, environment variables and readiness check | Tier self-check | feat/security-demo Branch |
| 1 | 00–06 | Security scanning overview and tiers | Scanner × tier matrix; “can run” ≠ “can govern”; report artifacts; security configuration page; Security Manager role | Tier matrix explorer | View the security configuration page and report artifacts |
| 2 | 06–13 | SAST, Secret Detection, and push protection | Semgrep analyzer vs Advanced SAST; pipeline secret detection; push protection blocking, bypass, and auditing | Core animation: secret push → block → bypass → pipeline finding → approval policy | Push fake token is blocked |
| 3 | 13–21 | Dependency scanning, container scanning, and SBOM | SBOM-based dependency scanning (Gemnasium deprecated), Trivy container scanning, CycloneDX, dependency list | SBOM pipeline simulation | Scan myapp:1.0 Image |
| 4 | 21–28 | DAST and API security testing | Browser DAST (proxy DAST removed), target environments, authentication, API security testing, and OpenAPI | DAST crawling and attack simulation | Run DAST against a temporary environment |
| 5 | 28–35 | Security policies | Security policy project, scan execution policy, MR approval policy (fail closed), pipeline execution policy, vulnerability management policy | Approval policy evaluator | Group-level policy enforces secret_detection |
| 6 | 35–42 | Compliance frameworks, compliance pipelines, and audit events | Framework labels, requirements and controls, compliance center, compliance pipeline deprecation and migration, audit event API and event streaming | Audit event stream delivery | Create a framework + query audit events |
| 7 | 42–50 | Identity governance | SAML SSO / SCIM, SSO enforcement, token lifetime, service accounts, IP allowlists, domain restrictions | Access request evaluator | Service accounts + token rotation |
| 8 | 50–60 | Governance architecture review | Layered control model, Free / Premium / Ultimate three-tier options, review checklist and troubleshooting tree | Governance maturity scoring + interactive troubleshooting tree | Produce the review report |
| — | After class | Cheat sheet · Capstone lab | Implement “push protection + group policies + approvals + audit streaming + token governance” for mygroup-lab | Final quiz (12 questions) | Capstone lab |
Knowledge Coverage Matrix
| Target skills | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | Key commands / keywords | Lab |
|---|---|---|---|---|---|---|---|---|---|---|
| Explain the tier required for each security capability | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | Tier matrix | M1 |
| Connect scanners using official components | ✓ | ✓ | ✓ | · | · | · | · | · | include: component | M2 / M3 |
| Push protection: enable, block, bypass, and audit | · | ✓ | · | · | ✓ | ✓ | · | ✓ | PUT /projects/:id/security_settings | M2 |
| Dependency / container scanning and SBOM | · | · | ✓ | · | ✓ | · | · | ✓ | gl-sbom-*.cdx.json,CS_IMAGE | M3 |
| DAST / API security testing | · | · | · | ✓ | ✓ | · | · | · | DAST_TARGET_URL,APISEC_OPENAPI | M4 |
| Security policy as code | · | ✓ | · | · | ✓ | ✓ | · | ✓ | .gitlab/security-policies/policy.yml | M5 |
| Compliance frameworks and auditing | · | · | · | · | ✓ | ✓ | ✓ | ✓ | GET /groups/:id/audit_events | M6 |
| Identity and token governance | · | · | · | · | · | ✓ | ✓ | ✓ | POST /groups/:id/service_accounts | M7 |
| Free tier alternatives | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | ✓ | jq gates, gitleaks, trivy, ZAP | Modules |
Topics not covered in this lesson (and where to learn them)
| Topic | Why not in this lesson | Where to learn |
|---|---|---|
| Basics of protected branches, MR approval rules, push rules, and CODEOWNERS | Repository-side basics were covered in the Git course; this lesson only shows how security policies add a layer on top | Git Lesson 4 (GitLab repository side) · Lesson 1 |
| Writing and publishing CI/CD components, include merge rules | Lesson 2 covers usage; Lesson 5 covers publishing | Lesson 2 · Lesson 5 |
| OIDC and short-lived cloud credentials | Covered in Lessons 3 and 4; this lesson only references it in identity governance | Lesson 3 (Azure) · Lesson 4 (AWS) |
| Runner hardening, admin setup for self-managed instances, API rate limiting | Belongs to operations and scaling | Lesson 7 |
| How the same topics are handled in GitHub (Advanced Security, rulesets, EMU) | This lesson covers GitLab only; read the comparison for reference | GitHub Lesson 6 (security and governance) · Azure DevOps Lesson 6 |
| Image hardening, signing, and runtime security | Belongs to the container and cluster topics | Docker Lesson 6 · K8s course |
| GitLab Duo vulnerability explanation / remediation and AI governance | Requires an additional Duo subscription or credits; changes quickly | GitLab Duo documentation |
How to use this courseware
Principles · diagrams · animations · commands · labs · production cases · troubleshooting · quizzes · audio · video. The “secret push → block → bypass → approval policy” animation in Module 2 is the core of the course; the troubleshooting page in Module 8 is an interactive troubleshooting tree.
Ultimate route: in a top-level group
mygroup-lab , enable a 30-day Ultimate trial; all labs can be completed. Free route: each module gives alternative steps of “scanners still run + jq gate / open-source tools”, labeled “Free alternative”.A quiz score ≥ 70% or clicking “Mark this module complete” counts toward progress (saved in this browser). The “Audio” page reads aloud using the browser Web Speech API (en-US).
sast 3.5.0 (2026-09-25),secret-detection 2.4.0 (2026-08-12),dependency-scanning 2.1.1 (2026-07-29, component name main),container-scanning 5.2.0 (2026-02-05); DAST and API security testing are still integrated via CI/CD templates (Security/DAST.gitlab-ci.yml,Security/API-Security.gitlab-ci.yml). SBOM-based dependency scanning went GA in 19.0; Gemnasium dependency scanning was deprecated in 17.9 and is scheduled for removal in 20.0; proxy-based DAST was removed in 17.3; compliance pipelines were deprecated in 17.3. The Security Manager role was introduced as beta in 18.11 (enabled on GitLab.com). glab v1.130.0.Module 0 · Preparation: security scanning sample project (complete before class)
- CompletedLesson 1(group
mygroup-lab: private, 2FA enforced, subgroupsplatform;mainprotected, push: no one, merge: Maintainer) andLesson 2(.gitlab-ci.yml, release tagsv1.0, imagesregistry.gitlab.com/mygroup-lab/myapp:1.0, referencedsecret-detection@2.4.0andsast@3.5.0components, “pipeline must succeed” enabled). - You are the top-level group
mygroup-lab's Owner Owner (linking the security policy project, configuring SSO, and audit event streaming all require this). - This machine: logged-in
glab(v1.130.0,glab auth status),jq, Git, Docker (optional, for local Trivy / gitleaks on the Free route).
Choosing between the two routes
| Ultimate route (recommended for this lesson) | Free route | |
|---|---|---|
| How to get it | In mygroup-lab 's “Settings → Billing” start the Ultimate trial; requires Owner of the top-level group; 30 days, counted from receipt of the confirmation email | No action needed |
| Labs you can do | All modules (push protection, policies, vulnerability reports, DAST, audit streaming, SSO configuration UI) | SAST / Secret Detection / container scanning run as usual, with jq reading the reports as a gate; push protection is replaced by a local gitleaks pre-commit hook; policies are replaced by “protected shared CI template + required pipeline” |
| Note | During the trial, only 1 project access token is allowed (GitLab.com); after the trial ends, policies are no longer enforced—do not run production on a trial group | Audit events are limited to one category, “successful sign-in”; there is no SSO / SCIM |
mygroup-sec-lab) for the trial, replicate myapp into it, and avoid affecting the original group's settings after the trial ends. Below, it is consistently written as mygroup-lab, replace as needed.Step 1: Environment variables and project information
cd ~/gitlablab/myapp
export GL_USER=$(glab api user | jq -r .username)
export GL_GROUP=mygroup-lab # replace with your <username>-lab
export GL_PROJECT=$GL_GROUP/myapp
export PROJECT_ID=$(glab api "projects/$(printf %s "$GL_PROJECT" | jq -sRr @uri)" | jq -r .id)
export GROUP_ID=$(glab api "groups/$GL_GROUP" | jq -r .id)
echo "user=$GL_USER project=$GL_PROJECT($PROJECT_ID) group=$GL_GROUP($GROUP_ID)"
glab api "groups/$GROUP_ID" | jq '{full_path, plan: .plan // "(the group API may not return plan for non-admins)", visibility}'
user=alice project=mygroup-lab/myapp(12345678) group=mygroup-lab(87654321)
{
"full_path": "mygroup-lab",
"plan": "(the group API may not return plan for non-admins)",
"visibility": "private"
}
The most reliable way to confirm the tier is the UI: group → Settings → Billing, which shows “Ultimate Trial” and the days remaining.
Step 2: Create a demo branch with intentional problems
Add three kinds of problems to myapp: a dangerous pattern that SAST can detect, an outdated dependency, and a fake token (assembled at runtime)—the fake token is generated temporarily only in the Module 2 lab, so it is not added here.
git switch main && git pull
git switch -c feat/security-demo
mkdir -p demo
cat > demo/unsafe.py <<'EOF'
"""Intentionally insecure sample code, for SAST demonstration only; not imported by app.py."""
import subprocess
import yaml
def run(cmd: str) -> str:
# Semgrep rules flag command injection risk from shell=True
return subprocess.check_output(cmd, shell=True).decode()
def load(text: str):
# Insecure YAML deserialization
return yaml.load(text, Loader=yaml.Loader)
EOF
printf 'PyYAML==5.3.1\n' > demo/requirements-demo.txt # an old version with a known public vulnerability, for scanning only
git add demo && git commit -m "demo: intentionally vulnerable samples for security scanning"
git push -u origin feat/security-demo
demo/ The directory is not imported by the app and is not included in the image (the Dockerfile copies only app files; if your Dockerfile is COPY . ., in .dockerignore , add demo/). Delete this branch after the course (see the capstone cleanup).Step 3: Extend the readiness check script
The Lesson 2 ~/gitlablab/gitlab_ready.py has 19 checks. This lesson adds a separate small script that checks security-related prerequisites (without modifying the original script):
cat > ~/gitlablab/security_ready.sh <<'EOF'
#!/usr/bin/env bash
# Prerequisite checks for this lesson: read-only, does not modify any settings
set -u
ok(){ printf ' [OK] %s\n' "$1"; }; no(){ printf ' [WARN] %s\n' "$1"; }
glab auth status >/dev/null 2>&1 && ok "glab is logged in" || no "glab is not logged in"
role=$(glab api "groups/$GROUP_ID/members/all/$(glab api user | jq .id)" 2>/dev/null | jq -r .access_level)
[ "$role" = "50" ] && ok "you are the Owner of $GL_GROUP" || no "not an Owner (access_level=$role); the policy linking and SSO labs cannot be completed"
glab api "projects/$PROJECT_ID/repository/files/.gitlab-ci.yml?ref=main" >/dev/null 2>&1 && ok ".gitlab-ci.yml exists" || no "missing .gitlab-ci.yml (complete Lesson 2 first)"
if glab api "projects/$PROJECT_ID/security_settings" >/dev/null 2>&1; then
ok "security_settings API is available (Ultimate / trial)"
else
no "security_settings API is unavailable → take the Free route"
fi
glab api "projects/$PROJECT_ID/repository/branches/feat%2Fsecurity-demo" >/dev/null 2>&1 && ok "demo branch exists" || no "missing feat/security-demo"
EOF
chmod +x ~/gitlablab/security_ready.sh && ~/gitlablab/security_ready.sh
[OK] glab is logged in [OK] you are the Owner of mygroup-lab [OK] .gitlab-ci.yml exists [OK] security_settings API available (Ultimate / trial) [OK] demo branch exists
Connections to previous lessons
| From | Reused in this lesson | New in this lesson |
|---|---|---|
| Lesson 1 | group mygroup-lab, protected main, CODEOWNERS, merge checks | Security policies add “security approval” on top of approval rules |
| Lesson 2 | secret-detection@2.4.0,sast@3.5.0 components; docker:29 builds; images :1.0 | dependency scanning and container scanning components; report artifacts and gates |
| Lessons 3 and 4 | id_tokens, protected tags v*, environments dev/prod | DAST targets dev / review environments; in token governance, “prefer OIDC, don't store long-lived secrets” |
Warm-up: answer from memory (30 seconds)
The secret_detection job from Lesson 2 finished on the Free tier. Why doesn't the MR page show “1 secret found”?
On the Free tier, the scanner can run and produce gl-secret-detection-report.json artifacts, but “showing new findings in MR reports”, “the pipeline Security tab”, and “vulnerability management” are all Ultimate features. On the Free tier you can only download the artifact and read it yourself (or write a jq gate job).
If the scanner finds a problem, will the pipeline fail because of it?
By default, no: the official scanning jobs are all allow_failure: true, and finding vulnerabilities does not make the job return a non-zero exit code. Real “blocking” comes from Ultimate's merge request approval policies (requiring additional approval), or a gate job you write yourself.
What is the difference between push protection and pipeline secret detection?
Push protection runs in the pre-receive stage of git push and rejects commits containing high-confidence secrets, so the secret never enters the repository (Ultimate); pipeline secret detection runs in after the push a CI job; by the time it finds a secret, the secret is already in Git history and must be rotated (runs on Free).
Module 1 · GitLab security scanning overview and tiers
- Name GitLab's scanner families (repository scanning: SAST, IaC, Secret Detection, dependency scanning; behavioral testing: DAST, API security testing, coverage-guided fuzzing; images: container scanning) and the minimum tier for each.
- Distinguish three layers of capability: Run (jobs + JSON report artifacts) → Present (MR reports, pipeline Security tab, vulnerability reports, dependency list) → Govern (security policies, compliance frameworks, auditing).
- Know the Security Manager role (18.11 beta) and the permission assignments for “who can view vulnerabilities and who can change policies”.
What: scanner families and minimum tiers (verified 2026-11-16 against the Tier line on each feature's documentation page)
| Capability | What it finds | Minimum tier | Current recommended integration | Report artifact |
|---|---|---|---|---|
| SAST | Dangerous patterns in source code | Free (GitLab Advanced SAST requires Ultimate) | Component components/sast/sast@3.5.0 or template Jobs/SAST.gitlab-ci.yml | gl-sast-report.json |
| IaC scanning | Misconfigurations such as in Terraform / K8s manifests | Free | Component components/sast/iac-sast@3.5.0 | SAST report format |
| Pipeline Secret Detection | Secrets committed to the repository | Free | Component components/secret-detection/secret-detection@2.4.0 | gl-secret-detection-report.json |
| Secret push protection | High-confidence secrets in a push (blocked before the push is accepted) | Ultimate | Project “Security configuration” toggle / API | None (push rejected) + audit events |
| Dependency scanning (SBOM-based) | Known vulnerabilities and malicious packages in third-party dependencies | Ultimate | Component components/dependency-scanning/main@2.1.1 or template Jobs/Dependency-Scanning.v2.gitlab-ci.yml | gl-sbom-*.cdx.json,gl-dependency-scanning-report.json |
| Container scanning (Trivy) | OS / language package vulnerabilities in images | Free (MR / Security tab / dependency list require Ultimate) | Component components/container-scanning/container-scanning@5.2.0 | gl-container-scanning-report.json, CycloneDX SBOM |
| DAST (browser) | Running web applications | Ultimate | Template Security/DAST.gitlab-ci.yml | DAST report |
| API security testing | REST / GraphQL / SOAP APIs | Ultimate | Template Security/API-Security.gitlab-ci.yml | DAST report format |
| Security policies (scan execution / MR approval / pipeline execution / vulnerability management / dependency firewall) | Enforce scans, require approvals, inject jobs | Ultimate | Security policy project | — |
| Compliance framework | Tag projects as “regulated” | Premium (requirements and controls, and policy enforcement, require Ultimate) | Compliance center | — |
| Audit events / audit event streaming | Who changed what, and when | Premium / Ultimate | Security → Audit events | — |
Why: why “can run” does not equal “can govern”
Using the official feature table for Pipeline Secret Detection as an example (SAST and container scanning tables have the same structure):
| Capability | Free & Premium | Ultimate |
|---|---|---|
| Custom analyzer behavior | ✓ | ✓ |
| Download output (JSON artifact) | ✓ | ✓ |
| See new findings in merge request reports | ✗ | ✓ |
| Pipeline “Security” tab | ✗ | ✓ |
| Vulnerability management (vulnerability reports, status, dismissal reasons) | ✗ | ✓ |
| Security dashboard | ✗ | ✓ |
| Custom rulesets | ✗ | ✓ |
| Enable security policies | ✗ | ✓ |
In other words, on the Free tier you get “a JSON file”; nobody reads it unless you write a gate job that turns it into a red/green pipeline result. Ultimate turns the same JSON into triageable, trackable, and referenceable by policies vulnerability objects: vulnerability reports show by default the default branch data; each vulnerability has a status (needs triage / confirmed / dismissed / resolved), and dismissal requires a comment.
How: the three-layer model
- Run layer: the job runs the analyzer image (
$CI_TEMPLATE_REGISTRY_HOST/security-products/…), outputs JSON following a unified security report schema, and declares it withartifacts:reports:sast/secret_detection/container_scanning/cyclonedxetc. - Present layer (Ultimate): GitLab parses the reports and diffs findings between the MR source and target branches, showing only newly introduced findings; results from the default branch feed into vulnerability reports.
- Govern layer (Ultimate): security policies decide “which scans must run” and “who must approve which findings”; compliance frameworks decide “which projects a policy applies to”; audit events record bypasses and changes.
When: minimum viable combination
- Free: SAST + Secret Detection + container scanning component + one jq gate job + local gitleaks pre-commit hook + protected branches and CODEOWNERS.
- Premium: add SAML SSO / SCIM, audit events, compliance framework labels, IP allowlists, and MR approval rules (not security policies).
- Ultimate: push protection + group-level scan execution policy + MR approval policy (fail closed) + vulnerability report triage + audit event streaming to a SIEM.
Who can do what: roles
| Action | Required role (default) |
|---|---|
| Enable push protection for a project | Security Manager, Maintainer, or Owner |
| Link a security policy project to a group / project | Owner of the target, or a custom role with manage_security_policy_link permission |
| Create a compliance framework | Owner or Security Manager of the top-level group, or a custom role with admin_compliance_framework permission |
| View and manage vulnerabilities, compliance configuration, and audit events, but cannot push code | Security Manager (introduced as beta in 18.11; enabled on GitLab.com) |
allow_failure: true they do not fail based on findings. ③ “Turning on Ultimate makes you secure automatically”—without policies configured, developers can still merge MRs with high-severity findings. ④ “Vulnerability reports show all branches”—by default they show only the default branch (up to 3 additional branches/tags can be tracked, which requires advanced vulnerability management).Comparison with GitHub / Azure DevOps
| Capability | GitLab | GitHub | Azure DevOps |
|---|---|---|---|
| Secret push blocking | Secret push protection (Ultimate) | Secret Protection push protection (free for public repositories, paid for private) | GitHub Advanced Security for Azure DevOps |
| SAST | Semgrep analyzer (Free) / Advanced SAST (Ultimate) | CodeQL (Code Security) | GHAzDO CodeQL |
| Policy as code | Security policy project (YAML) | Rulesets + required workflows | Branch policies |
| See | this lesson | GitHub Lesson 6 | Azure DevOps Lesson 6 |
Run → Present → Govern
Where scanners sit in the SDLC
Interactive: tier matrix explorer
Select a tier to see which capabilities “light up”; click any capability to see how it actually behaves at that tier and its Free alternative.
Core commands: see the project's current security status
| Command | Purpose | Tier |
|---|---|---|
glab ci view / glab ci list | View pipelines and scan jobs | Free |
glab api projects/:id/jobs/:job_id/artifacts/gl-sast-report.json | Download a single report file | Free |
glab api projects/:id/security_settings | View security settings such as push protection | Ultimate |
glab api graphql -f query='…vulnerabilities…' | Query vulnerability reports | Ultimate |
glab api groups/:id/audit_events | Group audit events | Premium |
# 1) Find the security jobs in the most recent main pipeline
PIPE=$(glab api "projects/$PROJECT_ID/pipelines?ref=main&per_page=1" | jq -r '.[0].id')
glab api "projects/$PROJECT_ID/pipelines/$PIPE/jobs" \
| jq -r '.[] | select(.name|test("sast|secret|scanning")) | "\(.id)\t\(.name)\t\(.status)"'
# 2) Download the SAST report and count severities (also works on Free)
SAST_JOB=$(glab api "projects/$PROJECT_ID/pipelines/$PIPE/jobs" | jq -r '[.[]|select(.name=="semgrep-sast")][0].id')
glab api "projects/$PROJECT_ID/jobs/$SAST_JOB/artifacts/gl-sast-report.json" \
| jq '[.vulnerabilities[].severity] | group_by(.) | map({(.[0]): length}) | add'
9123456781 semgrep-sast success
9123456782 secret_detection success
{
"High": 1,
"Medium": 1
}
# 3) Ultimate: query project vulnerabilities with GraphQL (read-only)
glab api graphql -f query='
query($p: ID!) { project(fullPath: $p) {
vulnerabilities(first: 5, state: [DETECTED, CONFIRMED]) {
nodes { title severity state reportType } } } }' -f p="$GL_PROJECT" | jq '.data.project.vulnerabilities.nodes'
In GraphQL, the enum value for the “needs triage” status is DETECTED (also shown as detected in CSV exports). Field names follow the GraphQL reference.
Lab 1: see what you can see at your current tier (about 4 min)
glab mr create --source-branch feat/security-demo --target-branch main \ --title "Draft: security demo (do not merge)" --description "Security lesson demo, do not merge" --draft --yes
- Ultimate trial: the MR page shows a “security scanning” section listing new SAST findings (
subprocessshell=True, unsafe yaml.load). - Free: the MR page shows only the pipeline status; open the semgrep-sast job → “Job artifacts → Download” on the right, and count using the jq command from the previous page.
security-gate:
stage: test
image: alpine:3.22
needs:
- job: semgrep-sast
artifacts: true
- job: secret_detection
artifacts: true
script:
- apk add --no-cache jq >/dev/null
- |
high=$(cat gl-sast-report.json gl-secret-detection-report.json 2>/dev/null \
| jq -s '[.[].vulnerabilities[]? | select(.severity=="Critical" or .severity=="High")] | length')
echo "Critical/High findings: $high"
test "$high" -eq 0
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
Note: the component defaults to enable_mr_pipelines: false, if the scan job does not exist in the MR pipeline, needs it errors—either pass the component enable_mr_pipelines: true (Lesson 2 already does this), or run the gate on branch pipelines too. The gate checks “all findings” rather than “new findings,” which suits small projects; for large projects, establish a baseline first.
security-gate fails and prints Critical/High findings: 1 or above; Ultimate route: the MR security section lists new findings.Case 1: “We turned on SAST,” but nobody read the reports for three years
Problem: The Free-tier team included the SAST template in every project. During an audit they were asked “how were last quarter's high-severity findings handled?” and could not answer—the reports were just stale artifacts. Approach: Add a jq gate to the shared CI template (enforced only for new projects; older projects first produce baseline reports), extend artifact retention to 30 days, and export statistics weekly. Lesson learned: Without a presentation layer and a governance layer, scanning just consumes compute minutes.
Case 2: Bought Ultimate, but developers still merged high-severity issues
Problem: After upgrading, red security findings appeared in MRs, but nothing blocked the “merge.”Approach: Link a security policy project at the group level and configure an MR approval policy: scan_finding, Critical/High,vulnerabilities_allowed: 0, requiring 1 approval from the security team (Module 5). Lesson learned: Ultimate's value lies in policies, not dashboards.
Case 3: “Policies suddenly stopped working” after the trial ended
Problem: The team started a 30-day trial on a production group and configured push protection and approval policies. After the trial ended, all blocking silently disappeared, and nobody noticed. Approach: Run trials only in lab groups; before a purchasing decision, use this module's tier matrix to list “which controls will disappear when the trial ends.”
Common errors and fixes
The MR page has no “security scanning” section
Cause:① Not on Ultimate; ② the scan jobs run only in branch pipelines while the MR shows MR pipeline results (or vice versa), so source and target cannot be compared; ③ no successful scan has run yet on the target branch (main) to serve as a baseline. Fix: Confirm the tier; make the scans run in the same type of pipeline; first run a full pipeline on main.
This job depends on other jobs with expired/erased artifacts
Cause: The gate job needs 's scan artifacts have expired. Fix: Re-run the entire pipeline; in the shared template, set a reasonable expire_in.
'security-gate' job needs 'semgrep-sast' job, but 'semgrep-sast' does not exist in the pipeline
Cause: The SAST analyzer is selected automatically based on the repository language, or the component is not enabled in MR pipelines. Fix: Pass to the component enable_mr_pipelines: true; or add in needs optional: true (in this case the gate must handle the “report missing” situation and must not allow by default).
404 Not Found: GET /projects/:id/security_settings
Cause: This API is an Ultimate feature, or the token lacks the api/read_api scope, or the role is insufficient (GET requires Security Manager / Developer or higher).
1. Using one command, list the ID and status of the jobs whose names contain “sast” in the most recent main pipeline.
PIPE=$(glab api "projects/$PROJECT_ID/pipelines?ref=main&per_page=1" | jq -r '.[0].id')
glab api "projects/$PROJECT_ID/pipelines/$PIPE/jobs" | jq -r '.[]|select(.name|test("sast"))|"\(.id) \(.status)"'2. From the secret_detection report, print only the file and line number of each finding.
jq -r '.vulnerabilities[] | "\(.location.file):\(.location.start_line) \(.name)"' gl-secret-detection-report.json
A company of 40 people has only a Premium budget, and audit requires “all high-severity findings must be handled before merge.” How would you design this?
Premium has no MR approval policies or vulnerability reports. Approach: ① a group-level shared CI template project (protected; only the platform team can change it) containing the SAST / secret / container scanning components and a jq gate; ② use compliance framework labels (Premium) to mark regulated projects, and require security group approval in MR approval rules + CODEOWNERS .gitlab-ci.yml changes, to prevent developers from removing the include; ③ use audit events (Premium) to regularly check changes to CI files and approval rules; ④ a local gitleaks pre-commit hook in place of push protection. Tell the auditor explicitly: this is “process control,” not platform enforcement, and developers could in theory bypass it—this is exactly the gap that Ultimate policies are meant to close.
Verified instructional videos
Official documentation
- Detect (scanner families)
- SAST (including the Free / Ultimate feature table)
- Vulnerability report
- Free trials
Video storyboard script (about 60 seconds)
This courseware cannot directly generate video or MP3 files; the storyboard and narration below can be handed to a video tool.
Visual: a JSON file pops out of a SAST job and lands in a “Free” tray, with nobody paying attention to it.
Narration: on the Free tier, the scanner still runs, but all you get is a JSON report.
Visual: the same JSON enters the “Ultimate” tray and becomes a red finding card in the MR, a row in the vulnerability report, and a lock on the policy panel.
Narration: Ultimate turns it into a vulnerability that can be triaged, tracked, and referenced by policies.
Visual: a three-layer pyramid: run, present, govern.
Narration: remember the three-layer model: “can run” does not mean “can govern.”
Module 2 · SAST, Secret Detection, and push protection
- Use
sast@3.5.0andsecret-detection@2.4.0components to configure scanning, and understand the difference between the Semgrep analyzer and GitLab Advanced SAST (Ultimate,run_advanced_sast: true) and their differences. - Enable Secret push protection, and see real
PUSH BLOCKED: Secrets detected in code changes, and know what it does not check (files over 1 MiB, binaries, the first push that creates a repository, pushes over 3,150 paths or 350,000 lines, etc.). - Understand the two bypass methods and their consequences: audit events + pipeline secret detection + MR approval policies form defense in depth; any secret that has been pushed must be rotated, not just deleted.
What: three checkpoints
| Secret push protection | Pipeline Secret Detection | SAST | |
|---|---|---|---|
| When it runs | Pre-receive check on git push (HTTP(S) and SSH) | CI job after the push secret_detection | CI jobs (semgrep-sast,gitlab-advanced-sast , etc.) |
| Scan scope | Scans only the diff of this push, using only high-confidence rules | commits on the branch in an MR; the latest commit on the default branch; a one-time full history scan is possible | Working-tree source code |
| When a finding is detected | the push is rejected, the secret never enters the repository | Secret already in history → must rotate | Code defect → fix |
| Tier | Ultimate | Runs on Free; MR / Security tab / vulnerability management require Ultimate | Free (Advanced SAST and custom rulesets require Ultimate) |
| How to enable | Security configuration toggle / PUT /projects/:id/security_settings / group security settings API | Component, template Jobs/Secret-Detection.gitlab-ci.yml or scan execution policy | Component, template Jobs/SAST.gitlab-ci.yml, Security configuration page |
Why: why push protection is the first checkpoint
Once a secret is pushed, it appears in Git history, forks, mirror repositories, CI logs, and developers' local clones; “delete it and commit again” cannot take it back. Push protection blocks at the pre-receive stage, and the only cost is that the developer amends a local commit. However, it deliberately uses only high-confidence rules to avoid false positives (for example, PATs with custom prefixes are not detected), and it skips oversized pushes—so pipeline detection is still needed as a backstop.
How: push protection working details (official docs)
- Enable: for self-managed / Dedicated, an administrator first goes to Admin → Settings → Security and compliance → Secret detection and checks “Allow secret push protection”; on GitLab.com, go directly to the project Security → Security configuration and turn on the toggle (Security Manager, Maintainer, or Owner); you can also use the group security settings API to enable it for all projects in a group at once.
- Blocking output:
remote: PUSH BLOCKED: Secrets detected in code changes, then lists the commit SHA,file:lineand the secret type, and finally! [remote rejected] … (pre-receive hook declined). - Does not check: files or diffs larger than 1 MiB; binary files; renames, moves, or deletions with unchanged content; content identical to another file in the repository; the first push that creates a repository; pushes changing more than 3,150 paths or 350,000 lines (skipped and recorded as audit events).
- Bypass: on the command line, use
git push -o secret_push_protection.skip_all; other clients add[skip secret push protection]to any commit message. A bypass records an audit event (method, account, time, project, target branch, skipped commits). - Automatic response (Ultimate, only public projects): when pipeline detection finds a GitLab PAT, it is revoked immediately and the owner is notified by email; AWS, Google Cloud, and Postman credentials are reported to the respective vendors.
How: SAST analyzers
| Analyzer | Coverage | Tier | Component input |
|---|---|---|---|
| Semgrep-based (GitLab-managed rules) | Python, JS/TS, Go, Java, C#, and most other languages | Free | Default |
| GitLab Advanced SAST | Cross-file, cross-function taint analysis (C, C++, C#, Go, Java, JS, Python, TS, etc.) | Ultimate | run_advanced_sast: true (C/C++ additionally has run_advanced_sast_cpp) |
| PMD-Apex, Sobelow, SpotBugs | Apex, Elixir, Groovy/Java | Free | Automatically selected |
| Kubesec | K8s manifests | Free | run_kubesec_sast: true (disabled by default) |
When: typical combinations
- All projects: push protection (Ultimate) or gitleaks pre-commit hook (Free) + pipeline secret detection + SAST.
- After enabling secret detection for the first time: run once a history scan (
historic_scan: true/SECRET_DETECTION_HISTORIC_SCAN=true); large repositories may be slow, so don't put it in every pipeline. - MR pipelines: the component defaults to
enable_mr_pipelines: false; if the project uses MR pipelines (enabled in Lesson 2), passtrue, otherwise the MR report will be missing data.
Defense in depth: the four checkpoints a secret must pass through
How MR reports show only “new” findings
Core animation: secret push → push protection block → (if bypassed) pipeline finding → MR approval policy
Choose a scenario, then click “Next” or “Auto-play.” The highlighted box is the current handler; the terminal shows the real output the developer sees (fake tokens are masked when displayed).
Core commands
| Command / configuration | Purpose | Tier |
|---|---|---|
glab api -X PUT projects/:id/security_settings -f secret_push_protection_enabled=true | Enable push protection (parameter name since 17.11; old name pre_receive_secret_detection_enabled) | Ultimate, Maintainer+ |
git push -o secret_push_protection.skip_all | Bypass push protection (records audit event) | — |
[skip secret push protection] | Bypass by writing in any commit message (Web IDE and other clients) | — |
historic_scan: true | Component input: scan the entire history once | Free |
run_advanced_sast: true | Component input: enable GitLab Advanced SAST | Ultimate |
include:
- component: $CI_SERVER_FQDN/components/secret-detection/secret-detection@2.4.0
inputs:
stage: test
enable_mr_pipelines: true
- component: $CI_SERVER_FQDN/components/sast/sast@3.5.0
inputs:
stage: test
enable_mr_pipelines: true
excluded_paths: "spec, tests, tmp" # Note: demo/ is not excluded, to make the demo easier
run_advanced_sast: true # Ultimate; on the Free tier this job produces no results
advanced_sast_partial_scan: differential # in MRs, scan only changed files and their dependencies (optional)
excluded_paths Default "spec, test, tests, tmp", so when you override it, include the default value too. advanced_sast_partial_scan is an input in the 3.5.0 component; for valid values, see the component README.
# Enable / view push protection (Ultimate)
glab api -X PUT "projects/$PROJECT_ID/security_settings" -f secret_push_protection_enabled=true \
| jq '{project_id, secret_push_protection_enabled}'
glab api "projects/$PROJECT_ID/security_settings" | jq .secret_push_protection_enabled
{
"project_id": 12345678,
"secret_push_protection_enabled": true
}
true
Free alternative: gitleaks pre-commit hook (local blocking)
repos:
- repo: https://github.com/gitleaks/gitleaks
rev: v8.30.1 # latest release as of 2026-03; update per the releases page
hooks:
- id: gitleaks
pipx install pre-commit && pre-commit install # Or, without the pre-commit framework, scan the staging area directly: gitleaks git --pre-commit --staged --redact --verbose
A pre-commit hook is a client-side control; developers can git commit --no-verify skip it, or it may not be installed at all—it lowers the chance of a leak but cannot replace server-side blocking.
Lab 2: push a fake token and see it blocked (about 6 min)
printf concatenation, in the form shown in the official tutorial: glpat- + 20 digits,not a real token. Do not use a real token for this lab.glab api -X PUT ….git switch feat/security-demo printf 'hello, world!\nGITLAB_TOKEN=glpat-%s\n' "12345678901234567890" > demo/leak.txt git add demo/leak.txt && git commit -m "demo: add config" git push
remote: PUSH BLOCKED: Secrets detected in code changes remote: remote: Secret push protection found the following secrets in commit: 5f2c1a9e… remote: remote: -- demo/leak.txt:2 | GitLab Personal Access Token remote: remote: To push your changes you must remove the identified secrets. To gitlab.com:mygroup-lab/myapp.git ! [remote rejected] feat/security-demo -> feat/security-demo (pre-receive hook declined) error: failed to push some refs to 'gitlab.com:mygroup-lab/myapp.git'
git reset --soft HEAD~1 sed -i '/GITLAB_TOKEN=/d' demo/leak.txt # macOS: sed -i '' … git add demo/leak.txt && git commit -m "demo: add config" git push
If the secret is in an earlier commit, edit that commit with an interactive rebase (or follow the official “Remove a secret from your commits” tutorial).
git push -o secret_push_protection.skip_all -u origin HEAD. After the push succeeds:
- Group → Security → Audit events shows a record of the skipped push protection (account, project, target branch, skipped commits).
- Open an MR for this branch:
secret_detectionThe job lists a new “GitLab personal access token” finding in the MR security report (Ultimate). - After you configure approval policies in Module 5, this MR will require security group approval.
git push origin --delete <branch>.secret_detection artifact, and have the Module 1 gate security-gate fail.Finding: GITLAB_TOKEN=REDACTED RuleID: gitlab-pat File: demo/leak.txt Line: 2 1 commits scanned. leaks found: 1
feat/security-demo history contains no glpat- string: git log -p origin/feat/security-demo | grep -c 'glpat-' Output 0.Case 1: “Bypassing” became a habit
Problem: A month after enabling push protection, the audit stream showed more than 40 skip_all records, mostly for fake tokens in test fixtures. Approach: Change the tokens in test fixtures to runtime concatenation or clearly invalid formats; for paths that truly need it, set exclusions in the security configuration (using exclusion types that the official documentation supports); set an alert in the SIEM for “2 or more bypasses by the same user within 24 hours,” and keep a backstop in the MR approval policy. Lesson learned: A bypass itself is not the problem; bypasses that nobody sees are.
Case 2: Pushes during a large-scale migration were not scanned
Problem: 200 repositories were migrated from a legacy system. All mirror pushes (first pushes that create a repository / pushes over 3,150 paths) were skipped, and a later history scan found 17 real cloud keys. Approach: After migration, run once for each project historic_scan: true; revoke the discovered keys first, then clean up history with git filter-repo and force-push (this requires temporarily lifting branch protection, with auditing throughout).
Case 3: GitLab PAT leaked in a public project was automatically revoked
Problem: An open-source maintainer committed a real PAT in an example configuration. A few minutes later they received a GitLab email saying the token had been revoked, and the release job in CI that depended on it failed as a result. Note: This is Ultimate's automatic response (public projects only, based on pipeline secret detection). Approach: Switch to CI/CD job tokens or OIDC; for the release job, use a service account + short-lived token (Module 7).
Common errors and fixes
remote: PUSH BLOCKED: Secrets detected in code changes
This is expected behavior. Remove the secret using the “file:line” from the output,git commit --amend or rewrite the local commit with rebase before pushing. If it is a false positive (test data), prefer rewriting the test data; when a bypass is truly needed, use -o secret_push_protection.skip_all and explain it in the MR.
A real token was pushed but not blocked
Possible causes: Project not enabled / not Ultimate; the token format is not covered by high-confidence rules (e.g., PATs with custom prefixes); file > 1 MiB or binary; the first push creating the repository; push exceeds 3,150 paths or 350,000 lines; the secret is in an existing file that was not modified. Response: Revoke the token immediately, then clean up the history.
The secret_detection job succeeded with an empty report, but findings were expected in the MR
Cause: Branch pipelines scan only the latest commit; to scan all commits on the branch in an MR, you need MR pipelines. Fix: Component enable_mr_pipelines: true; or run once historic_scan.
The gitlab-advanced-sast job does not appear
Cause: not set run_advanced_sast: true; not on Ultimate; the repository has no files in a supported language.
sed: -e expression #1, char 1: unknown command
Cause: macOS's BSD sed requires -i ''. Fix:sed -i '' '/GITLAB_TOKEN=/d' demo/leak.txt.
1. Use the API to enable push protection for a project, and output only the value of that setting.
glab api -X PUT "projects/$PROJECT_ID/security_settings" -f secret_push_protection_enabled=true | jq .secret_push_protection_enabled
2. How do you bypass push protection when committing in the Web IDE?
Add to the commit message: [skip secret push protection]
A developer used skip_all to push a real AWS access key to a feature branch, and the MR has not been merged yet. List the response steps in priority order.
① ① Immediately deactivate and delete the access key in AWS (do not wait for the MR outcome), and check CloudTrail for usage; ② remove the commit from the branch history (rebase, then force-push the feature branch), and check forks, mirrors, CI logs, and artifacts for the value; ③ mark the finding as resolved or add a note in the vulnerability report / MR; ④ based on the audit events, talk with the developer about why they bypassed, and switch to OIDC (Lesson 4) to eliminate long-lived keys entirely; ⑤ add an alert for bypass events in the audit stream. Order matters: rotation comes before cleanup.
Verified instructional videos
Official documentation
- Secret push protection
- Tutorial: Protect your project with secret push protection
- Pipeline secret detection
- SAST
Video storyboard script (about 60 seconds)
Visual: git push in a terminal, with one line of red text: PUSH BLOCKED.
Narration: push protection keeps the push out before the secret ever enters the repository.
Visual: the developer adds -o secret_push_protection.skip_all and the push succeeds; a record lights up in the audit panel at the top right; secret_detection turns yellow in the pipeline.
Narration: it can be bypassed, but every bypass is audited, and pipeline detection will find it again.
Visual: the MR merge button is locked with a prompt requiring security group approval; next to it, a key icon appears with “rotate first.”
Narration: the last checkpoint is the approval policy. Remember: for a secret that has already been pushed, the first step is always rotation.
Module 3 · Dependency scanning, container scanning, and SBOM
- Know the current state of dependency scanning: SBOM-based dependency scanning GA in 19.0 and recommended for new projects; Gemnasium dependency scanning deprecated in 17.9 and scheduled for removal in 20.0; malicious package matching GA since 19.5.
- Use
components/dependency-scanning/main@2.1.1to scan myapp's Python dependencies, and understand the differences between lock files, dependency resolution, and manifest fallback. - Use
components/container-scanning/container-scanning@5.2.0to scan the image built in Lesson 2, and readCS_IMAGE, registry authentication, and CycloneDX output; know how to use Trivy as the local alternative on the Free tier.
registry.gitlab.com/mygroup-lab/myapp:1.0, short SHA tags on main). Importance:★★★★☆What: two scanners, one model
| Dependency scanning (SBOM-based) | Container scanning | |
|---|---|---|
| Scan target | Lock files / dependency graph exports in the repository (application dependencies, including transitive dependencies) | Built images (OS packages + language packages) |
| Engine | Dependency Scanning analyzer v2: generates an SBOM → compares it against the GitLab advisory database and malicious package advisories | Trivy (analyzer image security-products/container-scanning:8) |
| Outputs | one per lock file gl-sbom-<package-type>-<package-manager>.cdx.json (placed next to the source file) + gl-dependency-scanning-report.json | gl-container-scanning-report.json + CycloneDX SBOM (the filename in the documentation is gl-sbom-report.cdx.json) |
| Tier | Ultimate | Free; MR / Security tab / dependency list / auto-remediation suggestions require Ultimate; “registry container scanning” requires Ultimate |
| Recommended integration | Component dependency-scanning/main@2.1.1 or template Jobs/Dependency-Scanning.v2.gitlab-ci.yml | Component container-scanning/container-scanning@5.2.0 or template Jobs/Container-Scanning.gitlab-ci.yml |
Why: why switch to “SBOM first, then compare”
An SBOM (software bill of materials) turns “which components I use, what versions, and where they came from” into a standard file (CycloneDX JSON). The benefits: ① the same list can be compared repeatedly—when new advisories are published, there's no need to rebuild; ② it can be shared with customers and regulators (supply-chain transparency requirements); ③ the dependency list, license policies, and malicious package detection all rely on the same data.
How: three inputs for Python projects (official support matrix)
| Files in myapp | How the scanner handles it | Accuracy |
|---|---|---|
poetry.lock,uv.lock,Pipfile.lock,pipdeptree.json,pipenv.graph.json | parsed directly into a dependency graph (supports static reachability) | Highest: exact versions + transitive dependencies |
pip-compile The generated requirements.txt | treated as a lock file (in component 2.x, pipcompile_requirements_file_name_pattern the default has been changed to empty; set it explicitly when needed) | High |
Normal requirements.txt (current state of myapp) | Added in 2.0.0: dependency resolution job generates the dependency graph first; or manifest fallback (reports only direct dependencies; versions may be imprecise) | Medium |
Only Pipfile None Pipfile.lock | Not supported | — |
Component 2.0.0 changes (from its release notes): the analyzer is upgraded to v2; allow_failure the default changes to true; max_scan_depth the default changes to 2; log_level renamed to analyzer_log_level; CI/CD variables take precedence over inputs; added DS_SKIP_IF_NO_SUPPORTED_FILES. The official documentation examples still show main@1, but this lesson pins 2.1.1.
How: key container scanning variables
CS_IMAGE(component inputcs_image): the image to scan; default$CI_APPLICATION_REPOSITORY:$CI_APPLICATION_TAG—your own pipeline should explicitly set it to the image you just built.CS_REGISTRY_USER/CS_REGISTRY_PASSWORD: when the image is in the GitLab Container Registry, the default is taken from$CI_REGISTRY_USER/$CI_REGISTRY_PASSWORD; when scanning images in ECR / ACR, you must provide it yourself (not supported in FIPS mode).cs_dockerfile_path: used to generate remediation suggestions;git_strategydefaultnone(does not check out code); when you need remediation suggestions or an allowlist, change it tofetch.- Component job
container_scanningwithallow_failure: true, artifactsaccess: 'developer'(Guest users cannot see the reports).
When
- Every pipeline that produces an image: run container scanning right after the build (scanning the digest that will be deployed).
- Dependency scanning: MRs that change lock files + the default branch; continuous detection of new advisories is done by GitLab based on existing SBOMs (continuous vulnerability scanning, see
continuous_vulnerability_scans_enabledsettings). - Images already pushed to the registry and not rebuilt for a long time: Ultimate's “registry container scanning” runs automatically when a
latesttag is pushed on the default branch.
SBOM-driven scanning pipeline
What a CycloneDX fragment looks like
{
"bomFormat": "CycloneDX",
"specVersion": "1.6",
"metadata": { "tools": { "components": [ { "name": "dependency-scanning" } ] } },
"components": [
{ "type": "library", "name": "flask", "version": "3.1.2", "purl": "pkg:pypi/flask@3.1.2" },
{ "type": "library", "name": "pyyaml", "version": "5.3.1", "purl": "pkg:pypi/pyyaml@5.3.1" }
]
}
specVersion Tool metadata follows the actual artifact; the key field is purl (Package URL), which is what advisory matching relies on.
Interactive: SBOM scanning pipeline simulation
Choose a dependency format for myapp to see how the analyzer builds the dependency graph, what it can find, and what it misses.
Core configuration
include:
# Dependency scanning (Ultimate) — the component name is main
- component: $CI_SERVER_FQDN/components/dependency-scanning/main@2.1.1
inputs:
stage: test
max_scan_depth: 2
enable_static_reachability: false # Python lock file support; can be turned on once you are familiar with it
# Container scanning (runs on Free)
- component: $CI_SERVER_FQDN/components/container-scanning/container-scanning@5.2.0
inputs:
stage: scan
cs_image: $CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA
cs_dockerfile_path: Dockerfile
git_strategy: fetch # when you need remediation suggestions / allowlists
stages: [lint, test, build, scan] # add scan after Lesson 2's lint/test/build; keep any existing stages (verify, deploy…) in their original order
container_scanning:
needs: [build-image] # the job name from Lesson 2 that builds and pushes :short-SHA; change it to your actual name
The component's job name defaults to container_scanning (input job_name can be changed),dependency-scanning. In the main file, using a key with the same name can append to or override needs fields such as these (Lesson 2's merge rules). If the Lesson 2 build pushes short-SHA tags only on main, then in MR pipelines either also push a temporary tag, or run container scanning only on main.
Free alternative: Trivy (local or CI)
# Scan the image (run docker login registry.gitlab.com first) docker run --rm -v /var/run/docker.sock:/var/run/docker.sock aquasec/trivy:0.76.2 \ image --severity HIGH,CRITICAL --ignore-unfixed registry.gitlab.com/mygroup-lab/myapp:1.0 # Generate a CycloneDX SBOM docker run --rm -v "$PWD":/w -w /w aquasec/trivy:0.76.2 \ fs --format cyclonedx --output myapp.cdx.json . jq '.components | length' myapp.cdx.json
registry.gitlab.com/mygroup-lab/myapp:1.0 (debian 13.x) Total: 0 (HIGH: 0, CRITICAL: 0) Python (python-pkg) Total: 0 (HIGH: 0, CRITICAL: 0) 27
Trivy version v0.76.2 (2026-11-05). In production, pin the scanner image by digest, and use an internal mirror of the vulnerability database (offline environments).
View the dependency list (Ultimate, API)
glab api "projects/$PROJECT_ID/dependencies?per_page=100" | jq -r '.[] | "\(.name) \(.version) \(.package_manager)"' | head
Lab 3: add dependency and container scanning to myapp (about 7 min)
demo/requirements-demo.txt in place (the old PyYAML version); commit and push:
git switch feat/security-demo $EDITOR .gitlab-ci.yml glab ci lint && git commit -am "ci: add dependency and container scanning" && git push
[INFO] Detected supported file: requirements.txt (pip) [INFO] Detected supported file: demo/requirements-demo.txt (pip) [INFO] No lockfile found for requirements.txt, using dependency resolution / manifest fallback [INFO] Generated SBOM: gl-sbom-pypi-pip.cdx.json [INFO] Vulnerability scan: 1 vulnerability found (pyyaml 5.3.1)
The log format changes with the analyzer version; for reference only. Note max_scan_depth: 2: demo/ is within level 2, so it gets scanned.
gl-container-scanning-report.json:
JOB=$(glab api "projects/$PROJECT_ID/pipelines/$(glab api "projects/$PROJECT_ID/pipelines?ref=feat/security-demo&per_page=1" | jq '.[0].id')/jobs" | jq '[.[]|select(.name=="container_scanning")][0].id') glab api "projects/$PROJECT_ID/jobs/$JOB/artifacts/gl-container-scanning-report.json" \ | jq -r '.vulnerabilities[] | "\(.severity)\t\(.location.dependency.package.name)\t\(.location.dependency.version)\t\(.identifiers[0].name)"' | sort | head
uv pip compile requirements.txt -o requirements.lock.txt or pip-compile to generate a locked-version file, and set the input pipcompile_requirements_file_name_pattern: "requirements.lock.txt", then compare the number of transitive dependencies.pyyaml 5.3.1 known vulnerabilities (Ultimate); the container scanning job succeeds and produces a CycloneDX file (Free works too).Case 1: scanned the “wrong image”
Problem: The container scan kept the default CS_IMAGE, so it actually scanned the previous latest, which had a different digest from the one about to be deployed, so vulnerabilities were missed. Approach: The build job exports via dotenv IMAGE_DIGEST, and both container scanning and deployment reference $CI_REGISTRY_IMAGE@$IMAGE_DIGEST.
Case 2: finding count surged after migrating dependency scanning
Problem: After migrating from Gemnasium to the SBOM analyzer, one Java project's finding count went from 12 to 140. Cause: The new analyzer reports transitive dependencies based on the dependency graph, while the old configuration only saw direct dependencies. Approach: First establish a baseline (bulk-triage vulnerabilities on the default branch); MR approval policies target only “new findings”; once static reachability is enabled, prioritize vulnerabilities that are reachable.
Case 3: a customer requires an SBOM with every release
Problem: A major customer's procurement contract requires delivery of a CycloneDX SBOM. Approach: Release pipeline (v* tags) keeps the container scanning SBOM artifact and attaches it to the release via a Release asset link from Lesson 5; SBOM files can also be signed with cosign (Lesson 5 / Docker Lesson 6).
Common errors and fixes
Component 'gitlab.com/components/dependency-scanning/dependency-scanning@2.1.1' - content not found
Cause: In this component project, the component name is main (templates/main/template.yml), not the project name. Fix:components/dependency-scanning/main@2.1.1.
unable to retrieve image … UNAUTHORIZED: authentication required (container_scanning)
Cause: The image is not in the GitLab Container Registry (default credentials do not apply), or the job token has no permission to access that project's registry. Fix: Set CS_REGISTRY_USER / CS_REGISTRY_PASSWORD (stored as protected, masked variables), or change the scan target to an image pushed by this project.
dependency-scanning: no supported files found (the job is skipped or the report is empty)
Cause: File depth exceeds max_scan_depth (default 2 in 2.x); the file is in excluded_paths (tests, vendor, etc. are excluded by default); or only a Pipfile exists with no lock file. Fix: Adjust the input or generate a lock file.
No container_scanning job in the pipeline (MR pipeline)
Cause: Component rules: when an MR exists, branch pipelines do not include this job; and your build job may not exist in MR pipelines. Fix: Make sure the build and the scan both exist in the same kind of pipeline, or set enable_mr_pipelines to false so the scan runs only in branch pipelines.
1. Count the components in a CycloneDX SBOM, and list the purl of every PyPI component.
jq '.components | length' gl-sbom-pypi-pip.cdx.json
jq -r '.components[] | select(.purl|startswith("pkg:pypi/")) | .purl' gl-sbom-pypi-pip.cdx.json2. Use Trivy to show only CRITICAL vulnerabilities that have a fixed version.
trivy image --severity CRITICAL --ignore-unfixed registry.gitlab.com/mygroup-lab/myapp:1.0
The team is on the Free tier only, and the security team requires “evidence of an SBOM and zero high-severity vulnerabilities for every release.” How would you do this?
In the release pipeline: ① use the container scanning component (Free) to scan the digest about to be released, and save gl-container-scanning-report.json and the CycloneDX SBOM artifact (with a longer expire_in) retention; ② add a jq gate: the release job runs only when the report shows zero Critical/High findings; ③ link the SBOM as a Release asset; ④ at the application-dependency level, use Trivy fs to generate the SBOM (dependency scanning is Ultimate). Note the limitation: without vulnerability report lifecycle management and continuous scanning, you need to rerun periodically (scheduled pipelines) when new advisories appear.
Verified instructional videos
Official documentation
- Dependency scanning by using SBOM
- Container scanning
- components/dependency-scanning · components/container-scanning
Video storyboard script (about 60 seconds)
Visual: the lock file and the image each “output” a list full of purls (SBOM).
Narration: the new generation of scanning first generates a bill of materials, recording what is used and which versions.
Visual: the list is compared line by line against the advisory database; the pyyaml 5.3.1 line turns red; the next day a new advisory is published, and another line turns red without any rebuild.
Narration: compare the list against advisories again; when new advisories appear, the existing list can be re-compared.
Visual: the Free tray holds JSON and Trivy; the Ultimate tray holds the dependency list and MR findings.
Narration: container scanning runs on Free; dependency scanning and the dependency list require Ultimate.
Module 4 · DAST and API security testing
- Know the current state of GitLab DAST: Browser-based DAST analyzer (DAST 5) scans web applications (including single-page apps); proxy-based DAST was deprecated in 16.9 and removed in 17.3; the “DAST API analyzer” was renamed in 17.0 to API security testing analyzer.
- Use
Security/DAST.gitlab-ci.ymlto run against myapp's temporary instance (CI services) to run a passive scan, and understandDAST_TARGET_URL/environment_url.txt,DAST_FULL_SCAN(active checks) and authentication variables. - Write a minimal OpenAPI file for myapp, and use
Security/API-Security.gitlab-ci.yml+APISEC_PROFILE: Quickto run API security testing; know that the Free tier can use OWASP ZAP as an alternative.
dev environments and Lesson 2's service containers. Importance:★★★☆☆What: two analyzers
| Browser DAST | API security testing | |
|---|---|---|
| Target | Web applications (including SPAs): use a headless browser to crawl pages, forms, and links | REST, SOAP, GraphQL, and form / JSON / XML request bodies |
| Input | DAST_TARGET_URL or the file in the job directory environment_url.txt | each scan uses one specification: OpenAPI v2/v3, GraphQL schema, HAR, Postman Collection v2.0/v2.1; APISEC_TARGET_URL |
| Checks | By default, only passive checks; DAST_FULL_SCAN: "true" run active checks as well (these send attack payloads) | run by profile (the documentation recommends starting with Quick) |
| Integrate with | template Security/DAST.gitlab-ci.yml (stable version; .latest versions may include breaking changes), with the job name dast, requires dast stage | template Security/API-Security.gitlab-ci.yml,dast stage |
| Other methods | on-demand scans (can be scheduled) + site / scanner profile; in scan execution policies, scan: dast | — |
| Tier | Ultimate (results go to MRs, the pipeline Security tab, and vulnerability reports; if any job fails, the security dashboard does not show DAST results) | |
Why: why DAST is still needed
SAST cannot see configuration and runtime behavior: missing security response headers, cookie attributes, exposed server versions, real injection points, and pages behind authentication. DAST accesses the application from the outside like an attacker; it usually has a low false-positive rate but only covers pages the crawler can reach. API security testing “mutates” requests parameter by parameter according to the specification, which addresses the problem that crawlers cannot find APIs.
How: three choices of scan target
| Approach | Pros | Risks / costs | This lesson |
|---|---|---|---|
CI service container: in the dast job, use services: to start the freshly built myapp + redis | fully isolated, clean every time, no deployment needed | configuration differs from real environments (no TLS, no WAF) | Mainline |
Review / dev environment: the deploy job writes environment_url.txt, and DAST reads | close to real | active scans write data; it must be reachable by the Runner | optional (the dev environment from Lessons 3/4) |
| Production | — | active checks may cause data corruption, trigger alerts, or get blocked | Do not (at most a read-only passive scan, with written approval) |
When
- MR pipeline: passive DAST (a few minutes), only against the temporary instance.
- Nightly scheduled pipeline / on-demand scan:
DAST_FULL_SCANfull + authenticated scan, against a dedicated test environment. - Services with OpenAPI: API security testing takes priority over crawler-based DAST.
DAST_TARGET_URL and APISEC_*. ③ “DAST finds every page”—the crawler can find only pages reachable by clicking; APIs need a specification file. ④ “DAST results are visible on Free”—DAST itself is Ultimate.Inside the dast job
Passive vs active
| Passive checks (default) | Active checks (DAST_FULL_SCAN=true) | |
|---|---|---|
| Behavior | only observes crawled requests / responses | actively sends attack payloads |
| Duration | minutes | may take tens of minutes to hours |
| Impact on target | similar to normal browsing | may create / modify data and trigger alerts |
| Suited for | every MR | nightly, dedicated test environment |
Interactive: stages of a DAST scan
Select a scenario to see what the DAST analyzer does in each stage—target check, authentication, crawl, checks, and report—and where it stops when it fails.
Core configuration
include:
- template: Security/DAST.gitlab-ci.yml
stages: [lint, test, build, scan, dast]
dast:
needs: [build-image]
services:
- name: redis:8-alpine
alias: redis
- name: $CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA
alias: myapp
variables:
DAST_TARGET_URL: "http://myapp:5000"
DAST_FULL_SCAN: "false" # passive checks only in MRs
DAST_CRAWL_TIMEOUT: "5m"
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
The service container alias is resolvable within the job network (Lesson 2's services mechanism); myapp by default REDIS_HOST=redis, which matches the alias exactly. redis:8-alpine is an example tag; pin it by digest. In the template, dast the rules built into the job are overridden by the rules here (arrays are replaced as a whole).
API security testing
{
"openapi": "3.0.3",
"info": { "title": "myapp", "version": "1.0" },
"servers": [ { "url": "http://myapp:5000" } ],
"paths": {
"/": { "get": { "responses": { "200": { "description": "hit counter" } } } },
"/healthz": { "get": { "responses": { "200": { "description": "ok" } } } }
}
}
include:
- template: Security/API-Security.gitlab-ci.yml
variables:
APISEC_PROFILE: Quick
APISEC_OPENAPI: openapi.json
APISEC_TARGET_URL: http://myapp:5000
api_security:
services:
- { name: redis:8-alpine, alias: redis }
- { name: "$CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA", alias: myapp }
The job name follows the template (glab ci lint / view the actual name in the full configuration in the pipeline editor; if it is not api_security, change it to the matching name when overriding).
Free alternative: OWASP ZAP baseline scan
zap-baseline:
stage: dast
image: ghcr.io/zaproxy/zaproxy:stable # ZAP 2.17.0; pin by digest in production
services:
- { name: redis:8-alpine, alias: redis }
- { name: "$CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA", alias: myapp }
script:
- mkdir -p /zap/wrk
- zap-baseline.py -t http://myapp:5000 -r zap.html -J zap.json -I || true
- cp /zap/wrk/zap.* . 2>/dev/null || true
artifacts:
paths: [zap.html, zap.json]
expire_in: 7 days
zap-baseline.py passive scan only,-I means warnings do not cause failure. Report output directory /zap/wrk conventions follow the ZAP documentation.
Lab 4: passive DAST against a disposable myapp instance (about 6 min, Ultimate)
build-image pushed by : short SHA tag on main.
glab api "projects/$PROJECT_ID/registry/repositories" | jq -r '.[0].id' | xargs -I{} \
glab api "projects/$PROJECT_ID/registry/repositories/{}/tags" | jq -r '.[].name' | head$CI_COMMIT_BRANCH, and make build-image push a short-SHA tag on that branch (revert after the lab).Checking target http://myapp:5000 is available ... ok Crawl: 3 pages, 0 forms, 2 navigations (timeout 5m) Running passive checks ... Findings: 4 (Low: 3, Info: 1) - Missing Content-Security-Policy header - Missing X-Content-Type-Options header - Server header leaks version information Report written: gl-dast-report.json
@app.after_request
def security_headers(resp):
resp.headers["X-Content-Type-Options"] = "nosniff"
resp.headers["Content-Security-Policy"] = "default-src 'none'"
return respzap.html and review similar alerts.Case 1: a nightly full DAST filled the test database
Problem: Full active scanning was enabled against a shared staging environment DAST_FULL_SCAN, active checks repeatedly submitted the sign-up form, creating tens of thousands of junk accounts and bringing the QA environment down. Approach: Prepare a dedicated environment that can be reset at any time for full scans; use DAST_CHECKS_TO_EXCLUDE to exclude highly destructive checks; exclude the sign-up endpoint from the scan scope.
Case 2: WAF blocked the Runner IP
Problem: While scanning a public test environment, the WAF detected attack payloads and blocked the egress IP of the hosted runner, so deployment jobs in other projects also failed. Approach: Run DAST on a dedicated self-managed runner (with a fixed egress IP), and configure a WAF exception for that IP + the test host; or simply use the service container approach.
Case 3: the SPA scan reached only the login page
Problem: The DAST report only has findings from the login page. Cause: Authentication was not configured. Approach: Set DAST_AUTH_URL,DAST_AUTH_USERNAME,DAST_AUTH_PASSWORD (masked + protected variables) and the form field selectors, using a dedicated low-privilege test account; for the API portion, switch to API security testing + OpenAPI.
Common errors and fixes
Symptom: the dast job fails immediately, and the log reports a missing scan target (neither DAST_TARGET_URL nor environment_url.txt is present)
Cause: Neither was provided. Fix: Set DAST_TARGET_URL, or have the deploy job write the URL into environment_url.txt and pass it to the dast job as an artifact.
Symptom: target availability check fails (connection refused / timeout)
Cause: The service container is not ready yet, the alias is misspelled, the port is wrong (non-standard ports must be included in the URL), or the Runner cannot reach the target network. Fix: Check the alias against :5000; if necessary, DAST_TARGET_CHECK_SKIP: "true" is for troubleshooting only.
stage dast not defined / chosen stage does not exist
Cause: The template job uses dast stage. Fix: In stages add dast.
DAST results do not appear in the security dashboard
Cause: The documentation notes that if any job in the pipeline fails, the security dashboard does not show DAST output; or the scan was not run on the default branch. Fix: Make the pipeline succeed; run on the default branch.
Symptom: variables such as DAST_WEBSITE and DAST_API_* from the old configuration no longer take effect
Cause: The configuration carried over from the removed proxy-based DAST. Fix: Following the official migration guide, switch to the browser DAST 5 variables (DAST_TARGET_URL etc.).
1. Write the minimal variables for the dast job: scan http://myapp:5000, passive checks only, crawl for at most 5 minutes.
dast:
variables:
DAST_TARGET_URL: "http://myapp:5000"
DAST_FULL_SCAN: "false"
DAST_CRAWL_TIMEOUT: "5m"2. How does the deploy job pass a dynamic URL to DAST?
deploy-review:
script:
- ./deploy.sh && echo "$DYNAMIC_URL" > environment_url.txt
artifacts:
paths: [environment_url.txt]The business side requires “DAST on every MR, without slowing down merges.” How would you balance this?
MRs: service container + passive checks + short crawl timeout, finishing in a few minutes, running only for web-layer changes (rules:changes) to run; API: API security testing Quick profile; nightly: a scheduled pipeline runs a full + authenticated scan in a dedicated environment, and results go to vulnerability reports; the MR approval policy requires approval only for new Critical/High DAST findings, so low-severity noise does not block merges.
Verified instructional videos
Official documentation
Video storyboard script (about 60 seconds)
Visual: three containers start together in the dast job box: the analyzer, myapp, and redis.
Narration: the safest DAST target is a temporary instance that is recreated every time.
Visual: the headless browser crawls three pages, and passive checks flag missing security response headers; after switching to “full,” red payloads fly toward the form.
Narration: passive checks are the default; a full scan sends attack payloads and may be used only against a dedicated environment.
Visual: the OpenAPI file expands into a set of requests, and API security testing mutates the parameters one by one.
Narration: for services with an API spec, use API security testing to cover what the crawler cannot see.
Module 5 · Security policies: scan execution and merge request approval policies
- Understand security policy project: policies are stored in
.gitlab/security-policies/policy.yml, and once linked to a group / subgroup / project they are inherited downward; linking requires being an Owner of the target (or having a custom role withmanage_security_policy_linkpermission). - Write the three core policy types: Scan execution policy (enforce
secret_detectionetc.),Merge request approval policy (scan_finding+fallback_behavior: fail: closed),Pipeline execution policy (injects custom jobs,inject_policy); know that vulnerability management policies and dependency firewalls also exist. - Remember the key limits: each policy project allows at most 5 MR approval policies and 5 scan execution policies (each with at most 5 rules); pipeline execution policies default to 5 and can be raised to a maximum of 20.
What: policy types (Ultimate)
| Type | Top-level YAML key | What it does | Typical use |
|---|---|---|---|
| Scan execution policy | scan_execution_policy | forces scans to run in pipelines or on a schedule (sast,sast_iac,dast,secret_detection,container_scanning,dependency_scanning) | “Every project's default branch and MRs must run secret detection” |
| Merge request approval policy | approval_policy | requires approval based on scan findings / license findings / any MR condition, and can enforce project settings | “New Critical/High or any secret findings require 1 approval from the security group” |
| Pipeline execution policy | pipeline_execution_policy | injects jobs into project pipelines (or overrides the project CI); also has a scheduled variant | “All regulated projects must run the compliance check job” (replacing compliance pipelines) |
| Vulnerability management policy | vulnerability_management_policy | automatically resolves vulnerabilities no longer detected on the default branch | reduces stale entries in vulnerability reports |
| Dependency firewall | — (see documentation) | blocks packages with disallowed licenses, high risk, or malicious packages before installation | Supply chain protection (newer feature; evaluate per documentation) |
Why: why put it in a separate project
- Separation of duties: developers can change their own project's
.gitlab-ci.yml, but cannot change the security policy project; for the project, the policy is “imposed from outside.” - Inheritance: once linked to the top-level group
mygroup-lab,mygroup-lab/myapp,mygroup-lab/platform/*all take effect, and new projects are automatically included. - Auditable: policy changes are themselves MRs in the policy project, with review and history.
How: key fields of merge request approval policies
| Field | Meaning |
|---|---|
rules[].type | scan_finding (security scan findings),license_finding (licenses),any_merge_request (any MR, e.g., based on commit signatures) |
scanners,severity_levels,vulnerabilities_allowed,vulnerability_states | which scanners' which severities, how many are allowed, and what states (new_needs_triage etc.) |
branch_type: protected / branches | Target branch scope |
actions: require_approval | approvals_required + role_approvers / group_approvers / user_approvers |
actions: send_bot_message | a bot comment in the MR explains the violation |
approval_settings | Enforce project settings: block_branch_modification,prevent_pushing_and_force_pushing etc. |
fallback_behavior.fail | closed (default): invalid or unenforceable rules require approval; open: no approval required; only a notice is given |
What happens if a scanner doesn't run? The documentation is explicit: if a scanner the policy specifies is not configured / enabled, or the job fails, is canceled, or produces no report, the policy cannot be evaluated,and the corresponding approval becomes required (with fail closed, the MR is blocked). This is exactly why “deleting the scan job to avoid approval” doesn't work.
How: pipeline execution policy essentials
content.includepoints to a CI file in another project (project/file/ optionalref).pipeline_config_strategy:inject_policy(recommended; adds jobs to the existing pipeline),override_project_ci(replaces the project CI; if needed, include the project config back in the policy file viainclude:project),inject_ciis deprecated in 17.9.- Reserved stages
.pipeline-policy-pre(run first; if they fail or are all skipped, subsequent jobs are skipped, includingneeds: []andwhen: always) and.pipeline-policy-post(run last). - Ignored by default
[skip ci](can be allowed withskip_ci.allowed+ a user allowlist);variables_overridecontrols whether projects can override policy variables. - The user triggering the pipeline must be able to read the project containing the policy CI file (auto-authorization can be enabled in the security policy project).
When: recommended combination
- Group-level scan execution policy: enforce on MRs and the default branch of all projects
secret_detection+sast(whether or not the project has an include). - Group-level MR approval policy A:
secret_detectionany new finding → 1 approval from the security group, fail closed. - MR approval policy B: Critical/High new findings from other scanners → security group approval; Medium only triggers a bot message.
- Regulated projects (within compliance framework scope): a pipeline execution policy injects compliance checks (Module 6).
.gitlab-ci.yml still gets the configuration created implicitly. ③ “Fail open is friendlier”—it turns scan failures into a shortcut around approval; production should stay closed. ④ “Approval policies verify report authenticity”—the documentation notes that policies do not verify the authenticity of scan results, so you must prevent developers from forging report artifacts (protected scan job origin = scan execution / pipeline execution policies).Comparison with GitHub
GitHub achieves a similar effect with “rulesets + required workflows / code scanning merge protection”; see GitHub Lesson 6. The GitLab difference: policies are tied directly to “findings” (new finding → approval), and are inherited uniformly at the group level through the policy project.
Policy project → group → project
Evaluation of MR approval policies
Interactive: MR approval policy evaluator
Adjust the MR's scan results and policy settings to see whether the policy requires approval, who must approve, and what the bot will say.
Core configuration: policy.yml
---
scan_execution_policy:
- name: Enforce secret detection and SAST
description: MRs and the default branch of all projects must run
enabled: true
rules:
- type: pipeline
branch_type: all
actions:
- scan: secret_detection
template: default
- scan: sast
template: default
approval_policy:
- name: Any new secret needs security approval
description: any new secret finding requires security group approval
enabled: true
rules:
- type: scan_finding
branch_type: protected
scanners: [secret_detection]
vulnerabilities_allowed: 0
severity_levels: [critical, high, medium, low, info, unknown]
vulnerability_states: [new_needs_triage]
actions:
- type: require_approval
approvals_required: 1
group_approvers: [mygroup-lab/security]
- type: send_bot_message
enabled: true
approval_settings:
block_branch_modification: true
prevent_pushing_and_force_pushing: true
fallback_behavior:
fail: closed
- name: Critical and high findings need security approval
enabled: true
rules:
- type: scan_finding
branch_type: protected
scanners: [sast, dependency_scanning, container_scanning, dast]
vulnerabilities_allowed: 0
severity_levels: [critical, high]
vulnerability_states: [new_needs_triage]
actions:
- type: require_approval
approvals_required: 1
group_approvers: [mygroup-lab/security]
fallback_behavior:
fail: closed
Note: branch_type Possible values of all / protected / default) and severity_levels enum syntax follows the policy schema ; in the UI, it is recommended to first generate the policy using the form in the “policy editor,” then switch to YAML mode to fine-tune—the editor performs schema validation. group_approvers Accepts group paths; you can also use group_approvers_ids. Secret findings are usually Critical; listing all severities is meant to ensure “no secret slips through.”
policy-sbom-present:
stage: .pipeline-policy-post
image: alpine:3.22
script:
- echo "compliance check for $CI_PROJECT_PATH @ $CI_COMMIT_SHORT_SHA"
- test -f Dockerfile || { echo "Dockerfile missing"; exit 1; }
pipeline_execution_policy:
- name: Inject compliance checks
description: checks that regulated projects must run
enabled: true
pipeline_config_strategy: inject_policy
content:
include:
- project: mygroup-lab/security-policies
file: ci/policy-checks.yml
ref: main
policy_scope:
compliance_frameworks:
- id: 1234 # framework ID created in Module 6
Link the policy project (API)
# UI: group → Security → Policies → Edit policy project → select project → Save
# GraphQL (field names per the GraphQL reference):
glab api graphql -f query='
mutation($fp: String!, $sp: ProjectID!) {
securityPolicyProjectAssign(input: {fullPath: $fp, securityPolicyProjectId: $sp}) { errors } }' \
-f fp="$GL_GROUP" -f sp="gid://gitlab/Project/$SPP_ID"
Lab 5: group-level “zero tolerance for secrets” policy (about 7 min, Ultimate)
mygroup-lab create a subgroup security, and add a colleague (or your second account); note that the MR author's own approval usually does not count (depends on project approval settings).policy.yml as an MR. Merge that MR..gitlab/security-policies/policy.yml), and merge.
glab api "projects/$(printf %s "$GL_GROUP/$GL_GROUP-security-policy-project" | jq -sRr @uri)" 2>/dev/null | jq '{id, path_with_namespace}' \
echo "query using the policy project path shown in the UI"-o secret_push_protection.skip_all to push a fake token, and open an MR to main. Expected: the MR shows “Requires 1 approval from mygroup-lab/security,” and the bot comment lists the new findings.
Security policy violations detected Policy: Any new secret needs security approval - secret_detection: GitLab personal access token (demo/leak.txt) — New, needs triage Approvals required from: mygroup-lab/security (1)
.gitlab-ci.yml remove the secret-detection component — the scan execution policy still injects secret-detection-<n> job; then try to make that job fail (e.g., temporarily set a nonexistent analyzer image tag variable), and observe that the MR still requires approval.include:project + pinned ref references; ② Premium: in CODEOWNERS, assign .gitlab-ci.yml to the platform group and enable “require code owner approval” to prevent removing the include; ③ the Module 1 jq gate + “pipeline must succeed.” Limitation: project Maintainers can still change settings—this is the essential difference between policies and “conventions.”Case 1: the sixth approval policy “didn't take effect”
Problem: The security team wrote 7 MR approval policies in one policy project; the last two never triggered. Cause: Each policy project allows at most 5 MR approval policies. Approach: Consolidate rules (each policy allows at most 5 rules); split into multiple policy projects by subgroup.
Case 2: a broken scanner blocked MRs company-wide
Problem: An analyzer image pull failure caused secret_detection to fail widely; fail closed made every MR require security approval, and the security group was overwhelmed. Approach: Image proxy / internal mirror (SECURE_ANALYZERS_PREFIX); the runbook defines the temporary measures for a “scanning infrastructure failure” (e.g., bulk approval by the security group with records), rather than changing the policy to fail open.
Case 3: a pipeline execution policy stopped some projects from “starting pipelines”
Problem: After enabling the injection policy, pipelines for some projects were never created at all. Cause: The triggering user had no read access to the project containing the policy CI file. Approach: Enable auto-authorization for pipeline execution policies in the security policy project settings, or grant Reporter to the relevant groups.
Common errors and fixes
The MR keeps showing “Requires approval,” but the scans have no findings
Cause: fail closed: a scanner the policy requires produced no report (not enabled, job failed / canceled, or it runs only in branch pipelines while the MR uses MR pipelines). Fix: Check the policy explanation in the MR; add the missing scanner, or use a scan execution policy to enforce it.
The policy editor reports invalid YAML (schema validation failed)
Cause: Misspelled fields, indentation, array format, or exceeding limits (number of rules, number of actions). Fix: Rebuild it in the policy editor's rule mode, then switch back to YAML; check against the policy schema.
The job name injected by the scan execution policy is secret-detection-1, and overrides in the project have no effect
Cause: Policy job names get a hyphen and sequence number appended to avoid conflicts, so projects cannot override them with the same key. Note: This is by design; to customize, configure variables in the policy's action.
Pipeline not created: the CI file referenced by the policy is inaccessible
Cause: The triggering user has no permission to read the policy CI project. Fix: Enable auto-authorization or adjust member permissions; for private/internal projects, you can enable “Allow access to CI/CD configuration files in this project.”
1. Write a scan execution policy that runs container_scanning on main every day at 02:00.
scan_execution_policy:
- name: Nightly container scan
enabled: true
rules:
- type: schedule
branches: [main]
cadence: '0 2 * * *'
actions:
- scan: container_scanning2. Change an approval policy so that “scan failures do not block, only notify.”
fallback_behavior:
fail: openA developer removed the SAST include in an MR, trying to make the approval policy “not see any findings.” What happens under your policy combination?
① the group-level scan execution policy still injects sast-<n> jobs, and reports are still produced as usual; ② even without a scan execution policy, the MR approval policy cannot be evaluated when the SAST report is missing, so fail closed requires security approval; ③ changes to .gitlab-ci.yml also require platform group approval via CODEOWNERS (Premium); ④ audit events record the related settings changes. Conclusion: removing the scan only makes the MR harder to merge.
Verified instructional videos
Official documentation
- Policies
- Merge request approval policies
- Scan execution policies
- Pipeline execution policies
- Tutorial: Set up a merge request approval policy
Video storyboard script (about 60 seconds)
Visual: a locked “policy project” safe, with a chain running from it to the root of the group tree.
Narration: security policies are written in a separate project; once linked to a group, all projects inherit them automatically.
Visual: the MR card shows “security group approval required,” and a bot comment lists the new findings; the developer deletes the scan job, and the lock gets tighter instead (fail closed).
Narration: new secret findings need approval; if the scan didn't run, approval is needed too.
Visual: gray .pipeline-policy-pre and .pipeline-policy-post stages appear in the pipeline.
Narration: a pipeline execution policy injects compliance jobs into every pipeline, and projects cannot remove them.
Module 6 · Compliance frameworks, compliance pipelines, and audit events
- Create a compliance framework and apply it to myapp (up to 20 frameworks per project; a group default framework can be set); understand requirements and controls (control, e.g.,
scanner_sast_running,minimum_approvals_required_2) and compliance status reports. - Know that compliance pipelines were deprecated in 17.3; the documentation says “planned for removal in 20.0” (the migration section on the same page says 19.0). Use the “Migrate pipeline to a policy” action in the compliance center to migrate to pipeline execution policies, and do not let both coexist in the same project.
- Use the API to query group / project audit events (Premium; Free has only successful sign-in events), configure audit event streaming (Ultimate: HTTP, Google Cloud Logging, AWS S3), and verify
X-Gitlab-Event-Streaming-Token.
policy_scope. Importance:★★★★☆What: three concepts
| Concept | What it is | Tier | Entry point |
|---|---|---|---|
| Compliance framework | A “label” defined at the top-level group (such as SOC2,PCI), applied to projects | Premium, Ultimate | Security → Compliance center (Frameworks / Projects tabs) |
| Requirements and controls | Requirements under a framework; each requirement has at most 5 controls: GitLab controls (e.g., SAST is running, at least two approvals) or external controls (an external system reports pass/fail via the API) | Ultimate | Compliance center; compliance status report |
| Policy scope | The security policy's policy_scope.compliance_frameworks: enforces only on projects with a given framework | Ultimate | policy.yml |
| Compliance pipeline (deprecated) | A pipeline configuration specified on the framework, replacing the project pipeline | Ultimate | Migrate to pipeline execution policy |
| Audit events | Change records for groups / projects / instances; retention is “indefinite” | Premium (Free has only successful sign-in events) | Security → Audit events; GET /groups/:id/audit_events |
| Audit event stream | pushed in real time to an HTTP endpoint / Google Cloud Logging / AWS S3 | Ultimate | Audit events → Streams tab |
Why: a framework is a “selector,” not a “control”
A compliance framework by itself blocks nothing—it is just a project selector. The real controls come from: ① policies (using policy_scope to select projects that carry the framework); ② requirements and controls (continuously check whether projects comply, generate compliance status reports; GitLab controls are evaluated on a schedule or by triggered scans); ③ audit events and streams (evidence). This way, a new project automatically falls into the controlled scope as soon as it gets the framework label (or inherits the group's default framework).
How: create frameworks and controls
- Who can create: an Owner or Security Manager of the top-level group, or a custom role with
admin_compliance_frameworkpermission. - Default framework: a group Owner can set it; it applies to newly created and imported projects (not retroactive to existing projects), and cannot be deleted.
- External controls: status
pending/pass/fail/not_applicable; when “Ping enabled” is on, GitLab requests an update every 12 hours;pendinga status older than 6 hours is treated as a failure. - The standards adherence dashboard went GA in 18.3 and is now presented by the compliance status report.
How: migrating from compliance pipelines
- In the compliance center, edit a framework that uses a compliance pipeline → the banner “Migrate pipeline to a policy” appears → click it to generate a pipeline execution policy (scoped to that framework).
- Edit the framework again and delete the compliance pipeline configuration.
- Check the policy's
pipeline_config_strategy: the compliance pipeline's semantics are “replace the project pipeline,” corresponding tooverride_project_ci; it is better to change toinject_policy, so the project pipeline runs as usual and only compliance jobs are injected.
How: audit event stream delivery and verification
- Each event is sent to the target as an HTTP POST; the request header
X-Gitlab-Event-Streaming-Tokencarries the target's verification token (can be customized only via GraphQL); the receiver accepts the event only after comparing the token. - Each target allows at most 20 custom request headers; events can be filtered by event type and by group / project namespace; without filtering, all events are received.
- On GitLab.com, the target must allow GitLab.com's egress IP ranges; use the
idin the payload to de-duplicate (events may be redelivered).
When: which events are worth alerting on
| Event (example category) | Why |
|---|---|
| Push protection bypassed / skipped | Module 2's defense in depth depends on “someone seeing it” |
Security policy project linked / unlinked, policy limits exceeded and ignored (security_policy_limit_exceeded) | A signal that policies have stopped working |
| Changes to protected branches, approval rules, and merge checks | the common “turn off protection, then merge” pattern |
| Member and role changes, token creation / rotation / revocation, service account creation | Identity governance (Module 7) |
| SSO / IP allowlist setting changes | A boundary is being modified |
Framework → policy → evidence
Compliance pipeline vs pipeline execution policy
| Compliance pipeline (deprecated) | Pipeline execution policy | |
|---|---|---|
| Where it is defined | References a CI file in the framework settings | policy.yml in the security policy project |
| Effect on project pipeline | Replaces (must include the project CI back in the compliance configuration) | inject_policy Injects / override_project_ci Replaces |
| Scope | Projects with that framework | Project / group / framework (policy_scope) |
| Reserved stages | None | .pipeline-policy-pre / .pipeline-policy-post |
| Status | Deprecated in 17.3, planned for removal | Recommended |
Interactive: delivery of an audit event
Starting from “a developer bypasses push protection,” see how the event is recorded, filtered, delivered with a token, and verified by the receiver.
Core commands
| Command | Purpose | Tier / role |
|---|---|---|
glab api "groups/:id/audit_events?created_after=…" | Group audit events (Owners see all; Developer/Maintainer see only their own) | Premium |
glab api "projects/:id/audit_events" | Project audit events (Maintainer+ see all) | Premium |
glab api graphql …complianceFrameworks… | Query frameworks | Premium |
| Compliance center → Frameworks → New framework | Create frameworks, requirements, and controls | Premium / Ultimate |
# Group audit events from the last 7 days (GNU date; on macOS use gdate) SINCE=$(date -u -d '7 days ago' +%Y-%m-%dT%H:%M:%SZ) glab api "groups/$GROUP_ID/audit_events?created_after=$SINCE&per_page=50" \ | jq -r '.[] | [.created_at, .details.author_name, (.details.custom_message // .details.change // "-"), .details.target_details] | @tsv' | head
2026-11-16T09:12:03.000Z Alice Secret push protection skipped mygroup-lab/myapp 2026-11-16T09:05:41.000Z Alice Linked security policy project mygroup-lab 2026-11-15T22:30:10.000Z Bob access_level Developer
Output fields and custom_message wording vary by event type; follow the actual response (the example values are constructed). Offset pagination of the audit event API is deprecated (the documentation says “planned for removal in 19.0”); for bulk retrieval, use keyset pagination.
# Query the group's compliance frameworks (GraphQL; field names per the reference)
glab api graphql -f query='
query($g: ID!) { group(fullPath: $g) { complianceFrameworks { nodes { id name default } } } }' \
-f g="$GL_GROUP" | jq '.data.group.complianceFrameworks.nodes'
Minimal audit stream receiver (verifies token)
import hmac, json, os
from http.server import BaseHTTPRequestHandler, HTTPServer
TOKEN = os.environ["GITLAB_STREAM_TOKEN"] # must match the target's verification token
seen = set()
class H(BaseHTTPRequestHandler):
def do_POST(self):
got = self.headers.get("X-Gitlab-Event-Streaming-Token", "")
if not hmac.compare_digest(got, TOKEN):
self.send_response(401); self.end_headers(); return
body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
if body.get("id") in seen: # de-duplicate by id
self.send_response(200); self.end_headers(); return
seen.add(body.get("id"))
print(body.get("event_type"), body.get("author_name"), body.get("entity_path"))
self.send_response(200); self.end_headers()
HTTPServer(("0.0.0.0", 8080), H).serve_forever()
payload field names (event_type,author_name,entity_path etc.) follow the audit event schema; in production, place it behind a TLS reverse proxy and persist the de-duplication state.
Lab 6: framework + audit evidence (about 7 min)
SOC2-lab, any color. (Ultimate) add the requirement “Change review,” and choose the controls “At least two approvals” (minimum_approvals_required_2) and “SAST running” (scanner_sast_running).SOC2-lab. Note the framework ID (from the GraphQL query on the previous page, in gid://gitlab/ComplianceManagement::Framework/1234 the number), and enter it in the Module 5 pipeline execution policy's policy_scope.GITLAB_STREAM_TOKEN, then perform an action that generates an event (for example, editing a project's description), and observe the receiver's logs.Case 1: the auditor asks “who ever turned off protection on main?”
Problem: The quarterly audit must prove that protected branches were never temporarily turned off. Approach: Stream audit events to the SIEM, with retention set per regulation; in the SIEM, build alerts and a monthly report for “protected branch / approval rule changes”; audit events in GitLab are retained indefinitely and can serve as cross-validation.
Case 2: jobs ran twice after migrating compliance pipelines
Problem: The team enabled pipeline execution policies first and then migrated compliance pipelines; during this period, some projects had duplicate jobs and a few checks were missed. Approach: Follow the documented order: first use “Migrate pipeline to a policy” to generate the policy, then remove the compliance pipeline from the framework; freeze policy changes for these projects during the migration window.
Case 3: the event stream receiver was flooded
Problem: All events from the top-level group were pushed to a small function without filtering; at peak times, timeouts caused redelivery and duplicate ingestion. Approach: Filter each target by event type; on the receiver, use id to de-duplicate and enqueue asynchronously; set up two targets, one for “security alerts” and one for “archive” (S3 archives everything; HTTP receives only high-value events).
Common errors and fixes
The compliance center does not show “Requirements” / cannot add controls
Cause: Requirements and controls are Ultimate features; or you are not an Owner / Security Manager of the top-level group.
403 Forbidden: GET /groups/:id/audit_events
Cause: Free tier; or the token lacks the read_api; or the role is insufficient. Note that Developer/Maintainer can see only the group events produced by their own actions.
Event stream target receives no events for a long time
Cause: The target firewall does not allow GitLab.com IP ranges; the filter excludes that event type or namespace; the receiver returns a non-2xx response. Fix: Check the filters in the target configuration; log all requests on the receiver (including 401s).
Project pipeline behaves abnormally: jobs duplicated or missing (compliance pipeline + pipeline execution policy coexisting)
Fix: Complete the compliance pipeline migration and delete the pipeline configuration in the framework.
1. List the project's recent audit events, showing only the time and author.
glab api "projects/$PROJECT_ID/audit_events?per_page=20" | jq -r '.[] | "\(.created_at) \(.details.author_name)"'
2. Write a policy_scope snippet that makes a pipeline execution policy apply only to a given compliance framework.
policy_scope:
compliance_frameworks:
- id: 1234The company has 300 projects, 40 of which handle payment data (PCI). How do you make “newly created payment projects” automatically controlled, without disturbing ordinary projects?
Put payment projects in a dedicated subgroup (such as mygroup-lab/payments), and set a default framework there PCI (a default framework applies only to newly created / imported projects; existing projects need bulk labeling); in security policies, use policy_scope.compliance_frameworks: PCI to inject compliance jobs and stricter approval policies; define requirements and controls under the PCI framework (two-person approval, SAST running, external controls integrated with the change management system); set up a separate audit event stream target for the payments namespace. Ordinary projects are subject only to the global baseline policies.
Verified instructional videos
Official documentation
- Compliance frameworks
- Compliance pipelines (deprecated)
- Audit events
- Audit event streaming
- Audit events API
Video storyboard script (about 60 seconds)
Visual: a project card gets an “SOC2” label, and the policy's “scope” spotlight immediately lights it up.
Narration: a compliance framework is a selector; policies find them through scope.
Visual: in the compliance status report, “at least two approvals” turns red, and “SAST running” turns green.
Narration: requirements and controls continuously check whether projects truly meet the requirements.
Visual: a “push protection bypassed” event flies to the SIEM carrying a token header; after the receiver checks the token, an alert lights up.
Narration: the audit event stream delivers evidence to the SIEM in real time; remember to verify the token and de-duplicate by id.
Module 7 · Identity governance: SSO / SCIM, tokens, and access policies
- Design SAML SSO + SCIM for a GitLab.com top-level group: what the two “enforce SSO” switches (Web activity; Git and Dependency Proxy activity) each govern and what they cannot govern (tokens, deploy keys, and Git activity from CI jobs are not covered by Web enforcement).
- Master the token governance facts: new tokens must have an expiry date by default, with a maximum of 365 days (since 17.6 administrators can adjust it; the 400-day ceiling requires a feature flag); email reminders 60 / 30 / 7 days before expiry; on GitLab.com, project access tokens require Premium/Ultimate (only 1 during the trial).
- Use service accounts Replace “shared human accounts”: no seat used, cannot sign in to the UI, authenticates only with tokens; create, issue, and rotate tokens via the API.
- Configure IP allowlists and email domain restrictions, and understand their effects on GitLab-hosted runners, the container registry, and LFS.
What: four identity types, four governance methods
| Identity | Recommended authentication | Governance essentials | Tier |
|---|---|---|---|
| Employees | SAML SSO (IdP: Entra ID, Okta, Google Workspace, OneLogin, Keycloak, etc.) + IdP-side MFA | Enforce SSO; SCIM provisions and deprovisions automatically; SAML group links map roles | Premium (GitLab.com top-level groups only) |
| Employees' API / Git access | Short-lived PATs (or SSH keys) + enforce SSO for Git activity | Maximum lifetime, expiry reminders; enterprise users can have password authentication disabled | From Free; some settings Premium/Ultimate |
| Automation (bots, integrations) | Service accounts + tokens with an expiry date; project / group access tokens | Minimum scope per purpose; rotation; unaffected by departures | Service accounts from Free; project access tokens on GitLab.com require Premium+ |
| CI/CD jobs | CI_JOB_TOKEN (job token allowlist),id_tokens → cloud OIDC (Lessons 3/4) | Do not store long-lived cloud keys; job tokens grant access only to the projects that are needed | Free |
How: the two SAML enforcement switches (GitLab.com)
| Setting | Effect | Not covered |
|---|---|---|
| Enforce SSO-only authentication for web activity for this group | Members must access group resources through the group's SSO URL; members cannot be added manually | Owners can still access the top-level group without SSO; tokens, deploy keys, and other non-“regular user” credentials; Git activity from CI jobs; API requests |
| Enforce SSO-only authentication for Git and Dependency Proxy activity for this group | SSH/HTTPS Git operations and Dependency Proxy pulls require a valid SSO session; API endpoints involving Git activity are also constrained | — |
- Session: if the last SSO sign-in was more than 24 hours ago, sign in again (the IdP can be used to adjust
SessionNotOnOrAfter); by default, sessions end after 7 days of inactivity. - Blocking password-based API access: SSO enforcement does not cover the API; you need to enterprise users disable password and passkey authentication (17.4+, requires a verified domain); afterwards they can sign in only through SAML and access the API / Git with PATs.
- SCIM: users added / removed in the IdP → GitLab automatically adds / removes group members. Documented examples: Microsoft Entra ID, Okta (the GitLab app in the Okta directory supports only SCIM, not SAML).
- Default member role: on GitLab.com you can choose the role for new SSO users; combined with SAML group links, roles can be mapped from IdP groups; Minimal Access can be used to “grant sign-in but no content.”
How: token governance facts (verified 2026-11-16)
| Item | Fact |
|---|---|
| Default expiry | If no expiry date is set, tokens expire after 365 days; new tokens must have an expiry date by default (administrators can turn this requirement off—not recommended) |
| Maximum lifetime | Default 365 days; since 17.6 administrators can adjust it; the 400-day ceiling is behind the buffered_token_expiration_limit feature flag (off by default); the documentation says Ultimate administrators can configure the maximum allowed lifetime |
| Expiry reminders | Checked daily at 01:00 UTC; email 7 days before expiry; since 17.6 additional 30- and 60-day reminders (GA in 17.7) |
| Project access tokens | On GitLab.com requires Premium/Ultimate (trial limit: 1); creation generates a bot user project_{id}_bot_{random}, not billed; the bot is deleted 30 days after the last token is invalidated |
| Service accounts | GA in 18.11 on the Free tier; on GitLab.com Free allows up to 100 per top-level group (including subgroups / projects), Premium/Ultimate unlimited; they use no seat, are always external users, and cannot sign in to the UI; on GitLab.com only top-level group Owners can create group-level service accounts |
| Service account token expiry | “Require expiration date for service accounts” is set separately: on GitLab.com it is managed by top-level group Owners; you may allow service account tokens without an expiry date (not recommended) |
How: network and domain boundaries (Premium)
- Restrict group access by IP: a top-level group setting that covers the UI (subgroups, projects, issues, excluding Pages), the API, and Git (SSH and HTTP share one list); the container registry and LFS always is restricted; IPv4/IPv6 CIDR, one per line. Administrators always have access; Owners can access group settings and subgroups, but not projects.
- GitLab.com hosted runners: their IP ranges are globally allowed, so they can clone repositories, but LFS downloads and container image pulls/pushes will fail—fix: add the hosted runner IPs of all regions to the list, switch to group / project runners with fixed egress IPs, or disable instance runners for the group. Runner registration is not restricted, but jobs claimed by runners outside the allowed range will fail.
- Restrict by email domain: the user's primary email domain must match; subgroups inherit it; public domains such as gmail.com and outlook.com cannot be added; removing a domain does not remove existing members.
Comparison with GitHub
GitHub's counterparts are organization SAML SSO, Enterprise Managed Users (EMU), fine-grained PATs, and GitHub Apps; see GitHub Lesson 6, Module 5. On GitLab.com, “enterprise users + verified domain” achieves some effects similar to EMU, but accounts are still global GitLab.com accounts.
Employee lifecycle: the IdP is the single source of truth
Token selection decision
| Scenario | Preferred | Avoid |
|---|---|---|
| A CI job accessing another project's packages / repository | CI_JOB_TOKEN + the target project's job token allowlist | Storing someone's PAT as a CI variable |
| CI job deploying to Azure / AWS | id_tokens + federated identity (Lessons 3/4) | Long-lived cloud keys |
| External system calling the GitLab API (e.g., a ticketing system) | Group service account + token with an expiry date, minimal scope (e.g., read_api) | Administrator personal tokens |
| Single-project automation (e.g., Renovate) | Project access token (Premium+) or service account | Tokens without an expiry date |
Interactive: access request evaluator
Choose “who, from where, with what credential, doing what,” and see what result the GitLab.com group SSO, IP allowlist, and token rules produce (simplified from the official rules in this module's “Principles”).
Core commands: service accounts and tokens
| API | Purpose |
|---|---|
POST /groups/:id/service_accounts (name,username,email optional) | Create a group service account (top-level group Owner on GitLab.com) |
GET /groups/:id/service_accounts | List |
POST /groups/:id/service_accounts/:user_id/personal_access_tokens (name,scopes[],expires_at) | Issue a token |
POST …/personal_access_tokens/:token_id/rotate | Rotate: revoke the old token and issue a new token with the same name and scope (if expires_at is not given and an expiry is required, the default is one week) |
DELETE /groups/:id/service_accounts/:user_id (hard_delete optional) | Delete |
# 1) Create a service account
SA=$(glab api -X POST "groups/$GROUP_ID/service_accounts" -f name="Ticket Bot" -f username="ticket_bot_$GROUP_ID")
SA_ID=$(echo "$SA" | jq -r .id); echo "$SA" | jq '{id, username, name}'
# 2) Add to the project and give minimal role (Reporter = 20)
glab api -X POST "projects/$PROJECT_ID/members" -f user_id=$SA_ID -f access_level=20 | jq '{username, access_level}'
# 3) Issue a 30-day, read-API-only token (output is shown only once; write it directly to your secrets manager, do not print it)
EXP=$(date -u -d '+30 days' +%F)
glab api -X POST "groups/$GROUP_ID/service_accounts/$SA_ID/personal_access_tokens" \
-f name=ticket-sync -f "scopes[]=read_api" -f expires_at=$EXP | jq '{id, name, scopes, expires_at, token: "(omitted)"}'
{
"id": 30123456,
"username": "ticket_bot_87654321",
"name": "Ticket Bot"
}
{
"username": "ticket_bot_87654321",
"access_level": 20
}
{
"id": 9876543,
"name": "ticket-sync",
"scopes": ["read_api"],
"expires_at": "2026-12-16",
"token": "(omitted)"
}
# 4) Rotation (run periodically, ideally via a scheduled pipeline or your secrets manager)
glab api -X POST "groups/$GROUP_ID/service_accounts/$SA_ID/personal_access_tokens/9876543/rotate" \
-f expires_at=$(date -u -d '+30 days' +%F) | jq '{id, expires_at}'
# 5) Inventory your own tokens that are about to expire
glab api "personal_access_tokens?state=active&per_page=100" | jq -r '.[] | "\(.expires_at)\t\(.name)\t\(.scopes|join(","))"' | sort | head
IP allowlist (UI)
Top-level group → Settings → General → Permissions and group features → Restrict access by IP address, one CIDR per line. Add your current egress IP before saving, otherwise even Owners cannot get into projects (they can access only group settings). In the same area, “Restrict membership by email domain” sets domain restrictions.
Lab 7: replace a “shared human account” with a service account (about 7 min)
glab variable list -R "$GL_PROJECT" glab api "projects/$PROJECT_ID/variables" | jq -r '.[] | "\(.key)\tmasked=\(.masked)\tprotected=\(.protected)"'
export SA_TOKEN=… # retrieve from your secrets manager
curl -s -H "PRIVATE-TOKEN: $SA_TOKEN" "https://gitlab.com/api/v4/projects/$PROJECT_ID" | jq '{path_with_namespace}'
curl -s -o /dev/null -w '%{http_code}\n' -X POST -H "PRIVATE-TOKEN: $SA_TOKEN" \
"https://gitlab.com/api/v4/projects/$PROJECT_ID/issues" -d title=test
{
"path_with_namespace": "mygroup-lab/myapp"
}
403
The second request fails: the token has only the read_api scope (if the scope is insufficient, the API returns 403 insufficient_scope).
glab api -X DELETE "groups/$GROUP_ID/service_accounts/$SA_ID".Case 1: a departed engineer's PAT still powers production releases
Problem: An engineer left; after the account was disabled, all release pipelines returned 401—the CI variable stored his PAT. Approach: Switch to a group service account + 30-day token (rotated automatically by the secrets manager), or use CI_JOB_TOKEN / OIDC; include the token inventory in the quarterly access review.
Case 2: image pulls all failed after enabling the IP allowlist
Problem: The security team enabled an IP allowlist for the top-level group; all docker pull registry.gitlab.com/... on GitLab.com hosted runners failed, while git clone worked. Cause: Hosted runner clones are globally allowed, but the container registry and LFS are always restricted. Approach: Move to a group runner with a fixed egress IP (Lesson 7), or add the hosted runner IP ranges for all regions to the list (this requires ongoing maintenance).
Case 3: scripts still used passwords for the API after SSO enforcement
Problem: After Web SSO enforcement was enabled, an audit found that password-based API access was still happening. Cause: SSO enforcement does not cover the API. Approach: Verify the company domain, convert employees to enterprise users, and disable their password and passkey authentication; also shorten the maximum token lifetime.
Common errors and fixes
403 Forbidden: POST /groups/:id/service_accounts
Cause: On GitLab.com only top-level group Owners can create group service accounts; the call was made with a subgroup ID; or the Free tier has reached its 100 limit; or the Owner has not completed identity verification during the trial.
Symptom: creating a token returns 400, saying the expiry date is invalid or exceeds the maximum allowed lifetime
Cause: The expiry date exceeds the maximum lifetime allowed by the instance / group (default 365 days), or the format is not YYYY-MM-DD.
Symptom: after enabling Git enforcement of SSO, git clone / push is rejected, asking for SSO sign-in
Cause: Git activity SSO enforcement is enabled, and the last SSO sign-in was more than 24 hours ago. Fix: Sign in again through the group SSO URL in the browser, then run the git operation.
docker pull registry.gitlab.com/… on a hosted runner returns denied / 403 (the group has IP restrictions enabled)
Fix: See Production case 2: use a self-managed runner with a fixed IP, or allow the hosted runner IP ranges.
Cannot create project access tokens (GitLab.com)
Cause: On GitLab.com project access tokens require Premium/Ultimate; the trial allows only 1. Alternative: Service accounts (available on Free).
1. Issue a token for a service account that expires in 7 days and is read-only for repositories.
glab api -X POST "groups/$GROUP_ID/service_accounts/$SA_ID/personal_access_tokens" \
-f name=ro-7d -f "scopes[]=read_repository" -f expires_at=$(date -u -d '+7 days' +%F) | jq '{id, expires_at}'2. List the usernames of all service accounts in the group.
glab api "groups/$GROUP_ID/service_accounts" | jq -r '.[].username'
A 200-person company is migrating from “one GitLab.com account per person with free joining” to centralized governance. Give the sequence and reasons.
① Verify the company domain, so existing employee accounts become enterprise users; ② configure SAML SSO (do not enforce yet) and use SAML group links to map roles, with the security team mapped to Security Manager (beta) or a custom role; ③ configure SCIM for automatic provisioning / deprovisioning; ④ after all members have bound SSO, enable Web enforcement, then Git and Dependency Proxy enforcement; ⑤ disable password and passkey authentication for enterprise users to close off password-based API access; ⑥ inventory personal tokens in CI variables and replace them with service accounts / CI_JOB_TOKEN / OIDC; ⑦ domain restrictions + IP allowlist (first assess the impact on hosted runners); ⑧ monitor changes to members, tokens, and SSO settings via the audit event stream. Ordering principle: observe first, then enforce; at every step keep at least one backup Owner who does not depend on SSO.
Verified instructional videos
Official documentation
- SAML SSO for GitLab.com groups
- Personal access tokens
- Service accounts · API
- Group access and permissions (IP / domain restrictions)
- Project access tokens
Video storyboard script (about 60 seconds)
Visual: adding an employee in the IdP makes a member card appear in the GitLab group automatically; removing the employee makes the card disappear.
Narration: SCIM makes the IdP the single source of truth.
Visual: two locks, the Web lock and the Git lock; a key (PAT) bypasses the Web lock and reaches the API directly, then is stopped by “enterprise users have passwords disabled + token expiry.”
Narration: Web enforcement does not cover tokens and the API; combine it with Git enforcement, token lifetimes, and enterprise user settings.
Visual: a service account bot works with a 30-day token, which is rotated automatically before it expires.
Narration: use service accounts for automation—they use no seat, and they don't break when a person leaves.
Module 8 · Governance architecture review
- Review using a six-layer model: “identity → code entry → pipeline → artifacts → deployment → evidence”
mygroup-lab, listing the controls, tier, and owner for each layer. - Give actionable plans for the three tiers Free, Premium, and Ultimate, and honestly note each tier's residual risk (for example, on the Free tier a gate can be removed by a project Maintainer).
- Use the interactive troubleshooting tree to locate why “scanning did not run / policy did not block / push was not blocked / audit cannot see it.”
What: six-layer control model
| Layer | Risk | Free | Added by Premium | Added by Ultimate | Evidence |
|---|---|---|---|---|---|
| ① Identity | Departed accounts, shared accounts, long-lived tokens | Enforced 2FA (Lesson 1), service accounts (≤100 per top-level group), tokens must have an expiry date | SAML SSO + SCIM, IP / domain restrictions, project / group access tokens (GitLab.com) | Configurable maximum token lifetime (as documented), fine-grained roles such as Security Manager (beta) | Audit events (Premium) |
| ② Code entry | Secrets entering the repository, unreviewed code reaching main | Protected branches, gitleaks pre-commit (client-side) | Approval rules, CODEOWNERS approval, push rules | Push protection, policy-enforced approval settings | Audit events (blocks / bypasses) |
| ③ Pipeline | Scans deleted or skipped | Shared template + jq gate (can be removed) | CODEOWNERS protects CI files | Scan execution policies / pipeline execution policies (projects cannot remove them) | Pipeline records, policy audit |
| ④ Finding handling | High-severity code merged | Gate failure + “pipeline must succeed” | — | MR approval policy (fail closed), vulnerability report triage, vulnerability management policies | Vulnerability report history, MR approval records |
| ⑤ Artifacts and deployment | Scan and deployment are not the same image; unauthorized deployment | Deploy by digest, protected tags, OIDC (Lessons 3/4) | Protected environments + deployment approval | Dependency list / SBOM management, registry container scanning | Deployment records, SBOM artifacts |
| ⑥ Evidence and monitoring | After an incident, you cannot answer “who, when, and what” | Only sign-in events; artifacts and pipeline logs | Audit events (retained indefinitely), compliance framework labels | Audit event stream, requirements and controls, compliance status reports | SIEM, compliance reports |
Why: the output of a review is “decisions + residual risk,” not a feature list
A good governance review states explicitly: which controls are adopted, why, at which tier, who maintains them, what the residual risk is, and when to review again. For example: “Under the Premium plan, the scan gate is provided by a shared template and a project Maintainer could in theory remove it; CODEOWNERS plus a weekly audit-event digest serve as compensating controls, we accept this residual risk, and we will evaluate Ultimate next quarter.”
How: review steps (a 60–90 minute meeting is recommended)
- Scope: the top-level group tree, regulated projects (compliance frameworks), external integrations, and runners.
- Current-state collection: export settings (push protection, policy project links, tokens, members, protected branches) using the read-only script on this module's “Commands” page.
- Score each layer: use the maturity scorer on the “Animation” page.
- Gaps and options: for each gap, give two options: a Free compensating control and a paid option.
- Decision record: write it as an ADR (architecture decision record), store it in the security policy project or a platform documentation repository, and make changes through MRs.
- Metrics: push protection block / bypass counts, approvals triggered by policies, average time to fix Critical/High, number of tokens about to expire, number of members not bound to SSO.
When: three blueprints
- Enforce 2FA; service accounts + 30–90-day tokens
- SAST / secret / container scanning components + jq gate (shared template with a pinned ref)
- gitleaks pre-commit; “pipeline must succeed”
- OIDC deployment, deploy by digest
- All of Free +
- SAML SSO + SCIM + enforcement (Web and Git) + disable passwords for enterprise users
- IP / domain restrictions; CODEOWNERS approval to protect CI files
- Weekly audit-event digest; compliance framework labels; protected environment approvals
- All of Premium +
- Push protection (enabled in bulk via the group API)
- Group-level scan execution + MR approval (fail closed) + pipeline execution policies
- Vulnerability report triage SLA; audit event stream → SIEM; requirements and controls
Comparison with the GitHub course
GitHub Lesson 6, Module 8 does the same thing (GHAS, rulesets, EMU, audit log streaming); you can put the two review templates side by side:GitHub Lesson 6.
mygroup-lab target architecture (Ultimate blueprint)
Review report template (excerpt)
| # | Finding | Risk | Recommendation (tier) | Compensating control (Free) | Owner / deadline |
|---|---|---|---|---|---|
| R1 | Personal PAT stored in CI variables | High | Service account + 30-day token (Free) / OIDC | Same as left | Platform group / 2 weeks |
| R2 | No push protection | High | Push protection (Ultimate) | gitleaks pre-commit + pipeline secret detection + jq gate | Security group / 1 month |
| R3 | Scans can be removed by projects | Medium | Scan execution policy (Ultimate) | CODEOWNERS protects CI files (Premium) | Security group / 1 month |
| R4 | No audit evidence | Medium | Audit events (Premium) + event streaming (Ultimate) | Export pipeline and MR records | Compliance / quarterly |
Interactive: governance maturity scorer
Check the controls mygroup-lab has already put in place to see each layer's score, the overall level, and the three “most worthwhile next steps” (with the required tier).
Read-only current-state collection script
cat > ~/gitlablab/governance_snapshot.sh <<'EOF'
#!/usr/bin/env bash
# Read-only: export mygroup-lab's key governance settings (requires GROUP_ID / PROJECT_ID / GL_GROUP)
set -u
echo "## Group"; glab api "groups/$GROUP_ID" | jq '{full_path, require_two_factor_authentication, two_factor_grace_period, visibility}'
echo "## Project push protection (Ultimate)"; glab api "projects/$PROJECT_ID/security_settings" 2>/dev/null | jq '{secret_push_protection_enabled}' || echo "n/a"
echo "## Protected branches"; glab api "projects/$PROJECT_ID/protected_branches" | jq -r '.[] | "\(.name) push=\(.push_access_levels|map(.access_level)|join(",")) merge=\(.merge_access_levels|map(.access_level)|join(","))"'
echo "## Service accounts"; glab api "groups/$GROUP_ID/service_accounts" 2>/dev/null | jq -r '.[]?.username' || echo "n/a"
echo "## Project CI variables (names only)"; glab api "projects/$PROJECT_ID/variables" | jq -r '.[] | "\(.key) masked=\(.masked) protected=\(.protected)"'
echo "## Group members (Owner=50)"; glab api "groups/$GROUP_ID/members?per_page=100" | jq -r '.[] | "\(.username) \(.access_level)"'
echo "## Recent audit events (Premium)"; glab api "groups/$GROUP_ID/audit_events?per_page=5" 2>/dev/null | jq -r '.[]? | "\(.created_at) \(.details.author_name) \(.details.custom_message // "-")"' || echo "n/a"
EOF
chmod +x ~/gitlablab/governance_snapshot.sh && ~/gitlablab/governance_snapshot.sh | tee ~/gitlablab/governance-$(date +%F).txt
## Group
{
"full_path": "mygroup-lab",
"require_two_factor_authentication": true,
"two_factor_grace_period": 48,
"visibility": "private"
}
## Project push protection (Ultimate)
{
"secret_push_protection_enabled": true
}
## Protected branches
main push=0 merge=40
## Service accounts
ticket_bot_87654321
The link status of the security policy project can be queried in GraphQL (field names per the reference), or viewed in the UI under “Security → Policies.” The script output contains no tokens or variable values, so it can be attached to the review report.
Enable push protection for the whole group in bulk (Ultimate)
The documentation explains that you can use the group security settings API to enable push protection for all projects in the group (for endpoints and parameters, see Group security settings API). To enable it project by project, use PUT /projects/:id/security_settings.
Lab 8: write a one-page review for mygroup-lab (about 8 min)
governance_snapshot.sh.docs/adr/0001-governance-baseline.md:
# ADR 0001: mygroup-lab security governance baseline Status: accepted (2026-11-16) Context: myapp is in regulated scope (SOC2-lab framework). Decision: 1. Enable push protection for all projects in the group (Ultimate). 2. Group-level scan execution policy: secret_detection + sast (all branch pipelines). 3. MR approval policy: any new secret or new Critical/High finding requires 1 approval from the security group, fail closed. 4. Automation uniformly uses service accounts, with 30-day tokens rotated automatically. 5. Stream audit events to the SIEM; a push protection bypass triggers an alert. Residual risk: policy project Owner permissions are concentrated; approval pressure when the scanning infrastructure fails. Review again: 2027-02.
Case 1: the policy project became a single point of failure
Problem: Only one security engineer could merge to the policy project; while he was on vacation, a scanner upgrade required policy changes, and MR approvals piled up company-wide. Approach: The policy project should have at least two Maintainers (security group), with changes requiring a second person's approval; the policy change process is written into the runbook.
Case 2: the review looked only at features, not at “who is Owner”
Problem: The audit found 9 Owners in the top-level group, 3 of which were accounts of departed employees (added before SCIM went live). Approach: No more than 3 Owners; export the member list in the quarterly access review; clean up legacy members after SCIM goes live; cap Owners' personal tokens at 30 days.
Case 3: a “good enough” approach for a Free-tier team
Problem: A 10-person startup team with no budget. Approach: Free blueprint + 30 minutes each week reviewing jq gate failures and artifacts; the review report states the residual risks and upgrade triggers (for example, “upgrade to Premium when the first enterprise customer requires SOC2; upgrade to Ultimate when an audit requires enforced policies”).
Interactive troubleshooting tree: security and governance “why isn't it working”
Common errors and fixes
Features still unavailable after upgrading / starting a trial
Cause: The trial or subscription is tied to a different top-level group; subgroups cannot start a trial on their own; browser cache. Fix: Group → Settings → Billing: confirm which group the plan belongs to.
Policies silently stop working after the trial ends
Note: Paid features stop working when the trial ends; this is expected. Prevention: Run trials only in lab groups; list “controls that depend on a paid tier” in the review.
1. With one command, output whether the group enforces 2FA and the grace period.
glab api "groups/$GROUP_ID" | jq '{require_two_factor_authentication, two_factor_grace_period}'2. List all Owners in the group (access_level 50).
glab api "groups/$GROUP_ID/members?per_page=100" | jq -r '.[] | select(.access_level==50) | .username'
The CTO asks: “We are on Premium—should we upgrade to Ultimate for push protection?” Give your answer in review style.
First quantify: over the past year, how many real secrets did pipeline secret detection (which runs on Free) find, and what did each rotation cost? Then look at what Ultimate brings beyond push protection: policy enforcement (scans cannot be removed, findings trigger approval), vulnerability reports, and audit event streaming—these are usually the “unbypassable” controls auditors focus on. If the only need is reducing secret leaks, first use gitleaks pre-commit + pipeline detection + a jq gate as compensating controls and accept the residual risk; if there are compliance audits, multiple teams, or an existing leak incident, the benefit of upgrading is clearer. Use a 30-day trial in a lab group to validate the false-positive rate and approval burden before deciding.
Verified instructional videos
Official documentation
- Application security
- Compliance
- Roles and permissions
- Tutorials: Secure your application and check compliance
Video storyboard script (about 60 seconds)
Visual: a six-layer stacked wall: identity, code entry, pipeline, finding handling, artifact deployment, evidence.
Narration: a governance review starts with the six-layer model; each layer must answer: what control, at which tier, and who is responsible.
Visual: three blueprint cards, Free, Premium, and Ultimate, flip open in turn; each has a line of red text at the bottom: “residual risk.”
Narration: each tier's plan must honestly state the residual risk and the compensating controls.
Visual: an ADR document is merged into the policy project as an MR.
Narration: decisions are written as ADRs; policy is code; changes are MRs.
Command cheat sheet
include: - component: $CI_SERVER_FQDN/components/sast/sast@3.5.0 - component: $CI_SERVER_FQDN/components/sast/iac-sast@3.5.0 - component: $CI_SERVER_FQDN/components/secret-detection/secret-detection@2.4.0 - component: $CI_SERVER_FQDN/components/dependency-scanning/main@2.1.1 # Ultimate - component: $CI_SERVER_FQDN/components/container-scanning/container-scanning@5.2.0 - template: Security/DAST.gitlab-ci.yml # Ultimate - template: Security/API-Security.gitlab-ci.yml # Ultimate
enable_mr_pipelines: true # sast / secret-detection / container-scanning historic_scan: true # secret-detection, one time run_advanced_sast: true # sast, Ultimate cs_image: $CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA max_scan_depth: 2 # dependency-scanning 2.x default DAST_TARGET_URL: http://myapp:5000 DAST_FULL_SCAN: "false" # true = active checks APISEC_PROFILE: Quick APISEC_OPENAPI: openapi.json APISEC_TARGET_URL: http://myapp:5000
glab api -X PUT projects/$PROJECT_ID/security_settings -f secret_push_protection_enabled=true glab api projects/$PROJECT_ID/security_settings | jq .secret_push_protection_enabled git push -o secret_push_protection.skip_all # bypass (audited) # In the commit message: [skip secret push protection] # Not checked: >1 MiB, binaries, first push, >3,150 paths or >350,000 lines
gl-sast-report.json gl-secret-detection-report.json gl-dependency-scanning-report.json gl-sbom-<type>-<pm>.cdx.json # dependency scanning SBOM gl-container-scanning-report.json gl-sbom-report.cdx.json # container scanning SBOM (name per documentation)
# .gitlab/security-policies/policy.yml
scan_execution_policy:
- name: …
enabled: true
rules: [{type: pipeline, branch_type: all}]
actions: [{scan: secret_detection}]
approval_policy:
- name: …
enabled: true
rules: [{type: scan_finding, branch_type: protected, scanners: [secret_detection],
vulnerabilities_allowed: 0, severity_levels: [critical, high],
vulnerability_states: [new_needs_triage]}]
actions: [{type: require_approval, approvals_required: 1, group_approvers: [mygroup-lab/security]}]
fallback_behavior: {fail: closed}
pipeline_execution_policy:
- name: …
enabled: true
pipeline_config_strategy: inject_policy
content: {include: [{project: mygroup-lab/security-policies, file: ci/policy-checks.yml}]}MR approval policies: ≤5 per policy project, ≤5 rules each Scan execution policies: ≤5 per policy project, ≤5 rules and ≤10 actions each (18.0+) Pipeline execution policies: 5 by default, can be raised to a maximum of 20 Compliance frameworks: ≤20 per project; ≤5 controls per requirement Audit stream targets: ≤20 custom headers each Service accounts: GitLab.com Free ≤100 per top-level group; Premium+ unlimited Tokens: expire in 365 days by default; reminders at 60/30/7 days
glab api "groups/$GROUP_ID/audit_events?created_after=2026-11-01T00:00:00Z" glab api "projects/$PROJECT_ID/audit_events" # Event stream header: X-Gitlab-Event-Streaming-Token (verified by the receiver); de-duplicate on payload.id # Compliance pipelines: deprecated in 17.3 → Compliance center “Migrate pipeline to a policy”
glab api -X POST groups/$GROUP_ID/service_accounts -f name="Bot" -f username=bot_x glab api -X POST groups/$GROUP_ID/service_accounts/$SA_ID/personal_access_tokens \ -f name=t -f "scopes[]=read_api" -f expires_at=2026-12-16 glab api -X POST groups/$GROUP_ID/service_accounts/$SA_ID/personal_access_tokens/$TID/rotate glab api "personal_access_tokens?state=active" | jq -r '.[]|"\(.expires_at) \(.name)"' # SAML SSO / SCIM / IP allowlist / domain restrictions: Premium (GitLab.com top-level group)
gitleaks git --pre-commit --staged --redact --verbose # block secrets locally trivy image --severity HIGH,CRITICAL --ignore-unfixed IMAGE # image vulnerabilities trivy fs --format cyclonedx --output sbom.cdx.json . # SBOM zap-baseline.py -t http://myapp:5000 -r zap.html # passive DAST jq -s '[.[].vulnerabilities[]?|select(.severity=="Critical" or .severity=="High")]|length' gl-*-report.json
Free : SAST · pipeline secret detection · container scanning (run + JSON) · service accounts
Premium : SSO/SCIM · audit events · compliance framework labels · IP/domain restrictions · approval rules
Ultimate : push protection · dependency scanning · DAST · API testing · MR findings · vulnerability reports
· security policies · requirements and controls · audit event streaming
Trial : Ultimate for 30 days, started by a top-level group OwnerCapstone lab + final quiz
You are the platform security engineer for mygroup-lab. The auditor requires: ① secrets must not enter the repository, and any exception must be recorded; ② MRs in all projects must run secret detection and SAST, and projects cannot turn them off; ③ any new secret or Critical/High finding requires security group approval before merge; ④ myapp is marked as a regulated project, with two-person approval continuously checked; ⑤ automation must not use personal tokens; ⑥ all of the above must have audit evidence.
security (with at least 1 member other than yourself); run security_ready.sh.Free route: skip the paid steps, and complete each step using the alternative in parentheses..gitlab-ci.yml includes sast, secret-detection (enable_mr_pipelines: true), the container-scanning component, and (Ultimate) dependency-scanning main@2.1.1.(Free: also add the security-gate from Module 1.).pre-commit-config.yaml and require installation in the README.)---
scan_execution_policy:
- name: Baseline scans on every pipeline
enabled: true
rules:
- type: pipeline
branch_type: all
actions:
- scan: secret_detection
- scan: sast
approval_policy:
- name: Zero tolerance for new secrets
enabled: true
rules:
- type: scan_finding
branch_type: protected
scanners: [secret_detection]
vulnerabilities_allowed: 0
severity_levels: [critical, high, medium, low, info, unknown]
vulnerability_states: [new_needs_triage]
actions:
- type: require_approval
approvals_required: 1
group_approvers: [mygroup-lab/security]
- type: send_bot_message
enabled: true
fallback_behavior:
fail: closed
- name: Critical and high need security approval
enabled: true
rules:
- type: scan_finding
branch_type: protected
scanners: [sast, dependency_scanning, container_scanning]
vulnerabilities_allowed: 0
severity_levels: [critical, high]
vulnerability_states: [new_needs_triage]
actions:
- type: require_approval
approvals_required: 1
group_approvers: [mygroup-lab/security]
fallback_behavior:
fail: closed
(Free / Premium: a shared CI template project + the include:project with a pinned ref; Premium uses CODEOWNERS to protect .gitlab-ci.yml.)SOC2-lab, apply it to myapp; (Ultimate) add the requirement “change review,” with the controls minimum_approvals_required_2 and scanner_sast_running; optional: pipeline execution policy inject_policy,policy_scope pointing to this framework.(Free: record the list of regulated projects in the README.)release_bot, issue a 30-day, minimal-scope token, and replace any personal token in CI variables; demonstrate one rotation.- on a new branch, use
printfto generate a fake token and push → blocked (screenshotPUSH BLOCKED). - Switch to
-o secret_push_protection.skip_allto push → succeeds; open an MR → the MR shows “Requires mygroup-lab/security approval,” and the bot comment lists the secret findings. - Remove the secret-detection include from the MR → the scan execution policy still injects the job, and the approval requirement is unchanged.
- Remove the fake-token commit (rebase + force-push the feature branch) → the new pipeline has no findings → the approval requirement is lifted (or close the MR after security group approval).
governance_snapshot.sh to archive; delete the demo branch (git push origin --delete feat/security-demo and temporary branches), close the demo MR, delete the service account (if no longer needed); decide whether to keep or delete the trial group before the trial expires.Open-ended self-check (6 questions)
1. Explain in one sentence to a non-technical manager why you would buy Ultimate when scanners can run on Free.
Free can find issues but produces a report nobody reads; Ultimate puts the findings into merge requests, into a trackable vulnerability list, and lets policies enforce “must scan, approve on findings,” while providing unbypassable evidence.
2. With push protection on, why do you still need pipeline secret detection and approval policies?
Push protection can be bypassed (push options / commit messages), and it intentionally does not check oversized pushes, files over 1 MiB, binaries, first pushes, and low-confidence formats; pipeline detection is the backstop for findings, approval policies force human handling before merge, and audit events make bypasses visible.
3. What are fail closed and fail open each suited for?
closed (default): requires approval when a scan is missing or fails, which prevents “remove the scan to avoid approval”; suited to production and regulated projects. open: only warns and does not block; suited to pilot periods or when the scanning infrastructure is not yet stable, but it must be paired with monitoring and have a deadline for switching back to closed.
4. What is the relationship between compliance pipelines and pipeline execution policies? What is the biggest pitfall when migrating?
Compliance pipelines were deprecated in 17.3; the replacement is pipeline execution policies (which can be scoped by compliance framework). The biggest pitfall is coexistence in the same project: the compliance pipeline replaces the project pipeline while the policy is still applied to the original pipeline, causing duplicates, failures, or missed checks. Follow the documentation: generate the policy with the migration button, then remove the compliance pipeline.
5. Why does “SSO enforcement is on” not mean “all access goes through SSO”?
Web enforcement does not cover tokens, deploy keys, Git activity from CI jobs, or the API; you also need to enable Git and Dependency Proxy enforcement, disable password authentication for enterprise users, limit token lifetimes, and manage machine access with service accounts and OIDC.
6. On the Free tier, which three controls give you the most benefit? What is the residual risk of each?
① Service accounts + tokens with expiry dates (residual: still long-lived credentials; requires rotation discipline); ② scan components + jq gate + “pipeline must succeed” (residual: a Maintainer can remove the gate); ③ gitleaks pre-commit + pipeline secret detection (residual: the client side can be skipped, and the secret may already be in history). Add OIDC deployment to eliminate long-lived cloud keys.
Sources and version notes
Source
| Topic | Source | Verified on | Facts used in this lesson |
|---|---|---|---|
| SAST | docs.gitlab.com/user/application_security/sast | 2026-11-16 | Tier: Free / Premium / Ultimate; Free includes open-source analyzer scanning and JSON reports; Ultimate includes Advanced SAST, new findings in MRs, vulnerability management, and rule customization; Semgrep, PMD-Apex, Sobelow, SpotBugs, Kubesec (disabled by default) |
| Pipeline secret detection | …/secret_detection/pipeline | 2026-11-16 | Free/Premium vs Ultimate feature table; job secret_detection; gl-secret-detection-report.json; SECRET_DETECTION_HISTORIC_SCAN; MR pipeline scans all commits on the branch |
| Push protection | Secret push protection · Tutorial | 2026-11-16 | Ultimate; GitLab.com / self-managed / Dedicated; enabling roles; blocking output text; skip_all push options and [skip secret push protection]; audit event content; limits such as 1 MiB, binaries, first push, 3,150 paths / 350,000 lines; high-confidence rules only |
| Automatic response | Automatic response to leaked secrets | 2026-11-16 | Ultimate, public projects only; GitLab PAT revoked immediately with an email notification; AWS / Google Cloud / Postman notify the vendor |
| Security settings API | Project security settings API · Group | 2026-11-16 | PUT /projects/:id/security_settings,secret_push_protection_enabled (renamed from pre_receive_secret_detection_enabled in 17.11); Ultimate |
| Dependency scanning | Dependency scanning · by using SBOM | 2026-11-16 | Ultimate; Gemnasium deprecated in 17.9, planned removal in 20.0; SBOM-based approach GA in 19.0; malicious package matching GA in 19.5; Jobs/Dependency-Scanning.v2.gitlab-ci.yml; artifact naming; Python lock-file support matrix; manifest fallback reports only direct dependencies |
| Container scanning | Container scanning | 2026-11-16 | From Free; Trivy; CycloneDX (gl-sbom-report.cdx.json); only Ultimate has MR / Security tab / dependency list / remediation suggestions; CS_IMAGE,CS_REGISTRY_USER defaults; registry container scanning is Ultimate |
| DAST / API testing | DAST · Variables · API security testing | 2026-11-16 | Ultimate; proxy-based DAST deprecated in 16.9, removed in 17.3; Security/DAST.gitlab-ci.yml,dast stage; DAST_TARGET_URL or environment_url.txt; DAST_FULL_SCAN default false; DAST_CRAWL_TIMEOUT default 24h; API analyzer renamed in 17.0; APISEC_*; Quick profile |
| Security policies | Policies and the three policy-type subpages | 2026-11-16 | five policy types (including dependency firewall); .gitlab/security-policies/policy.yml; link roles; approval policy rule types,fallback_behavior (default closed); approval required when a scan is missing; 5 per project, 5 rules each; scan execution policy scan values, 5 policies, 10 actions (18.0+); job names get a sequence number appended; injected even without a CI file; dependency_scanning defaults to v2 from 19.1; pipeline execution policy inject_policy / inject_ci (deprecated in 17.9) / override_project_ci, reserved stages, default 5 (max 20), access permission requirements |
| Compliance | Compliance frameworks · Compliance pipelines | 2026-11-16 | framework Premium, requirements and controls Ultimate; creating roles; 20 per project; default framework; 5 controls per requirement; external controls 12 hours / 6 hours; compliance pipelines deprecated in 17.3, migration button, risk of coexistence with policies |
| Auditing | Audit events · Streaming · API | 2026-11-16 | Premium; Free has only successful sign-in events; retained indefinitely; event streaming Ultimate (HTTP / GCP Logging / S3),X-Gitlab-Event-Streaming-Token, 20 custom headers, GitLab.com IP ranges,id de-duplication; API endpoints and role visibility |
| Identity | SAML SSO · Access and permissions | 2026-11-16 | Premium, GitLab.com top-level group; the two enforcement switches and their coverage; 24-hour / 7-day sessions; disabling password authentication for enterprise users (17.4+); SCIM with the IdP; IP restriction coverage, hosted runner exceptions, and registry / LFS impact; domain restrictions |
| Tokens and service accounts | PAT · Project access tokens · Service accounts · API | 2026-11-16 | Default 365 days, adjustable since 17.6, 400-day feature flag; reminders 7 / 30 / 60 days; project access tokens on GitLab.com require Premium+ (1 during trial); service accounts GA in 18.11 on Free, ≤100, no seat, cannot sign in to the UI; API endpoints and default rotation of one week |
| Roles | Roles and permissions | 2026-11-16 | Default roles include Planner, Security Manager (18.11 beta, enabled on GitLab.com) |
| Trial | Free trials | 2026-11-16 | Ultimate trial for 30 days, counted from receipt of the confirmation email; GitLab.com requires top-level group Owner; paid features are lost after it ends |
| Component versions | Releases / Tags of each project under gitlab.com/components (API query) | 2026-11-16 | sast 3.5.0 (2026-09-25), secret-detection 2.4.0 (2026-08-12), dependency-scanning 2.1.1 (2026-07-29, component main), container-scanning 5.2.0 (2026-02-05); component inputs taken from the corresponding version's templates/ file; dependency-scanning 2.0.0 release notes |
| Open-source tools | GitHub Releases (gitleaks, trivy, zaproxy) | 2026-11-16 | gitleaks v8.30.1, Trivy v0.76.2, ZAP 2.17.0 |
| GitLab version | docs.gitlab.com/releases(carried over from verification in Lessons 1–4) | 2026-11-16 | GitLab 19.5 (patch 19.5.6); 19.6 not released; glab v1.130.0 |
| Related courses | GitHub Lesson 6 · Azure DevOps Lesson 6 · Git Lesson 4 | — | How the same topics are handled on other platforms; repository-side basics |
Video verification notes
All listed videos were verified on 2026-11-16 via YouTube oEmbed (https://www.youtube.com/oembed?url=…&format=json) for title and channel:
- New GitLab Security Dashboard (18.9): Vulnerability Management & Risk Scoring — GitLab
- Vulnerability report - The basics (HD) — GitLab
- Introduction to Secret Push Protection — GitLab Unfiltered
- Configuration - Enabling Secret Push Protection for your project — GitLab Unfiltered
- Secret Push Protection - Scan diffs instead of entire file — GitLab Unfiltered
- GitLab 17 - Secret Detection Updates including Push Protection — GitLab
- How to Enable Dependency Scanning and Manage SBOMs in GitLab 19 — GitLab
- How to set up Container Scanning using GitLab — GitLab Unfiltered
- How to Scan Multiple Container Images with a Single GitLab Pipeline — GitLab
- How to set up Dynamic Application Security Testing (DAST) with GitLab — GitLab Unfiltered
- Tutorial: Setting up DAST with Authentication — GitLab Unfiltered
- DAST On Demand - Advanced Security Testing (HD) — GitLab
- Creating security policies - The basics (HD) — GitLab
- Overview of GitLab Scan Result Policies — GitLab Unfiltered
- Security Policies: Pipeline Execution Policy Type — GitLab Unfiltered
- Using GitLab Security Policies to Enforce Vulnerability Management SLAs — GitLab Unfiltered
- GitLab's Compliance Framework Explained | DevSecOps Automation — GitLab
- GitLab 17.2 - Assuring Compliance with Pipeline Execution Policies — GitLab
- Demo: Streaming audit events from GitLab to AWS S3 — GitLab Unfiltered
- Exploring a few use cases for Streaming Audit Events for Compliance Purposes — GitLab Unfiltered
- SSO/SCIM Walkthrough with OneLogin and GitLab SaaS — GitLab Unfiltered
- Service Accounts UI Walkthrough — GitLab Unfiltered
- View Expiring Personal Access Tokens in GitLab — GitLab Unfiltered
- SAML vs. SCIM — C1
- Managing Security Vulnerabilities with the GitLab Security Dashboard (DevSecOps) — GitLab
- Thales & GitLab: A DevSecOps Case Study — GitLab
- GitLab Security- Golden Rules for Troubleshooting Vulnerability Reports — GitLab Unfiltered
Older recordings (labeled 16.x / 17.x or “HD” older demos) may show UI and names that have changed (for example, “Scan result policy” was renamed “merge request approval policy” and proxy-based DAST was removed); follow the 19.x facts verified in this lesson. Each module has a storyboard script.
Audio note
The “Audio” page uses the browser's built-in Web Speech API: Chinese narration uses the zh-CN voice, and English terms use the en-US voice. Without a Chinese voice pack, the narration script can still be read directly or handed to another TTS tool.
Known limitations
- When this courseware was written,these commands, policies, and pipelines were not run in a real GitLab.com group (including an Ultimate trial); all output (job logs, API responses, bot comments, audit events) is an “example” constructed from the official documentation, and IDs, SHAs, dates, and usernames are placeholders. The push protection blocking output follows the format from the official documentation and tutorials.
- The removal version of compliance pipelines appears in two forms on the same official page (“planned for removal in 20.0” and “will be removed in GitLab 19.0” in the migration section); as of GitLab 19.5 the documentation page still exists, and this lesson treats it as “deprecated, migrate soon.”
- The official dependency scanning documentation's component example still shows
dependency-scanning/main@1, while the latest component project release is 2.1.1 (2.0.0 changed input names and defaults); this lesson pins 2.1.1 and lists the changes; refer to the component README. - The SBOM file produced by the container scanning component uses the wildcard
**/gl-sbom-*.cdx.json, and the filename in the documentation isgl-sbom-report.cdx.json; follow the actual artifact. - In the policy YAML,
branch_type: all,group_approverspath syntax, severity enums, and similar details are validated by the policy editor's schema; the documentation does not provide a single example containing all fields, so this lesson's examples are composed according to the schema. - For the GraphQL examples (vulnerability query,
securityPolicyProjectAssign, compliance framework query), follow the GraphQL reference for field names; the audit event stream verification token can only be set via GraphQL, and this lesson does not give a specific mutation. - The Security Manager role is beta; the description of the maximum token lifetime tier has two versions in the PAT documentation (“configurable by Ultimate administrators” and “administrators can modify since 17.6”), and this lesson presents both.
- For the job names of the API security testing template and the rules that come with the DAST template, follow the “full configuration” view; for the ZAP report directory convention, follow the ZAP documentation.
- Dependency firewall is a newer policy type; this lesson only introduces it and gives no configuration example.