Production-grade guide to security testing in ci covering architecture patterns, implementation strategies, testing approaches, and operational best practices for enterprise engineering teams.
Security Testing In CI is the practice of automating security checks within a continuous integration pipeline, executed on every code change, pull request, or merge to main. It ensures that security is not a gate at the end of development but a recurring, integrated part of every build. This happens early and often—on every commit, before deployment, and before merge approval—making it critical for catching vulnerabilities, misconfigurations, and policy violations as code evolves.
For every pull request, the CI system checks the code changes against a suite of security tests. These tests run in isolation, using a clean environment, and report results directly in the PR interface. The goal is to block or suggest changes before merging, ensuring that security is part of the code review workflow.
A typical setup uses git and bash with docker and curl for orchestration. The pipeline triggers on pull_request events in GitHub Actions, GitLab CI, or Bitbucket Pipelines. The workflow file—.github/workflows/security.yml—defines the steps:
name: Security Testing
on:
pull_request:
branches: [ main ]
jobs:
security:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: '3.11'
- name: Install dependencies
run: |
pip install bandit
pip install safety
pip install flake8
pip install pyre-check
- name: Run static analysis
run: |
bandit -f json -o bandit-results.json -r .
flake8 . --output-format=pylint
pyre check --output-format=json
- name: Run dependency vulnerability scan
run: |
safety check --full-report --output=json > safety-results.json
- name: Run container image security scan
run: |
docker build -t app:latest .
trivy image --exit-code 1 --format json --output trivy-results.json app:latest
- name: Upload results
run: |
echo "::set-output name=results::$(cat bandit-results.json safety-results.json trivy-results.json | jq -c '.[]')"
Each step produces structured output. bandit generates a JSON report with issues like CWE-79, CWE-80, CWE-113, and CWE-126. safety reports pip-based vulnerabilities with package, installed_version, latest_version, cve, and fix_version. trivy outputs a JSON with vulnerabilities, misconfigurations, image, metadata, and summary.
The results are uploaded as artifacts and linked in the PR. A failing trivy scan adds a comment with all vulnerabilities, including title, description, severity, cvss, references, and fixed_in_version.
Security policies are expressed as code and validated against infrastructure configurations. This includes Terraform, Ansible, Kubernetes manifests, and Docker Compose. The validation runs as a CI job, comparing actual infrastructure against expected security standards.
The pipeline uses terraform and jq to validate configurations. A job checks that all S3 buckets are encrypted and have versioning enabled:
terraform plan -out=tfplan -no-color
terraform show -json tfplan > tfplan.json
jq -r '
.resources[] |
select(.type == "aws_s3_bucket") |
.values |
select(.encryption != null) |
select(.versioning != null) |
select(.versioning.enabled == true) |
.id as $id |
.encryption.sse_algorithm as $algorithm |
.versioning.enabled as $enabled |
[$id, $algorithm, $enabled] |
join(" | ")
' tfplan.json
The output is parsed to identify buckets that fail the policy. A terraform plan with a bucket missing encryption generates the following error:
Error: S3 Bucket Missing Encryption
- s3-bucket-prod
- Algorithm: AES256
- Versioning: false
- Expected: true
This error is written to a file, policy-violations.txt, which is used to generate a PR comment via curl:
curl -X POST \
-H "Authorization: Bearer $GITHUB_TOKEN" \
-H "Accept: application/vnd.github.v3+json" \
-d '{
"body": "### Security Policy Violations\n\n- s3-bucket-prod: Versioning disabled\n- s3-bucket-staging: SSE algorithm not AES256\n\nFix by setting `versioning.enabled = true` and `encryption.sse_algorithm = \"AES256\"`."
}' \
"https://api.github.com/repos/organization/project/issues/123/comments"
This comment appears in the PR, linking directly to the Terraform code and suggesting fixes.
Dynamic Application Security Testing (DAST) runs against a live, deployed instance of the application. The CI pipeline starts a test environment and runs DAST tools like owasp-zap, selenium, or cypress to probe the application.
The job starts a server in a Docker container and runs zap-cli to perform automated scans:
docker run -d --name app-server -p 8080:8080 app:latest
sleep 30 # Allow server to initialize
zap-cli quick-scan -t http://localhost:8080 -f html -o zap-report.html
# Export scan results to JSON
zap-cli report -f json -o zap-results.json
The zap-results.json contains a top-level alerts array with entries like:
{
"risk": "High",
"name": "Cross-Site Scripting (XSS)",
"description": "The application is vulnerable to XSS due to unsanitized input.",
"solution": "Use input validation and output encoding.",
"cwe": 79,
"url": "http://localhost:8080/login",
"evidence": "<input name=\"username\" type=\"text\">"
}
The pipeline checks for high-risk alerts and fails the build if any are found:
jq -r '
.alerts[] |
select(.risk == "High") |
.name |
select(. == "Cross-Site Scripting (XSS)") |
.url
' zap-results.json | grep -v "^$" > high-risk-xss.txt
if [ -s high-risk-xss.txt ]; then
echo "High-risk XSS detected. Failing CI."
exit 1
fi
The cypress test suite complements this by simulating user flows and capturing HTTP traffic. The results are stored as HAR files, which zap-cli consumes directly:
npx cypress run --record --parallel --headless
cypress export --format har --output cypress.har
zap-cli scan -f har -i cypress.har
Security testing isn't limited to code and infrastructure. Runtime checks validate that deployed services behave securely. These tests run at build time and are embedded in the container image.
A common pattern is validating that a service listens on the correct ports and exposes security headers. The CI job runs curl and grep to verify HTTP responses:
# Start service in container
docker run -d --name test-service -p 8080:8080 app:latest
# Wait for service to be ready
until curl -f http://localhost:8080/health; do
sleep 5
done
# Check for security headers
curl -I http://localhost:8080/ | grep -E 'Server|Content-Security-Policy|X-Frame-Options|X-Content-Type-Options'
# Output expected headers
expected_headers=(
"Server: nginx"
"Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline'"
"X-Frame-Options: DENY"
"X-Content-Type-Options: nosniff"
)
# Verify each header is present
for header in "${expected_headers[@]}"; do
if ! grep -q "$header" <(curl -I http://localhost:8080/); then
echo "Missing header: $header"
exit 1
fi
done
The job fails if any header is missing. The error includes the actual response headers:
Expected header: X-Frame-Options: DENY
Actual response:
HTTP/1.1 200 OK
Server: Apache
Content-Type: application/json
X-Frame-Options: ALLOW-FROM https://example.com
X-Content-Type-Options: nosniff
Content-Length: 123
Connection: keep-alive
Missing header: X-Frame-Options: DENY
The pipeline also checks that the service binds to the correct network interface and port:
docker inspect test-service --format='{{.NetworkSettings.IPAddress}}'
It expects the IP to be 0.0.0.0 or 127.0.0.1, and fails if the service listens only on 127.0.0.1.
When a test fails, the CI job produces a detailed report. The trivy failure includes a list of vulnerabilities with title, severity, cvss, references, and fixed_in_version. The safety check reports package, installed_version, latest_version, cve, and fix_version. The DAST report includes name, description, solution, cwe, url, and evidence.
The pipeline collects all results into a single JSON artifact:
{
"static_analysis": {
"bandit": {
"issues": [
{
"issue_id": "B101",
"severity": "High",
"line_number": 42,
"code": "request.form['username']",
"description": "SQL injection vulnerability"
}
]
}
},
"dependency_scanning": {
"safety": {
"vulnerabilities": [
{
"package": "django",
"installed_version": "4.1.7",
"latest_version": "5.0.0",
"cve": "CVE-2023-3456",
"fix_version": "5.0.1"
}
]
}
},
"container_scanning": {
"trivy": {
"vulnerabilities": [
{
"title": "OpenSSH 9.0 vulnerable to CVE-2023-2343",
"severity": "Critical",
"cvss": 9.8,
"references": [
"https://nvd.nist.gov/vuln/detail/CVE-2023-2343"
],
"fixed_in_version": "9.1"
}
]
}
}
}
This artifact is uploaded as a build artifact and used to generate a PR comment with a summary:
cat << EOF > pr-comment.md
### Security Testing Summary
- **Static Analysis**: 3 issues (1 High, 2 Medium)
- **Dependency Vulnerabilities**: 2 packages (1 Critical, 1 High)
- **Container Vulnerabilities**: 4 issues (1 Critical, 3 High)
#### High-Risk Issues
- SQL injection in `login` endpoint
- Django 4.1.7 vulnerable to CVE-2023-3456
#### Critical Issues
- OpenSSH 9.0 vulnerable to CVE-2023-2343
EOF
curl -X POST \
-H "Authorization: Bearer $GITHUB_TOKEN" \
-H "Accept: application/vnd.github.v3+json" \
-d '{"body": "$(cat pr-comment.md)"}' \
"https://api.github.com/repos/organization/project/issues/123/comments"
trivy image command expects a tag. If app:latest is not built, it uses app from docker build, but trivy fails to find the image. The fix is to ensure docker build -t app:latest runs before trivy.safety check output format: safety check --full-report produces json, but safety check --json produces a flat array. The pipeline expects a vulnerabilities array, but safety outputs a results top-level key. The error is: {
"results": [
{
"package": "requests",
"installed_version": "2.28.1",
"latest_version": "2.31.0",
"cve": "CVE-2023-4567"
}
]
}
The job fails because it expects vulnerabilities instead of results.
zap-cli quick-scan starts at /, but if the application has a /app route, the scan may miss /app if start_url is not set. The pipeline must explicitly set it: zap-cli quick-scan -t http://localhost:8080/app -f html -o zap-report.html
terraform plan generates a plan, but if the working directory has uncommitted changes, the plan output differs from what was expected. The job must use git add . and git commit before terraform plan.curl -f http://localhost:8080/health may fail if the service takes longer than 30 seconds to start. The pipeline must use timeout: timeout 60s curl -f http://localhost:8080/health
jq in CI environment: The jq command is required for processing JSON, but the CI runner image may not include it. The job must install jq: sudo apt-get update && sudo apt-get install -y jq
Security Testing In CI is not a checklist. It is a pipeline that evolves with the codebase, catching subtle issues before they become production incidents. The pattern is clear: run tests on every PR, validate policy code, integrate DAST, and enforce runtime behavior. The tools are standard, the failure modes predictable, and the feedback immediate.
This page was rewritten on 12 October 2026. It replaced a templated version that was not specific to its own title. How these pages are written and checked. If anything here is wrong, tell us at [email protected] and we will correct it.
We use cookies for analytics (Google Analytics) and advertising (Google AdSense) to improve your experience and support free content. Privacy Policy