diff --git a/.github/workflows/trivy-config-alerts.yml b/.github/workflows/trivy-config-alerts.yml new file mode 100644 index 0000000000..1dd273e6d8 --- /dev/null +++ b/.github/workflows/trivy-config-alerts.yml @@ -0,0 +1,50 @@ +# File one issue for each open Trivy-config code scanning alert group that has none (#4401). +# The Security Scan step of the CI workflow uploads the results of `trivy config`, and no job +# turned an alert into work. SECURITY.md ("Judging a Trivy-config Alert") names who judges the +# issue and in what time. The job is no step of CI: a step of a pull request run must not write +# issues. It has no `workflow_run` trigger either: zizmor reports that trigger as a HIGH finding +# (dangerous-triggers), which would add one more alert that nobody judged. The CI run on `main` +# uploads the alerts, and this job files their issues on the next day. +name: Trivy Config Alerts + +on: + schedule: + # Once a day at 06:00 UTC. + - cron: "0 6 * * *" + workflow_dispatch: + +permissions: + contents: read + security-events: read + issues: write + +concurrency: + group: trivy-config-alerts + cancel-in-progress: false + +env: + # uv runs only its own CPython builds, never the runner image's Python (#1494). + UV_MANAGED_PYTHON: "1" + +jobs: + file-alert-issues: + name: File Alert Issues + runs-on: ubuntu-26.04 + # The filer reads two listings and posts at most 5 issues. The step limit is shorter. + timeout-minutes: 10 + + steps: + - name: Check out repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + persist-credentials: false + + - name: Set up uv toolchain + uses: ./.github/actions/setup-toolchain + + - name: File the issues + timeout-minutes: 5 + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + REPOSITORY: ${{ github.repository }} + run: uv run devops scan alerts --repo "$REPOSITORY" diff --git a/README.md b/README.md index 0365f0eb09..8b76c316a8 100644 --- a/README.md +++ b/README.md @@ -339,6 +339,7 @@ and excessive permissions fail it, and every other finding is shown. | | | `devops scan injection [OPTIONS] ` | Scan target files for prompt-injection smuggling vectors and canary tokens. | | | `devops scan report [OPTIONS] ` | Run every registered scanner and report deduplicated, correlated findings. | | | `devops scan sarif [OPTIONS] ` | Ingest a SARIF document from any tool and report it in the unified taxonomy. | +| | `devops scan alerts [OPTIONS]` | File one issue for each open Trivy-config code scanning alert group that has none. | | [**ai**](docs/commands/ai.md) | `devops ai config [OPTIONS]` | Show or update AI provider configuration. | | | `devops ai models [OPTIONS]` | List available models for the configured provider. | | | `devops ai preload [OPTIONS]` | Preload configured model into VRAM across all configured Ollama servers. | diff --git a/SECURITY.md b/SECURITY.md index 1ade5ef1ff..5c92056530 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -77,6 +77,17 @@ A scanner can name a finding that no update of the pinned package solves yet. Th **Report.** The pull request comment lists each ignore that the agent added, its expiry and its tracking issue. The final message of the agent says the same. +## Judging a Trivy-config Alert + +The `Security Scan` step of CI uploads the results of `trivy config` to code scanning. Each result is an alert of the tool `Trivy-config`. The workflow `.github/workflows/trivy-config-alerts.yml` runs `devops scan alerts` each day, after the CI run on `main` that uploaded the alerts. The command files one issue for each rule and file that has open alerts and no open issue: at most 5 in one run, the worst severity first. The title is `fix(security): judge Trivy-config in `. + +**Who judges, and in what time.** The owner judges a CRITICAL alert within 24 hours. An agent judges an alert of severity HIGH, MEDIUM or LOW within 14 days. After 14 days the owner decides. + +**What judging means.** Do one of these, and close the issue with it: +1. Fix the file in a pull request that closes the issue. This is the first choice. +2. If the fix breaks the workload or needs a change that is not released yet, add an entry to `.trivyignore.yaml`. Give it the rule `id`, the `paths` of the file, a `statement` that holds the reason and the tracking issue, and an `expired_at` date. `devops scan report` names this file, and Trivy stops applying an entry after its date. An agent follows the limits of "A Finding with No Fix": 3 days, renewed at most up to 14 days in all, never for a CRITICAL alert, never for a secret. A longer date is the decision of the owner, and the `statement` names that decision. +3. A person dismisses the alert in code scanning, with a reason. An agent does not dismiss an alert. + ## Reporting a Vulnerability We deeply appreciate responsible security disclosures. If you discover a security vulnerability within DevOps CLI: diff --git a/docs/CLI_REFERENCE.md b/docs/CLI_REFERENCE.md index cdc808437d..679e17037c 100644 --- a/docs/CLI_REFERENCE.md +++ b/docs/CLI_REFERENCE.md @@ -3721,6 +3721,22 @@ devops scan sarif [OPTIONS] | `--format`, `-f` | `string` | `table` | Output format type (table, json, yaml, markdown). | | `--json` | `boolean` | - | Output findings or metrics as JSON. | +### `devops scan alerts` + +**File one issue for each open Trivy-config code scanning alert group that has none.** + +```bash +devops scan alerts [OPTIONS] +``` + +**Options:** + +| Option / Flag | Type | Default | Description | +|---|---|---|---| +| `--repo`, `-R` | `string` | - | Repository (owner/name); the origin of the current directory by default. | +| `--limit` | `integer` | `5` | The most issues that one run files; the worst severity goes first. | +| `--dry-run` | `boolean` | - | Preview execution plan without mutating external state. | + --- ## devops ai diff --git a/docs/commands/scan.md b/docs/commands/scan.md index 0ed0456ead..ed27fee13d 100644 --- a/docs/commands/scan.md +++ b/docs/commands/scan.md @@ -295,3 +295,21 @@ devops scan sarif [OPTIONS] | `--json` | `boolean` | - | Output findings or metrics as JSON. | --- + +## `devops scan alerts` + +**File one issue for each open Trivy-config code scanning alert group that has none.** + +```bash +devops scan alerts [OPTIONS] +``` + +**Options:** + +| Option / Flag | Type | Default | Description | +|---|---|---|---| +| `--repo`, `-R` | `string` | - | Repository (owner/name); the origin of the current directory by default. | +| `--limit` | `integer` | `5` | The most issues that one run files; the worst severity goes first. | +| `--dry-run` | `boolean` | - | Preview execution plan without mutating external state. | + +--- diff --git a/openspec/changes/archive/2026-11-11-4401-52-trivy-config-alerts-stay-open/.openspec.yaml b/openspec/changes/archive/2026-11-11-4401-52-trivy-config-alerts-stay-open/.openspec.yaml new file mode 100644 index 0000000000..2a7773d65e --- /dev/null +++ b/openspec/changes/archive/2026-11-11-4401-52-trivy-config-alerts-stay-open/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-11 diff --git a/openspec/changes/archive/2026-11-11-4401-52-trivy-config-alerts-stay-open/design.md b/openspec/changes/archive/2026-11-11-4401-52-trivy-config-alerts-stay-open/design.md new file mode 100644 index 0000000000..db919694d1 --- /dev/null +++ b/openspec/changes/archive/2026-11-11-4401-52-trivy-config-alerts-stay-open/design.md @@ -0,0 +1,18 @@ +# Design + +## Decisions + +- **One group, one issue.** The key is the rule id and the path. One alert for each issue would make 52 issues at once, and one issue for a run would hold several fixes. The title is the key of the check for an open issue, so the check needs no state of its own. +- **The title is compared exactly.** An open issue with the same title means the group has an owner. The cost: intake can correct the type of a title (`fix` to `chore`), and the next run then files the group again. The filer limit of 5 bounds that cost. A hidden marker in the body would remove it, and the requirement of the issue asks for the title. +- **The worst severity first.** With a limit of 5, a CRITICAL alert never waits behind a LOW one. +- **A workflow, not a step of CI, and no `workflow_run`.** It needs `issues: write`, and a pull request run must not write issues. A `workflow_run` trigger would make zizmor report a HIGH finding (`dangerous-triggers`), one more alert with no judge, and the project allows no ignore of it. A daily schedule gives a new alert its issue in one day at most. The group `concurrency` stops two runs from filing the same issue. +- **Session and not `gh`.** The filer uses the GitHub session that `devops pr evidence` uses, so it paces and retries each request as the other commands do. +- **`.trivyignore.yaml` only for the IaC scan.** The image scans keep `.trivyignore` with `exp:`. The YAML form is the one that holds a path, a reason and an expiry, which a finding in one file of `k8s/` or `tf/` needs. +- **Judge and time.** The owner judges CRITICAL in 24 hours, because `SECURITY.md` forbids an agent to ignore CRITICAL. An agent judges the rest in 14 days, the longest total of an agent ignore. + +## Rejected alternatives + +- A rule in `SECURITY.md` only: it leaves the alert in the Security tab until a person looks. +- A job only: an issue with no judge and no time waits like the 52 alerts. +- A row on the status lane of the Service: it needs a new row, a setting and a token scope for work that CI already starts. +- A step in the CI workflow: a pull request run must not write issues. diff --git a/openspec/changes/archive/2026-11-11-4401-52-trivy-config-alerts-stay-open/proposal.md b/openspec/changes/archive/2026-11-11-4401-52-trivy-config-alerts-stay-open/proposal.md new file mode 100644 index 0000000000..cebe7ac09e --- /dev/null +++ b/openspec/changes/archive/2026-11-11-4401-52-trivy-config-alerts-stay-open/proposal.md @@ -0,0 +1,43 @@ +# Proposal + +## Why + +52 `Trivy-config` code scanning alerts stay open on `main`, and no fix, dismissal or ignore names them. Other scanners get a fix in days. Nothing turns a new `Trivy-config` alert into work, and `SECURITY.md` names no judge and no time. Closes #4401. + +## What Changes + +- Add `src/devops_cli/security/alert_filer.py` and the command `devops scan alerts`. It reads the open `Trivy-config` alerts, groups them by rule and path, and files one issue for each group that no open issue names, at most 5 in one run, the worst severity first. +- Add the workflow `.github/workflows/trivy-config-alerts.yml`. It runs `devops scan alerts` each day, with `security-events: read` and `issues: write`. +- Add the section "Judging a Trivy-config Alert" to `SECURITY.md`: the owner judges a CRITICAL alert within 24 hours, an agent judges the others within 14 days, and an IaC ignore goes to `.trivyignore.yaml` with `statement` and `expired_at`. +- Make the `trivy config` scan name `.trivyignore.yaml` of its directory with `--ignorefile`, so the entry of that file has an effect. +- The 52 alerts that are open now stay for #4409. This change adds no ignore entry and dismisses no alert. +- The change fits one pull request. + +## Capabilities + +### New Capabilities + +- `trivy-config-alerts`: The filer, its workflow, the policy rule and the ignore file of the IaC scan + +### Modified Capabilities + +None. + +## Impact + +- Code: `src/devops_cli/security/alert_filer.py`, `src/devops_cli/security/trivy.py`, `src/devops_cli/security/scan_plans.py`, `src/devops_cli/commands/scan.py`, constants and language entries +- Workflow: `.github/workflows/trivy-config-alerts.yml` +- Documents: `SECURITY.md`, the generated command pages +- Tests: `tests/security/test_alert_filer.py`, `tests/security/test_trivy_config_ignore.py`, `tests/commands/test_scan_alerts.py`, `tests/invariants/test_workflow_contracts.py`, `tests/invariants/test_agents_md.py` + +## Feasibility + +- The alerts exist now. `devops gh api 'repos/dan-petty/devops-cli/code-scanning/alerts?state=open&per_page=100' --paginate` on 2026-11-11 gave 52 open alerts of the tool `Trivy-config` (1 critical, 10 high, 19 medium, 22 low). The latest analysis of the category `/devops-scan` for `Trivy-config` reports 52 results, so the scan still finds them. +- The read path works on the real payload: `read_open_alerts` parsed the 52 alerts, `group_alerts` made 52 groups, and `plan_filing` with the 400 open issues of that day chose `AZU-0041` first and left 47 for later runs. No issue was filed in this check. +- The issue text proposes `.trivyignore.yaml`. The repository holds `.trivyignore` only, which `trivy` reads by default. A test with Trivy 0.75.0 shows that a `.trivyignore.yaml` entry with `paths`, `statement` and `expired_at` hides `DS-0002` only when `--ignorefile .trivyignore.yaml` is named, and that Trivy fails with `ignore file not found` when the file is missing. So the scan names the file only when it exists (task 1.3). The plain `.trivyignore` with `exp:` cannot name a path, so the IaC rule uses the YAML file. +- A new issue needs no intake label: `docs/ROADMAP_WORKFLOW.md` lists "a new issue on GitHub" as a way to capture, and the filer sets only `type/bug` and `scope/security`. +- The issue text asks for a `workflow_run` trigger after CI. `devops scan workflows` on 2026-11-11 reports that trigger as a HIGH zizmor finding (`dangerous-triggers`), and the project publishes such findings to code scanning, so the trigger would add one more alert with no judge. The workflow therefore runs on a daily schedule only. The CI run on `main` uploads the alerts, and the next daily run files their issues. A step of the CI workflow is no choice either: a pull request run must not write issues. + +## Existing Tool Considered + +Trivy covers the detection, and the scoped ignore with `statement` and `expired_at`, and this change uses both. The alerts API of GitHub covers the record. No open tool files an issue for a code scanning alert group: the alternatives check of 2026-11-11 found none. The code is about 190 lines on the GitHub session that exists. The cost is about 350k tokens to build, about 120k tokens a year to keep and fix, and about 6 hours of elapsed time. diff --git a/openspec/changes/archive/2026-11-11-4401-52-trivy-config-alerts-stay-open/specs/trivy-config-alerts/spec.md b/openspec/changes/archive/2026-11-11-4401-52-trivy-config-alerts-stay-open/specs/trivy-config-alerts/spec.md new file mode 100644 index 0000000000..399510ee4b --- /dev/null +++ b/openspec/changes/archive/2026-11-11-4401-52-trivy-config-alerts-stay-open/specs/trivy-config-alerts/spec.md @@ -0,0 +1,57 @@ +## ADDED Requirements + +### Requirement: The filer lists the open Trivy-config alerts +The alert filer SHALL list each open code scanning alert whose tool is `Trivy-config` and no other alert. + +#### Scenario: A payload with a second tool +- **WHEN** the alerts payload holds three `Trivy-config` alerts and one `CodeQL` alert +- **THEN** the filer groups the three `Trivy-config` alerts and no `CodeQL` alert + +### Requirement: The filer groups the alerts by rule and path +The filer SHALL group the open alerts by rule id and file path, and it SHALL put the group with the worst severity first. + +#### Scenario: Two alerts of one rule in one file +- **WHEN** two open alerts hold the rule id `KSV-0017` and the path `k8s/gpu-feature-discovery/daemonset.yaml` +- **THEN** the filer gives one group, and the body of the group names both alert numbers + +### Requirement: A group that an open issue names gets no new issue +The filer SHALL skip each group whose exact title an open issue holds. A pull request with that title is no issue. + +#### Scenario: One group with an open issue +- **WHEN** an open issue holds the title of one group and the other group has no issue +- **THEN** the filer files one issue, for the group with no open issue + +### Requirement: One run files a bounded number of issues +The filer MUST file at most five issues in one run, and it SHALL name the groups that it leaves for the next run. + +#### Scenario: Eight groups with no issue +- **WHEN** eight groups have no open issue and the limit is five +- **THEN** the filer files five issues and names the three groups that it leaves for the next run + +### Requirement: The filed issue holds the rule, the path and the severity +The filer SHALL put the rule id, the path, the severity and the alert numbers in the issue that it files. The title SHALL be `fix(security): judge Trivy-config in `. + +#### Scenario: The body of a filed issue +- **WHEN** the filer files an issue for the rule id `DS-0002` at `.devcontainer/Dockerfile` with the severity `HIGH` +- **THEN** the title holds `DS-0002` and `.devcontainer/Dockerfile`, and the body holds `HIGH` and the alert number + +### Requirement: The workflow runs every day with the least permissions +The alert workflow MUST run on a daily schedule, with the permissions `contents: read`, `security-events: read` and `issues: write` only. It SHALL have no `workflow_run` trigger, which zizmor reports as a HIGH finding. + +#### Scenario: The triggers of the workflow +- **WHEN** a test reads the `on` block of `.github/workflows/trivy-config-alerts.yml` +- **THEN** the block holds a `schedule` trigger and no `workflow_run` trigger + +### Requirement: The policy names the judge and the time +`SECURITY.md` SHALL name who judges a new `Trivy-config` alert, the time in which it happens, and the ignore file with its reason and expiry fields. + +#### Scenario: The Trivy-config rule in the policy +- **WHEN** a test reads the `Trivy-config` rule of `SECURITY.md` +- **THEN** the rule names the owner for a CRITICAL alert within 24 hours, an agent for the other severities within 14 days, and `.trivyignore.yaml` with `statement` and `expired_at` + +### Requirement: The IaC scan reads the ignore file with an expiry +The `trivy config` scan SHALL name `.trivyignore.yaml` of its directory with `--ignorefile` when that file exists, and it SHALL name no ignore file when it does not. + +#### Scenario: A directory with the file +- **WHEN** the scan starts in a directory that holds `.trivyignore.yaml` +- **THEN** the command holds `--ignorefile` and the path of that file, and Trivy hides a finding of an entry whose `expired_at` is later than today diff --git a/openspec/changes/archive/2026-11-11-4401-52-trivy-config-alerts-stay-open/tasks.md b/openspec/changes/archive/2026-11-11-4401-52-trivy-config-alerts-stay-open/tasks.md new file mode 100644 index 0000000000..e82a989210 --- /dev/null +++ b/openspec/changes/archive/2026-11-11-4401-52-trivy-config-alerts-stay-open/tasks.md @@ -0,0 +1,15 @@ +# Tasks + +## 1. Behavior + +- [x] 1.1 Write the failing tests of the filer, the command, the workflow, the policy rule and the ignore file + - Verification: `$ uv run devops ci test tests/security/test_alert_filer.py tests/commands/test_scan_alerts.py tests/invariants/test_workflow_contracts.py tests/invariants/test_agents_md.py tests/security/test_trivy_config_ignore.py` +- [x] 1.2 Add the filer, the command `devops scan alerts` and the workflow + - Verification: `$ uv run devops ci test tests/security/test_alert_filer.py tests/commands/test_scan_alerts.py tests/invariants/test_workflow_contracts.py tests/invariants/test_agents_md.py` +- [x] 1.3 Make the `trivy config` scan name `.trivyignore.yaml` when it exists + - Verification: `$ uv run devops ci test tests/security/test_trivy_config_ignore.py` + +## 2. Documents + +- [x] 2.1 Add the section "Judging a Trivy-config Alert" to `SECURITY.md`, and regenerate the command pages + - Verification: `$ uv run devops ci docs` diff --git a/openspec/specs/trivy-config-alerts/spec.md b/openspec/specs/trivy-config-alerts/spec.md new file mode 100644 index 0000000000..25ffc830a2 --- /dev/null +++ b/openspec/specs/trivy-config-alerts/spec.md @@ -0,0 +1,62 @@ +# trivy-config-alerts Specification + +## Purpose +How `devops scan alerts` turns each open `Trivy-config` code scanning alert group into one issue, the daily workflow that runs it, the rule of SECURITY.md that names the judge and the time, and the ignore file that the `trivy config` scan reads. + +## Requirements + +### Requirement: The filer lists the open Trivy-config alerts +The alert filer SHALL list each open code scanning alert whose tool is `Trivy-config` and no other alert. + +#### Scenario: A payload with a second tool +- **WHEN** the alerts payload holds three `Trivy-config` alerts and one `CodeQL` alert +- **THEN** the filer groups the three `Trivy-config` alerts and no `CodeQL` alert + +### Requirement: The filer groups the alerts by rule and path +The filer SHALL group the open alerts by rule id and file path, and it SHALL put the group with the worst severity first. + +#### Scenario: Two alerts of one rule in one file +- **WHEN** two open alerts hold the rule id `KSV-0017` and the path `k8s/gpu-feature-discovery/daemonset.yaml` +- **THEN** the filer gives one group, and the body of the group names both alert numbers + +### Requirement: A group that an open issue names gets no new issue +The filer SHALL skip each group whose exact title an open issue holds. A pull request with that title is no issue. + +#### Scenario: One group with an open issue +- **WHEN** an open issue holds the title of one group and the other group has no issue +- **THEN** the filer files one issue, for the group with no open issue + +### Requirement: One run files a bounded number of issues +The filer MUST file at most five issues in one run, and it SHALL name the groups that it leaves for the next run. + +#### Scenario: Eight groups with no issue +- **WHEN** eight groups have no open issue and the limit is five +- **THEN** the filer files five issues and names the three groups that it leaves for the next run + +### Requirement: The filed issue holds the rule, the path and the severity +The filer SHALL put the rule id, the path, the severity and the alert numbers in the issue that it files. The title SHALL be `fix(security): judge Trivy-config in `. + +#### Scenario: The body of a filed issue +- **WHEN** the filer files an issue for the rule id `DS-0002` at `.devcontainer/Dockerfile` with the severity `HIGH` +- **THEN** the title holds `DS-0002` and `.devcontainer/Dockerfile`, and the body holds `HIGH` and the alert number + +### Requirement: The workflow runs every day with the least permissions +The alert workflow MUST run on a daily schedule, with the permissions `contents: read`, `security-events: read` and `issues: write` only. It SHALL have no `workflow_run` trigger, which zizmor reports as a HIGH finding. + +#### Scenario: The triggers of the workflow +- **WHEN** a test reads the `on` block of `.github/workflows/trivy-config-alerts.yml` +- **THEN** the block holds a `schedule` trigger and no `workflow_run` trigger + +### Requirement: The policy names the judge and the time +`SECURITY.md` SHALL name who judges a new `Trivy-config` alert, the time in which it happens, and the ignore file with its reason and expiry fields. + +#### Scenario: The Trivy-config rule in the policy +- **WHEN** a test reads the `Trivy-config` rule of `SECURITY.md` +- **THEN** the rule names the owner for a CRITICAL alert within 24 hours, an agent for the other severities within 14 days, and `.trivyignore.yaml` with `statement` and `expired_at` + +### Requirement: The IaC scan reads the ignore file with an expiry +The `trivy config` scan SHALL name `.trivyignore.yaml` of its directory with `--ignorefile` when that file exists, and it SHALL name no ignore file when it does not. + +#### Scenario: A directory with the file +- **WHEN** the scan starts in a directory that holds `.trivyignore.yaml` +- **THEN** the command holds `--ignorefile` and the path of that file, and Trivy hides a finding of an entry whose `expired_at` is later than today diff --git a/src/devops_cli/commands/scan.py b/src/devops_cli/commands/scan.py index 802928296e..666458f9ea 100644 --- a/src/devops_cli/commands/scan.py +++ b/src/devops_cli/commands/scan.py @@ -13,7 +13,11 @@ from devops_cli.ai.review_schema import Finding from devops_cli.config.commands import BIN_TRIVY -from devops_cli.config.constants import CONST_OUTPUT_FORMAT_TABLE, CONST_SCAN_NO_RESULT_STATUSES +from devops_cli.config.constants import ( + CONST_OUTPUT_FORMAT_TABLE, + CONST_SCAN_NO_RESULT_STATUSES, + CONST_TRIVY_CONFIG_ALERT_ISSUES_PER_RUN, +) from devops_cli.config.defaults import ( DEFAULT_CURRENT_PATH, DEFAULT_SEMGREP_CONFIG, @@ -24,9 +28,11 @@ ) from devops_cli.core.binaries import check_binary from devops_cli.core.cli import new_typer +from devops_cli.core.repo import find_repo_root, get_repo_origin_name from devops_cli.dry_run.decorator import dry_run_class from devops_cli.dry_run.requests import render_request_plan from devops_cli.dry_run.state import is_dry_run +from devops_cli.exceptions.git import GitHubOperationError from devops_cli.exceptions.tools import ToolExecutionError from devops_cli.lang import HELP, MESSAGES from devops_cli.models.vulnerability import VulnerabilityRemediationResult @@ -55,6 +61,7 @@ from devops_cli.security.sarif import SarifError, read_sarif, write_sarif from devops_cli.security.sbom import run_trivy_sbom from devops_cli.security.scan_plans import ( + plan_scan_alerts, plan_scan_fix, plan_scan_report, plan_semgrep_scan, @@ -1157,3 +1164,44 @@ def scan_sarif( if fail_on and report.exceeds(fail_on): raise typer.Exit(1) + + +@app.command("alerts", help=HELP.scan.alerts) +@dry_run_class("request-plan") +def scan_alerts( + repo: Annotated[str | None, typer.Option("--repo", "-R", help=HELP.scan.alerts_repo)] = None, + limit: Annotated[ + int, + typer.Option("--limit", min=1, help=HELP.scan.alerts_limit), + ] = CONST_TRIVY_CONFIG_ALERT_ISSUES_PER_RUN, + dry_run: Annotated[bool, typer.Option("--dry-run", help=HELP.options.dry_run)] = False, +) -> None: + """File one issue for each open `Trivy-config` alert group that no open issue names. + + The alerts are the results of `devops scan report` that the Security Scan step of CI uploads + to code scanning. A run files at most `--limit` issues, the worst severity first, and names the + groups that it leaves for the next run.""" + if dry_run or is_dry_run(): + render_request_plan(MESSAGES.scan.alerts_dry_run_heading, plan_scan_alerts(repo)) + return + from devops_cli.github.session import get_github_session + from devops_cli.security.alert_filer import file_alert_issues + + target = repo or get_repo_origin_name(find_repo_root(Path.cwd())) + if not target or "/" not in target: + print_error(MESSAGES.scan.alerts_no_repo, safe=True, to_stderr=True) + raise typer.Exit(1) + try: + outcome = file_alert_issues(get_github_session(), target, limit=limit) + except GitHubOperationError as exc: + print_error(str(exc), safe=True, to_stderr=True) + raise typer.Exit(1) from exc + if not (outcome.filed or outcome.held or outcome.left): + print_success(MESSAGES.scan.alerts_none_open) + return + for group, number in outcome.filed: + print_success(MESSAGES.scan.alerts_filed.format(number=number, title=group.title)) + for group in outcome.held: + print_muted(MESSAGES.scan.alerts_held.format(title=group.title)) + for group in outcome.left: + print_muted(MESSAGES.scan.alerts_left.format(title=group.title)) diff --git a/src/devops_cli/config/constants.py b/src/devops_cli/config/constants.py index 3c984a3666..80b5072350 100644 --- a/src/devops_cli/config/constants.py +++ b/src/devops_cli/config/constants.py @@ -4890,6 +4890,16 @@ class WebhookExposure(StrEnum): CONST_TRIVY_CACHE_DIR_ENV: Final[str] = "TRIVY_CACHE_DIR" CONST_TRIVY_CACHE_DIR_NAME: Final[str] = "trivy" CONST_TRIVY_CONFIG_SCAN_TYPE: Final[str] = "config" +# The ignore file of the IaC scan: an entry holds the path, the `statement` and `expired_at` of one +# finding, and Trivy reads it only when it is named with `--ignorefile` (#4401). +CONST_TRIVY_CONFIG_IGNORE_FILE: Final[str] = ".trivyignore.yaml" +# The tool name that GitHub code scanning shows for the `trivy config` results of the SARIF upload. +CONST_TRIVY_CONFIG_ALERT_TOOL: Final[str] = "Trivy-config" +# The most issues that one run of `devops scan alerts` files, so a first run over a long list of +# alerts files a few and leaves the rest for the next run (#4401). +CONST_TRIVY_CONFIG_ALERT_ISSUES_PER_RUN: Final[int] = 5 +# The labels of an issue that `devops scan alerts` files; intake sets the rest. +CONST_TRIVY_CONFIG_ALERT_ISSUE_LABELS: Final[tuple[str, ...]] = ("type/bug", "scope/security") CONST_TRIVY_CHECKS_METADATA: Final[tuple[str, ...]] = ("policy", "metadata.json") CONST_TRIVY_DB_METADATA: Final[tuple[str, ...]] = ("db", "metadata.json") diff --git a/src/devops_cli/lang/en/help.py b/src/devops_cli/lang/en/help.py index 9c2b6f9ca7..621d6d0577 100644 --- a/src/devops_cli/lang/en/help.py +++ b/src/devops_cli/lang/en/help.py @@ -2008,6 +2008,11 @@ class ScanCommandHelp: "Target file or directory to scan for prompt-injection smuggling vectors." ) fail_on: str = "Exit non-zero when a finding at or above this severity survives suppression." + alerts: str = ( + "File one issue for each open Trivy-config code scanning alert group that has none." + ) + alerts_repo: str = "Repository (owner/name); the origin of the current directory by default." + alerts_limit: str = "The most issues that one run files; the worst severity goes first." @dataclass(frozen=True) diff --git a/src/devops_cli/lang/en/messages.py b/src/devops_cli/lang/en/messages.py index dfb48fe412..ca80596463 100644 --- a/src/devops_cli/lang/en/messages.py +++ b/src/devops_cli/lang/en/messages.py @@ -1555,6 +1555,12 @@ class ScanMessages: semgrep_file_not_scanned: str = "Semgrep did not list the file as scanned" injection_executing: str = "Scanning '{target}' for prompt-injection smuggling vectors..." injection_passed: str = "✓ No prompt-injection smuggling vectors detected." + alerts_dry_run_heading: str = "Requests that `devops scan alerts` would make" + alerts_no_repo: str = "No repository: pass --repo owner/name or run in a clone of one." + alerts_none_open: str = "No open Trivy-config alert." + alerts_filed: str = "Filed #{number}: {title}" + alerts_held: str = "Open issue holds: {title}" + alerts_left: str = "Left for the next run: {title}" @dataclass(frozen=True) diff --git a/src/devops_cli/security/alert_filer.py b/src/devops_cli/security/alert_filer.py new file mode 100644 index 0000000000..7de29bf939 --- /dev/null +++ b/src/devops_cli/security/alert_filer.py @@ -0,0 +1,194 @@ +"""The issue of each open `Trivy-config` code scanning alert group (#4401). + +The `Security Scan` step of CI uploads the results of `trivy config` to GitHub code scanning, and +nothing turned an alert there into work. `file_alert_issues` reads the open alerts, groups them by +rule and file, and files one issue for each group that no open issue names. `SECURITY.md` ("Judging +a Trivy-config Alert") names who judges the issue and in what time. +""" + +from __future__ import annotations + +from collections.abc import Iterable, Sequence +from dataclasses import dataclass +from typing import Final + +from pydantic import AliasPath, BaseModel, Field + +from devops_cli.config.constants import ( + CONST_TRIVY_CONFIG_ALERT_ISSUE_LABELS, + CONST_TRIVY_CONFIG_ALERT_ISSUES_PER_RUN, + CONST_TRIVY_CONFIG_ALERT_TOOL, +) +from devops_cli.config.defaults import DEFAULT_GH_REST_PER_PAGE +from devops_cli.exceptions.git import GitHubUnreadError +from devops_cli.github.session import GitHubSession + +# The severities of Trivy, worst first: a run that files too few issues files the worst first. +_SEVERITY_ORDER: Final[tuple[str, ...]] = ("CRITICAL", "HIGH", "MEDIUM", "LOW", "UNKNOWN") +_TITLE: Final[str] = "fix(security): judge Trivy-config {rule_id} in {path}" + + +class CodeScanningAlert(BaseModel): + """The fields of one code scanning alert that the filer reads.""" + + number: int + tool_name: str = Field(validation_alias=AliasPath("tool", "name")) + rule_id: str = Field(validation_alias=AliasPath("rule", "id")) + severity_level: str | None = Field( + default=None, validation_alias=AliasPath("rule", "security_severity_level") + ) + severity_label: str | None = Field(default=None, validation_alias=AliasPath("rule", "severity")) + path: str = Field( + validation_alias=AliasPath("most_recent_instance", "location", "path"), + ) + + @property + def severity(self) -> str: + """The severity of Trivy in capitals, or the coarse level of GitHub when it gives none.""" + return (self.severity_level or self.severity_label or "UNKNOWN").upper() + + +@dataclass(frozen=True) +class AlertGroup: + """The open alerts of one rule in one file.""" + + rule_id: str + path: str + severity: str + numbers: tuple[int, ...] + + @property + def title(self) -> str: + """The title of the issue, which is also the key that tells an open issue holds the group.""" + return _TITLE.format(rule_id=self.rule_id, path=self.path) + + def body(self, repo: str) -> str: + """The text of the issue: the rule, the path, the severity and the alerts.""" + alerts = "\n".join( + f"- alert {number}: https://github.com/{repo}/security/code-scanning/{number}" + for number in self.numbers + ) + return ( + "Trivy reports a misconfiguration that no issue names.\n\n" + f"- Rule: {self.rule_id}\n" + f"- Path: {self.path}\n" + f"- Severity: {self.severity}\n\n" + f"Open alerts:\n{alerts}\n\n" + 'Judge it under "Judging a Trivy-config Alert" in SECURITY.md: fix the file, dismiss ' + "the alert with a reason, or add a time-limited entry to `.trivyignore.yaml`. The " + "owner judges a CRITICAL alert within 24 hours. An agent judges any other alert " + "within 14 days.\n" + ) + + +@dataclass(frozen=True) +class FilingPlan: + """The groups that a run files, and those that it leaves for the next run.""" + + to_file: tuple[AlertGroup, ...] + left: tuple[AlertGroup, ...] + + +@dataclass(frozen=True) +class FilingOutcome: + """What a run did: the issue of each group it filed, the groups that an open issue holds, and + the groups it left for the next run.""" + + filed: tuple[tuple[AlertGroup, int], ...] + held: tuple[AlertGroup, ...] + left: tuple[AlertGroup, ...] + + +class _CreatedIssue(BaseModel): + number: int + + +def _rank(severity: str) -> int: + return _SEVERITY_ORDER.index(severity) if severity in _SEVERITY_ORDER else len(_SEVERITY_ORDER) + + +def group_alerts(alerts: Iterable[CodeScanningAlert]) -> list[AlertGroup]: + """The `Trivy-config` alerts of `alerts` grouped by rule id and file path, the worst severity + first. An alert of another tool belongs to no group.""" + by_key: dict[tuple[str, str], list[CodeScanningAlert]] = {} + for alert in alerts: + if alert.tool_name == CONST_TRIVY_CONFIG_ALERT_TOOL: + by_key.setdefault((alert.rule_id, alert.path), []).append(alert) + groups = [ + AlertGroup( + rule_id=rule_id, + path=path, + severity=min((a.severity for a in members), key=_rank), + numbers=tuple(sorted(a.number for a in members)), + ) + for (rule_id, path), members in by_key.items() + ] + return sorted(groups, key=lambda g: (_rank(g.severity), g.rule_id, g.path)) + + +def plan_filing(groups: Sequence[AlertGroup], open_titles: set[str], *, limit: int) -> FilingPlan: + """The groups with no open issue, split into the first `limit` and the rest. A group that an + open issue names uses none of the limit.""" + wanted = [group for group in groups if group.title not in open_titles] + return FilingPlan(to_file=tuple(wanted[:limit]), left=tuple(wanted[limit:])) + + +def _repo_path(repo: str, tail: str) -> str: + return f"/repos/{repo}/{tail}" + + +def read_open_alerts(session: GitHubSession, repo: str) -> list[CodeScanningAlert]: + """Every open `Trivy-config` alert of `repo`, all pages read.""" + path = _repo_path( + repo, + f"code-scanning/alerts?state=open&tool_name={CONST_TRIVY_CONFIG_ALERT_TOOL}" + f"&per_page={DEFAULT_GH_REST_PER_PAGE}", + ) + return [CodeScanningAlert.model_validate(item) for item in session.paginate(path)] + + +def read_open_issue_titles(session: GitHubSession, repo: str) -> set[str]: + """The title of every open issue of `repo`, all pages read. A pull request is no issue.""" + path = _repo_path(repo, f"issues?state=open&per_page={DEFAULT_GH_REST_PER_PAGE}") + return { + str(item["title"]) + for item in session.paginate(path) + if isinstance(item, dict) and "pull_request" not in item + } + + +def file_alert_issues( + session: GitHubSession, + repo: str, + *, + limit: int = CONST_TRIVY_CONFIG_ALERT_ISSUES_PER_RUN, +) -> FilingOutcome: + """File one issue for each open `Trivy-config` alert group of `repo` that no open issue names, + at most `limit` of them, the worst severity first.""" + groups = group_alerts(read_open_alerts(session, repo)) + if not groups: + return FilingOutcome((), (), ()) + open_titles = read_open_issue_titles(session, repo) + plan = plan_filing(groups, open_titles, limit=limit) + filed: list[tuple[AlertGroup, int]] = [] + for group in plan.to_file: + path = _repo_path(repo, "issues") + answer = session.rest( + "POST", + path, + body={ + "title": group.title, + "body": group.body(repo), + "labels": list(CONST_TRIVY_CONFIG_ALERT_ISSUE_LABELS), + }, + ) + try: + created = _CreatedIssue.model_validate(answer) + except ValueError as exc: + raise GitHubUnreadError( + f"GitHub's answer to POST {path} holds no issue number", + details={"path": path}, + ) from exc + filed.append((group, created.number)) + held = tuple(group for group in groups if group.title in open_titles) + return FilingOutcome(filed=tuple(filed), held=held, left=plan.left) diff --git a/src/devops_cli/security/scan_plans.py b/src/devops_cli/security/scan_plans.py index 6005f1254a..0e3e56d67c 100644 --- a/src/devops_cli/security/scan_plans.py +++ b/src/devops_cli/security/scan_plans.py @@ -6,6 +6,10 @@ from pathlib import Path from devops_cli.config.commands import build_trivy_scan_cmd +from devops_cli.config.constants import ( + CONST_TRIVY_CONFIG_ALERT_ISSUE_LABELS, + CONST_TRIVY_CONFIG_ALERT_TOOL, +) from devops_cli.config.defaults import ( DEFAULT_SEMGREP_CONFIG, DEFAULT_TRIVY_HIGH_SEVERITY, @@ -37,6 +41,37 @@ def plan_trivy_scan( ] +def plan_scan_alerts(repo: str | None = None) -> list[PlannedRequest]: + """Planned requests for `devops scan alerts` (#4401): the session reads the open alerts of the + `Trivy-config` tool and the open issues, then files one issue for each group with none. The + requests go through the GitHub session, not gh, so they hold no argv.""" + target = repo or ":owner/:repo" + labels = ", ".join(CONST_TRIVY_CONFIG_ALERT_ISSUE_LABELS) + return [ + PlannedRequest( + method="GET", + target=( + f"repos/{target}/code-scanning/alerts?state=open" + f"&tool_name={CONST_TRIVY_CONFIG_ALERT_TOOL}" + ), + repeat="for each page", + ), + PlannedRequest( + method="GET", + target=f"repos/{target}/issues?state=open", + repeat="for each page", + condition="an alert is open", + ), + PlannedRequest( + method="POST", + target=f"repos/{target}/issues", + stdin=f'{{"title": "", "body": "<group>", "labels": [{labels}]}}', + condition="no open issue holds the title of a group", + repeat="for each group, up to the limit", + ), + ] + + def plan_semgrep_scan( target: Path | list[Path], config: str = DEFAULT_SEMGREP_CONFIG, diff --git a/src/devops_cli/security/trivy.py b/src/devops_cli/security/trivy.py index d3542a96a2..2e4a1c3aa1 100644 --- a/src/devops_cli/security/trivy.py +++ b/src/devops_cli/security/trivy.py @@ -17,6 +17,7 @@ CONST_TRIVY_CACHE_DIR_ENV, CONST_TRIVY_CACHE_DIR_NAME, CONST_TRIVY_CHECKS_METADATA, + CONST_TRIVY_CONFIG_IGNORE_FILE, CONST_TRIVY_CONFIG_SCAN_TYPE, CONST_TRIVY_DB_METADATA, CONST_TRIVY_NO_DB_ERROR, @@ -227,6 +228,23 @@ class TrivyConfigScanner(TrivyScanner): name: str = "trivy-config" scan_type: ClassVar[str] = CONST_TRIVY_CONFIG_SCAN_TYPE + def build_command( + self, + target_path: Path, + scan_type: str | None = None, + severity: str = DEFAULT_TRIVY_SEVERITIES, + **kwargs: Any, + ) -> list[str]: + """The `trivy config` command. It names `.trivyignore.yaml` of its directory when that + file exists: Trivy reads the entries with a path, a `statement` and `expired_at` only from + a YAML file that `--ignorefile` names (#4401).""" + cmd = super().build_command(target_path, scan_type, severity, **kwargs) + cwd = kwargs.get("cwd") + ignore = Path(cwd) / CONST_TRIVY_CONFIG_IGNORE_FILE if cwd else None + if ignore is not None and ignore.is_file(): + cmd.extend(("--ignorefile", str(ignore))) + return cmd + def run_trivy_scan( target: Path, diff --git a/tests/commands/test_scan_alerts.py b/tests/commands/test_scan_alerts.py new file mode 100644 index 0000000000..e28f02f25a --- /dev/null +++ b/tests/commands/test_scan_alerts.py @@ -0,0 +1,92 @@ +"""`devops scan alerts` files one issue for each open `Trivy-config` alert group that has none +(#4401). The groups and the issue text are tested in `tests/security/test_alert_filer.py`. GitHub +is faked at the HTTP edge. +""" + +from __future__ import annotations + +from collections.abc import Callable +from typing import Any + +import pytest + +from tests.support.fakes.github import GitHubApiFake, github_json + +_REPO = "owner/repo" + + +def _raw(number: int, rule: str, path: str, severity: str) -> dict[str, Any]: + return { + "number": number, + "tool": {"name": "Trivy-config"}, + "rule": {"id": rule, "security_severity_level": severity}, + "most_recent_instance": {"location": {"path": path}}, + } + + +@pytest.fixture +def api(github_api: GitHubApiFake) -> GitHubApiFake: + """Three alerts of three groups, and no open issue.""" + alerts = [ + _raw(1, "AZU-0041", "tf/azure/main.tf", "critical"), + _raw(2, "DS-0002", ".devcontainer/Dockerfile", "high"), + _raw(3, "KSV-0001", "k8s/a.yaml", "medium"), + ] + github_api.route( + "GET", + f"/repos/{_REPO}/code-scanning/alerts?state=open&tool_name=Trivy-config&per_page=100", + github_json(alerts), + ) + github_api.route("GET", f"/repos/{_REPO}/issues?state=open&per_page=100", github_json([])) + github_api.route("POST", f"/repos/{_REPO}/issues", github_json({"number": 60}, status=201)) + return github_api + + +def _writes(api: GitHubApiFake) -> int: + return len([r for r in api.sent if r.method == "POST"]) + + +def test_alerts_files_each_group_and_says_which_issue_it_filed( + cli: Callable[..., Any], api: GitHubApiFake +) -> None: + result = cli("scan", "alerts", "--repo", _REPO) + + output = " ".join(result.output.split()) + assert (result.exit_code, _writes(api)) == (0, 3) + assert "Filed #60: fix(security): judge Trivy-config AZU-0041 in tf/azure/main.tf" in output + + +def test_alerts_names_the_groups_that_the_limit_leaves_for_the_next_run( + cli: Callable[..., Any], api: GitHubApiFake +) -> None: + result = cli("scan", "alerts", "--repo", _REPO, "--limit", "1") + + output = " ".join(result.output.split()) + assert (result.exit_code, _writes(api)) == (0, 1) + assert "Left for the next run: fix(security): judge Trivy-config DS-0002" in output + assert "Left for the next run: fix(security): judge Trivy-config KSV-0001" in output + + +def test_a_dry_run_lists_the_requests_and_makes_none( + cli: Callable[..., Any], api: GitHubApiFake +) -> None: + result = cli("scan", "alerts", "--repo", _REPO, "--dry-run") + + assert (result.exit_code, api.sent) == (0, []) + assert f"repos/{_REPO}/code-scanning/alerts" in result.output + + +def test_alerts_says_so_when_no_alert_is_open( + cli: Callable[..., Any], github_api: GitHubApiFake +) -> None: + github_api.route( + "GET", + f"/repos/{_REPO}/code-scanning/alerts?state=open&tool_name=Trivy-config&per_page=100", + github_json([]), + ) + github_api.route("GET", f"/repos/{_REPO}/issues?state=open&per_page=100", github_json([])) + + result = cli("scan", "alerts", "--repo", _REPO) + + assert result.exit_code == 0 + assert "No open Trivy-config alert" in " ".join(result.output.split()) diff --git a/tests/invariants/test_agents_md.py b/tests/invariants/test_agents_md.py index c11824ee9d..47752cb59f 100644 --- a/tests/invariants/test_agents_md.py +++ b/tests/invariants/test_agents_md.py @@ -711,3 +711,31 @@ def test_retired_test_phrase_in_agents_md_fails_ban(tmp_path: Path) -> None: doc = tmp_path / "AGENTS.md" doc.write_text("Rule: assert tuple equality in all tests.\n", encoding="utf-8") assert _find_retired_test_phrases(doc.read_text(encoding="utf-8")) == [(1, "tuple equality")] + + +def _trivy_config_rule() -> str: + """The text of the section of SECURITY.md that judges a `Trivy-config` alert (#4401).""" + text = Path("SECURITY.md").read_text(encoding="utf-8") + start = text.index("## Judging a Trivy-config Alert") + end = text.find("\n## ", start + 1) + return " ".join(text[start : end if end != -1 else None].split()) + + +def test_the_policy_names_the_judge_the_time_and_the_ignore_file() -> None: + rule = _trivy_config_rule() + + assert "owner" in rule + assert "CRITICAL" in rule + assert "24 hours" in rule + assert "agent" in rule + assert "14 days" in rule + assert "`.trivyignore.yaml`" in rule + assert "`statement`" in rule + assert "`expired_at`" in rule + + +def test_the_policy_keeps_the_limits_of_a_finding_with_no_fix() -> None: + rule = _trivy_config_rule() + + assert "A Finding with No Fix" in rule + assert "3 days" in rule diff --git a/tests/invariants/test_workflow_contracts.py b/tests/invariants/test_workflow_contracts.py index 31051bf7c2..777d8298e5 100644 --- a/tests/invariants/test_workflow_contracts.py +++ b/tests/invariants/test_workflow_contracts.py @@ -32,6 +32,7 @@ WORKFLOWS_DIR = Path(".github/workflows") RELEASE_PATH = WORKFLOWS_DIR / "release.yml" AUDIT_PATH = WORKFLOWS_DIR / "defect-pr-hardening-audit.yml" +ALERTS_PATH = WORKFLOWS_DIR / "trivy-config-alerts.yml" def _load_workflow(path: Path) -> dict[str, Any]: @@ -1996,3 +1997,27 @@ def test_the_test_job_uploads_the_coverage_xml_report() -> None: "if-no-files-found": "warn", "retention-days": 7, } + + +def test_the_alert_workflow_runs_every_day_and_has_no_workflow_run_trigger() -> None: + """zizmor reports a `workflow_run` trigger as a HIGH finding, one more alert with no judge.""" + triggers = _load_workflow(ALERTS_PATH)["on"] + + assert triggers["schedule"] == [{"cron": "0 6 * * *"}] + assert "workflow_run" not in triggers + + +def test_the_alert_workflow_holds_only_the_permissions_it_needs() -> None: + workflow = _load_workflow(ALERTS_PATH) + + assert workflow["permissions"] == { + "contents": "read", + "security-events": "read", + "issues": "write", + } + + +def test_the_alert_workflow_runs_the_filer_command() -> None: + text = ALERTS_PATH.read_text(encoding="utf-8") + + assert "uv run devops scan alerts" in text diff --git a/tests/security/test_alert_filer.py b/tests/security/test_alert_filer.py new file mode 100644 index 0000000000..bcf2b8e7fd --- /dev/null +++ b/tests/security/test_alert_filer.py @@ -0,0 +1,183 @@ +"""The filer of the open `Trivy-config` code scanning alerts: which alerts it reads, how it groups +them, which groups get an issue, and the text of that issue (#4401). GitHub is faked at the HTTP +edge. +""" + +from __future__ import annotations + +import json +from typing import Any + +import pytest + +from devops_cli.github.session import get_github_session +from devops_cli.security.alert_filer import ( + AlertGroup, + CodeScanningAlert, + file_alert_issues, + group_alerts, + plan_filing, +) +from tests.support.fakes.github import GitHubApiFake, github_json + +_REPO = "owner/repo" +_ALERTS = f"/repos/{_REPO}/code-scanning/alerts?state=open&tool_name=Trivy-config&per_page=100" +_ISSUES = f"/repos/{_REPO}/issues?state=open&per_page=100" +_NEW_ISSUE = f"/repos/{_REPO}/issues" +_GPU = "k8s/gpu-feature-discovery/daemonset.yaml" + + +def _raw( + number: int, rule: str, path: str, severity: str = "high", tool: str = "Trivy-config" +) -> dict[str, Any]: + """One alert as GitHub's code scanning API answers it, with the fields the filer reads.""" + return { + "number": number, + "tool": {"name": tool}, + "rule": {"id": rule, "severity": "error", "security_severity_level": severity}, + "most_recent_instance": {"location": {"path": path}}, + } + + +def _alert(*args: Any, **kwargs: Any) -> CodeScanningAlert: + return CodeScanningAlert.model_validate(_raw(*args, **kwargs)) + + +def _group(rule: str, path: str, severity: str = "HIGH", *numbers: int) -> AlertGroup: + return AlertGroup(rule_id=rule, path=path, severity=severity, numbers=numbers or (1,)) + + +def test_the_groups_hold_the_trivy_config_alerts_and_no_other_tool() -> None: + alerts = [ + _alert(1, "KSV-0017", _GPU), + _alert(2, "DS-0002", ".devcontainer/Dockerfile"), + _alert(3, "AZU-0041", "tf/azure/main.tf", "critical"), + _alert(4, "py/sql-injection", "src/a.py", tool="CodeQL"), + ] + + groups = group_alerts(alerts) + + assert sorted(n for group in groups for n in group.numbers) == [1, 2, 3] + + +def test_two_alerts_of_one_rule_in_one_file_make_one_group_that_names_both() -> None: + alerts = [_alert(7, "KSV-0017", _GPU), _alert(9, "KSV-0017", _GPU)] + + (group,) = group_alerts(alerts) + + assert group.numbers == (7, 9) + assert "alert 7" in group.body(_REPO) + assert "alert 9" in group.body(_REPO) + + +def test_a_rule_in_two_files_makes_two_groups_and_the_worst_severity_comes_first() -> None: + alerts = [ + _alert(1, "KSV-0001", "k8s/a.yaml", "low"), + _alert(2, "KSV-0001", "k8s/b.yaml", "critical"), + ] + + groups = group_alerts(alerts) + + assert [(g.path, g.severity) for g in groups] == [ + ("k8s/b.yaml", "CRITICAL"), + ("k8s/a.yaml", "LOW"), + ] + + +def test_the_title_and_body_hold_the_rule_the_path_the_severity_and_the_alert_number() -> None: + group = _group("DS-0002", ".devcontainer/Dockerfile", "HIGH", 214) + + body = group.body(_REPO) + + assert group.title == "fix(security): judge Trivy-config DS-0002 in .devcontainer/Dockerfile" + assert "HIGH" in body + assert "alert 214" in body + assert f"https://github.com/{_REPO}/security/code-scanning/214" in body + assert "#214" not in body + + +def test_a_group_that_an_open_issue_names_gets_no_new_issue() -> None: + held = _group("KSV-0017", _GPU) + new = _group("DS-0002", ".devcontainer/Dockerfile") + + plan = plan_filing([held, new], {held.title}, limit=5) + + assert (plan.to_file, plan.left) == ((new,), ()) + + +def test_a_run_files_at_most_the_limit_and_names_the_groups_it_leaves() -> None: + groups = [_group(f"KSV-{i:04d}", "k8s/a.yaml") for i in range(8)] + + plan = plan_filing(groups, set(), limit=5) + + assert (plan.to_file, plan.left) == (tuple(groups[:5]), tuple(groups[5:])) + + +def test_a_group_that_an_open_issue_holds_does_not_use_the_limit() -> None: + groups = [_group(f"KSV-{i:04d}", "k8s/a.yaml") for i in range(3)] + + plan = plan_filing(groups, {groups[0].title}, limit=2) + + assert (plan.to_file, plan.left) == (tuple(groups[1:]), ()) + + +@pytest.fixture +def api(github_api: GitHubApiFake) -> GitHubApiFake: + """Three alerts of two groups, and one open issue that is no group.""" + alerts = [ + _raw(1, "KSV-0017", _GPU), + _raw(2, "KSV-0017", _GPU), + _raw(3, "DS-0002", ".devcontainer/Dockerfile"), + ] + github_api.route("GET", _ALERTS, github_json(alerts)) + github_api.route("GET", _ISSUES, github_json([{"number": 5, "title": "feat: something"}])) + github_api.route("POST", _NEW_ISSUE, github_json({"number": 60}, status=201)) + return github_api + + +def test_the_filer_files_one_issue_for_each_group_with_no_open_issue(api: GitHubApiFake) -> None: + outcome = file_alert_issues(get_github_session(), _REPO, limit=5) + + posted = [json.loads(r.content) for r in api.sent if r.method == "POST"] + assert [p["title"] for p in posted] == [ + "fix(security): judge Trivy-config DS-0002 in .devcontainer/Dockerfile", + f"fix(security): judge Trivy-config KSV-0017 in {_GPU}", + ] + assert all(p["labels"] == ["type/bug", "scope/security"] for p in posted) + assert len(outcome.filed) == 2 + + +def test_the_filer_files_nothing_when_each_group_has_an_open_issue( + github_api: GitHubApiFake, +) -> None: + group = _group("DS-0002", ".devcontainer/Dockerfile", "HIGH", 3) + github_api.route( + "GET", + _ALERTS, + github_json([_raw(3, "DS-0002", ".devcontainer/Dockerfile")]), + ) + github_api.route("GET", _ISSUES, github_json([{"number": 8, "title": group.title}])) + + outcome = file_alert_issues(get_github_session(), _REPO, limit=5) + + assert [r for r in github_api.sent if r.method == "POST"] == [] + assert (outcome.filed, outcome.held) == ((), (group,)) + + +def test_an_open_pull_request_with_the_title_of_a_group_is_no_issue( + github_api: GitHubApiFake, +) -> None: + group = _group("DS-0002", ".devcontainer/Dockerfile", "HIGH", 3) + github_api.route( + "GET", + _ALERTS, + github_json([_raw(3, "DS-0002", ".devcontainer/Dockerfile")]), + ) + github_api.route( + "GET", _ISSUES, github_json([{"number": 8, "title": group.title, "pull_request": {}}]) + ) + github_api.route("POST", _NEW_ISSUE, github_json({"number": 60}, status=201)) + + outcome = file_alert_issues(get_github_session(), _REPO, limit=5) + + assert [number for _, number in outcome.filed] == [60] diff --git a/tests/security/test_trivy_config_ignore.py b/tests/security/test_trivy_config_ignore.py new file mode 100644 index 0000000000..3dd463ef12 --- /dev/null +++ b/tests/security/test_trivy_config_ignore.py @@ -0,0 +1,35 @@ +"""The IaC scan reads the ignore file of the repository that has a reason and an expiry (#4401). + +`.trivyignore.yaml` holds the entries of a finding in an IaC file: Trivy takes the path, the +`statement` and `expired_at` of an entry only from the YAML form, and reads that file only when it +is named with `--ignorefile`. +""" + +from __future__ import annotations + +from pathlib import Path + +from devops_cli.security.trivy import TrivyConfigScanner, TrivyScanner + + +def test_the_config_scan_names_the_yaml_ignore_file_of_its_directory(tmp_path: Path) -> None: + ignore = tmp_path / ".trivyignore.yaml" + ignore.write_text("misconfigurations: []\n", encoding="utf-8") + + cmd = TrivyConfigScanner().build_command(tmp_path, cwd=tmp_path) + + assert cmd[cmd.index("--ignorefile") + 1] == str(ignore) + + +def test_the_config_scan_names_no_ignore_file_when_the_directory_has_none(tmp_path: Path) -> None: + cmd = TrivyConfigScanner().build_command(tmp_path, cwd=tmp_path) + + assert "--ignorefile" not in cmd + + +def test_the_other_trivy_scans_keep_the_plain_ignore_file(tmp_path: Path) -> None: + (tmp_path / ".trivyignore.yaml").write_text("misconfigurations: []\n", encoding="utf-8") + + cmd = TrivyScanner().build_command(tmp_path, cwd=tmp_path) + + assert "--ignorefile" not in cmd