Skip to content

Extend Trivy scanning with action recommendations - #981

Open
hggutvik wants to merge 33 commits into
mainfrom
devsecops/recommend-actions-on-trivy-findings
Open

Extend Trivy scanning with action recommendations#981
hggutvik wants to merge 33 commits into
mainfrom
devsecops/recommend-actions-on-trivy-findings

Conversation

@hggutvik

@hggutvik hggutvik commented Jul 6, 2026

Copy link
Copy Markdown
Contributor

Run additional scan of latest base-image (if a newer one exists) to see if the vulnerability findings are fixed there. Use this reference to recommend mitigations - bump if patch exists and it fixes things, else do workaround or ignore.

Relevant mitigations are given in the scan summary.
When app third-party deps with vulnerabilities are found, the mitigation is to update app dependencies in csproj (example).
When the OS image contains vulnerable libraries, the mitigation is to bump to newer image (if exists) or to await fix. (example)

SARIF upload seems to work as expected, opening new issues for unaddressed findings, and closing them when fixed or ignored.

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Enhanced container scan mitigation output, distinguishing base-origin vulnerabilities from app dependency issues with clear verdicts and counts.
    • Workflow now derives base image metadata from the Dockerfile, compares against the “floating” base, and optionally evaluates against the latest base scan.
  • Bug Fixes

    • Scan job failure is now based on computed critical/high finding counts, aligning results with real risk.
  • Tests

    • Added script-based tests and new JSON fixtures to validate base metadata derivation and mitigation-summary rendering.

Run additional scan of latest base-image (if a newer one exists) to see if the vulnerability findings are fixed there. Use this reference to recommend mitigations - bump if patch exists and it fixes things, else do workaround or ignore
@hggutvik
hggutvik requested a review from martivj July 6, 2026 06:57
@coderabbitai

coderabbitai Bot commented Jul 6, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Important

Review available on request

  • 🔍 Trigger review

Reviews should be triggered manually for repositories with fewer than 10 stars. Select Trigger review above or comment @coderabbitai review to review the latest changes. For a full review, comment @coderabbitai full review.

⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 1ccd28a3-9ee9-4759-a16d-c80a45e0a49e

📝 Walkthrough

Walkthrough

This PR adds scripts for deriving Dockerfile base-image metadata and analyzing Trivy findings, fixture-based tests for both scripts, and workflow changes for inline scanning, SARIF conversion, base comparison, mitigation reporting, and conditional failure.

Changes

Base image fix mitigation pipeline

