diff --git a/.github/custom_tools/trivy/compare_summaries.py b/.github/custom_tools/trivy/compare_summaries.py new file mode 100644 index 00000000..304e59b0 --- /dev/null +++ b/.github/custom_tools/trivy/compare_summaries.py @@ -0,0 +1,129 @@ +# Copyright (C) 2024-2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +import argparse +import csv +import os + + +KEY_FIELDS = ("image", "cve", "name") +IMPORTANT_SEVERITIES = {"HIGH", "CRITICAL"} +PYTHON_VULN_CLASS = "lang-pkgs" +PYTHON_VULN_TYPE = "python-pkg" + + +def load_rows(csv_path: str): + rows = [] + with open(csv_path, newline="") as fh: + reader = csv.DictReader(fh) + for row in reader: + rows.append(row) + return rows + + +def build_keyed_rows(rows): + keyed = {} + for row in rows: + key = tuple(row.get(field, "") for field in KEY_FIELDS) + keyed[key] = row + return keyed + + + + + + +def fmt_row(row: dict) -> str: + return ( + f"| {row.get('image', '')} | {row.get('severity', '')} | " + f"{row.get('cve', '')} | {row.get('name', '')} | " + f"{row.get('version', '')} |" + ) + + +def build_markdown(mitigated_rows, baseline_count, current_count): + mitigated_count = len(mitigated_rows) + lines = [ + "## Trivy CVE delta", + "", + f"- Baseline (`latest`) findings: **{baseline_count}**", + f"- Current PR findings: **{current_count}**", + f"- Mitigated HIGH/CRITICAL Python-library findings: **{mitigated_count}**", + "", + ] + + if mitigated_count == 0: + lines.append("No mitigated HIGH/CRITICAL CVEs were detected for Python libraries.") + lines.append("") + return "\n".join(lines) + + lines.extend([ + "### Mitigated HIGH/CRITICAL Python-library findings", + "", + "| Image | Severity | CVE | Package | Old version |", + "| --- | --- | --- | --- | --- |", + ]) + + for row in mitigated_rows: + lines.append(fmt_row(row)) + + lines.append("") + return "\n".join(lines) + + +def write_github_outputs(baseline_count, current_count, mitigated_count): + github_output = os.getenv("GITHUB_OUTPUT") + if not github_output: + return + + with open(github_output, "a", encoding="utf-8") as fh: + fh.write(f"baseline_count={baseline_count}\n") + fh.write(f"current_count={current_count}\n") + fh.write(f"mitigated_count={mitigated_count}\n") + + +def is_python_library_vuln(row: dict) -> bool: + vuln_class = (row.get("vuln_class") or "").strip().lower() + vuln_type = (row.get("vuln_type") or "").strip().lower() + return vuln_class == PYTHON_VULN_CLASS and vuln_type == PYTHON_VULN_TYPE + + +def main(): + parser = argparse.ArgumentParser(description="Compare Trivy summary CSV files") + parser.add_argument("baseline_csv", help="Baseline summary CSV (e.g. latest images)") + parser.add_argument("current_csv", help="Current summary CSV (e.g. PR images)") + parser.add_argument("output_markdown", help="Output markdown report") + args = parser.parse_args() + + baseline_rows = load_rows(args.baseline_csv) + current_rows = load_rows(args.current_csv) + + baseline_keyed = build_keyed_rows(baseline_rows) + current_keyed = build_keyed_rows(current_rows) + + mitigated_keys = sorted(set(baseline_keyed) - set(current_keyed)) + mitigated_rows = [baseline_keyed[key] for key in mitigated_keys] + mitigated_rows = [ + row for row in mitigated_rows + if (row.get("severity") or "").upper() in IMPORTANT_SEVERITIES and is_python_library_vuln(row) + ] + + markdown = build_markdown( + mitigated_rows=mitigated_rows, + baseline_count=len(baseline_rows), + current_count=len(current_rows), + ) + + with open(args.output_markdown, "w", encoding="utf-8") as fh: + fh.write(markdown) + + write_github_outputs( + baseline_count=len(baseline_rows), + current_count=len(current_rows), + mitigated_count=len(mitigated_rows), + ) + + +if __name__ == "__main__": + main() + diff --git a/.github/custom_tools/trivy/data_models.py b/.github/custom_tools/trivy/data_models.py new file mode 100644 index 00000000..32b9b67f --- /dev/null +++ b/.github/custom_tools/trivy/data_models.py @@ -0,0 +1,89 @@ +# Copyright (C) 2024-2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +import os +from datetime import datetime, timezone +from enum import IntEnum + + +def errors_path(postprocessed_path: str) -> str: + """Sidecar file next to the postprocessed results, holding the + vulnerabilities that could not be processed. Written by + json_postprocess.py, reported on by the summary builder.""" + base, ext = os.path.splitext(postprocessed_path) + return f"{base}-errors{ext or '.json'}" + + +class Severity(IntEnum): + CRITICAL = 4 + HIGH = 3 + MEDIUM = 2 + LOW = 1 + UNKNOWN = 0 + + +class AffectedDependency: + """To avoid duplicates of vulnerabilities coming from different + places of same package, __hash__ and __eq__ are implemented, + so that objects are suitable to use in sets.""" + + def __init__( + self, + vuln_class: str, + vuln_type: str, + name: str, + version: str, + severity: Severity, + published_date: str, + fix: str, + cve: str, + cve_url: str, + title: str + ): + self.vuln_class = vuln_class + self.vuln_type = vuln_type + self.name = name + self.version = version + if isinstance(severity, int): + severity = Severity(severity) + self.severity = severity + self.published_date = published_date + self.fix = fix + self.cve = cve + self.cve_url = cve_url + self.title = title + + def __eq__(self, other): + if not isinstance(other, AffectedDependency): + return False + return self.name == other.name and self.cve == other.cve + + def __hash__(self): + return hash((self.name, self.cve)) + + @property + def age(self) -> int: + if self.published_date is None: + return 0 + # Handle case with and without microseconds + try: + published = datetime.strptime(self.published_date, "%Y-%m-%dT%H:%M:%S.%fZ") + except ValueError: + published = datetime.strptime(self.published_date, "%Y-%m-%dT%H:%M:%SZ") + now = datetime.now(timezone.utc) + age_days = (now - published.replace(tzinfo=timezone.utc)).days + return age_days + + def to_dict(self): + return { + "vuln_class": self.vuln_class, + "vuln_type": self.vuln_type, + "name": self.name, + "version": self.version, + "severity": self.severity, + "published_date": self.published_date, + "fix": self.fix, + "cve": self.cve, + "cve_url": self.cve_url, + "title": self.title + } diff --git a/.github/custom_tools/trivy/json_postprocess.py b/.github/custom_tools/trivy/json_postprocess.py new file mode 100644 index 00000000..ba972711 --- /dev/null +++ b/.github/custom_tools/trivy/json_postprocess.py @@ -0,0 +1,79 @@ +# Copyright (C) 2024-2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +""" +This script processes Trivy JSON to form that will be used +for per-image results and summary. +""" + +import json +import argparse + +from data_models import AffectedDependency, Severity, errors_path + +parser = argparse.ArgumentParser(description="Process Trivy JSON results.") +parser.add_argument("input_file", help="Input Trivy JSON filename") +parser.add_argument("output_file", help="Output processed JSON filename") +args = parser.parse_args() + +with open(args.input_file, 'r') as f: + data = json.load(f) + + +def vuln_url(vuln: dict) -> str: + """Trivy omits PrimaryURL for advisories without an NVD entry, + e.g. Go-only ones like GO-2026-5932. Fall back to a reference + pointing at the advisory itself, then to its data source.""" + if vuln.get("PrimaryURL"): + return vuln["PrimaryURL"] + for ref in vuln.get("References", []): + if vuln["VulnerabilityID"] in ref: + return ref + return vuln.get("DataSource", {}).get("URL", "") + + +deps = [] +errors = [] + +for r in data["Results"]: + if "Vulnerabilities" not in r: + continue + + for vuln in r["Vulnerabilities"]: + try: + fix = None + if vuln["Status"] == "fixed": + fix = vuln["FixedVersion"] + dep = AffectedDependency( + r["Class"], + r["Type"], + vuln["PkgName"], + vuln["InstalledVersion"], + Severity[vuln["Severity"]], + vuln.get("PublishedDate"), + fix, + vuln["VulnerabilityID"], + vuln_url(vuln), + vuln.get("Title", f"Title not found. Description: {vuln.get('Description', 'Also not found.')}") + ) + deps.append(dep) + except KeyError as e: + print( + f"ERROR: missing key {e} in vulnerability " + f"{json.dumps(vuln, indent=4)}", + ) + errors.append({"missing_key": e.args[0], "vulnerability": vuln}) + +# Remove duplicates +deps = set(deps) +deps = list(deps) +deps_dicted = [d.to_dict() for d in deps] + +with open(args.output_file, 'w') as f: + f.write(json.dumps(deps_dicted, indent=4)) + +# The summary builder picks this up to report that some vulnerabilities +# are missing from its tables. +if errors: + with open(errors_path(args.output_file), 'w') as f: + f.write(json.dumps(errors, indent=4)) diff --git a/.github/custom_tools/trivy/sdl-config.yaml b/.github/custom_tools/trivy/sdl-config.yaml new file mode 100644 index 00000000..1b46104e --- /dev/null +++ b/.github/custom_tools/trivy/sdl-config.yaml @@ -0,0 +1,14 @@ +timeout: 40m +exit-code: 2 +list-all-pkgs: true +format: template +template: '@.github/custom_tools/trivy/sdl-template.tpl' +output: sdl-scan-results.csv +scan: + scanners: + - vuln +severity: + - HIGH + - CRITICAL +skip-dirs: + - /compliance/ diff --git a/.github/custom_tools/trivy/sdl-template.tpl b/.github/custom_tools/trivy/sdl-template.tpl new file mode 100644 index 00000000..0c1e5074 --- /dev/null +++ b/.github/custom_tools/trivy/sdl-template.tpl @@ -0,0 +1,29 @@ +{{ range . }} +Trivy Vulnerability Scan Results ({{- .Target -}}) +VulnerabilityID,Severity,CVSS Score,Title,Library,Vulnerable Version,Fixed Version,Information URL,Triage Information +{{ range .Vulnerabilities }} + {{- .VulnerabilityID }}, + {{- .Severity }}, + {{- range $key, $value := .CVSS }} + {{- if (eq $key "nvd") }} + {{- .V3Score -}} + {{- end }} + {{- end }}, + {{- quote .Title }}, + {{- quote .PkgName }}, + {{- quote .InstalledVersion }}, + {{- quote .FixedVersion }}, + {{- .PrimaryURL }} +{{ else -}} + No vulnerabilities found at this time. +{{ end }} +Trivy Dependency Scan Results ({{ .Target }}) +ID,Name,Version,Notes +{{ range .Packages -}} + {{- quote .ID }}, + {{- quote .Name }}, + {{- quote .Version }} +{{ else -}} + No dependencies found at this time. +{{ end }} +{{ end }} diff --git a/.github/custom_tools/trivy/summary_builder_all.py b/.github/custom_tools/trivy/summary_builder_all.py new file mode 100644 index 00000000..f8413df2 --- /dev/null +++ b/.github/custom_tools/trivy/summary_builder_all.py @@ -0,0 +1,70 @@ +# Copyright (C) 2024-2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +import os +import json +import csv +from data_models import AffectedDependency +import argparse + +parser = argparse.ArgumentParser(description="Build summary CSV from Trivy results") +parser.add_argument("results_dir", help="Directory containing Trivy results") +parser.add_argument("output_csv", help="Output CSV file name") +parser.add_argument( + "--strip-prefix", + default="", + help="Prefix to strip from artifact directory names to recover the bare image name", +) +args = parser.parse_args() + +results_dir = args.results_dir +output_csv = args.output_csv +strip_prefix = args.strip_prefix + + +fieldnames = [ + "image", + "vuln_class", + "vuln_type", + "name", + "version", + "severity", + "published_date", + "fix", + "cve", + "cve_url", + "title" +] + + +def extract_image_name(directory_name: str) -> str: + """Extract the bare image name from an artifact directory name. + + Artifact namespacing (e.g. a ``pr-``/``latest-`` prefix) is owned by the + caller, which passes the prefix to strip via ``--strip-prefix`` so that + the same image compares equal across scan variants. + """ + if strip_prefix and directory_name.startswith(strip_prefix): + return directory_name[len(strip_prefix):] + return directory_name + + +with open(output_csv, "w", newline="") as csvfile: + writer = csv.DictWriter(csvfile, fieldnames=fieldnames) + writer.writeheader() + + for img_dir in os.listdir(results_dir): + full_path = os.path.join(results_dir, img_dir) + if os.path.isdir(full_path): + json_path = os.path.join(full_path, "trivy-postprocessed.json") + if os.path.isfile(json_path): + with open(json_path, "r") as f: + data = json.load(f) + for obj_dict in data: + dep = AffectedDependency(**obj_dict) + row = dep.to_dict() + row["image"] = extract_image_name(img_dir) + # If severity is an enum, convert to string + if hasattr(row["severity"], "name"): + row["severity"] = row["severity"].name + writer.writerow(row) diff --git a/.github/custom_tools/trivy/summary_builder_one_image.py b/.github/custom_tools/trivy/summary_builder_one_image.py new file mode 100644 index 00000000..d2ba8154 --- /dev/null +++ b/.github/custom_tools/trivy/summary_builder_one_image.py @@ -0,0 +1,122 @@ +# Copyright (C) 2024-2026 Intel Corporation +# SPDX-License-Identifier: Apache-2.0 + +import os +import json +import argparse + +from data_models import AffectedDependency, Severity, errors_path + +parser = argparse.ArgumentParser(description="Build summary CSV from Trivy results") +parser.add_argument("trivy_json", help="File with postprocessed Trivy JSON results") +args = parser.parse_args() + +# choices from Trivy: lang-pkgs, os-pkgs +IMPORTANT_VULN_CLASSES = ['lang-pkgs', 'os-pkgs'] +IMPORTANT_VULN_SEVERITIES = [Severity.CRITICAL, Severity.HIGH] + +vulns = [] +with open(args.trivy_json, 'r') as f: + data = json.load(f) + for obj_dict in data: + dep = AffectedDependency(**obj_dict) + vulns.append(dep) + +had_errors = os.path.isfile(errors_path(args.trivy_json)) + +vulns = sorted(vulns, key=lambda v: (v.severity, v.age), reverse=True) + +vulns_important_fixable = [ + vuln for vuln in vulns + if ( + vuln.vuln_class in IMPORTANT_VULN_CLASSES + and vuln.severity in IMPORTANT_VULN_SEVERITIES + and vuln.fix is not None + ) +] +important_rows_fixable = "\n".join( + f"| {vuln.vuln_class} | {vuln.vuln_type} | {vuln.name} | {vuln.version} | {vuln.severity.name} | {vuln.age} | {vuln.fix} | " + f"[{vuln.cve}]({vuln.cve_url}) | {vuln.title} |" + for vuln in vulns_important_fixable +) + +important_rows_unfixable = "\n".join( + f"| {vuln.vuln_class} | {vuln.vuln_type} | {vuln.name} | {vuln.version} | {vuln.severity.name} | " + f"[{vuln.cve}]({vuln.cve_url}) | {vuln.title} |" + for vuln in vulns + if ( + vuln.vuln_class in IMPORTANT_VULN_CLASSES + and vuln.severity in IMPORTANT_VULN_SEVERITIES + and vuln.fix is None + ) +) + +minor_rows = "\n".join( + f"| {vuln.vuln_class} | {vuln.vuln_type} | {vuln.name} | {vuln.version} | {vuln.severity.name} | " + f"[{vuln.cve}]({vuln.cve_url}) | {vuln.title} |" + for vuln in vulns + if ( + vuln.vuln_class not in IMPORTANT_VULN_CLASSES + or vuln.severity not in IMPORTANT_VULN_SEVERITIES + ) +) + +important_fixable_section = "" +if important_rows_fixable: + important_fixable_section = f""" +### :exclamation: Important vulnerabilities + +- Total: {len(vulns_important_fixable)} +- Critical: {len([vuln for vuln in vulns_important_fixable if vuln.severity == Severity.CRITICAL])} +- High: {len([vuln for vuln in vulns_important_fixable if vuln.severity == Severity.HIGH])} + +| Class | Type | Dep. name | Version | Severity | Vuln. age (days) | Fix | CVE ID | Title | +| --- | --- | --- | --- | --- | --- | --- | --- | --- | +{important_rows_fixable} +""" + +important_unfixable_section = "" +if important_rows_unfixable: + important_unfixable_section = f""" +
+ +:warning: Important, but not fixable + +
+ +| Class | Type | Dep. name | Version | Severity | CVE ID | Title | +| --- | --- | --- | --- | --- | --- | --- | +{important_rows_unfixable} + +
+""" + +minor_section = "" +if minor_rows: + minor_section = f""" +### :information_source: Other vulnerabilities + +
+ +Minor packages vulnerabilities + +
+ +| Class | Type | Dep. name | Version | Severity | CVE ID | Title | +| --- | --- | --- | --- | --- | --- | --- | +{minor_rows} + +
+""" + +errors_section = "" +if had_errors: + errors_section = ":warning: At least one vulnerability could not be processed, see job logs\n" + +strtpl = f""" +{errors_section} +{important_fixable_section} +{important_unfixable_section} +{minor_section} +""" +print(strtpl) diff --git a/.github/workflows/checkov.yml b/.github/workflows/checkov.yml index e2be369b..fac32f13 100644 --- a/.github/workflows/checkov.yml +++ b/.github/workflows/checkov.yml @@ -74,7 +74,7 @@ jobs: # reason: as raw files they are Go-templated text, not Kubernetes YAML, so # the `kubernetes` framework cannot parse them. Between those two rules # Checkov does not report on the chart bodies at all -- Helm - # misconfiguration coverage is Trivy's job in trivy.yml, which renders + # misconfiguration coverage is Trivy's job in trivy-code.yml, which renders # charts through its own Helm parser and anchors findings at real paths. # # NOTE: unlike the inference repository this workflow was adapted from, diff --git a/.github/workflows/trivy.yml b/.github/workflows/trivy-code.yml similarity index 99% rename from .github/workflows/trivy.yml rename to .github/workflows/trivy-code.yml index 479f51c6..b8b811ed 100644 --- a/.github/workflows/trivy.yml +++ b/.github/workflows/trivy-code.yml @@ -1,5 +1,5 @@ --- -name: Trivy +name: "Trivy - Code" # Actions are pinned to full commit SHAs (the trailing `# vX.Y.Z` is the tag # that SHA corresponded to) and every tool to an exact version -- no floating diff --git a/.github/workflows/trivy-images-build-scan-reusable.yml b/.github/workflows/trivy-images-build-scan-reusable.yml new file mode 100644 index 00000000..775dbbf1 --- /dev/null +++ b/.github/workflows/trivy-images-build-scan-reusable.yml @@ -0,0 +1,66 @@ +--- +name: "Trivy - Images: build and scan" + +on: + workflow_call: + inputs: + image_name: + required: true + type: string + dockerfile_path: + required: true + type: string + docker_context: + required: true + type: string + ref: + description: "Git ref (branch, tag, or commit SHA) to checkout" + required: false + type: string + outputs: + scan-status: + description: "Outcome of the scan: 'error', 'vulnerable', or 'clean' (see trivy-images-scan-reusable.yml)" + value: ${{ jobs.scan.outputs.scan-status }} + +permissions: + contents: read + +jobs: + build: + name: "Build" + runs-on: intel-ubuntu-latest + timeout-minutes: 60 + steps: + - name: Harden the runner (audit all outbound calls) + uses: step-security/harden-runner@e14015d583714f6e62063499dc959a02595150a1 # v2.21.1 + with: + egress-policy: audit + + - name: Checkout code + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ inputs.ref || github.ref }} + persist-credentials: false + + - name: Build image + env: + IMAGE_NAME: ${{ inputs.image_name }} + DOCKERFILE_PATH: ${{ inputs.dockerfile_path }} + BUILD_CONTEXT: ${{ inputs.docker_context }} + run: | + docker build --pull --no-cache -f "$DOCKERFILE_PATH" -t "$IMAGE_NAME:latest" "$BUILD_CONTEXT" + docker save "$IMAGE_NAME:latest" -o "$IMAGE_NAME.tar" + + - name: Upload image artifact + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: image-${{ inputs.image_name }} + path: ${{ inputs.image_name }}.tar + retention-days: 1 + + scan: + name: "Scan" + needs: build + uses: ./.github/workflows/trivy-images-scan-reusable.yml + with: + image_name: ${{ inputs.image_name }} diff --git a/.github/workflows/trivy-images-scan-reusable.yml b/.github/workflows/trivy-images-scan-reusable.yml new file mode 100644 index 00000000..b4b7fb55 --- /dev/null +++ b/.github/workflows/trivy-images-scan-reusable.yml @@ -0,0 +1,189 @@ +--- +name: "Trivy - Images: scan" + +on: + workflow_call: + inputs: + image_name: + required: true + type: string + outputs: + scan-status: + description: "Outcome of the scan: 'error' (scan failed to run), 'vulnerable' (scan ran, found fixable CVEs), or 'clean' (scan ran, no fixable CVEs)" + value: ${{ jobs.scan.outputs.scan-status }} + +permissions: + contents: read + +jobs: + scan: + name: "Trivy" + runs-on: intel-ubuntu-latest + timeout-minutes: 90 + outputs: + scan-status: ${{ steps.scan-status.outputs.scan-status }} + env: + TRIVY_DISABLE_VEX_NOTICE: true + TRIVY_CACHE_DIR: ${{ github.workspace }}/.cache/trivy + IMAGE_TAR: ${{ inputs.image_name }}.tar + ERROR_RC: 1 + FAIL_RC: 2 + steps: + - name: Harden the runner (audit all outbound calls) + uses: step-security/harden-runner@e14015d583714f6e62063499dc959a02595150a1 # v2.21.1 + with: + egress-policy: audit + + - name: Checkout code + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + sparse-checkout: .github/custom_tools/trivy + sparse-checkout-cone-mode: false + persist-credentials: false + + - name: Install Trivy + uses: aquasecurity/setup-trivy@81e514348e19b6112ce2a7e3ecbafe19c1e1f567 # v0.3.1 + with: + version: v0.74.0 + cache: true + + - name: Set up Python + uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + with: + python-version: '3.12.14' + + - name: Download image artifact + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: image-${{ inputs.image_name }} + + - name: Restore Trivy DB + id: trivy-db + uses: actions/cache/restore@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5.0.5 + with: + path: .cache/trivy/db + key: trivy-db-${{ github.run_id }} + + - name: Prepare Trivy DB + env: + CACHE_HIT: ${{ steps.trivy-db.outputs.cache-hit }} + run: | + if [ "$CACHE_HIT" != "true" ]; then + trivy image --download-db-only + fi + echo "TRIVY_SKIP_DB_UPDATE=true" >> "$GITHUB_ENV" + + - name: Create results dir + run: mkdir -p results + + - name: Run the full scan + id: trivy-full + run: | + trap 'echo "exit-code=$?" >> "$GITHUB_OUTPUT"' EXIT + trivy image -q \ + --input "$IMAGE_TAR" \ + --scanners vuln \ + --exit-code "$FAIL_RC" \ + --timeout 40m \ + --skip-dirs "/compliance" \ + --format table + continue-on-error: true + + - name: Rerun the full scan in debug + if: ${{ steps.trivy-full.outputs.exit-code == env.ERROR_RC }} + run: | + echo "::error::Trivy scan had errors when running" + trivy image -d \ + --input "$IMAGE_TAR" \ + --scanners vuln \ + --timeout 40m \ + --ignore-unfixed \ + --skip-dirs "/compliance" \ + --format table + exit "$ERROR_RC" + + - name: Run the scan for GitHub summaries + id: trivy-json + if: ${{ steps.trivy-full.outputs.exit-code != env.ERROR_RC }} + run: | + trap 'echo "exit-code=$?" >> "$GITHUB_OUTPUT"' EXIT + trivy image \ + --input "$IMAGE_TAR" \ + --scanners vuln \ + --timeout 40m \ + --skip-dirs "/compliance" \ + --format json \ + --output results/trivy-raw.json + + - name: Run the scan for SDL report + id: trivy-sdl + if: ${{ steps.trivy-full.outputs.exit-code != env.ERROR_RC }} + run: | + trap 'echo "exit-code=$?" >> "$GITHUB_OUTPUT"' EXIT + trivy image \ + --input "$IMAGE_TAR" \ + --config .github/custom_tools/trivy/sdl-config.yaml \ + --ignore-unfixed + continue-on-error: true + + - name: Move SDL report + if: ${{ steps.trivy-sdl.outputs.exit-code != env.ERROR_RC }} + run: mv sdl-scan-results.csv results/sdl-scan-results.csv + + - name: Trivy general feedback + if: always() + env: + FULL_RC: ${{ steps.trivy-full.outputs.exit-code }} + SDL_RC: ${{ steps.trivy-sdl.outputs.exit-code }} + run: | + if [ "$FULL_RC" = "$ERROR_RC" ] || [ "$SDL_RC" = "$ERROR_RC" ]; then + echo ":exclamation: Full or SDL Trivy scan faced errors" >> "$GITHUB_STEP_SUMMARY" + fi + + if [ "$SDL_RC" = "0" ]; then + echo ":white_check_mark: Scan positive" >> "$GITHUB_STEP_SUMMARY" + fi + + if [ "$SDL_RC" = "$FAIL_RC" ]; then + echo ":x: Scan negative" >> "$GITHUB_STEP_SUMMARY" + fi + + - name: Classify scan status + id: scan-status + if: always() + env: + FULL_RC: ${{ steps.trivy-full.outputs.exit-code }} + SDL_RC: ${{ steps.trivy-sdl.outputs.exit-code }} + run: | + if [ "$FULL_RC" = "$ERROR_RC" ] || [ "$SDL_RC" = "$ERROR_RC" ]; then + STATUS="error" + elif [ "$SDL_RC" = "$FAIL_RC" ] || [ "$FULL_RC" = "$FAIL_RC" ]; then + STATUS="vulnerable" + else + STATUS="clean" + fi + + echo "Scan status: $STATUS (FULL_RC=$FULL_RC, SDL_RC=$SDL_RC)" + echo "scan-status=$STATUS" >> "$GITHUB_OUTPUT" + + - name: Postprocess Trivy JSON + if: ${{ steps.trivy-json.outcome == 'success' }} + run: python .github/custom_tools/trivy/json_postprocess.py results/trivy-raw.json results/trivy-postprocessed.json + + - name: Run summary script + if: ${{ steps.trivy-json.outcome == 'success' }} + run: python .github/custom_tools/trivy/summary_builder_one_image.py results/trivy-postprocessed.json >> "$GITHUB_STEP_SUMMARY" + + - name: Upload artifacts + if: always() + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: trivy-${{ inputs.image_name }} + path: results/* + retention-days: 7 + + - name: Fail workflow if the Trivy SDL scan failed + if: ${{ steps.trivy-sdl.outcome == 'failure' }} + run: | + echo "::error::Trivy SDL scan did not finish successfully" + exit 1 diff --git a/.github/workflows/trivy-images.yml b/.github/workflows/trivy-images.yml new file mode 100644 index 00000000..c77c85d4 --- /dev/null +++ b/.github/workflows/trivy-images.yml @@ -0,0 +1,110 @@ +--- +name: "Trivy - Images" +run-name: "Trivy - Images (${{ inputs.branch || vars.TRIVY_DEFAULT_BRANCH || github.ref_name }})" + +on: + workflow_dispatch: + inputs: + branch: + description: "Branch to scan (default: TRIVY_DEFAULT_BRANCH variable)" + required: false + type: string + schedule: + - cron: '0 0 * * 1' + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ inputs.branch || vars.TRIVY_DEFAULT_BRANCH || github.ref }} + cancel-in-progress: true + +jobs: + read: + name: "Read image list" + uses: ./.github/workflows/read-images-reusable.yml + with: + ref: ${{ inputs.branch || vars.TRIVY_DEFAULT_BRANCH }} + + trivy-db: + name: "Download Trivy DB" + runs-on: intel-ubuntu-latest + timeout-minutes: 10 + env: + TRIVY_CACHE_DIR: ${{ github.workspace }}/.cache/trivy + steps: + - name: Harden the runner (audit all outbound calls) + uses: step-security/harden-runner@e14015d583714f6e62063499dc959a02595150a1 # v2.21.1 + with: + egress-policy: audit + + - name: Install Trivy + uses: aquasecurity/setup-trivy@81e514348e19b6112ce2a7e3ecbafe19c1e1f567 # v0.3.1 + with: + version: v0.74.0 + cache: true + + - name: Download Trivy DB + run: trivy image --download-db-only + + - name: Save Trivy DB + uses: actions/cache/save@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5.0.5 + with: + path: .cache/trivy/db + key: trivy-db-${{ github.run_id }} + + build-and-scan: + name: "Build & Scan - ${{ matrix.name }}" + needs: [ read, trivy-db ] + strategy: + matrix: ${{ fromJson(needs.read.outputs.matrix) }} + fail-fast: false + uses: ./.github/workflows/trivy-images-build-scan-reusable.yml + with: + image_name: ${{ matrix.image_name }} + dockerfile_path: ${{ matrix.dockerfile_path }} + docker_context: ${{ matrix.docker_context }} + ref: ${{ inputs.branch || vars.TRIVY_DEFAULT_BRANCH }} + + summary: + name: "Summarization" + needs: build-and-scan + if: always() + runs-on: intel-ubuntu-latest + timeout-minutes: 10 + steps: + - name: Harden the runner (audit all outbound calls) + uses: step-security/harden-runner@e14015d583714f6e62063499dc959a02595150a1 # v2.21.1 + with: + egress-policy: audit + + - name: Checkout code + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + sparse-checkout: .github/custom_tools/trivy + sparse-checkout-cone-mode: false + persist-credentials: false + + - name: Set up Python + uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + with: + python-version: '3.12.14' + + - name: Download scan results + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + pattern: trivy-* + path: results + + - name: List downloaded files + run: mkdir -p results && ls -R results + + - name: Run summary script + run: python .github/custom_tools/trivy/summary_builder_all.py results results/summary-all.csv --strip-prefix trivy- + + - name: Upload final archive + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: trivy-results-archive + path: results + retention-days: 30