Skip to content

About

Container vulnerability management: Trivy image/fs/IaC scanning, CVE classification and CI/CD policy gates, SBOM and cosign signing, aggregated dashboard from synthetic data, remediation workflow.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

devsecops-vulnerability-platform

Container vulnerability management platform: Trivy-based image, filesystem and IaC scanning, CVE classification with exploitability escalation, policy gates in CI/CD, SBOM generation and cosign signing, aggregated reporting, a static security dashboard built from synthetic data, and a remediation workflow with severity-based SLAs.

Scanner Signing Policy Python License

Project Overview

This repository implements the full lifecycle of a container vulnerability finding: detect it in a pull request or in the registry, classify it by severity, fix availability and real-world exploitability (CISA KEV, EPSS), decide with a per-environment policy whether it blocks, sign and attest what passes, enforce provenance at Kubernetes admission, and track remediation against SLAs on a dashboard that GitHub Pages can host. The scanning and policy tooling is a few hundred lines of shell and dependency-free Python that accept unmodified Trivy output.

Scope note: This is a personal reference implementation built to demonstrate production-grade patterns I use professionally. It is not the production code of any employer, and all project IDs, domains, IPs, and data are placeholders or synthetic.

The dashboard and every file under mock-data/ and reports/ are synthetic. tools/generate_mock_data.py produces Trivy-shaped reports for eight fictitious example/* images with made-up CVE-20xx-1xxxx identifiers, package versions, EPSS scores and KEV flags. They exist so the reporting pipeline can be demonstrated and tested end to end without a registry.

Problem Statement

Scanning images is easy; acting on the results is not. Teams typically run Trivy in CI with --exit-code 1 and then face three problems: the gate is either so strict that unfixable OS findings block every change, or so loose it never blocks; severity labels ignore whether a CVE is actually exploited; and findings that are not blocking simply disappear, so nobody knows how much debt exists, who owns it or whether the 30-day fix promise was kept. Exceptions end up as permanent .trivyignore lines nobody revisits.

This platform separates the concerns. Scanning produces one JSON artifact per image. Policy is a single data file that says what blocks in pr, main and prod, how KEV and EPSS escalate severity, what the SLAs are and how long exceptions may live. Tooling applies that policy consistently in PR comments, nightly aggregation, the dashboard and admission control, and exceptions expire on their own.

Architecture

Build and gate. A pull request builds examples/sample-app/Dockerfile into a tarball (never pushed), the reusable reusable-trivy-scan.yml workflow scans it once in JSON and derives SARIF and a table with trivy convert, and tools/triage.py evaluates policy/severity-policy.json for the pr environment: fixable CRITICALs block, KEV-listed CVEs block even when unfixed, unexpired exceptions from scanner/.trivyignore.yaml are honoured and listed. The result is posted as an updating PR comment and mirrored to GitHub code scanning.

Release. On a version tag sbom-and-sign.yml pushes the image to Artifact Registry through Workload Identity Federation, generates a CycloneDX SBOM, gates on fixable CRITICAL/HIGH, then signs the digest keylessly with cosign and attaches SBOM and vulnerability attestations. The certificate identity is the workflow itself, which Kyverno later pins.

Admission and runtime. kubernetes/admission/verify-images.yaml verifies the cosign signature and SBOM attestation, rejects latest, and requires digests in production namespaces. kubernetes/trivy-operator/ configures continuous in-cluster rescanning of running workloads with Prometheus metrics.

Nightly. nightly-registry-scan.yml enumerates tagged images in Artifact Registry (scanner/scan-registry.sh), scans each by digest including unfixed findings, merges everything with tools/aggregate.py (per image, per package, per CVE, CVE age, SLA breaches), renders the static dashboard, publishes it to GitHub Pages and opens labelled GitHub issues for images with new CRITICAL findings. A --mock mode runs the same path on the synthetic data.

Details: docs/architecture.md, docs/cve-classification.md, docs/remediation-workflow.md, docs/base-image-governance.md, docs/dashboard.md.

Architecture Diagram

flowchart LR
    subgraph PR["Pull request"]
        DF["Dockerfile"] --> BUILD["docker build to tarball"]
        BUILD --> SCAN["Trivy image scan JSON + SARIF"]
        SCAN --> GATE["triage.py policy gate env=pr"]
        GATE --> COMMENT["PR comment + code scanning"]
    end
    subgraph REL["Release tag"]
        PUSH["Push to Artifact Registry by digest"] --> SBOM["CycloneDX SBOM"]
        SBOM --> SIGN["cosign sign + attest keyless OIDC"]
    end
    subgraph GKE["GKE cluster"]
        KYV["Kyverno: verify signature, deny latest, require digest"] --> RUN["Workloads"]
        RUN --> OP["trivy-operator VulnerabilityReports"]
    end
    subgraph NIGHT["Nightly 02:00 UTC"]
        LIST["scan-registry.sh lists images via gcloud"] --> RESCAN["Trivy scan each digest incl. unfixed"]
        RESCAN --> AGG["aggregate.py"]
        AGG --> DASH["render_dashboard.py to GitHub Pages"]
        AGG --> ISSUES["GitHub issues for new CRITICAL"]
    end
    GATE -- "passes" --> PUSH
    SIGN --> KYV
    PUSH --> LIST
    POLICY["policy/severity-policy.json + .trivyignore.yaml"] -.-> GATE
    POLICY -.-> AGG
    ENRICH["KEV + EPSS enrichment"] -.-> GATE
    ENRICH -.-> AGG
Loading

Remediation flow (detect, triage, assign, fix or exception, verify, close) is drawn in docs/remediation-workflow.md.

Technology Stack

Layer Technology Notes
Scanner Trivy 0.5x+ (aquasecurity/trivy-action@0.28.0, aquasecurity/setup-trivy) Image, filesystem, IaC, SBOM (--format cyclonedx), trivy convert for SARIF/table
Policy as data JSON (canonical) + YAML copy policy/severity-policy.json; kept in sync by a unit test
Policy as code OPA / Rego (import rego.v1) policy/rego/image-policy.rego with unit tests
Admission Kyverno 1.12 ClusterPolicy cosign keyless verification, latest denial, digest requirement
Runtime scanning trivy-operator Helm chart VulnerabilityReport CRDs, Prometheus metrics
Signing Sigstore cosign (sigstore/cosign-installer@v3) Keyless via GitHub OIDC; SBOM and vuln attestations
CI/CD GitHub Actions Reusable workflow_call scan, PR gate, nightly, release, CI
Cloud Google Cloud Artifact Registry, GKE Auth via google-github-actions/auth@v2 Workload Identity Federation
Tooling Python 3.11+ standard library, Bash argparse, type hints, unittest; set -euo pipefail
Dashboard Static HTML, inline CSS and SVG No external assets; light and dark mode; GitHub Pages

Repository Structure

devsecops-vulnerability-platform/
├── .github/
│   ├── CODEOWNERS
│   └── workflows/
│       ├── ci.yml                      # unit tests, ruff, YAML/shell/Dockerfile lint, opa test, kyverno test, artifact drift
│       ├── pr-gate.yml                 # build tarball -> reusable scan -> triage.py -> PR comment; IaC scan
│       ├── reusable-trivy-scan.yml     # workflow_call: JSON/SARIF/table, counts as outputs, code scanning upload
│       ├── nightly-registry-scan.yml   # OIDC to GCP, scan registry, aggregate, dashboard to Pages, issues
│       └── sbom-and-sign.yml           # push by digest, CycloneDX SBOM, cosign sign + attest, verify
├── scanner/
│   ├── scan-image.sh                   # trivy image -> results.json/.sarif/.txt, optional sbom.cdx.json, gate exit code
│   ├── scan-fs.sh                      # trivy fs (lockfiles, secrets)
│   ├── scan-iac.sh                     # trivy config for Dockerfile/Kubernetes/Terraform/Helm
│   ├── scan-registry.sh                # gcloud artifacts docker images list -> scan each (or --mock)
│   ├── trivy.yaml                      # shared scanner configuration
│   └── .trivyignore.yaml               # exception register: id, paths, statement, expired_at
├── policy/
│   ├── severity-policy.json            # canonical gate thresholds, escalation, SLA, exception limits
│   ├── severity-policy.yaml            # human-readable copy (checked against JSON in tests)
│   ├── remediation-sla.md
│   ├── exception-process.md
│   └── rego/
│       ├── image-policy.rego           # deny: blocking vulns, latest tag, no digest, unsigned, EOL base
│       └── image-policy_test.rego
├── tools/
│   ├── vulnlib.py                      # Trivy JSON model, policy/enrichment loaders, .trivyignore reader
│   ├── triage.py                       # classify, escalate, gate, markdown for PR comment, exit code
│   ├── aggregate.py                    # merge scans -> reports/aggregate.json
│   ├── render_dashboard.py             # aggregate.json + history.json -> dashboard/index.html
│   ├── generate_mock_data.py           # deterministic synthetic Trivy-like reports
│   └── tests/
│       ├── test_triage.py
│       └── test_aggregate.py
├── mock-data/                          # SYNTHETIC: scans/*.json, first-seen.json, enrichment.json, history.json
├── reports/aggregate.json              # generated from mock-data (committed for browsing)
├── dashboard/index.html                # generated static dashboard (committed for browsing / GitHub Pages)
├── examples/sample-app/
│   ├── Dockerfile                      # hardened: multi-stage, distroless, non-root
│   ├── Dockerfile.insecure             # deliberately bad, for scan-iac.sh demos
│   └── app.py                          # stdlib HTTP service with /healthz
├── kubernetes/
│   ├── admission/
│   │   ├── verify-images.yaml          # Kyverno ClusterPolicies
│   │   ├── kyverno-test.yaml           # kyverno test fixture
│   │   └── test-resources.yaml
│   └── trivy-operator/
│       ├── values.yaml
│       └── README.md
├── docs/
│   ├── architecture.md
│   ├── cve-classification.md
│   ├── remediation-workflow.md
│   ├── base-image-governance.md
│   └── dashboard.md
├── Makefile
├── .env.example
├── .gitignore
├── LICENSE
└── README.md

Prerequisites

Tool Version Needed for
Python 3.11 or newer tools/ (standard library only)
Trivy 0.50 or newer (tested with 0.67) scanner/*.sh, local scans
Docker or Buildx recent Building examples/sample-app
gcloud CLI recent scan-registry.sh against Artifact Registry
OPA 0.60 or newer opa test policy/rego
cosign 2.x Verifying signatures locally
Kyverno CLI 1.12 kyverno test kubernetes/admission
GitHub repository settings - Actions enabled, code scanning (SARIF upload) available, Pages source set to "GitHub Actions"
GCP - Artifact Registry repository; Workload Identity Federation pool and provider for GitHub OIDC; two service accounts (scanner reader, publisher writer)

Only Python is required to regenerate the mock data, aggregate and dashboard and to run the tests.

Installation

git clone https://github.com/deveshr17/devsecops-vulnerability-platform.git
cd devsecops-vulnerability-platform

# Regenerate every committed artifact and run the unit tests (Python only)
make all

# Optional: local scanner tooling
brew install trivy opa cosign kyverno   # or the equivalent for your platform

Verify the tooling without any cloud access:

make triage ENV=pr      # expected: exit 1, blocking CRITICALs listed in the markdown
make triage ENV=prod    # zero-CRITICAL policy incl. unfixed
make scan-sample        # builds the hardened Dockerfile and scans it (requires docker + trivy)
make scan-iac           # flags examples/sample-app/Dockerfile.insecure on purpose

Configuration

Copy .env.example to .env for local use of the shell scripts (never commit .env):

Variable Default Purpose
GCP_PROJECT_ID example-project-dev Project hosting Artifact Registry
AR_LOCATION / AR_REPOSITORY asia-south1 / apps Registry to enumerate in scan-registry.sh
TRIVY_SEVERITY CRITICAL,HIGH Gate severities for scan-image.sh
TRIVY_IGNORE_UNFIXED true Drop findings without a fix in CI gates
TRIVY_DB_REPOSITORY public.ecr.aws/aquasecurity/trivy-db:2 DB mirror to avoid ghcr.io rate limits
GATE_ENV pr Policy environment for triage.py
SCAN_MAX_IMAGES 50 Cap for the nightly registry scan

GitHub Actions configuration (repository settings):

Kind Name Used by
Secret GCP_WORKLOAD_IDENTITY_PROVIDER projects/<number>/locations/global/workloadIdentityPools/<pool>/providers/<provider>
Secret GCP_SCANNER_SERVICE_ACCOUNT Nightly scan; needs roles/artifactregistry.reader
Secret GCP_PUBLISHER_SERVICE_ACCOUNT Release; needs roles/artifactregistry.writer on one repository
Variable GCP_PROJECT_ID, AR_LOCATION, AR_REPOSITORY Registry coordinates
Environment github-pages Created automatically by actions/deploy-pages

Policy configuration lives in policy/severity-policy.json (edit both the JSON and the YAML copy; the unit test fails if they diverge):

Environment Blocks Fixed only Intent
pr CRITICAL yes Never let a fixable CRITICAL into main
main CRITICAL, HIGH yes Images promoted from main must be fully patchable-clean
prod CRITICAL no Zero CRITICAL in production; unfixed ones need an exception

Escalation: KEV listing makes a finding CRITICAL and blocking regardless of fix status; EPSS at or above 0.5 bumps one level. SLAs: CRITICAL 7 days, HIGH 30, MEDIUM 90, LOW best effort. Exceptions are capped at 30/90/180/365 days by severity and must carry statement and expired_at.

Deployment

Scanner tooling needs no deployment; it runs where the workflows run.

Kyverno admission policies

kubectl apply -f kubernetes/admission/verify-images.yaml
kubectl get clusterpolicy
# Roll out in Audit mode first in dev/uat:
kubectl patch clusterpolicy verify-cosign-signature --type merge -p '{"spec":{"validationFailureAction":"Audit"}}'
kubectl get policyreport -A

trivy-operator

helm repo add aqua https://aquasecurity.github.io/helm-charts/
helm upgrade --install trivy-operator aqua/trivy-operator \
  --namespace trivy-system --create-namespace --version 0.24.1 \
  -f kubernetes/trivy-operator/values.yaml
kubectl get vulnerabilityreports -A

Dashboard is published by the nightly workflow to GitHub Pages (Settings, Pages, Source: GitHub Actions). Run the workflow manually with mock: true to publish the synthetic dashboard without any GCP access.

Rollback. Policy and exception changes are plain files: revert the commit and the next run applies the previous policy. Kyverno policies can be switched to Audit or deleted without affecting running pods. A signed image that later turns out to be vulnerable is handled by the remediation workflow, not by revoking signatures.

CI/CD

Workflow Trigger What it does
ci.yml push to main, pull requests py_compile, ruff, unittest, YAML parse of every file, bash -n + shellcheck, hadolint on the hardened Dockerfile, opa fmt/check/test, kyverno test, regenerates mock data, aggregate and dashboard and fails on drift
pr-gate.yml pull requests touching examples, scanner, policy, tools, kubernetes, workflows Builds the sample image to a tarball, calls the reusable scan, runs triage.py --env pr, posts or updates a PR comment, uploads SARIF, separate trivy config job for IaC
reusable-trivy-scan.yml workflow_call Inputs image_ref or image_tar_artifact, severity, exit_code, ignore_unfixed, upload_sarif; outputs critical_count, high_count, medium_count, low_count, total_count, gate_result
sbom-and-sign.yml tags v*.*.*, manual WIF auth, push by digest with semver and short-sha tags (never latest), CycloneDX SBOM, Trivy gate, cosign sign, SBOM and vuln attestations, verification
nightly-registry-scan.yml 0 2 * * *, manual (mock, max_images) Registry enumeration and scan, aggregate, dashboard, Pages deploy, one issue per image with new CRITICALs (labels security, vulnerability, severity:critical, team:<service>)

Conventions applied across workflows: permissions: declared at workflow and job level with id-token: write only where OIDC is needed; concurrency groups; timeout-minutes on every job; actions pinned to major versions and Trivy to 0.28.0; Trivy DB cached; exit-code: 1 with ignore-unfixed: true for the release gate. The github-pages environment is the only deployment environment in this repository; approval gates for uat/production belong to the deployment repositories that consume the signed images.

Security

  • No credentials in the repository. GCP access uses Workload Identity Federation; secrets referenced are the provider resource name and service account emails. .gitignore excludes .env, keys, kubeconfigs and scan output.
  • Least privilege. The scanner service account reads Artifact Registry only; the publisher writes one repository. Workflow tokens hold contents: read by default with security-events, pull-requests, issues, pages granted per job.
  • Supply chain. Images are addressed by digest after push, signed keylessly with an identity bound to the release workflow, and carry SBOM and vulnerability attestations. Kyverno pins the exact certificate subject and issuer, resolves tags to digests and denies latest.
  • Hardened sample image. Multi-stage build, distroless runtime, non-root user, exec-form entrypoint, OCI labels including the base image name. Dockerfile.insecure documents the anti-patterns the scanners detect.
  • Gate semantics. Gates fail closed on policy (exit 1) and surface scanner failures separately (exit 3) so a broken DB download is never mistaken for a clean scan.
  • Exceptions expire. scanner/.trivyignore.yaml entries require statement and expired_at; triage.py stops applying expired entries and lists them in the PR comment. CODEOWNERS routes changes to review.
  • Dashboard. Self-contained HTML with no third-party assets, so hosting it publicly leaks nothing beyond its own content, which here is synthetic.

Monitoring

Signal Source Consumer
Per-image severity counts, KEV hits, fixable share, SLA breaches, trend reports/aggregate.json, dashboard/index.html Nightly Pages deploy; teams and security review
Code scanning alerts SARIF from image and IaC scans GitHub Security tab, per-repository
New CRITICAL findings Nightly diff against the committed baseline GitHub issues labelled per team and severity
Running workload exposure trivy-operator trivy_image_vulnerabilities, trivy_vulnerability_id metrics Prometheus / Grafana; example alert in kubernetes/trivy-operator/README.md (for: 6h to avoid paging on transient findings)
Admission denials Kyverno PolicyReport / ClusterPolicyReport, kyverno_policy_results_total Cluster dashboards; a spike means a pipeline skipped signing
Workflow health GitHub Actions run status, gate_result output Branch protection requires PR security gate and CI

Troubleshooting

Symptom Likely cause How to check Fix
Trivy fails with TOOMANYREQUESTS downloading the DB ghcr.io rate limit on shared runners Job log around "Downloading vulnerability DB" Keep TRIVY_DB_REPOSITORY=public.ecr.aws/aquasecurity/trivy-db:2; ensure the cache step restored
PR gate fails but the comment shows only unfixed CRITICALs A KEV-listed CVE blocks regardless of fix status "Exploitability escalations" table shows KEV Fix, or open a short (max 14 day) exception approved by security
Gate passes locally, fails in CI Different --env or ignore file Compare triage.py --env and --ignore-file arguments Use make triage ENV=pr which mirrors the workflow
triage.py exits 2 Malformed or non-Trivy JSON (SchemaVersion not 2) python3 -c 'import json; print(json.load(open("results.json"))["SchemaVersion"])' Scan with --format json; SARIF and table cannot be re-imported
CI "artifact drift" step fails mock-data/, reports/ or dashboard/ regenerated differently make all && git status Commit the regenerated files; generation is deterministic (fixed seed and timestamps)
Kyverno rejects a signed image Certificate subject does not match the pinned workflow path or ref cosign verify --certificate-identity-regexp ... <image>; check policyreport message Sign from sbom-and-sign.yml on a v* tag, or adjust the subject pattern deliberately
Kyverno rejects every pod in prod-* after enabling policies Tag-only references and mutateDigest not applied in Audit mode kubectl describe pod events Roll out in Audit, fix manifests to digest references, then Enforce
scan-registry.sh scans zero images Filter or permissions gcloud artifacts docker images list <repo> --include-tags as the scanner SA Grant roles/artifactregistry.reader; adjust --filter
Dashboard shows no trend history.json missing or fewer than two points python3 -c 'import json; print(len(json.load(open("mock-data/history.json"))["points"]))' Regenerate with make mock-data; in production append a point per nightly run
.trivyignore.yaml entry does not suppress a finding Entry expired, paths too narrow, or wrong ID PR comment "Expired exceptions" section; trivy image --ignorefile ... --debug Renew via the exception process or remove the entry

Cost Considerations

  • GitHub Actions minutes. A PR gate run (build, scan, triage) takes roughly five minutes on ubuntu-latest; the nightly scan scales linearly with images (about 20 to 40 seconds each with a warm DB). Caching the Trivy DB saves about one minute per job and avoids rate limits. Public repositories run free; private repositories should watch the nightly job's max_images cap.
  • Artifact Registry. Storage is billed per GB-month; keep it bounded with cleanup policies (delete untagged images after 7 days, keep the last 10 tagged versions). Scanning does not pull layers to disk twice: Trivy streams and caches per layer.
  • GKE add-ons. trivy-operator adds one small deployment plus short-lived scan jobs; the ClientServer mode keeps the DB in one pod instead of downloading it per job. Kyverno webhooks add milliseconds to admissions and negligible cost.
  • Sigstore public good instance. Keyless signing against Fulcio and Rekor is free; the transparency log entry is public, which is acceptable for image digests and workflow identities.
  • GitHub Pages and code scanning. Included with the repository; the dashboard is a single file of a few tens of kilobytes.
  • Avoided cost. The main saving is engineering time: fixable findings are fixed by digest bumps proposed automatically, and exceptions expire instead of accumulating into audits.

Future Improvements

  • Download the live CISA KEV catalog and EPSS feed in the nightly job and cache them as workflow artifacts instead of the synthetic enrichment.json.
  • Persist first-seen dates and history across nightly runs (small Cloud Storage object or the previous aggregate.json from the gh-pages branch) so SLA clocks and trends are real rather than seeded.
  • Convert trivy-operator VulnerabilityReport objects into Trivy JSON and merge them into the same aggregate so the dashboard covers running workloads as well as registry contents.
  • Add VEX (OpenVEX) statements as the machine-readable form of exceptions and feed them to Trivy with --vex, retiring free-text ignore entries.
  • Group findings by base image digest to show the exact CVE reduction a base bump would deliver before the PR is opened.
  • Emit an OpenTelemetry or Prometheus push of the aggregate totals so the SLA breach count can be alerted on in the same stack as runtime metrics.
  • Extend the Rego policy into a Gatekeeper ConstraintTemplate variant for clusters that standardise on OPA rather than Kyverno.
  • Add Terraform for the Workload Identity Federation pool, provider and the two service accounts so the GCP side of the setup is reproducible.

About

Container vulnerability management: Trivy image/fs/IaC scanning, CVE classification and CI/CD policy gates, SBOM and cosign signing, aggregated dashboard from synthetic data, remediation workflow.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages