GitLab Hour 6: Security and Governance in Practice

First, make the boundary clear: scanners can run on the Free tier, but making results governable (MR widget, vulnerability reports, policy enforcement) requires Ultimate. Then walk through myapp: push protection → SAST / Secret Detection → dependency and container scanning + SBOM → DAST / API testing → security policies → compliance frameworks and audit streams → identity governance → a complete governance architecture review
GitLab.com · GitLab 19.5Official CI/CD componentsMost governance features require UltimateEvery item has a Free tier alternativeVerified against official docs · 2026-11-16
Overall learning objectives
  • 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 BLOCKED rejected; 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

#TimeModuleCore contentAnimation / interactionLab (mygroup-lab/myapp)
0Before classSecurity scanning sample projectUltimate trial (30 days) or Free route, sample vulnerable branch, environment variables and readiness checkTier self-checkfeat/security-demo Branch
100–06Security scanning overview and tiersScanner × tier matrix; “can run” ≠ “can govern”; report artifacts; security configuration page; Security Manager roleTier matrix explorerView the security configuration page and report artifacts
206–13SAST, Secret Detection, and push protectionSemgrep analyzer vs Advanced SAST; pipeline secret detection; push protection blocking, bypass, and auditingCore animation: secret push → block → bypass → pipeline finding → approval policyPush fake token is blocked
313–21Dependency scanning, container scanning, and SBOMSBOM-based dependency scanning (Gemnasium deprecated), Trivy container scanning, CycloneDX, dependency listSBOM pipeline simulationScan myapp:1.0 Image
421–28DAST and API security testingBrowser DAST (proxy DAST removed), target environments, authentication, API security testing, and OpenAPIDAST crawling and attack simulationRun DAST against a temporary environment
528–35Security policiesSecurity policy project, scan execution policy, MR approval policy (fail closed), pipeline execution policy, vulnerability management policyApproval policy evaluatorGroup-level policy enforces secret_detection
635–42Compliance frameworks, compliance pipelines, and audit eventsFramework labels, requirements and controls, compliance center, compliance pipeline deprecation and migration, audit event API and event streamingAudit event stream deliveryCreate a framework + query audit events
742–50Identity governanceSAML SSO / SCIM, SSO enforcement, token lifetime, service accounts, IP allowlists, domain restrictionsAccess request evaluatorService accounts + token rotation
850–60Governance architecture reviewLayered control model, Free / Premium / Ultimate three-tier options, review checklist and troubleshooting treeGovernance maturity scoring + interactive troubleshooting treeProduce the review report
—After classCheat sheet · Capstone labImplement “push protection + group policies + approvals + audit streaming + token governance” for mygroup-labFinal quiz (12 questions)Capstone lab

Knowledge Coverage Matrix

Target skillsM1M2M3M4M5M6M7M8Key commands / keywordsLab
Explain the tier required for each security capability✓✓✓✓✓✓✓✓Tier matrixM1
Connect scanners using official components✓✓✓·····include: componentM2 / M3
Push protection: enable, block, bypass, and audit·✓··✓✓·✓PUT /projects/:id/security_settingsM2
Dependency / container scanning and SBOM··✓·✓··✓gl-sbom-*.cdx.json,CS_IMAGEM3
DAST / API security testing···✓✓···DAST_TARGET_URL,APISEC_OPENAPIM4
Security policy as code·✓··✓✓·✓.gitlab/security-policies/policy.ymlM5
Compliance frameworks and auditing····✓✓✓✓GET /groups/:id/audit_eventsM6
Identity and token governance·····✓✓✓POST /groups/:id/service_accountsM7
Free tier alternatives✓✓✓✓✓✓✓✓jq gates, gitleaks, trivy, ZAPModules

Topics not covered in this lesson (and where to learn them)

TopicWhy not in this lessonWhere to learn
Basics of protected branches, MR approval rules, push rules, and CODEOWNERSRepository-side basics were covered in the Git course; this lesson only shows how security policies add a layer on topGit Lesson 4 (GitLab repository side) · Lesson 1
Writing and publishing CI/CD components, include merge rulesLesson 2 covers usage; Lesson 5 covers publishingLesson 2 · Lesson 5
OIDC and short-lived cloud credentialsCovered in Lessons 3 and 4; this lesson only references it in identity governanceLesson 3 (Azure) · Lesson 4 (AWS)
Runner hardening, admin setup for self-managed instances, API rate limitingBelongs to operations and scalingLesson 7
How the same topics are handled in GitHub (Advanced Security, rulesets, EMU)This lesson covers GitLab only; read the comparison for referenceGitHub Lesson 6 (security and governance) · Azure DevOps Lesson 6
Image hardening, signing, and runtime securityBelongs to the container and cluster topicsDocker Lesson 6 · K8s course
GitLab Duo vulnerability explanation / remediation and AI governanceRequires an additional Duo subscription or credits; changes quicklyGitLab Duo documentation

How to use this courseware

10 pages per module
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.
Two lab routes
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”.
Learning progress and audio
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).
Cost and safety notes This lesson creates no cloud resources; the cost is mainly GitLab-hosted runner compute minutes: each full security pipeline runs about 6–10 jobs. For the Free tier's monthly quota, seeLesson 2. The Ultimate trial lasts 30 days from receipt of the activation email; afterward, paid features stop working automatically (policies are no longer enforced, but project data is kept). Never push real tokens to any repository, all “leaks” in this lesson use fake tokens assembled at runtime; the DAST in Module 4 targets only your own temporary environment,never scan production or other people's sites.
Version notes (verified 2026-11-16) GitLab.com runs GitLab 19.x (latest released 19.5, patch 19.5.6; 19.6 not yet released). Latest official security component versions: 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)

Decide between the Ultimate trial and the Free route, create an intentionally flawed branch on myapp, and extend the readiness check script
Before class ≈ 10 minglab · jq · git
Prerequisites
  • CompletedLesson 1(group mygroup-lab: private, 2FA enforced, subgroups platform; main protected, push: no one, merge: Maintainer) andLesson 2(.gitlab-ci.yml, release tags v1.0, images registry.gitlab.com/mygroup-lab/myapp:1.0, referenced secret-detection@2.4.0 and sast@3.5.0 components, “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 itIn mygroup-lab 's “Settings → Billing” start the Ultimate trial; requires Owner of the top-level group; 30 days, counted from receipt of the confirmation emailNo action needed
Labs you can doAll 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”
NoteDuring 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 groupAudit events are limited to one category, “successful sign-in”; there is no SSO / SCIM
Recommendation If your real group will be used long-term, create a dedicated top-level group (for example 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
For demonstration onlydemo/ 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

FromReused in this lessonNew in this lesson
Lesson 1group mygroup-lab, protected main, CODEOWNERS, merge checksSecurity policies add “security approval” on top of approval rules
Lesson 2secret-detection@2.4.0,sast@3.5.0 components; docker:29 builds; images :1.0dependency scanning and container scanning components; report artifacts and gates
Lessons 3 and 4id_tokens, protected tags v*, environments dev/prodDAST 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).

Environment self-check checklist

Module 1 · GitLab security scanning overview and tiers

00:00 – 06:00 · “Scanners can run” and “results can be governed” are two different things—the former is mostly on Free, the latter almost entirely on Ultimate
6 minFree: SAST · Secret Detection · Container ScanningUltimate: MR findings · vulnerability reports · policies★★★★★
Learning objectives
  • 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”.
Prerequisites: Components and report artifacts from Lesson 2. Importance:★★★★★ (the map for the whole course)

What: scanner families and minimum tiers (verified 2026-11-16 against the Tier line on each feature's documentation page)

CapabilityWhat it findsMinimum tierCurrent recommended integrationReport artifact
SASTDangerous patterns in source codeFree (GitLab Advanced SAST requires Ultimate)Component components/sast/sast@3.5.0 or template Jobs/SAST.gitlab-ci.ymlgl-sast-report.json
IaC scanningMisconfigurations such as in Terraform / K8s manifestsFreeComponent components/sast/iac-sast@3.5.0SAST report format
Pipeline Secret DetectionSecrets committed to the repositoryFreeComponent components/secret-detection/secret-detection@2.4.0gl-secret-detection-report.json
Secret push protectionHigh-confidence secrets in a push (blocked before the push is accepted)UltimateProject “Security configuration” toggle / APINone (push rejected) + audit events
Dependency scanning (SBOM-based)Known vulnerabilities and malicious packages in third-party dependenciesUltimateComponent components/dependency-scanning/main@2.1.1 or template Jobs/Dependency-Scanning.v2.gitlab-ci.ymlgl-sbom-*.cdx.json,gl-dependency-scanning-report.json
Container scanning (Trivy)OS / language package vulnerabilities in imagesFree (MR / Security tab / dependency list require Ultimate)Component components/container-scanning/container-scanning@5.2.0gl-container-scanning-report.json, CycloneDX SBOM
DAST (browser)Running web applicationsUltimateTemplate Security/DAST.gitlab-ci.ymlDAST report
API security testingREST / GraphQL / SOAP APIsUltimateTemplate Security/API-Security.gitlab-ci.ymlDAST report format
Security policies (scan execution / MR approval / pipeline execution / vulnerability management / dependency firewall)Enforce scans, require approvals, inject jobsUltimateSecurity policy project—
Compliance frameworkTag projects as “regulated”Premium (requirements and controls, and policy enforcement, require Ultimate)Compliance center—
Audit events / audit event streamingWho changed what, and whenPremium / UltimateSecurity → 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):

CapabilityFree & PremiumUltimate
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

  1. 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 with artifacts:reports:sast / secret_detection / container_scanning / cyclonedx etc.
  2. 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.
  3. 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

ActionRequired role (default)
Enable push protection for a projectSecurity Manager, Maintainer, or Owner
Link a security policy project to a group / projectOwner of the target, or a custom role with manage_security_policy_link permission
Create a compliance frameworkOwner 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 codeSecurity Manager (introduced as beta in 18.11; enabled on GitLab.com)
Common misconceptions① “We're on Free, so we have no security scanning”—SAST, secret detection, and container scanning all run on Free. ② “A high-severity scanner finding will fail the pipeline”—by default, 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

CapabilityGitLabGitHubAzure DevOps
Secret push blockingSecret push protection (Ultimate)Secret Protection push protection (free for public repositories, paid for private)GitHub Advanced Security for Azure DevOps
SASTSemgrep analyzer (Free) / Advanced SAST (Ultimate)CodeQL (Code Security)GHAzDO CodeQL
Policy as codeSecurity policy project (YAML)Rulesets + required workflowsBranch policies
Seethis lessonGitHub Lesson 6Azure DevOps Lesson 6

Run → Present → Govern

① Run layer (mostly Free) semgrep-sast (SAST)secret_detectioncontainer_scanning (Trivy) dependency-scanning (Ultimate)dast / api security (Ultimate) ↓ JSON with a unified schemaartifacts:reports:*Free: can only download artifacts→ write your own jq gate ② Present layer (Ultimate) MR report: source vs target, showing only “new” findingsPipeline “Security” tabVulnerability report (default branch)Dependency list (SBOM)Security dashboard Vulnerability status: needs triage / confirmed/ dismissed (comment required) / resolved ③ Govern layer Scan execution policy (Ultimate)MR approval policy (Ultimate)Pipeline execution policy (Ultimate)Compliance framework (Premium+)Audit events (Premium) / streaming (Ultimate) SSO / SCIM / IP allowlist (Premium)Push protection (Ultimate)
Figure 1-1: the same JSON report has a completely different fate at each of the three tiers

Where scanners sit in the SDLC

git pushPush protection test stageSAST · secrets · dependencies After buildContainer scanning + SBOM Deploy to review/devDAST · API testing Before MR mergeApproval policy compares against new findings The further left, the cheaper: push protection keeps the secret “from ever entering the repository”, whereas a pipeline finding means it must be rotated
Figure 1-2 Shift left: each control point catches different problems

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.

Select a tier and click a capability.
# Explanation will appear here

Core commands: see the project's current security status

CommandPurposeTier
glab ci view / glab ci listView pipelines and scan jobsFree
glab api projects/:id/jobs/:job_id/artifacts/gl-sast-report.jsonDownload a single report fileFree
glab api projects/:id/security_settingsView security settings such as push protectionUltimate
glab api graphql -f query='…vulnerabilities…'Query vulnerability reportsUltimate
glab api groups/:id/audit_eventsGroup audit eventsPremium
# 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)

Open the security configuration page: Project → Security → Security configuration. Record whether each scanner shows “Enabled / Not enabled / Upgrade required”. Lesson 2 already integrated SAST and Secret Detection with components, so they should show as enabled here (based on the most recent default-branch pipeline).
Open an MR for the demo branch:
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
Compare what each route shows:
  • Ultimate trial: the MR page shows a “security scanning” section listing new SAST findings (subprocess shell=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.
Free alternative: jq gate job (turns the “JSON file” into a pipeline red/green result):
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.

Verify Free route: in the MR pipeline 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).

Command-line questions
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
Scenario analysis
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

▶
New GitLab Security Dashboard (18.9): Vulnerability Management & Risk Scoring — GitLab
English · Present layer: new security dashboard and vulnerability risk scoring
▶
Vulnerability report - The basics (HD) — GitLab
English · Basic vulnerability report operations (the interface may differ slightly from 19.x)

Official documentation

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.

Shot 1 · 0–20s
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.
Shot 2 · 20–40s
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.
Shot 3 · 40–60s
Visual: a three-layer pyramid: run, present, govern.
Narration: remember the three-layer model: “can run” does not mean “can govern.”
or score ≥ 70% on the quiz

Module 2 · SAST, Secret Detection, and push protection

06:00 – 13:00 · Keeping a secret “from ever entering the repository” is the cheapest option; once it's in, only “detect + rotate + approve” remain
7 minSAST / pipeline secret detection: FreePush protection: Ultimate★★★★★
Learning objectives
  • Use sast@3.5.0 and secret-detection@2.4.0 components 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.
Prerequisites: Component inputs from Lesson 2. Importance:★★★★★

What: three checkpoints

Secret push protectionPipeline Secret DetectionSAST
When it runsPre-receive check on git push (HTTP(S) and SSH)CI job after the push secret_detectionCI jobs (semgrep-sast,gitlab-advanced-sast , etc.)
Scan scopeScans only the diff of this push, using only high-confidence rulescommits on the branch in an MR; the latest commit on the default branch; a one-time full history scan is possibleWorking-tree source code
When a finding is detectedthe push is rejected, the secret never enters the repositorySecret already in history → must rotateCode defect → fix
TierUltimateRuns on Free; MR / Security tab / vulnerability management require UltimateFree (Advanced SAST and custom rulesets require Ultimate)
How to enableSecurity configuration toggle / PUT /projects/:id/security_settings / group security settings APIComponent, template Jobs/Secret-Detection.gitlab-ci.yml or scan execution policyComponent, 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:line and 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

AnalyzerCoverageTierComponent input
Semgrep-based (GitLab-managed rules)Python, JS/TS, Go, Java, C#, and most other languagesFreeDefault
GitLab Advanced SASTCross-file, cross-function taint analysis (C, C++, C#, Go, Java, JS, Python, TS, etc.)Ultimaterun_advanced_sast: true (C/C++ additionally has run_advanced_sast_cpp)
PMD-Apex, Sobelow, SpotBugsApex, Elixir, Groovy/JavaFreeAutomatically selected
KubesecK8s manifestsFreerun_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), pass true, otherwise the MR report will be missing data.
Common misconceptions① “Once the push is blocked, we're safe”—a bypass takes only one push option, so auditing and a pipeline backstop are required. ② “Deleting the commit containing the secret is enough”—you must first rotate / revoke it, and only then clean up the history. ③ “Push protection scans the whole repository”—it scans only the diff of this push; old secrets require a history scan. ④ “SAST findings block merges”—only approval policies or a gate you write yourself do.

Defense in depth: the four checkpoints a secret must pass through

Developer(Free) gitleakspre-commit hook Push protectionPre-receive · diff onlyPUSH BLOCKED Pipeline secret detectionsecret_detectiongl-secret-detection-report MR approval policyscan_finding · zero toleranceRequires security group approval mainProtected Audit eventsBlock · bypass (skip_all / [skip secret push protection]) · skipped due to limits→ audit event stream → SIEM alert (Module 6) Once in the repository:① revoke / rotate immediately ② clean up history ③ dismiss or resolve the vulnerabilityPublic project + Ultimate: GitLab PAT is automatically revoked
Figure 2-1: every checkpoint can be bypassed or miss something, which is why the next checkpoint is needed

How MR reports show only “new” findings

Latest report for the target branch mainFindings set A (baseline) MR source branch pipeline reportFindings set B Shown in the MR: B − ACompared by fingerprint; approval policies are also based on it Without a baseline (main has never been scanned successfully), the comparison is incomplete—first run a
Figure 2-2: new findings = source branch findings − target branch 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).

Developergit commitgit push Push protectionpre-receiveDiff · high-confidence rules Repository + auditCommit writtenAudit event Pipelinesecret_detectionMR report / gate MR approval policySecurity group approval→ Merge
Select a scenario to begin.
$ # Terminal output

Core commands

Command / configurationPurposeTier
glab api -X PUT projects/:id/security_settings -f secret_push_protection_enabled=trueEnable push protection (parameter name since 17.11; old name pre_receive_secret_detection_enabled)Ultimate, Maintainer+
git push -o secret_push_protection.skip_allBypass push protection (records audit event)—
[skip secret push protection]Bypass by writing in any commit message (Web IDE and other clients)—
historic_scan: trueComponent input: scan the entire history onceFree
run_advanced_sast: trueComponent input: enable GitLab Advanced SASTUltimate
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)

Safety convention Fake tokens are assembled at runtime by 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.
(Ultimate) enable push protection: in the UI, Security → Security configuration → Secret push protection turn it on, or run the command from the previous page: glab api -X PUT ….
Generate a fake token and commit it:
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'
The correct fix: rewrite the local commit (the secret has not reached the remote, so no rotation is needed):
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).

(observe the cost of a bypass) On another temporary branch, repeat step 2, but use 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_detection The 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.
After the lab, delete this temporary branch: git push origin --delete <branch>.
Free route: there is no push protection, so the push succeeds; after installing the gitleaks hook from the previous page and repeating step 2, the commit is rejected locally. Then, in the MR pipeline, check the 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
Verify remote branch 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.

Command-line questions
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]
Scenario analysis
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

▶
Introduction to Secret Push Protection — GitLab Unfiltered
English · the first video in the playlist referenced by the official documentation
▶
Configuration - Enabling Secret Push Protection for your project — GitLab Unfiltered
English · enabling push protection
▶
Secret Push Protection - Scan diffs instead of entire file — GitLab Unfiltered
English · why only diffs are scanned
▶
GitLab 17 - Secret Detection Updates including Push Protection — GitLab
English · feature overview from the 17.x era (for 19.x facts, follow this lesson)

Official documentation

Video storyboard script (about 60 seconds)

Shot 1 · 0–15s
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.
Shot 2 · 15–40s
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.
Shot 3 · 40–60s
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.
or score ≥ 70% on the quiz

Module 3 · Dependency scanning, container scanning, and SBOM

13:00 – 21:00 · First generate a “bill of materials” (CycloneDX SBOM), then compare the list against advisories—this is the underlying model shared by the new generation of dependency scanning and container scanning
8 minDependency scanning: UltimateContainer scanning (Trivy): FreeCycloneDX★★★★☆
Learning objectives
  • 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.1 to 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.0 to scan the image built in Lesson 2, and read CS_IMAGE, registry authentication, and CycloneDX output; know how to use Trivy as the local alternative on the Free tier.
Prerequisites: Image build from Lesson 2 (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 targetLock files / dependency graph exports in the repository (application dependencies, including transitive dependencies)Built images (OS packages + language packages)
EngineDependency Scanning analyzer v2: generates an SBOM → compares it against the GitLab advisory database and malicious package advisoriesTrivy (analyzer image security-products/container-scanning:8)
Outputsone per lock file gl-sbom-<package-type>-<package-manager>.cdx.json (placed next to the source file) + gl-dependency-scanning-report.jsongl-container-scanning-report.json + CycloneDX SBOM (the filename in the documentation is gl-sbom-report.cdx.json)
TierUltimateFree; MR / Security tab / dependency list / auto-remediation suggestions require Ultimate; “registry container scanning” requires Ultimate
Recommended integrationComponent dependency-scanning/main@2.1.1 or template Jobs/Dependency-Scanning.v2.gitlab-ci.ymlComponent 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 myappHow the scanner handles itAccuracy
poetry.lock,uv.lock,Pipfile.lock,pipdeptree.json,pipenv.graph.jsonparsed directly into a dependency graph (supports static reachability)Highest: exact versions + transitive dependencies
pip-compile The generated requirements.txttreated 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.lockNot 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 input cs_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_strategy default none (does not check out code); when you need remediation suggestions or an allowlist, change it to fetch.
  • Component job container_scanning with allow_failure: true, artifacts access: '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_enabled settings).
  • Images already pushed to the registry and not rebuilt for a long time: Ultimate's “registry container scanning” runs automatically when a latest tag is pushed on the default branch.
Common misconceptions① “Container scanning scans my Python code”—it scans the packages installed in the image and does not analyze source code. ② “Dependency scanning is also on the Free tier”—dependency scanning is Ultimate; on the Free tier you can use container scanning (which covers the Python packages installed in the image) or local Trivy. ③ “A requirements.txt is enough”—without a lock file you see only direct dependencies, and vulnerabilities in transitive dependencies are missed. ④ “An SBOM is a vulnerability report”—an SBOM is only an inventory; vulnerabilities are the result of comparing that inventory against advisories.

SBOM-driven scanning pipeline

Repositoryrequirements.txtuv.lock / poetry.lock Dependency resolution (optional)Generate dependency graph when there is no lock fileOtherwise, manifest fallback dependency-scanninggl-sbom-pypi-pip.cdx.jsongl-dependency-scanning-report.json build jobdocker:29 + dindpush :sha tag CS_IMAGE = $CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA container_scanningTrivy (gtcs scan)Report + CycloneDX SBOM GitLab (Ultimate) GitLab advisory database + malicious package advisories→ new MR findings / vulnerability report→ dependency list (project / group)→ license approval policy→ continuous scanning when new advisories are published Free: artifacts only→ local analysis with jq / Trivy
Figure 3-1: both scanners produce CycloneDX; the SBOM is the common language

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.

Select a scenario to begin.
# Job log

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)

On the demo branch, add the two components (snippets from the previous page), and keep 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
Observe the dependency scan: the job log shows the files found and how they were parsed:
[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.

Observe the container scan: download 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
(Ultimate) view in the UI: MR → the Security section shows “Dependency scanning: 1 new”; project → Security → Dependency list (data appears only after merging into main).
(Optional) improve accuracy: use 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.
Verify Dependency scanning reports at least 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.

Command-line questions
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.json
2. 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
Scenario analysis
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

▶
How to Enable Dependency Scanning and Manage SBOMs in GitLab 19 — GitLab
English · SBOM dependency scanning matching this lesson's version
▶
How to set up Container Scanning using GitLab — GitLab Unfiltered
English · container scanning configuration
▶
How to Scan Multiple Container Images with a Single GitLab Pipeline — GitLab
English · multi-image scanning

Official documentation

Video storyboard script (about 60 seconds)

Shot 1 · 0–20s
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.
Shot 2 · 20–45s
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.
Shot 3 · 45–60s
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.
or score ≥ 70% on the quiz

Module 4 · DAST and API security testing

21:00 – 28:00 · SAST reads code; DAST attacks the “running application”—so the first question is always: which environment will be scanned, who approves it, and could it damage data?
7 minDAST / API security testing: UltimateBrowser DAST (v5)Proxy-based DAST was removed in 17.3★★★☆☆
Learning objectives
  • 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.yml to run against myapp's temporary instance (CI services) to run a passive scan, and understand DAST_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: Quick to run API security testing; know that the Free tier can use OWASP ZAP as an alternative.
Prerequisites: From Lessons 3/4, the dev environments and Lesson 2's service containers. Importance:★★★☆☆

What: two analyzers

Browser DASTAPI security testing
TargetWeb applications (including SPAs): use a headless browser to crawl pages, forms, and linksREST, SOAP, GraphQL, and form / JSON / XML request bodies
InputDAST_TARGET_URL or the file in the job directory environment_url.txteach scan uses one specification: OpenAPI v2/v3, GraphQL schema, HAR, Postman Collection v2.0/v2.1; APISEC_TARGET_URL
ChecksBy 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 withtemplate Security/DAST.gitlab-ci.yml (stable version; .latest versions may include breaking changes), with the job name dast, requires dast stagetemplate Security/API-Security.gitlab-ci.yml,dast stage
Other methodson-demand scans (can be scheduled) + site / scanner profile; in scan execution policies, scan: dast—
TierUltimate (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

ApproachProsRisks / costsThis lesson
CI service container: in the dast job, use services: to start the freshly built myapp + redisfully isolated, clean every time, no deployment neededconfiguration differs from real environments (no TLS, no WAF)Mainline
Review / dev environment: the deploy job writes environment_url.txt, and DAST readsclose to realactive scans write data; it must be reachable by the Runneroptional (the dev environment from Lessons 3/4)
Production—active checks may cause data corruption, trigger alerts, or get blockedDo 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_SCAN full + authenticated scan, against a dedicated test environment.
  • Services with OpenAPI: API security testing takes priority over crawler-based DAST.
Common misconceptions① “DAST can scan production directly, since it's read-only”—active checks submit forms and inject payloads. ② “Still using DAST_WEBSITE / DAST_API_* variables”—the old variables belong to the removed proxy-based DAST and old naming; the current ones are 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

dast job (same network on the Runner) DAST analyzerHeadless browser crawlPassive / active checks service: myappalias myapp :5000 service: redisalias redis DAST_TARGET_URL=http://myapp:5000 DAST report artifactMissing security response headersCookie attributesServer information disclosure(active) injection / XSS UltimateNew MR findingsVulnerability reportapproval policy scanners: dast
Figure 4-1: a service container provides a “disposable target” without touching any shared environment

Passive vs active

Passive checks (default)Active checks (DAST_FULL_SCAN=true)
Behavioronly observes crawled requests / responsesactively sends attack payloads
Durationminutesmay take tens of minutes to hours
Impact on targetsimilar to normal browsingmay create / modify data and trigger alerts
Suited forevery MRnightly, 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.

Select a scenario to begin.
# dast job log

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)

Confirm the image is pushed: the dast job depends on the image 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
Add the DAST configuration (from the previous page) and commit on the demo branch; to also try it on the branch, temporarily change the rules to $CI_COMMIT_BRANCH, and make build-image push a short-SHA tag on that branch (revert after the lab).
Read the job log:
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
Fix one finding (add security response headers at the application layer), re-run, and confirm the corresponding finding disappears:
@app.after_request
def security_headers(resp):
    resp.headers["X-Content-Type-Options"] = "nosniff"
    resp.headers["Content-Security-Policy"] = "default-src 'none'"
    return resp
Free route: use the ZAP baseline job instead, download zap.html and review similar alerts.
Authorization Run DAST / ZAP only against targets you own and are authorized to test. Running active scans against third-party websites may be illegal.

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.).

Command-line questions
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]
Scenario analysis
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

▶
How to set up Dynamic Application Security Testing (DAST) with GitLab — GitLab Unfiltered
English · DAST configuration demo
▶
Tutorial: Setting up DAST with Authentication — GitLab Unfiltered
English · authenticated scanning
▶
DAST On Demand - Advanced Security Testing (HD) — GitLab
English · on-demand scans (early-version UI)

Official documentation

Video storyboard script (about 60 seconds)

Shot 1 · 0–20s
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.
Shot 2 · 20–45s
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.
Shot 3 · 45–60s
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.
or score ≥ 70% on the quiz

Module 5 · Security policies: scan execution and merge request approval policies

28:00 – 35:00 · Write “must scan” and “approve on findings” as YAML, put it in a project developers cannot change, and attach it to the group so all projects inherit it
7 minUltimate.gitlab/security-policies/policy.yml★★★★★
Learning objectives
  • 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 with manage_security_policy_link permission).
  • Write the three core policy types: Scan execution policy (enforce secret_detection etc.),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.
Prerequisites: Secret detection from Module 2, and protected branches and approval rules from the Git course. Importance:★★★★★

What: policy types (Ultimate)

TypeTop-level YAML keyWhat it doesTypical use
Scan execution policyscan_execution_policyforces 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 policyapproval_policyrequires 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 policypipeline_execution_policyinjects 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 policyvulnerability_management_policyautomatically resolves vulnerabilities no longer detected on the default branchreduces stale entries in vulnerability reports
Dependency firewall— (see documentation)blocks packages with disallowed licenses, high risk, or malicious packages before installationSupply 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

FieldMeaning
rules[].typescan_finding (security scan findings),license_finding (licenses),any_merge_request (any MR, e.g., based on commit signatures)
scanners,severity_levels,vulnerabilities_allowed,vulnerability_stateswhich scanners' which severities, how many are allowed, and what states (new_needs_triage etc.)
branch_type: protected / branchesTarget branch scope
actions: require_approvalapprovals_required + role_approvers / group_approvers / user_approvers
actions: send_bot_messagea bot comment in the MR explains the violation
approval_settingsEnforce project settings: block_branch_modification,prevent_pushing_and_force_pushing etc.
fallback_behavior.failclosed (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.include points to a CI file in another project (project / file / optional ref).
  • 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 via include:project ),inject_ci is deprecated in 17.9.
  • Reserved stages .pipeline-policy-pre (run first; if they fail or are all skipped, subsequent jobs are skipped, including needs: [] and when: always) and .pipeline-policy-post (run last).
  • Ignored by default [skip ci] (can be allowed with skip_ci.allowed + a user allowlist); variables_override controls 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

  1. 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).
  2. Group-level MR approval policy A: secret_detection any new finding → 1 approval from the security group, fail closed.
  3. MR approval policy B: Critical/High new findings from other scanners → security group approval; Medium only triggers a bot message.
  4. Regulated projects (within compliance framework scope): a pipeline execution policy injects compliance checks (Module 6).
Common misconceptions① “Policies are written in the project's .gitlab-ci.yml”—they are written in a separate security policy project. ② “Scan execution policies require the project to first include the template”—no, a project without .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

Security policy projectmygroup-lab/security-policies .gitlab/security-policies/policy.ymlscan_execution_policy ×1approval_policy ×2pipeline_execution_policy ×1 Only the security group can merge to mainChanges are MRs, with auditing Link Top-level groupmygroup-lab(linked by an Owner) mygroup-lab/myappInherits all policies mygroup-lab/platform/*Subgroups inherit as well (they can add their own policy projects on top) New projectBound by policies from creation
Figure 5-1: one policy project covers the entire group tree

Evaluation of MR approval policies

MR pipeline completesTarget: protected branch Do all required scanners have reports?No → fail closed → approval required New findings − baselineFilter by scanner / severity / state count > vulnerabilities_allowed ?Yes: require_approval + bot commentNo: this rule adds no approval Policy approvals stack with the project's own approval rules; project settings enforced by policy (such as preventing changes to protected branches) cannot be turned off in the project
Figure 5-2: simplified evaluation order

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)

Create a security group: under 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).
Create the policy project: group → Security → Policies → New policy → Merge request approval policy. On first save, GitLab automatically creates and links a security policy project, and submits policy.yml as an MR. Merge that MR.
Replace the policy with the YAML from the previous page (open an MR in the policy project to change .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"
Reproduce the Module 2 bypass: on a temporary branch, use -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)
Verify fail closed: in this branch's .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.
Cleanup: close the MR and delete the temporary branch; keep the policies for the capstone lab.
Free / Premium alternatives Without security policies: ① a shared CI template project (protected; only the platform group can merge), with projects using 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.”

Command-line questions
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_scanning
2. Change an approval policy so that “scan failures do not block, only notify.”
    fallback_behavior:
      fail: open
Scenario analysis
A 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

▶
Creating security policies - The basics (HD) — GitLab
English · policy editor and policy projects
▶
Overview of GitLab Scan Result Policies — GitLab Unfiltered
English · “Scan result policy” was the old name of MR approval policy (renamed in 16.9)
▶
Security Policies: Pipeline Execution Policy Type — GitLab Unfiltered
English · pipeline execution policies
▶
Using GitLab Security Policies to Enforce Vulnerability Management SLAs — GitLab Unfiltered
English · enforcing vulnerability remediation deadlines with policies

Official documentation

Video storyboard script (about 60 seconds)

Shot 1 · 0–20s
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.
Shot 2 · 20–45s
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.
Shot 3 · 45–60s
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.
or score ≥ 70% on the quiz

Module 6 · Compliance frameworks, compliance pipelines, and audit events

35:00 – 42:00 · Frameworks answer “which projects are regulated,” policies answer “what must be done,” and audit answers “what was actually done and who bypassed it”
7 minCompliance frameworks: Premium+Requirements and controls / audit event streaming: UltimateCompliance pipelines: deprecated since 17.3★★★★☆
Learning objectives
  • 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.
Prerequisites: The policies from Module 5 and policy_scope. Importance:★★★★☆

What: three concepts

ConceptWhat it isTierEntry point
Compliance frameworkA “label” defined at the top-level group (such as SOC2,PCI), applied to projectsPremium, UltimateSecurity → Compliance center (Frameworks / Projects tabs)
Requirements and controlsRequirements 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)UltimateCompliance center; compliance status report
Policy scopeThe security policy's policy_scope.compliance_frameworks: enforces only on projects with a given frameworkUltimatepolicy.yml
Compliance pipeline (deprecated)A pipeline configuration specified on the framework, replacing the project pipelineUltimateMigrate to pipeline execution policy
Audit eventsChange 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 streampushed in real time to an HTTP endpoint / Google Cloud Logging / AWS S3UltimateAudit 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_framework permission.
  • 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; pending a 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

  1. 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).
  2. Edit the framework again and delete the compliance pipeline configuration.
  3. Check the policy's pipeline_config_strategy: the compliance pipeline's semantics are “replace the project pipeline,” corresponding to override_project_ci; it is better to change to inject_policy, so the project pipeline runs as usual and only compliance jobs are injected.
Do not coexist The documentation warns: when a project has both a compliance pipeline and a pipeline execution policy, the compliance pipeline replaces the standard project pipeline, while the policy is still applied based on the original pipeline, which can cause duplicate or failed jobs, or missed checks. Do not enable pipeline execution policies for that project until migration is complete.

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-Token carries 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 id in the payload to de-duplicate (events may be redelivered).

When: which events are worth alerting on

Event (example category)Why
Push protection bypassed / skippedModule 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 checksthe common “turn off protection, then merge” pattern
Member and role changes, token creation / rotation / revocation, service account creationIdentity governance (Module 7)
SSO / IP allowlist setting changesA boundary is being modified
Common misconceptions① “Applying the SOC2 framework makes us compliant”—a framework is only a selector. ② “Compliance pipelines can be used long-term”—deprecated since 17.3; migrate as soon as possible. ③ “Free also has full audit logs”—Free has only successful sign-in events. ④ “The audit API can pull any time range”—the documentation notes date-filter spans are limited (30 days); for bulk forensics, use event streaming or export.

Framework → policy → evidence

Compliance framework SOC2Requirement: changes require two-person approvalControl: minimum_approvals_required_2Control: scanner_sast_running Applied to project myappLabel: SOC2(up to 20 frameworks) Pipeline execution policypolicy_scope:compliance_frameworks: SOC2 Compliance status reportEach control: pass / failEvaluated on a schedule or on trigger Audit eventsRetained indefinitely (Premium)API / CSV export Event streaming (Ultimate)HTTP · GCP Logging· AWS S3X-Gitlab-Event-Streaming-Token→ SIEM alerts
Figure 6-1: the framework selects projects, policies enforce requirements, and status reports and audit events provide evidence

Compliance pipeline vs pipeline execution policy

Compliance pipeline (deprecated)Pipeline execution policy
Where it is definedReferences a CI file in the framework settingspolicy.yml in the security policy project
Effect on project pipelineReplaces (must include the project CI back in the compliance configuration)inject_policy Injects / override_project_ci Replaces
ScopeProjects with that frameworkProject / group / framework (policy_scope)
Reserved stagesNone.pipeline-policy-pre / .pipeline-policy-post
StatusDeprecated in 17.3, planned for removalRecommended

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.

Select a scenario to begin.
# Events and HTTP logs

Core commands

CommandPurposeTier / 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 frameworksPremium
Compliance center → Frameworks → New frameworkCreate frameworks, requirements, and controlsPremium / 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)

(Premium+) create a framework: group → Security → Compliance center → Frameworks → New framework, name 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).
Apply to myapp: Compliance center → Projects → select myapp → Apply 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.
Observe compliance status: in the compliance center, the “At least two approvals” control for myapp should show as failed (the approver count set in Lesson 1 is fewer than 2), and the SAST control should pass. If needed, change the project approval rule to 2 approvers and wait for the next evaluation.
Check audit evidence: run the audit API command from the previous page and find the Module 2 push protection bypass and the Module 5 policy project link event. Free route: only sign-in events are visible—use the jq gate results in the pipeline as “evidence” instead, and extend the artifact retention period.
(Ultimate, optional) configure event streaming: group → Security → Audit events → Streams → Add streaming destination → HTTP endpoint, enter the HTTPS address you own; set the displayed verification token as the receiver's GITLAB_STREAM_TOKEN, then perform an action that generates an event (for example, editing a project's description), and observe the receiver's logs.
Do not point the audit event stream at a third-party “request collection” site you do not control—events contain member names, emails, IPs, and project paths.

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.

Command-line questions
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: 1234
Scenario analysis
The 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

▶
GitLab's Compliance Framework Explained | DevSecOps Automation — GitLab
English · compliance framework overview
▶
GitLab 17.2 - Assuring Compliance with Pipeline Execution Policies — GitLab
English · replacing compliance pipelines with pipeline execution policies
▶
Demo: Streaming audit events from GitLab to AWS S3 — GitLab Unfiltered
English · audit event streaming to S3
▶
Exploring a few use cases for Streaming Audit Events for Compliance Purposes — GitLab Unfiltered
English · compliance use cases for event streaming

Official documentation

Video storyboard script (about 60 seconds)

Shot 1 · 0–20s
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.
Shot 2 · 20–40s
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.
Shot 3 · 40–60s
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.
or score ≥ 70% on the quiz

Module 7 · Identity governance: SSO / SCIM, tokens, and access policies

42:00 – 50:00 · People sign in via SSO, machines use short-lived tokens or OIDC, and everyone connects from allowed networks—and every one of these can be automatically revoked on the day someone leaves
8 minSAML SSO / SCIM: Premium (GitLab.com top-level group)Service accounts: from Free (GA in 18.11)IP allowlist: Premium★★★★★
Learning objectives
  • 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.
Prerequisites: Groups and roles from Lesson 1, and OIDC from Lessons 3/4. Importance:★★★★★

What: four identity types, four governance methods

IdentityRecommended authenticationGovernance essentialsTier
EmployeesSAML SSO (IdP: Entra ID, Okta, Google Workspace, OneLogin, Keycloak, etc.) + IdP-side MFAEnforce SSO; SCIM provisions and deprovisions automatically; SAML group links map rolesPremium (GitLab.com top-level groups only)
Employees' API / Git accessShort-lived PATs (or SSH keys) + enforce SSO for Git activityMaximum lifetime, expiry reminders; enterprise users can have password authentication disabledFrom Free; some settings Premium/Ultimate
Automation (bots, integrations)Service accounts + tokens with an expiry date; project / group access tokensMinimum scope per purpose; rotation; unaffected by departuresService accounts from Free; project access tokens on GitLab.com require Premium+
CI/CD jobsCI_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 neededFree

How: the two SAML enforcement switches (GitLab.com)

SettingEffectNot covered
Enforce SSO-only authentication for web activity for this groupMembers must access group resources through the group's SSO URL; members cannot be added manuallyOwners 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 groupSSH/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)

ItemFact
Default expiryIf 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 lifetimeDefault 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 remindersChecked 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 tokensOn 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 accountsGA 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.
Common misconceptions① “With SSO enforcement on, tokens are also controlled by SSO”—Web enforcement does not cover tokens and the API; you need Git enforcement + disabling password authentication for enterprise users + token lifetimes. ② “Service accounts cost a seat”—they use no seat. ③ “An IP allowlist blocks hosted runners from cloning”—it does not, but it does block the registry and LFS. ④ “Deleting the GitLab account on departure is enough”—you must also revoke tokens they created and transfer pipeline schedules and integrations they own; SCIM + service accounts can automate this step.

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

IdP (Entra ID / Okta)Employee joins → assign GitLab appIdP group gitlab-developersIdP group gitlab-securityMFA / conditional accessEmployee leaves → unassign SCIM provisioning SAML sign-in SCIM deprovisioning GitLab.com top-level groupmygroup-lab (Premium+)SAML group link → Developer / Security ManagerEnforce SSO: Web + GitIP allowlist · domain restrictionMaximum token lifetime · expiry remindersEnterprise users: disable password authentication Machine identitiesService account + 30–90-day tokensDoes not expire when people leave CI jobsCI_JOB_TOKEN allowlistid_tokens → cloud OIDC
Figure 7-1: people go through the IdP, machines use service accounts, jobs use short-lived tokens

Token selection decision

ScenarioPreferredAvoid
A CI job accessing another project's packages / repositoryCI_JOB_TOKEN + the target project's job token allowlistStoring someone's PAT as a CI variable
CI job deploying to Azure / AWSid_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 accountTokens 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

APIPurpose
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_accountsList
POST /groups/:id/service_accounts/:user_id/personal_access_tokens (name,scopes[],expires_at)Issue a token
POST …/personal_access_tokens/:token_id/rotateRotate: 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)

Inventory: list all CI/CD variable names in the project and find values that look like personal tokens (look at the names only; do not print values):
glab variable list -R "$GL_PROJECT"
glab api "projects/$PROJECT_ID/variables" | jq -r '.[] | "\(.key)\tmasked=\(.masked)\tprotected=\(.protected)"'
Create a service account and issue a 30-day token (steps 1–3 on the previous page). A GitLab.com group on the Free tier can also create them (up to 100 per top-level group).
Verify it cannot sign in to the UI and can only do what it was granted:
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).

Rotate and confirm the old token is invalidated: run the rotation command, then access with the old token; it should return 401.
(Premium, optional) SSO and IP: if you have an IdP test tenant, configure it in the group Settings → SAML SSO , leave enforcement off at first, verify SSO sign-in with a test account, and only then enable enforcement; add your own IP to the IP allowlist first. Do not experiment with enforcement settings without a backup Owner.
Cleanup: 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).

Command-line questions
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'
Scenario analysis
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

▶
SSO/SCIM Walkthrough with OneLogin and GitLab SaaS — GitLab Unfiltered
English · full GitLab.com group SSO + SCIM walkthrough (IdP is OneLogin)
▶
Service Accounts UI Walkthrough — GitLab Unfiltered
English · service account UI
▶
View Expiring Personal Access Tokens in GitLab — GitLab Unfiltered
English · viewing tokens that are about to expire
▶
SAML vs. SCIM — C1
English · conceptual differences (not an official GitLab video)

Official documentation

Video storyboard script (about 60 seconds)

Shot 1 · 0–20s
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.
Shot 2 · 20–40s
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.
Shot 3 · 40–60s
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.
or score ≥ 70% on the quiz

Module 8 · Governance architecture review

50:00 – 60:00 · Put the first 7 modules together in one diagram: which layer controls each risk, at which tier it is available, who is responsible, and where the evidence lives
10 minFree / Premium / Ultimate three-tier blueprintInteractive troubleshooting tree★★★★★
Learning objectives
  • 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.”
Prerequisites: Modules 1–7. Importance:★★★★★

What: six-layer control model

LayerRiskFreeAdded by PremiumAdded by UltimateEvidence
① IdentityDeparted accounts, shared accounts, long-lived tokensEnforced 2FA (Lesson 1), service accounts (≤100 per top-level group), tokens must have an expiry dateSAML 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 entrySecrets entering the repository, unreviewed code reaching mainProtected branches, gitleaks pre-commit (client-side)Approval rules, CODEOWNERS approval, push rulesPush protection, policy-enforced approval settingsAudit events (blocks / bypasses)
③ PipelineScans deleted or skippedShared template + jq gate (can be removed)CODEOWNERS protects CI filesScan execution policies / pipeline execution policies (projects cannot remove them)Pipeline records, policy audit
④ Finding handlingHigh-severity code mergedGate failure + “pipeline must succeed”—MR approval policy (fail closed), vulnerability report triage, vulnerability management policiesVulnerability report history, MR approval records
⑤ Artifacts and deploymentScan and deployment are not the same image; unauthorized deploymentDeploy by digest, protected tags, OIDC (Lessons 3/4)Protected environments + deployment approvalDependency list / SBOM management, registry container scanningDeployment records, SBOM artifacts
⑥ Evidence and monitoringAfter an incident, you cannot answer “who, when, and what”Only sign-in events; artifacts and pipeline logsAudit events (retained indefinitely), compliance framework labelsAudit event stream, requirements and controls, compliance status reportsSIEM, 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)

  1. Scope: the top-level group tree, regulated projects (compliance frameworks), external integrations, and runners.
  2. 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.
  3. Score each layer: use the maturity scorer on the “Animation” page.
  4. Gaps and options: for each gap, give two options: a Free compensating control and a paid option.
  5. 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.
  6. 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

Free blueprint
  • 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
Residual risk: gates can be removed; no audit; no SSO.
Premium blueprint
  • 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
Residual risk: no push protection; findings do not enter MRs; no policy enforcement.
Ultimate blueprint
  • 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
Residual risk: permissions on the policy project itself, scanning infrastructure failures, rule coverage.
Common misconceptions① “A review means turning on every feature”—every control has a cost (false positives, approval burden, compute minutes); trade off by risk. ② “Ultimate solves everything”—write access to the policy project and Owner accounts remain the highest-value targets. ③ “Governance is impossible on the Free tier”—Free can achieve “secure by default”; it just lacks unbypassable enforcement and an evidence chain.

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)

① IdentityEntra ID / OktaSAML + SCIMEnforce SSO (Web + Git)IP allowlistService accounts · 30-day tokensBackup Owner (does not depend on SSO) ② Code entryPush protectionProtected main / v*CODEOWNERS ③ PipelineScan execution policyPipeline execution policy(scope: SOC2 framework) ④ Finding handlingMR approval policyfail closedVulnerability triage SLA ⑤ Artifacts and deploymentContainer scanning + SBOMDeploy by digestOIDC → cloud ⑥ Evidence: audit events (indefinite) → audit event stream (filtering + token verification) → SIEM alerts and reportsPush protection bypass · policy link changes · protected branch / approval rule changes · member / token / SSO setting changes Governance plane: security policy project (only the security group can merge) · ADRs · quarterly access review · metrics dashboardPolicy as code; changes via MRs
Figure 8-1: six control layers + evidence plane + governance plane

Review report template (excerpt)

#FindingRiskRecommendation (tier)Compensating control (Free)Owner / deadline
R1Personal PAT stored in CI variablesHighService account + 30-day token (Free) / OIDCSame as leftPlatform group / 2 weeks
R2No push protectionHighPush protection (Ultimate)gitleaks pre-commit + pipeline secret detection + jq gateSecurity group / 1 month
R3Scans can be removed by projectsMediumScan execution policy (Ultimate)CODEOWNERS protects CI files (Premium)Security group / 1 month
R4No audit evidenceMediumAudit events (Premium) + event streaming (Ultimate)Export pipeline and MR recordsCompliance / 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)

Collect current state: run the script from the previous page governance_snapshot.sh.
Score: on the “Animation” page, check the controls already in place, and record each layer's score and the recommended three items.
Write an ADR: create a new file in the security policy project: 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.
Metrics: define 5 metrics (block / bypass counts, policy approval counts, high-severity fix time, number of tokens about to expire, number of members not bound to SSO) and state each metric's data source (audit events, vulnerability reports, token API).
Troubleshooting drill: using the interactive troubleshooting tree on the “Troubleshooting” page, walk through both the “scan did not run” and “policy did not block” paths.

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.

Command-line questions
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'
Scenario analysis
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

▶
Managing Security Vulnerabilities with the GitLab Security Dashboard (DevSecOps) — GitLab
English · day-to-day vulnerability governance operations
▶
Thales & GitLab: A DevSecOps Case Study — GitLab
English · enterprise DevSecOps case
▶
GitLab Security- Golden Rules for Troubleshooting Vulnerability Reports — GitLab Unfiltered
English · principles for troubleshooting vulnerability reports, used with this module's troubleshooting tree

Official documentation

Video storyboard script (about 60 seconds)

Shot 1 · 0–20s
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.
Shot 2 · 20–45s
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.
Shot 3 · 45–60s
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.
or score ≥ 70% on the quiz

Command cheat sheet

Scan components, push protection, policy YAML, auditing, identity and tokens, Free alternatives
After-class reviewCopy-ready
Official scanning components (latest as of 2026-11-16)
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
Common inputs / variables
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
Push protection
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
Report artifacts
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)
Policy YAML skeleton
# .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}]}
Quick reference: limits
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
Audit and compliance
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”
Identity and tokens
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)
Free alternatives
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
Tiers in one line each
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 Owner

Capstone lab + final quiz

Implement “push protection + group scanning policies + zero-tolerance secret approval + compliance frameworks + audit evidence + service accounts” for mygroup-lab, and validate it with a realistic “leak drill”
About 45 minUltimate trial (see each step for the Free route)No cloud costs
Scenario

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.

1. Tier and preparation: start an Ultimate trial in the lab top-level group; create the subgroup 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.
2. Scanning baseline: myapp's .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.)
3. Push protection: enable it for myapp (or enable it for the whole group using the group security settings API).(Free: write the gitleaks pre-commit hook into the repository's .pre-commit-config.yaml and require installation in the README.)
4. Policy project: create it and link it to the top-level group, and merge the following policies:
---
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.)
5. Compliance framework: create 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.)
6. Service accounts: create release_bot, issue a 30-day, minimal-scope token, and replace any personal token in CI variables; demonstrate one rotation.
7. Leak drill:
  1. on a new branch, use printf to generate a fake token and push → blocked (screenshot PUSH BLOCKED).
  2. Switch to -o secret_push_protection.skip_all to push → succeeds; open an MR → the MR shows “Requires mygroup-lab/security approval,” and the bot comment lists the secret findings.
  3. Remove the secret-detection include from the MR → the scan execution policy still injects the job, and the approval requirement is unchanged.
  4. 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).
8. Evidence and cleanup: use the audit API to export the “push protection skipped”, “policy project linked”, and “service account created / token rotated” events; run 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.
Acceptance checklist

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

All facts were verified against official documentation on 2026-11-16; output of commands not run in a real GitLab.com group is labeled “example.”
Verified 2026-11-16

Source

TopicSourceVerified onFacts used in this lesson
SASTdocs.gitlab.com/user/application_security/sast2026-11-16Tier: 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/pipeline2026-11-16Free/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 protectionSecret push protection · Tutorial2026-11-16Ultimate; 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 responseAutomatic response to leaked secrets2026-11-16Ultimate, public projects only; GitLab PAT revoked immediately with an email notification; AWS / Google Cloud / Postman notify the vendor
Security settings APIProject security settings API · Group2026-11-16PUT /projects/:id/security_settings,secret_push_protection_enabled (renamed from pre_receive_secret_detection_enabled in 17.11); Ultimate
Dependency scanningDependency scanning · by using SBOM2026-11-16Ultimate; 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 scanningContainer scanning2026-11-16From 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 testingDAST · Variables · API security testing2026-11-16Ultimate; 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 policiesPolicies and the three policy-type subpages2026-11-16five 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
ComplianceCompliance frameworks · Compliance pipelines2026-11-16framework 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
AuditingAudit events · Streaming · API2026-11-16Premium; 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
IdentitySAML SSO · Access and permissions2026-11-16Premium, 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 accountsPAT · Project access tokens · Service accounts · API2026-11-16Default 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
RolesRoles and permissions2026-11-16Default roles include Planner, Security Manager (18.11 beta, enabled on GitLab.com)
TrialFree trials2026-11-16Ultimate 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 versionsReleases / Tags of each project under gitlab.com/components (API query)2026-11-16sast 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 toolsGitHub Releases (gitleaks, trivy, zaproxy)2026-11-16gitleaks v8.30.1, Trivy v0.76.2, ZAP 2.17.0
GitLab versiondocs.gitlab.com/releases(carried over from verification in Lessons 1–4)2026-11-16GitLab 19.5 (patch 19.5.6); 19.6 not released; glab v1.130.0
Related coursesGitHub 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:

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 is gl-sbom-report.cdx.json; follow the actual artifact.
  • In the policy YAML, branch_type: all,group_approvers path 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.