Layer / File(s) Summary
Derive base image metadata
.github/scripts/derive-base-image.sh
Parses the Dockerfile’s final FROM instruction into repository, tag, digest, version, channel, OS suffix, and floating-tag outputs.
Classify findings and render summary
.github/scripts/analyze-base-fixes.sh
Loads latest-base vulnerability IDs, extracts Trivy findings, classifies base-origin and app-dependency findings, computes mitigation verdicts, and writes the Markdown summary.
Fixtures and test runner
.github/scripts/tests/fixtures/*, .github/scripts/tests/run-tests.sh
Adds Trivy JSON fixtures and Bash tests covering metadata derivation, finding classification, verdicts, digest formatting, and summary output.
Container scan workflow
.github/workflows/container-scan.yml
Runs inline Trivy scans and SARIF conversion, derives and compares base-image digests, performs mitigation analysis, triggers on script changes, and conditionally fails on findings.

Estimated code review effort: 3 (Moderate) | ~30 minutes

Possibly related issues

  • Altinn/altinn-authentication 2079: Replaces a deprecated container-scan workflow with inline Trivy scanning, matching this PR’s workflow migration.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 66.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately reflects the main change: Trivy scanning was extended with recommendation logic for findings.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch devsecops/recommend-actions-on-trivy-findings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (3)
.github/workflows/container-scan.yml (3)

35-35: 🔒 Security & Privacy | 🔵 Trivial | ⚡ Quick win

Set persist-credentials: false on checkout.

The checkout step doesn't disable credential persistence, so the ephemeral GITHUB_TOKEN remains in the local git config for the rest of the job (docker build, curl to external registries, etc.) even though nothing downstream needs to push back to the repo.

🔒 Proposed fix
       - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
+        with:
+          persist-credentials: false
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In @.github/workflows/container-scan.yml at line 35, The checkout step in the
container-scan workflow is leaving GitHub credentials persisted in the job
environment. Update the existing actions/checkout usage in the workflow to set
persist-credentials to false so the ephemeral GITHUB_TOKEN is not stored in
local git config. Keep the change scoped to the checkout step in the workflow
and ensure no downstream steps rely on repository push credentials.

Source: Linters/SAST tools


34-41: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Wire run-tests.sh into CI.

The new fixture-based test harness (.github/scripts/tests/run-tests.sh) isn't invoked anywhere in this workflow, so regressions in derive-base-image.sh/analyze-base-fixes.sh won't be caught automatically unless it's run elsewhere.

✅ Proposed addition
       - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
+        with:
+          persist-credentials: false
+
+      - name: Run helper script tests
+        run: bash .github/scripts/tests/run-tests.sh
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In @.github/workflows/container-scan.yml around lines 34 - 41, The container
scan workflow currently builds the image but never exercises the new
fixture-based test harness, so regressions in derive-base-image.sh and
analyze-base-fixes.sh can slip through. Update the container-scan job to invoke
.github/scripts/tests/run-tests.sh as part of the existing steps, using the same
checkout context and environment it needs, so the workflow validates the script
behavior automatically alongside the Docker build.

37-38: 🔒 Security & Privacy | 🔵 Trivial | ⚡ Quick win

Pin the Trivy CLI version in setup-trivy .github/workflows/container-scan.yml:38 aquasecurity/setup-trivy defaults to latest, so the installed scanner can drift between runs. Set a fixed version input, e.g. v0.72.0, to keep scans reproducible.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In @.github/workflows/container-scan.yml around lines 37 - 38, The Trivy setup
step in the container-scan workflow is relying on the default latest CLI, which
can change between runs. Update the aquasecurity/setup-trivy action usage in the
Install Trivy step to pass a fixed version input so the scanner stays
reproducible, and keep the change anchored to the setup-trivy step in the
workflow.

Source: Linters/SAST tools

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In @.github/workflows/container-scan.yml:
- Line 35: The checkout step in the container-scan workflow is leaving GitHub
credentials persisted in the job environment. Update the existing
actions/checkout usage in the workflow to set persist-credentials to false so
the ephemeral GITHUB_TOKEN is not stored in local git config. Keep the change
scoped to the checkout step in the workflow and ensure no downstream steps rely
on repository push credentials.
- Around line 34-41: The container scan workflow currently builds the image but
never exercises the new fixture-based test harness, so regressions in
derive-base-image.sh and analyze-base-fixes.sh can slip through. Update the
container-scan job to invoke .github/scripts/tests/run-tests.sh as part of the
existing steps, using the same checkout context and environment it needs, so the
workflow validates the script behavior automatically alongside the Docker build.
- Around line 37-38: The Trivy setup step in the container-scan workflow is
relying on the default latest CLI, which can change between runs. Update the
aquasecurity/setup-trivy action usage in the Install Trivy step to pass a fixed
version input so the scanner stays reproducible, and keep the change anchored to
the setup-trivy step in the workflow.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: d43e46e5-6fdd-4550-aac3-b2184fc3913d

📥 Commits

Reviewing files that changed from the base of the PR and between 930d4f5 and fcd7400.

📒 Files selected for processing (6)
  • .github/scripts/analyze-base-fixes.sh
  • .github/scripts/derive-base-image.sh
  • .github/scripts/tests/fixtures/app-findings.json
  • .github/scripts/tests/fixtures/base-latest-findings.json
  • .github/scripts/tests/run-tests.sh
  • .github/workflows/container-scan.yml

@hggutvik
hggutvik marked this pull request as ready for review July 9, 2026 10:13
Comment on lines +31 to +33
TRIVY_DB_REPOSITORY: public.ecr.aws/aquasecurity/trivy-db,aquasec/trivy-db,ghcr.io/aquasecurity/trivy-db
TRIVY_JAVA_DB_REPOSITORY: public.ecr.aws/aquasecurity/trivy-java-db,aquasec/trivy-java-db,ghcr.io/aquasecurity/trivy-java-db
TRIVY_SHOW_SUPPRESSED: true

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Moved from step.env to job.env to make the variables available for both scan steps. The original app-image scanning ("Run Trivy vulnerability scanner") + the new base image scanning ("Scan the latest base image")

@hggutvik

hggutvik commented Jul 9, 2026

Copy link
Copy Markdown
Contributor Author

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Jul 9, 2026

Copy link
Copy Markdown
Contributor
✅ Action performed

Full review finished.


Your plan includes PR reviews subject to rate limits. More reviews will be available in 52 minutes.

@coderabbitai

coderabbitai Bot commented Jul 9, 2026

Copy link
Copy Markdown
Contributor
✅ Action performed

Full review finished.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (1)
.github/workflows/container-scan.yml (1)

95-122: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Add timeouts to network calls to prevent workflow hangs.

Both docker buildx imagetools inspect (line 98-99) and curl (line 119-121) make network calls without explicit timeouts. If the registry or MCR API is slow or unresponsive, the step can hang until the job timeout. The curl has || true for error tolerance, but that doesn't help if the command itself blocks indefinitely.

⏱️ Proposed fix: add timeouts to both network calls
           set -euo pipefail
           # Resolve the digest the floating tag points at right now (manifest
           # metadata only -- no image layers are pulled).
-          latest_digest=$(docker buildx imagetools inspect \
+          latest_digest=$(timeout 30 docker buildx imagetools inspect \
             "${BASE_REPO}:${FLOATING_TAG}" --format '{{.Manifest.Digest}}')
-          latest_version=$(curl -sfL --proto '=https' --proto-redir '=https' "https://mcr.microsoft.com/v2/${repo_path}/tags/list" \
+          latest_version=$(curl -sfL --max-time 30 --proto '=https' --proto-redir '=https' "https://mcr.microsoft.com/v2/${repo_path}/tags/list" \
             | jq -r --arg p "$pattern" '.tags[]? | select(test($p))' \
             | sort -V | tail -n1 || true)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In @.github/workflows/container-scan.yml around lines 95 - 122, The workflow
step that resolves the base image digest and latest version can hang because
`docker buildx imagetools inspect` and the `curl` call in the same script have
no explicit timeouts. Update the script in the container scan job to add bounded
timeout options around both network operations, keeping the current `set -euo
pipefail` and existing output behavior intact. Use the existing `latest_digest`,
`latest_version`, and `has_new_base` logic as-is, but ensure `imagetools
inspect` and the MCR tags request fail fast instead of waiting indefinitely.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In @.github/scripts/analyze-base-fixes.sh:
- Around line 82-88: The base-scan loading in analyze-base-fixes.sh does not
validate that base_json exists and contains valid JSON before populating
latest_base_ids, so a missing or broken scan can incorrectly mark all
base-origin findings as fixed. Update the base_json handling in the jq/while
block to explicitly check for a readable file and valid JSON before loading IDs,
and if validation fails, stop the “HAS_NEW_BASE=true” path from treating the
scan as loaded and leave base-origin findings classified as not yet fixed. Use
the latest_base_ids map and the HAS_NEW_BASE/base_json logic to locate the fix.

In @.github/scripts/derive-base-image.sh:
- Around line 45-47: The ref parsing in derive-base-image.sh currently strips
all whitespace after sed, which breaks FROM lines that include flags like
--platform. Update the logic around the ref assignment to ignore FROM flags
first and then capture the first non-flag token before any AS clause, so
BASE_REPO and BASE_TAG are derived from the actual image reference rather than a
flag string.

In @.github/workflows/container-scan.yml:
- Around line 35-40: The Install Trivy step in the container-scan workflow is
still relying on the setup-trivy default latest binary, which can change
behavior under the same pinned action version. Update the
aquasecurity/setup-trivy step to pass an explicit version input so the Trivy
binary is reproducible across runs, and keep the change localized to the Install
Trivy job step.

---

Nitpick comments:
In @.github/workflows/container-scan.yml:
- Around line 95-122: The workflow step that resolves the base image digest and
latest version can hang because `docker buildx imagetools inspect` and the
`curl` call in the same script have no explicit timeouts. Update the script in
the container scan job to add bounded timeout options around both network
operations, keeping the current `set -euo pipefail` and existing output behavior
intact. Use the existing `latest_digest`, `latest_version`, and `has_new_base`
logic as-is, but ensure `imagetools inspect` and the MCR tags request fail fast
instead of waiting indefinitely.
🪄 Autofix

❌ Autofix failed (check again to retry)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 84a917ae-6638-41fd-8ea5-0efdd75df0cb

📥 Commits

Reviewing files that changed from the base of the PR and between 930d4f5 and 0c4719f.

📒 Files selected for processing (6)
  • .github/scripts/analyze-base-fixes.sh
  • .github/scripts/derive-base-image.sh
  • .github/scripts/tests/fixtures/app-findings.json
  • .github/scripts/tests/fixtures/base-latest-findings.json
  • .github/scripts/tests/run-tests.sh
  • .github/workflows/container-scan.yml

Comment thread .github/scripts/analyze-base-fixes.sh
Comment thread .github/scripts/derive-base-image.sh Outdated
Comment thread .github/workflows/container-scan.yml Outdated
hggutvik added 4 commits July 10, 2026 09:53
Previously, the image ref wouldn't read correctly if new flags were to be added after FROM
latest_base_ids has a capture that strips trailing newline
@sonarqubecloud

Copy link
Copy Markdown

@coderabbitai

coderabbitai Bot commented Aug 17, 2026

Copy link
Copy Markdown
Contributor

Autofix skipped. No unresolved CodeRabbit review comments with fix instructions found.

@sonarqubecloud

Copy link
Copy Markdown

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant