Skip to content

[ci] Fail the source scan only on findings a change introduces - #3318

Merged
diemol merged 2 commits into
trunkfrom
ci-scan-source-known-findings
Nov 23, 2026
Merged

diemol merged 2 commits into
trunkfrom
ci-scan-source-known-findings

Conversation

@diemol

@diemol diemol commented Nov 23, 2026

Copy link
Copy Markdown
Member

Thanks for contributing to the Docker-Selenium project!
A PR well described will help maintainers to quickly review and merge it

Before submitting your PR, please check our contributing guidelines, applied for this repository.
Avoid large PRs, help reviewers by making them as simple and short as possible.

Description

scan-source.yml runs Trivy (secret,misconfig) on the whole tree. On pull requests and pushes it failed on any HIGH or CRITICAL finding, including findings that are already on trunk. Because the workflow only runs when a Dockerfile changes, every PR touching a Dockerfile failed (for example renovate/ubuntu-update since Nov 19, and #3317).

Findings already on trunk, all in files those PRs do not touch:

  • charts/selenium-grid/certs/tls.key (test certificate, private-key)
  • kubernetes/** and .keda-external-scaler/deploy/deployment.yaml examples (KSV-0014, KSV-0118)
  • Base/Dockerfile ENV defaults (DS-0031)

Changes:

  • Pull requests and pushes also scan the base commit (PR base, or the commit before the push) and fail only on findings that the base does not have. scripts/ci/new_scan_findings.py compares the two SARIF reports by rule, file and message, so moved code does not count as new.
  • The head scan still produces the SARIF report and annotations as before. Scheduled runs are unchanged (report everything, never fail).
  • .cache (the Trivy cache inside the checkout) is skipped in both scans so they cover the same files.
  • The workflow also runs when the workflow file or the script changes, so this PR tests itself.

Tested locally with Trivy 0.76.2:

Motivation and Context

The workflow comment says a secret or misconfiguration in a change is the author's to fix. The scan failed PRs for findings they did not introduce.

Types of changes

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)

Checklist

  • I have read the contributing document.
  • My change requires a change to the documentation.
  • I have updated the documentation accordingly.
  • I have added tests to cover my changes.
  • All new and existing tests passed.

🤖 Generated with Claude Code

On pull requests and pushes the scan covered the whole tree and failed
on any HIGH or CRITICAL finding, so every change to a Dockerfile failed
on findings that are already on trunk. It now also scans the base commit
and fails only on findings that the base does not have. Scheduled runs
are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@qodo-code-review

qodo-code-review Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

PR Summary by Qodo

Fail source scans only for newly introduced findings

🐞 Bug fix 🧪 Tests 🕐 20-40 Minutes

Grey Divider

AI Description

• Compare pull-request and push scans against a base commit so existing findings do not block
 changes.
• Preserve head-scan reporting and non-blocking scheduled scans while excluding the Trivy cache.
• Add tests for unchanged, moved, added, duplicated, and removed findings.
Merge Risk 🟡 Medium

Blast radius 🟢 Low 💥 1 capability

  • 1 affected end-to-end capability after fault-specific containment; implementation boundaries do not widen its functional scope.
  • The changed workflow, Trivy scans, SARIF comparison, and PR/push status decision form one bounded source-security integration.
  • The script consumes the workflow's two scan reports rather than creating an independent end-to-end capability; no separate product runtime behavior is affected.
  • The updated predecessor-fetch branch changes baseline acquisition within this same gate.
  • Baseline acquisition, predecessor fetching, detached worktree creation, base scanning, and comparison are execution stages of the same source-security gate.
  • They do not establish an independent functional scope or product capability.
Sources

scripts/ci/new_scan_findings.py[16-32]

def findings(path):
    """Returns a Counter of (rule, file, message) for every result in a SARIF report."""
    with open(path, encoding="utf-8") as f:
        report = json.load(f)
    found = Counter()
    for run in report.get("runs", []):
        for result in run.get("results", []):
            locations = result.get("locations") or [{}]
            uri = locations[0].get("physicalLocation", {}).get("artifactLocation", {}).get("uri", "")
            message = result.get("message", {}).get("text", "")
            found[(result.get("ruleId", ""), uri, message)] += 1
    return found


def new_findings(base_path, head_path):
    """Returns the findings of the head report that the base report does not have."""
    return findings(head_path) - findings(base_path)

scripts/ci/new_scan_findings.py[35-48]

def main(argv):
    if len(argv) != 3:
        print(__doc__.strip().splitlines()[-1], file=sys.stderr)
        return 2
    new = new_findings(argv[1], argv[2])
    if not new:
        print("No new findings compared to the base commit.")
        return 0
    print(f"{sum(new.values())} new finding(s) compared to the base commit:")
    for (rule, uri, message), count in sorted(new.items()):
        first_line = message.splitlines()[0] if message else ""
        suffix = f" (x{count})" if count > 1 else ""
        print(f"- {rule} in {uri}: {first_line}{suffix}")
    return 1

.github/workflows/scan-source.yml[85-101]

          if [ -n "${PR_BASE_SHA}" ]; then
            BASE_SHA="$(git merge-base "${PR_BASE_SHA}" HEAD)"
          elif [ -z "${PUSH_BEFORE_SHA}" ] || [ "${PUSH_BEFORE_SHA}" = "0000000000000000000000000000000000000000" ]; then
            # A new branch has no previous commit, so compare with where it left trunk
            BASE_SHA="$(git merge-base origin/trunk HEAD)"
          else
            # The previous tip of the branch. After a force-push it is not in the
            # checkout, so fetch it. Comparing with trunk instead would report
            # findings that were already on the branch as new.
            if ! git cat-file -e "${PUSH_BEFORE_SHA}^{commit}" 2>/dev/null; then
              git fetch --no-tags --depth=1 origin "${PUSH_BEFORE_SHA}" || true
            fi
            if ! git cat-file -e "${PUSH_BEFORE_SHA}^{commit}" 2>/dev/null; then
              echo "::error::Previous commit ${PUSH_BEFORE_SHA} of this branch is not available, so the scan has no base to compare with."
              exit 1
            fi
            BASE_SHA="${PUSH_BEFORE_SHA}"

.github/workflows/scan-source.yml[114-116]

      - name: Fail on new findings
        if: github.event_name == 'pull_request' || github.event_name == 'push'
        run: python3 scripts/ci/new_scan_findings.py base-results.sarif source-results.sarif
Behavioral complexity 🟡 Medium 🧩 Interacting branches, Data transformation

  • Before: PR/push validation relied on the head scan's exit behavior, while scheduled/manual runs reported without a base comparison.
  • After: PR/push execution selects a base using pull-request merge-base, trunk fallback for a new branch, or the prior push tip; when that tip is absent locally, the workflow attempts a shallow fetch and then explicitly rejects the run if the tip remains unavailable.
  • It then scans the detached base and computes a Counter difference over SARIF findings.
  • For interacting_branches_or_states: Before, push handling either used an available predecessor or fell back to trunk.
  • After, force-pushes introduce a fetch-and-verify transition with a distinct failure state.
  • The new correctness condition is that each event state uses the intended prior state or fails closed rather than silently comparing against an unrelated baseline.
  • For nontrivial_transformation: the Counter still identifies findings by rule, first URI, and message, preserving additions and duplicate counts while ignoring line movement.
  • The new correctness condition remains that this identity and multiset subtraction correspond to newly introduced findings.
  • The follow-up narrows the baseline premise for force-pushes but does not remove the interaction between event branching, repository state, scanning, and multiset comparison.
Sources

.github/workflows/scan-source.yml[85-101]

          if [ -n "${PR_BASE_SHA}" ]; then
            BASE_SHA="$(git merge-base "${PR_BASE_SHA}" HEAD)"
          elif [ -z "${PUSH_BEFORE_SHA}" ] || [ "${PUSH_BEFORE_SHA}" = "0000000000000000000000000000000000000000" ]; then
            # A new branch has no previous commit, so compare with where it left trunk
            BASE_SHA="$(git merge-base origin/trunk HEAD)"
          else
            # The previous tip of the branch. After a force-push it is not in the
            # checkout, so fetch it. Comparing with trunk instead would report
            # findings that were already on the branch as new.
            if ! git cat-file -e "${PUSH_BEFORE_SHA}^{commit}" 2>/dev/null; then
              git fetch --no-tags --depth=1 origin "${PUSH_BEFORE_SHA}" || true
            fi
            if ! git cat-file -e "${PUSH_BEFORE_SHA}^{commit}" 2>/dev/null; then
              echo "::error::Previous commit ${PUSH_BEFORE_SHA} of this branch is not available, so the scan has no base to compare with."
              exit 1
            fi
            BASE_SHA="${PUSH_BEFORE_SHA}"

.github/workflows/scan-source.yml[114-116]

      - name: Fail on new findings
        if: github.event_name == 'pull_request' || github.event_name == 'push'
        run: python3 scripts/ci/new_scan_findings.py base-results.sarif source-results.sarif

scripts/ci/new_scan_findings.py[16-32]

def findings(path):
    """Returns a Counter of (rule, file, message) for every result in a SARIF report."""
    with open(path, encoding="utf-8") as f:
        report = json.load(f)
    found = Counter()
    for run in report.get("runs", []):
        for result in run.get("results", []):
            locations = result.get("locations") or [{}]
            uri = locations[0].get("physicalLocation", {}).get("artifactLocation", {}).get("uri", "")
            message = result.get("message", {}).get("text", "")
            found[(result.get("ruleId", ""), uri, message)] += 1
    return found


def new_findings(base_path, head_path):
    """Returns the findings of the head report that the base report does not have."""
    return findings(head_path) - findings(base_path)

scripts/ci/new_scan_findings.py[35-48]

def main(argv):
    if len(argv) != 3:
        print(__doc__.strip().splitlines()[-1], file=sys.stderr)
        return 2
    new = new_findings(argv[1], argv[2])
    if not new:
        print("No new findings compared to the base commit.")
        return 0
    print(f"{sum(new.values())} new finding(s) compared to the base commit:")
    for (rule, uri, message), count in sorted(new.items()):
        first_line = message.splitlines()[0] if message else ""
        suffix = f" (x{count})" if count > 1 else ""
        print(f"- {rule} in {uri}: {first_line}{suffix}")
    return 1
Potential damage 🔴 High 🩹 Confidentiality

  • A false negative in the source-security gate can allow a newly introduced secret to pass PR/push validation and enter the repository or subsequent automation.
  • The follow-up removes the specific force-push fallback-to-trunk behavior that could misclassify findings already present on the branch, but other baseline-selection and tuple-identity errors remain plausible.
  • Ordinary misconfiguration false negatives are generally less severe; the serious consequence is conditional on the finding representing a real secret or credential.
  • Reverting or correcting the workflow restores future gate behavior, but it does not automatically remove a committed secret or compensate for downstream exposure.
  • Recovery from a missed secret requires identifying affected history and artifacts, rotating the secret, and manually remediating downstream consumers.
  • No automatic cleanup, rotation, or compensation path is established.
Sources

.github/workflows/scan-source.yml[85-101]

          if [ -n "${PR_BASE_SHA}" ]; then
            BASE_SHA="$(git merge-base "${PR_BASE_SHA}" HEAD)"
          elif [ -z "${PUSH_BEFORE_SHA}" ] || [ "${PUSH_BEFORE_SHA}" = "0000000000000000000000000000000000000000" ]; then
            # A new branch has no previous commit, so compare with where it left trunk
            BASE_SHA="$(git merge-base origin/trunk HEAD)"
          else
            # The previous tip of the branch. After a force-push it is not in the
            # checkout, so fetch it. Comparing with trunk instead would report
            # findings that were already on the branch as new.
            if ! git cat-file -e "${PUSH_BEFORE_SHA}^{commit}" 2>/dev/null; then
              git fetch --no-tags --depth=1 origin "${PUSH_BEFORE_SHA}" || true
            fi
            if ! git cat-file -e "${PUSH_BEFORE_SHA}^{commit}" 2>/dev/null; then
              echo "::error::Previous commit ${PUSH_BEFORE_SHA} of this branch is not available, so the scan has no base to compare with."
              exit 1
            fi
            BASE_SHA="${PUSH_BEFORE_SHA}"

.github/workflows/scan-source.yml[114-116]

      - name: Fail on new findings
        if: github.event_name == 'pull_request' || github.event_name == 'push'
        run: python3 scripts/ci/new_scan_findings.py base-results.sarif source-results.sarif

scripts/ci/new_scan_findings.py[16-32]

def findings(path):
    """Returns a Counter of (rule, file, message) for every result in a SARIF report."""
    with open(path, encoding="utf-8") as f:
        report = json.load(f)
    found = Counter()
    for run in report.get("runs", []):
        for result in run.get("results", []):
            locations = result.get("locations") or [{}]
            uri = locations[0].get("physicalLocation", {}).get("artifactLocation", {}).get("uri", "")
            message = result.get("message", {}).get("text", "")
            found[(result.get("ruleId", ""), uri, message)] += 1
    return found


def new_findings(base_path, head_path):
    """Returns the findings of the head report that the base report does not have."""
    return findings(head_path) - findings(base_path)

scripts/ci/new_scan_findings.py[35-48]

def main(argv):
    if len(argv) != 3:
        print(__doc__.strip().splitlines()[-1], file=sys.stderr)
        return 2
    new = new_findings(argv[1], argv[2])
    if not new:
        print("No new findings compared to the base commit.")
        return 0
    print(f"{sum(new.values())} new finding(s) compared to the base commit:")
    for (rule, uri, message), count in sorted(new.items()):
        first_line = message.splitlines()[0] if message else ""
        suffix = f" (x{count})" if count > 1 else ""
        print(f"- {rule} in {uri}: {first_line}{suffix}")
    return 1
Assessed commit cc6c9c5
Diagram

graph TD
  T["PR or push"] --> H["Head Trivy scan"] --> C["SARIF comparison"] --> D{"New findings?"} -->|Yes| F["Fail check"]
  T --> B["Resolve base commit"] --> S["Base Trivy scan"] --> C
  D -->|No| P["Pass check"]
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Maintain an allowlist of known findings
  • ➕ Avoids scanning a second checkout on each pull request or push.
  • ➖ Requires ongoing maintenance and can become stale as findings or detection rules change.

Recommendation: Use the PR’s base-scan comparison: it establishes the baseline from the relevant commit without maintaining exceptions. The extra scan cost is the principal trade-off; an allowlist would be cheaper to run but harder to keep accurate.

Files changed (3) +167 / -5

Bug fix (2) +96 / -5
scan-source.ymlGate PR and push scans on findings absent from the base commit +44/-5

Gate PR and push scans on findings absent from the base commit

• Fetches history, selects and scans a base commit, then runs the SARIF comparison to determine whether PR or push checks fail. Also triggers on workflow or comparator changes, excludes the Trivy cache from both scans, and retains head-report publishing and non-blocking scheduled scans.

.github/workflows/scan-source.yml

new_scan_findings.pyCompare base and head SARIF findings +52/-0

Compare base and head SARIF findings

• Subtracts counted findings identified by rule, file URI, and message, ignoring line-number changes. Prints new findings and exits unsuccessfully only when the head contains findings absent from the base.

scripts/ci/new_scan_findings.py

Tests (1) +71 / -0
test_new_scan_findings.pyCover SARIF comparison outcomes +71/-0

Cover SARIF comparison outcomes

• Tests unchanged and moved findings, new findings, additional copies of existing findings, and removed findings using temporary SARIF reports.

tests/ci/test_new_scan_findings.py

@qodo-code-review

qodo-code-review Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (0) 📜 Skill insights (0)

Grey Divider


Remediation recommended

1. Force-pushed branches can fail on old findings ✓ Resolved

Resolving commit: cc6c9c5

Resolution reason
Existing-branch pushes whose previous tip is missing locally now fetch that commit and, if
unavailable, fail with an explicit error instead of silently using origin/trunk as the baseline.
Trunk merge-base fallback is limited to new branches.
Description
When the previous push commit is unavailable locally, Scan base commit silently substitutes the
branch’s merge base with origin/trunk for github.event.before. After a force-push on a branch
with findings absent from trunk, those existing branch findings are compared against trunk instead
of the branch’s previous tip and are reported as new.

Grey Divider

Context sources
✅ Linked PRs:
  🌐 PR #3317
✅ Web pages:
  +19 more
Review mode: Auto: ⚖️ Balanced: CI behavior and finding-diff logic carry meaningful correctness risk.

Grey Divider

Tip of the day
💡 Did you know, you can keep summaries lean with Findings visible per group, which tucks the rest behind a View link

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

Comment thread .github/workflows/scan-source.yml Resolved
…g with trunk

Comparing a force-pushed branch with trunk would report findings that
were already on the branch as new. Fetch the previous tip when it is not
in the checkout, and fail with a clear error if it is not available. The
trunk fallback is kept for new branches only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@diemol
diemol merged commit d4811c8 into trunk Nov 23, 2026
41 checks passed
@diemol
diemol deleted the ci-scan-source-known-findings branch November 23, 2026 09:49
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