
Building Devsecops Pipeline With Gitlab Ci
- 176 installs
- 27.3k repo stars
- Updated August 2, 2026
- mukul975/anthropic-cybersecurity-skills
Helps with ai & agent building tasks.
About
building-devsecops-pipeline-with-gitlab-ci is a Claude Code skill in the AI & Agent Building category.
- building-devsecops-pipeline-with-gitlab-ci
- AI & Agent Building
- AI-coding skill
Building Devsecops Pipeline With Gitlab Ci by the numbers
- 176 all-time installs (skills.sh)
- +10 installs in the week ending Aug 4, 2026 (Skillselion tracking)
- Ranked #3,085 of 16,546 AI & Agent Building skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/mukul975/anthropic-cybersecurity-skills --skill building-devsecops-pipeline-with-gitlab-ciAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 176 |
|---|---|
| repo stars | ★ 27.3k |
| Last updated | August 2, 2026 |
| Repository | mukul975/anthropic-cybersecurity-skills ↗ |
What it does
Helps with ai & agent building tasks.
Files
Building DevSecOps Pipeline with GitLab CI
Overview
GitLab provides an integrated DevSecOps platform that embeds security testing directly into the CI/CD pipeline. By leveraging GitLab's built-in security scanners---SAST, DAST, container scanning, dependency scanning, secret detection, and license compliance---teams can shift security left, catching vulnerabilities during development rather than post-deployment. GitLab Duo AI assists with false positive detection for SAST vulnerabilities, helping security teams focus on genuine issues.
When to Use
- When deploying or configuring building devsecops pipeline with gitlab ci capabilities in your environment
- When establishing security controls aligned to compliance requirements
- When building or improving security architecture for this domain
- When conducting security assessments that require this implementation
Prerequisites
- GitLab Ultimate license (required for full security scanner suite)
- GitLab Runner configured (shared or self-hosted)
.gitlab-ci.ymlpipeline configuration familiarity- Docker-in-Docker (DinD) or Kaniko for container builds
- Application deployed to a staging environment for DAST scanning
Core Security Scanning Stages
Static Application Security Testing (SAST)
SAST analyzes source code for vulnerabilities before compilation. GitLab supports 14+ languages using analyzers such as Semgrep, SpotBugs, Gosec, Bandit, and NodeJsScan. The simplest inclusion uses GitLab's managed templates.
Dynamic Application Security Testing (DAST)
DAST tests running applications by simulating attack payloads against HTTP endpoints. It detects XSS, SQLi, CSRF, and other runtime vulnerabilities that static analysis cannot find. DAST requires a deployed, accessible target URL.
Container Scanning
Uses Trivy to scan Docker images for known CVEs in OS packages and application dependencies. Runs after the Docker build stage to gate images before they reach a registry.
Dependency Scanning
Inspects dependency manifests (package.json, requirements.txt, pom.xml, Gemfile.lock) for known vulnerable versions. Operates at the source code level, complementing container scanning.
Secret Detection
Scans commits for accidentally committed credentials, API keys, tokens, and private keys using pattern matching and entropy analysis. Runs on every commit to prevent secrets from reaching the repository.
Implementation
Complete Pipeline Configuration
# .gitlab-ci.yml
stages:
- build
- test
- security
- deploy-staging
- dast
- deploy-production
variables:
DOCKER_IMAGE: $CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA
SECURE_LOG_LEVEL: "info"
# Include GitLab managed security templates
include:
- template: Security/SAST.gitlab-ci.yml
- template: Security/Secret-Detection.gitlab-ci.yml
- template: Security/Dependency-Scanning.gitlab-ci.yml
- template: Security/Container-Scanning.gitlab-ci.yml
- template: DAST.gitlab-ci.yml
- template: Security/License-Scanning.gitlab-ci.yml
build:
stage: build
image: docker:24.0
services:
- docker:24.0-dind
variables:
DOCKER_TLS_CERTDIR: "/certs"
script:
- docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
- docker build -t $DOCKER_IMAGE .
- docker push $DOCKER_IMAGE
rules:
- if: $CI_COMMIT_BRANCH
unit-tests:
stage: test
image: $DOCKER_IMAGE
script:
- npm ci
- npm run test:coverage
coverage: '/Lines\s*:\s*(\d+\.?\d*)%/'
artifacts:
reports:
junit: junit-report.xml
coverage_report:
coverage_format: cobertura
path: coverage/cobertura-coverage.xml
# Override SAST to run in security stage
sast:
stage: security
variables:
SAST_EXCLUDED_PATHS: "spec,test,tests,tmp,node_modules"
SEARCH_MAX_DEPTH: 10
# Override container scanning
container_scanning:
stage: security
variables:
CS_IMAGE: $DOCKER_IMAGE
CS_SEVERITY_THRESHOLD: "HIGH"
# Override dependency scanning
dependency_scanning:
stage: security
# Override secret detection
secret_detection:
stage: security
# License compliance scanning
license_scanning:
stage: security
deploy-staging:
stage: deploy-staging
image: bitnami/kubectl:latest
script:
- kubectl set image deployment/app app=$DOCKER_IMAGE -n staging
- kubectl rollout status deployment/app -n staging --timeout=300s
environment:
name: staging
url: https://staging.example.com
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
# DAST runs against deployed staging
dast:
stage: dast
variables:
DAST_WEBSITE: https://staging.example.com
DAST_FULL_SCAN_ENABLED: "true"
DAST_BROWSER_SCAN: "true"
needs:
- deploy-staging
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
deploy-production:
stage: deploy-production
image: bitnami/kubectl:latest
script:
- kubectl set image deployment/app app=$DOCKER_IMAGE -n production
- kubectl rollout status deployment/app -n production --timeout=300s
environment:
name: production
url: https://app.example.com
when: manual
rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCHSecurity Approval Policies
Configure scan execution policies to enforce mandatory security scans:
1. Navigate to Security & Compliance > Policies 2. Create a "Scan Execution Policy" requiring SAST and secret detection on all branches 3. Create a "Merge Request Approval Policy" requiring security team approval when critical vulnerabilities are detected
Custom SAST Ruleset Configuration
Create .gitlab/sast-ruleset.toml to customize analyzer behavior:
[semgrep]
[[semgrep.ruleset]]
dirs = ["src"]
[[semgrep.passthrough]]
type = "url"
target = "/sgrep-rules/custom-rules.yml"
value = "https://semgrep.dev/p/owasp-top-ten"
[[semgrep.passthrough]]
type = "url"
target = "/sgrep-rules/java-rules.yml"
value = "https://semgrep.dev/p/java"Security Dashboard and Vulnerability Management
Vulnerability Report
GitLab consolidates all scanner findings into a single Vulnerability Report accessible at Security & Compliance > Vulnerability Report. Each vulnerability includes:
- Severity rating (Critical, High, Medium, Low, Info)
- Scanner source (SAST, DAST, Container, Dependency, Secret)
- Location in source code or image layer
- Remediation guidance and suggested fixes
- Status tracking (Detected, Confirmed, Dismissed, Resolved)
Merge Request Security Widget
Every merge request displays a security scanning widget showing:
- New vulnerabilities introduced by the MR
- Fixed vulnerabilities resolved by the MR
- Comparison against the target branch baseline
Pipeline Optimization
- Parallel execution: Security scanners run concurrently in the security stage
- Caching: Use CI cache for dependency downloads to speed up scanning
- Incremental scanning: SAST can scan only changed files using
SAST_INCREMENTAL: "true" - Fail conditions: Set
allow_failure: falseon critical scanners to enforce quality gates
Monitoring and Metrics
| Metric | Description | Target |
|---|---|---|
| Pipeline security coverage | Percentage of projects with all scanners enabled | > 95% |
| Critical vulnerability MTTR | Time from detection to resolution for critical findings | < 48 hours |
| False positive rate | Percentage of dismissed-as-false-positive findings | < 15% |
| Secret detection block rate | Percentage of secret commits blocked by push rules | > 99% |
References
GitLab DevSecOps Pipeline Implementation Template
Pipeline Security Scanner Checklist
| Scanner | Enabled | Template Included | Threshold Set | Blocking |
|---|---|---|---|---|
| SAST | [ ] | [ ] | Severity: _____ | [ ] |
| DAST | [ ] | [ ] | Severity: _____ | [ ] |
| Container Scanning | [ ] | [ ] | Severity: _____ | [ ] |
| Dependency Scanning | [ ] | [ ] | Severity: _____ | [ ] |
| Secret Detection | [ ] | [ ] | N/A | [ ] |
| License Scanning | [ ] | [ ] | Policy: _____ | [ ] |
Security Policy Configuration
| Policy Type | Name | Scope | Enforcement |
|---|---|---|---|
| Scan Execution | [ ] All branches [ ] Default only | [ ] Required | |
| MR Approval | Severity trigger: _____ | Approvers: _____ |
Environment-Specific DAST Targets
| Environment | URL | Auth Method | Scan Type | Schedule |
|---|---|---|---|---|
| Staging | [ ] None [ ] Token [ ] Cookie | [ ] Passive [ ] Full | ||
| Pre-production | [ ] None [ ] Token [ ] Cookie | [ ] Passive [ ] Full |
Vulnerability SLA Targets
| Severity | Detection to Triage | Triage to Fix | Total SLA |
|---|---|---|---|
| Critical | 4 hours | 24 hours | 48 hours |
| High | 24 hours | 5 days | 7 days |
| Medium | 48 hours | 14 days | 30 days |
| Low | 1 week | 30 days | 90 days |
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to the Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by the Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding any notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. Please do not remove or change
the license header comment from a contributed file except when
necessary.
Copyright 2026 mukul975
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
API Reference: GitLab CI DevSecOps Pipeline
GitLab Security Templates
| Template | Stage |
|---|---|
Security/SAST.gitlab-ci.yml | Static analysis |
Security/DAST.gitlab-ci.yml | Dynamic testing |
Security/Dependency-Scanning.gitlab-ci.yml | Dependency audit |
Security/Container-Scanning.gitlab-ci.yml | Container scan |
Security/Secret-Detection.gitlab-ci.yml | Secret detection |
Security/IaC-Scanning.gitlab-ci.yml | IaC security |
.gitlab-ci.yml Structure
include:
- template: Security/SAST.gitlab-ci.yml
- template: Security/Secret-Detection.gitlab-ci.yml
stages:
- build
- test
- security
- deploy
variables:
SECURE_LOG_LEVEL: infoGitLab CI Lint API
POST /api/v4/projects/:id/ci/lint
PRIVATE-TOKEN: your-token
Body: {"content": "yaml-string"}Security Variables
| Variable | Description |
|---|---|
SAST_DEFAULT_ANALYZERS | Comma-separated analyzer list |
SAST_EXCLUDED_ANALYZERS | Analyzers to skip |
CS_IMAGE | Container image to scan |
DAST_WEBSITE | Target URL for DAST |
SECRET_DETECTION_HISTORIC_SCAN | Scan full history |
Vulnerability Report API
GET /api/v4/projects/:id/vulnerability_findingsSecurity Scanning Tools
| Tool | Type | Language |
|---|---|---|
| Semgrep | SAST | Multi-language |
| Bandit | SAST | Python |
| Trivy | Container | Container images |
| Gitleaks | Secret | Git history |
| KICS | IaC | Terraform/CloudFormation |
| ZAP | DAST | Web applications |
Standards and Compliance Reference
OWASP DevSecOps Pipeline Maturity Model
| Level | SAST | DAST | SCA | Container | Secrets | License |
|---|---|---|---|---|---|---|
| Level 1 (Basic) | Manual runs | None | Manual dependency check | None | Pre-commit hooks | None |
| Level 2 (Integrated) | CI-triggered on MR | Scheduled scans | CI-triggered | Image scan on build | CI scan on commits | CI-triggered |
| Level 3 (Enforced) | Required for merge | Gate before deploy | Block on critical CVE | Block vulnerable images | Push protection | Policy enforcement |
| Level 4 (Optimized) | Custom rules, tuned FP | Authenticated full scan | Auto-remediation PRs | Signed images only | Auto-rotation | SBOM generation |
NIST SP 800-218 (SSDF) Mapping
| SSDF Practice | GitLab Feature | Pipeline Stage |
|---|---|---|
| PO.1 Define security requirements | Security policies | Policy configuration |
| PW.1 Design software securely | Threat modeling integration | Pre-build |
| PW.4 Reuse well-secured software | Dependency scanning | Security stage |
| PW.5 Create source code securely | SAST, secret detection | Security stage |
| PW.7 Review and test code | MR security widget | Merge request |
| PW.8 Test executable code | DAST | Post-deploy staging |
| PW.9 Configure software securely | Container scanning | Security stage |
| RV.1 Identify vulnerabilities | Vulnerability report | Dashboard |
| RV.2 Assess and prioritize | Severity classification | Triage workflow |
| RV.3 Remediate vulnerabilities | Issue tracking integration | Sprint planning |
CIS Software Supply Chain Security
- SCS-1: Secure source code management with protected branches and signed commits
- SCS-2: Secure build pipelines with pinned template versions and runner isolation
- SCS-3: Verified dependencies through dependency scanning and license compliance
- SCS-4: Secure artifacts with container scanning and signed images
- SCS-5: Deployment security with manual gates and environment approvals
GitLab Scanner Coverage Matrix
| Vulnerability Type | Primary Scanner | Secondary Scanner |
|---|---|---|
| SQL Injection | SAST (Semgrep) | DAST |
| XSS | SAST | DAST |
| SSRF | SAST | DAST |
| Command Injection | SAST | DAST |
| Insecure Deserialization | SAST | N/A |
| Known CVE in dependency | Dependency Scanning | Container Scanning |
| Hardcoded credentials | Secret Detection | SAST |
| License violation | License Scanning | N/A |
| OS-level CVE in image | Container Scanning | N/A |
| Authentication flaws | DAST | SAST |
GitLab DevSecOps Pipeline Workflows
Workflow 1: Merge Request Security Review
Developer creates merge request
|
Pipeline triggers security scanners in parallel:
[SAST] [Secret Detection] [Dependency Scanning] [License Scanning]
|
MR Security Widget displays results:
- New vulnerabilities introduced
- Existing vulnerabilities fixed
- Comparison with target branch
|
[No Critical/High] --> Reviewers can approve and merge
[Critical/High found] --> MR blocked by approval policy
|
Security team reviews findings
|
[Confirmed] --> Developer remediates and re-pushes
[False Positive] --> Dismissed with documented reason
|
All findings resolved --> MR eligible for mergeWorkflow 2: Container Image Security Gate
Docker image built in CI
|
Container scanning (Trivy) analyzes image layers
|
Findings categorized by severity
|
[Below threshold] --> Image pushed to registry with metadata
[Above threshold] --> Pipeline fails, image not pushed
|
Registry stores scan results as artifact
|
Deployment pulls only scanned/approved imagesWorkflow 3: DAST Against Staging Environment
Application deployed to staging
|
DAST browser scan initiated against staging URL
|
Authenticated scan crawls application pages
|
Active testing for XSS, SQLi, CSRF, etc.
|
Results added to vulnerability report
|
[Pass] --> Manual deploy-to-production gate enabled
[Fail on critical] --> Staging deployment rolled back
|
Production deploy requires manual approvalWorkflow 4: Vulnerability Lifecycle Management
Scanner detects vulnerability
|
Status: "Detected" in vulnerability report
|
Security analyst triages finding
|
[Confirmed vulnerability] [False positive]
| |
Status: "Confirmed" Status: "Dismissed"
Issue created automatically Reason documented
|
Developer assigned fix
|
Fix merged, scanner re-runs
|
Vulnerability no longer detected
|
Status: "Resolved"#!/usr/bin/env python3
"""DevSecOps Pipeline Builder Agent - Generates GitLab CI security scanning pipeline configurations."""
import json
import logging
import argparse
from datetime import datetime
import requests
logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
logger = logging.getLogger(__name__)
SECURITY_STAGES = {
"sast": {
"template": "Security/SAST.gitlab-ci.yml",
"description": "Static Application Security Testing",
"tools": ["semgrep", "bandit", "eslint-security"],
},
"dast": {
"template": "Security/DAST.gitlab-ci.yml",
"description": "Dynamic Application Security Testing",
"tools": ["zap"],
},
"dependency_scanning": {
"template": "Security/Dependency-Scanning.gitlab-ci.yml",
"description": "Dependency vulnerability scanning",
"tools": ["gemnasium", "retire.js"],
},
"container_scanning": {
"template": "Security/Container-Scanning.gitlab-ci.yml",
"description": "Container image vulnerability scanning",
"tools": ["trivy", "grype"],
},
"secret_detection": {
"template": "Security/Secret-Detection.gitlab-ci.yml",
"description": "Secret and credential detection",
"tools": ["gitleaks"],
},
"license_scanning": {
"template": "Jobs/License-Scanning.gitlab-ci.yml",
"description": "License compliance scanning",
"tools": ["license-finder"],
},
"iac_scanning": {
"template": "Security/IaC-Scanning.gitlab-ci.yml",
"description": "Infrastructure as Code scanning",
"tools": ["kics"],
},
}
def generate_gitlab_ci(stages, project_type="python", registry="$CI_REGISTRY"):
"""Generate .gitlab-ci.yml with security scanning stages."""
ci_config = {
"stages": ["build", "test", "security", "deploy"],
"include": [],
"variables": {
"SECURE_LOG_LEVEL": "info",
"SAST_EXCLUDED_ANALYZERS": "",
},
}
for stage_name in stages:
stage = SECURITY_STAGES.get(stage_name)
if stage:
ci_config["include"].append({"template": stage["template"]})
if "container_scanning" in stages:
ci_config["variables"]["CS_IMAGE"] = f"{registry}/$CI_PROJECT_PATH:$CI_COMMIT_SHA"
if project_type == "python":
ci_config["variables"]["SAST_DEFAULT_ANALYZERS"] = "semgrep,bandit"
elif project_type == "javascript":
ci_config["variables"]["SAST_DEFAULT_ANALYZERS"] = "semgrep,eslint"
return ci_config
def validate_pipeline(gitlab_url, token, project_id, ci_content):
"""Validate CI configuration via GitLab API."""
headers = {"PRIVATE-TOKEN": token, "Content-Type": "application/json"}
data = {"content": json.dumps(ci_content)}
try:
resp = requests.post(f"{gitlab_url}/api/v4/projects/{project_id}/ci/lint", headers=headers, json=data, timeout=15)
return resp.json()
except requests.RequestException as e:
return {"error": str(e)}
def assess_pipeline_coverage(stages):
"""Assess security coverage of the pipeline."""
all_stages = set(SECURITY_STAGES.keys())
covered = set(stages) & all_stages
missing = all_stages - covered
coverage = len(covered) / len(all_stages) * 100
return {
"coverage_percent": round(coverage, 1),
"covered_stages": list(covered),
"missing_stages": list(missing),
"recommendation": "Add " + ", ".join(missing) if missing else "Full coverage",
}
def generate_report(ci_config, coverage, stages):
"""Generate DevSecOps pipeline report."""
report = {
"timestamp": datetime.utcnow().isoformat(),
"stages_configured": stages,
"security_coverage": coverage,
"gitlab_ci_config": ci_config,
}
print(f"DEVSECOPS REPORT: {len(stages)} stages, {coverage['coverage_percent']}% coverage")
return report
def main():
parser = argparse.ArgumentParser(description="DevSecOps Pipeline Builder Agent")
parser.add_argument("--stages", nargs="*", choices=list(SECURITY_STAGES.keys()), default=list(SECURITY_STAGES.keys()))
parser.add_argument("--project-type", choices=["python", "javascript", "java", "go"], default="python")
parser.add_argument("--gitlab-url", help="GitLab URL for validation")
parser.add_argument("--token", help="GitLab private token")
parser.add_argument("--project-id", help="GitLab project ID")
parser.add_argument("--output", default="devsecops_report.json")
args = parser.parse_args()
ci_config = generate_gitlab_ci(args.stages, args.project_type)
coverage = assess_pipeline_coverage(args.stages)
report = generate_report(ci_config, coverage, args.stages)
with open(args.output, "w") as f:
json.dump(report, f, indent=2)
logger.info("Report saved to %s", args.output)
if __name__ == "__main__":
main()
#!/usr/bin/env python3
"""
GitLab DevSecOps Pipeline Security Report Generator
Queries GitLab API to aggregate security scanning results
across projects and generate compliance reports.
"""
import json
import os
import sys
import urllib.request
import urllib.error
from datetime import datetime
from collections import defaultdict
def gitlab_api_get(url: str, token: str) -> list | dict:
headers = {"PRIVATE-TOKEN": token, "Content-Type": "application/json"}
results = []
page = 1
while True:
sep = "&" if "?" in url else "?"
paginated = f"{url}{sep}per_page=100&page={page}"
req = urllib.request.Request(paginated, headers=headers)
try:
with urllib.request.urlopen(req) as resp:
data = json.loads(resp.read().decode())
if isinstance(data, list):
if not data:
break
results.extend(data)
page += 1
else:
return data
except urllib.error.HTTPError as e:
print(f"HTTP {e.code}: {e.read().decode()}")
break
return results
def get_group_projects(base_url: str, token: str, group_id: str) -> list:
url = f"{base_url}/api/v4/groups/{group_id}/projects?include_subgroups=true"
return gitlab_api_get(url, token)
def get_project_vulnerabilities(base_url: str, token: str, project_id: int) -> list:
url = f"{base_url}/api/v4/projects/{project_id}/vulnerabilities?state=detected"
return gitlab_api_get(url, token)
def get_pipeline_jobs(base_url: str, token: str, project_id: int, pipeline_id: int) -> list:
url = f"{base_url}/api/v4/projects/{project_id}/pipelines/{pipeline_id}/jobs"
return gitlab_api_get(url, token)
def check_security_scanners(jobs: list) -> dict:
scanner_names = {
"sast": False,
"secret_detection": False,
"dependency_scanning": False,
"container_scanning": False,
"dast": False,
"license_scanning": False,
}
for job in jobs:
name = job.get("name", "").lower()
for scanner in scanner_names:
if scanner.replace("_", "-") in name or scanner in name:
scanner_names[scanner] = True
return scanner_names
def generate_report(base_url: str, token: str, group_id: str) -> dict:
projects = get_group_projects(base_url, token, group_id)
report = {
"gitlab_instance": base_url,
"group_id": group_id,
"generated_at": datetime.utcnow().isoformat() + "Z",
"total_projects": len(projects),
"scanner_coverage": defaultdict(int),
"severity_totals": defaultdict(int),
"project_details": [],
}
for project in projects:
pid = project["id"]
name = project["path_with_namespace"]
vulns = get_project_vulnerabilities(base_url, token, pid)
severity_counts = defaultdict(int)
scanner_counts = defaultdict(int)
for v in vulns:
severity_counts[v.get("severity", "unknown")] += 1
scanner_counts[v.get("scanner", {}).get("name", "unknown")] += 1
report["severity_totals"][v.get("severity", "unknown")] += 1
pipelines = gitlab_api_get(
f"{base_url}/api/v4/projects/{pid}/pipelines?per_page=1&status=success", token
)
scanners_enabled = {}
if pipelines and isinstance(pipelines, list):
jobs = get_pipeline_jobs(base_url, token, pid, pipelines[0]["id"])
scanners_enabled = check_security_scanners(jobs)
for scanner, enabled in scanners_enabled.items():
if enabled:
report["scanner_coverage"][scanner] += 1
report["project_details"].append({
"project": name,
"open_vulnerabilities": len(vulns),
"by_severity": dict(severity_counts),
"by_scanner": dict(scanner_counts),
"scanners_enabled": scanners_enabled,
})
report["scanner_coverage"] = dict(report["scanner_coverage"])
report["severity_totals"] = dict(report["severity_totals"])
return report
def print_report(report: dict) -> None:
print(f"\n{'='*65}")
print(f"GitLab DevSecOps Security Report")
print(f"Instance: {report['gitlab_instance']}")
print(f"Generated: {report['generated_at']}")
print(f"{'='*65}")
print(f"\nTotal Projects: {report['total_projects']}")
print(f"\nScanner Coverage:")
for scanner, count in sorted(report["scanner_coverage"].items()):
pct = count / report["total_projects"] * 100 if report["total_projects"] > 0 else 0
print(f" {scanner:25s}: {count:3d}/{report['total_projects']} ({pct:.0f}%)")
print(f"\nVulnerability Summary:")
for sev in ["critical", "high", "medium", "low", "info", "unknown"]:
count = report["severity_totals"].get(sev, 0)
if count > 0:
print(f" {sev.upper():12s}: {count}")
total = sum(report["severity_totals"].values())
print(f" {'TOTAL':12s}: {total}")
print(f"\nTop 10 Projects by Open Vulnerabilities:")
sorted_projects = sorted(
report["project_details"], key=lambda p: p["open_vulnerabilities"], reverse=True
)
for p in sorted_projects[:10]:
print(f" {p['project']:45s} | Vulns: {p['open_vulnerabilities']}")
def main():
token = os.environ.get("GITLAB_TOKEN")
base_url = os.environ.get("GITLAB_URL", "https://gitlab.com")
group_id = os.environ.get("GITLAB_GROUP_ID")
if not token:
print("Error: GITLAB_TOKEN environment variable required")
sys.exit(1)
if not group_id:
print("Error: GITLAB_GROUP_ID environment variable required")
sys.exit(1)
report = generate_report(base_url, token, group_id)
print_report(report)
output = f"gitlab_devsecops_report_{datetime.utcnow().strftime('%Y%m%d')}.json"
with open(output, "w") as f:
json.dump(report, f, indent=2, default=str)
print(f"\nReport saved to: {output}")
if __name__ == "__main__":
main()