Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 41 additions & 16 deletions workflows/cve-fixer/.claude/commands/cve.find.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,13 +54,45 @@ Report: artifacts/cve-fixer/find/cve-issues-20260226-145018.md

2. **Verify Jira Access**

Secrets may be injected by the Ambient session, a secrets manager, or an MCP server — do NOT rely solely on bash env var checks. Instead, attempt a lightweight test API call and let the response determine whether credentials are available.
**ALWAYS check for a Jira MCP server first** before attempting any curl/env var approach.

**2.1: Check for Jira MCP server (do this first, every time)**

Look at the available tools in the current session. If any tool matching `mcp__jira*`,
`mcp__atlassian*`, or any Jira-related MCP tool is present:
- Use the MCP tool directly for all Jira queries in Step 3
- Skip the curl/auth setup entirely
- Print: "✅ Using Jira MCP server — no credentials required"

**Do NOT assume MCP is unavailable just because the user has not mentioned it.**
Always proactively check the available tool list before falling back to curl.

**2.2: Fallback — curl with credentials (only if no MCP found)**

If no Jira MCP server is available, first check whether the credentials are accessible
to the bash shell — Ambient custom env vars are sometimes available to Claude but not
automatically exported to bash subprocesses:

```bash
# Diagnose accessibility before attempting auth
TOKEN_SET=$([ -n "${JIRA_API_TOKEN}" ] && echo "yes" || echo "no")
EMAIL_SET=$([ -n "${JIRA_EMAIL}" ] && echo "yes" || echo "no")
echo "JIRA_API_TOKEN accessible to bash: $TOKEN_SET"
echo "JIRA_EMAIL accessible to bash: $EMAIL_SET"
```

- If either is **"no"** → the Ambient custom env vars are not being passed to bash
subprocesses. Ask the user to export them explicitly in the session:
```bash
export JIRA_API_TOKEN="your-token-here"
export JIRA_EMAIL="[email protected]"
```
- If both are **"yes"** → proceed with the auth test call:
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Outdated

```bash
JIRA_BASE_URL="https://redhat.atlassian.net"
AUTH=$(echo -n "${JIRA_EMAIL}:${JIRA_API_TOKEN}" | base64)

# Retry once on network failure (curl exit code 000 = timeout/no response)
for ATTEMPT in 1 2; do
TEST_RESPONSE=$(curl -s -o /dev/null -w "%{http_code}" -X GET \
--connect-timeout 10 --max-time 15 \
Expand All @@ -74,29 +106,22 @@ Report: artifacts/cve-fixer/find/cve-issues-20260226-145018.md
```

- **HTTP 200** → credentials valid, proceed
- **HTTP 401** → credentials missing or invalid. Note: `/rest/api/3/myself` returns 401 for all authentication failures — there is no separate 403 for this endpoint. Only now inform the user:
- Check if `JIRA_API_TOKEN` and `JIRA_EMAIL` are configured as Ambient session secrets
- If not, generate a token at https://id.atlassian.com/manage-profile/security/api-tokens and export:

```bash
export JIRA_API_TOKEN="your-token-here"
export JIRA_EMAIL="[email protected]"
```
- **HTTP 000 after retry** → persistent network issue — inform user and stop

**Do NOT pre-check env vars with `[ -z "$JIRA_API_TOKEN" ]` and stop.** The variables may be available to the API call even if not visible to the shell check (e.g. Ambient secrets injection).
- **HTTP 401** → token is invalid or expired. Generate a new token at
https://id.atlassian.com/manage-profile/security/api-tokens and export it
- **HTTP 000 after retry** → network issue — inform user and stop

3. **Query Jira for CVE Issues**

a. Set up variables (AUTH already set from Step 2):
a. Set up variables:

```bash
COMPONENT_NAME="[from step 1]"
JIRA_BASE_URL="https://redhat.atlassian.net"
# AUTH already constructed in Step 2 — reuse it
# If using MCP (Step 2.1): pass JQL directly to MCP tool — no AUTH needed
# If using curl (Step 2.2): AUTH already constructed in Step 2 — reuse it
```

b. Construct JQL query and execute API call:
b. Construct JQL query and execute via MCP or curl:

```bash
# Normalize component name with case-insensitive lookup against mapping file
Expand Down
114 changes: 103 additions & 11 deletions workflows/cve-fixer/.claude/commands/cve.fix.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,11 @@ Summary:

1. **Load CVEs from Find Output or User-Specified Jira Issue**

**Supported flags:**
- `--automerge` — After creating each PR, enable GitHub's automerge so the PR merges automatically once all required checks pass. Off by default — the user must explicitly opt in.

Parse this flag before processing Jira issues. Store as `AUTOMERGE=true/false`.

**Option A: User specifies one or more Jira issues**
- If user provides one or more Jira issue IDs (e.g., `/cve.fix RHOAIENG-4973` or `/cve.fix RHOAIENG-4973 RHOAIENG-5821`):
- Process each issue independently -- extract CVE ID and component from each
Expand Down Expand Up @@ -565,19 +570,40 @@ This issue can be closed as 'Not a Bug / ${VEX_JUSTIFICATION}' if the above evid

**How to check:**

Two searches are needed — bots like Dependabot and Renovate open PRs that fix the same
vulnerability without mentioning the CVE ID, only the package name and version bump.

```bash
REPO_FULL="opendatahub-io/models-as-a-service" # org/repo from mapping
CVE_ID="CVE-YYYY-XXXXX"
PACKAGE="urllib3" # extracted from Jira summary in Step 1
TARGET_BRANCH="main" # from mapping or user input

# Search open PRs for this specific CVE ID targeting this branch
EXISTING_PR=$(gh pr list --repo "$REPO_FULL" --state open --base "$TARGET_BRANCH" --search "$CVE_ID" --json number,title,url,headRefName,baseRefName --jq '.[0]' 2>/dev/null)
EXISTING_PR=""

# Search 1: by CVE ID (catches our own PRs and manually created ones)
EXISTING_PR=$(gh pr list --repo "$REPO_FULL" --state open --base "$TARGET_BRANCH" \
--search "$CVE_ID" --json number,title,url --jq '.[0]' 2>/dev/null)

# Search 2: by package name (catches Dependabot/Renovate PRs that don't mention CVE ID)
if [ -z "$EXISTING_PR" ] || [ "$EXISTING_PR" = "null" ]; then
EXISTING_PR=$(gh pr list --repo "$REPO_FULL" --state open --base "$TARGET_BRANCH" \
--search "$PACKAGE" --json number,title,url,author \
--jq '[.[] | select(.author.login | test("dependabot|renovate|renovate-bot"; "i"))] | .[0]' \
2>/dev/null)

# If no bot PR, still check for any open PR bumping this package
# (a human may have already opened a fix PR without mentioning the CVE)
if [ -z "$EXISTING_PR" ] || [ "$EXISTING_PR" = "null" ]; then
EXISTING_PR=$(gh pr list --repo "$REPO_FULL" --state open --base "$TARGET_BRANCH" \
--search "$PACKAGE" --json number,title,url --jq '.[0]' 2>/dev/null)
fi
Comment thread
coderabbitai[bot] marked this conversation as resolved.
fi
Comment on lines +642 to +645
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.

⚠️ Potential issue | 🟠 Major

Package-name fallback can skip unrelated PRs on common package terms.

At Line 597-Line 599, the third search picks the first open PR matching $PACKAGE on the target branch. For common names, this can create false positives and incorrectly skip required CVE fixes.

Proposed tightening
-EXISTING_PR=$(gh pr list --repo "$REPO_FULL" --state open --base "$TARGET_BRANCH" \
-  --search "$PACKAGE" --json number,title,url --jq '.[0]' 2>/dev/null)
+EXISTING_PR=$(gh pr list --repo "$REPO_FULL" --state open --base "$TARGET_BRANCH" \
+  --search "$PACKAGE" --json number,title,url \
+  --jq '[.[] | select(.title | test("(^|[^A-Za-z0-9])" + $pkg + "([^A-Za-z0-9]|$)"; "i"))
+              | select(.title | test("bump|upgrade|security|cve"; "i"))] | .[0]' \
+  --arg pkg "$PACKAGE" 2>/dev/null)

Also applies to: 642-647

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@workflows/cve-fixer/.claude/commands/cve.fix.md` around lines 597 - 600, The
EXISTING_PR lookup uses a loose gh pr list --search "$PACKAGE" which can match
unrelated PRs for common package names; update the EXISTING_PR query (the gh pr
list invocation that writes to EXISTING_PR) to tighten matching by requiring the
package name appear as an exact word in the PR title or by additionally
filtering for a security/CVE context (e.g., require "CVE" or "security" in the
title/body) using the gh --jq filter so false positives are avoided; apply the
same fix to the second occurrence of the gh pr list that appears around the
642–647 region so both searches use the stricter filter referencing $PACKAGE,
TARGET_BRANCH and REPO_FULL.


if [ -n "$EXISTING_PR" ] && [ "$EXISTING_PR" != "null" ]; then
PR_NUMBER=$(echo "$EXISTING_PR" | jq -r '.number')
PR_TITLE=$(echo "$EXISTING_PR" | jq -r '.title')
PR_URL=$(echo "$EXISTING_PR" | jq -r '.url')
echo "⏭️ Skipping $CVE_ID — existing open PR found:"
echo "⏭️ Skipping $CVE_ID — existing open PR found (may be Dependabot/Renovate):"
echo " PR #${PR_NUMBER}: ${PR_TITLE}"
echo " URL: ${PR_URL}"

Expand Down Expand Up @@ -613,11 +639,13 @@ This issue can be closed as 'Not a Bug / ${VEX_JUSTIFICATION}' if the above evid
- Proceed with the fix (Step 6 onwards)

**Search strategy:**
- Search by exact CVE ID first (e.g., `CVE-2025-61726`) — this is the most reliable match
- **Search 1 — by CVE ID**: catches our own PRs and any manually created ones
- **Search 2 — by package name filtered to bots**: catches Dependabot/Renovate PRs that bump the vulnerable package without mentioning the CVE ID (e.g. "Bump urllib3 from 1.26.5 to 2.2.3")
- **Search 3 — by package name broadly**: catches any human-opened PR for the same package, regardless of author
- The `gh pr list --search` command searches PR titles and bodies
- A single PR may address multiple CVEs (e.g., "fix: cve-2025-61726 and cve-2025-68121") — if ANY of the target CVEs appear in an existing PR, consider all CVEs in that PR as already handled
- **IMPORTANT: Only skip for OPEN PRs.** Closed or merged PRs should be ignored — if a previous PR was closed without merging (e.g., it was incorrect or superseded), it is valid to create a new fix PR for the same CVE. The `--state open` flag in the `gh pr list` command ensures only open PRs are checked.
- **Stale remote branches**: A previous automation run may have left a remote branch with the same name (e.g., `fix/cve-YYYY-XXXXX-attempt-1`) from a closed PR. If push fails due to a conflicting remote branch, increment the attempt number (e.g., `attempt-2`) or delete the stale remote branch with `git push origin --delete <branch-name>` before pushing.
- A single PR may address multiple CVEs — if any of the target CVEs or the affected package appears in an existing open PR, skip creating a duplicate
- **IMPORTANT: Only skip for OPEN PRs.** Closed or merged PRs should be ignored — it is valid to create a new fix PR for the same CVE if a previous PR was closed without merging. The `--state open` flag ensures only open PRs are checked.
- **Stale remote branches**: If push fails due to a conflicting remote branch from a previous run, increment the attempt number (e.g., `attempt-2`) or delete the stale branch with `git push origin --delete <branch-name>`.

**Example output when PR exists:**
```
Expand Down Expand Up @@ -982,10 +1010,59 @@ This issue can be closed as 'Not a Bug / ${VEX_JUSTIFICATION}' if the above evid
**Full test log**: `artifacts/cve-fixer/fixes/test-results/test-run-20260218-143022.log`
```

10.5. **Post-Fix CVE Verification**

After applying the fix and running tests, re-run the same scanner used in Step 5 to
confirm the CVE is actually gone. This catches cases where the fix was insufficient
(e.g. transitive dependency still pulling in the old version, toolchain directive not
propagating, or the wrong package was updated).

```bash
echo "Re-scanning to verify CVE-${CVE_ID} is resolved..."
# Run same scan as Step 5 with same GOTOOLCHAIN/language tooling
POST_SCAN_OUTPUT=$(GOTOOLCHAIN="go${TARGET_GO_VERSION}" govulncheck -show verbose ./... 2>&1)
# For Python: pip-audit -r requirements.txt 2>/dev/null
# For Node: npm audit --json 2>/dev/null

if echo "$POST_SCAN_OUTPUT" | grep -q "$CVE_ID"; then
CVE_STILL_PRESENT=true
else
CVE_STILL_PRESENT=false
fi
```
Comment thread
coderabbitai[bot] marked this conversation as resolved.

**If CVE is gone** (`CVE_STILL_PRESENT=false`) → proceed to PR creation ✅

**If CVE is still present** (`CVE_STILL_PRESENT=true`) → **do NOT create a PR**:
- Print: "❌ CVE-YYYY-XXXXX still detected after fix attempt in [repo] ([branch]). Fix was insufficient."
- Add a Jira comment:

```bash
COMMENT_TEXT="Automated fix attempted but CVE still detected after applying changes.

Fix attempted: ${FIX_DESCRIPTION}
Post-fix scan: CVE still present in ${REPO_FULL} on branch ${TARGET_BRANCH}
Scan date: $(date -u +%Y-%m-%dT%H:%M:%SZ)

Manual investigation required — the automated fix did not resolve this CVE.
Possible causes: transitive dependency conflict, incorrect package targeted, or
the fix requires additional changes beyond a version bump."

COMMENT_JSON=$(jq -n --arg body "$COMMENT_TEXT" '{"body": $body}')
AUTH=$(echo -n "${JIRA_EMAIL}:${JIRA_API_TOKEN}" | base64)
curl -s -X POST \
-H "Authorization: Basic ${AUTH}" \
-H "Content-Type: application/json" \
-d "$COMMENT_JSON" \
"${JIRA_BASE_URL}/rest/api/3/issue/${JIRA_KEY}/comment"
```
Comment thread
coderabbitai[bot] marked this conversation as resolved.
- Document in `artifacts/cve-fixer/fixes/fix-failed-CVE-YYYY-XXXXX.md`
- Skip to next CVE/branch — do not create PR for this one

11. **Create Pull Requests**
- **CRITICAL**: You MUST actually CREATE the PRs using `gh pr create` command
- **CRITICAL**: Create a SEPARATE PR for EACH CVE (NOT combined)
- **CRITICAL**: Only create PRs for CVEs that were ACTUALLY FIXED (not for CVEs that were already fixed in Step 5)
- **CRITICAL**: Only create PRs for CVEs that passed post-fix verification in Step 10.5 (not for CVEs that were already fixed in Step 5 or where the fix was insufficient)
- For each CVE fix that was successfully committed and pushed:
- Generate PR title: `Security: Fix CVE-YYYY-XXXXX (<package-name>)`
- **Extract Jira issue IDs for this CVE:**
Expand Down Expand Up @@ -1074,10 +1151,16 @@ This PR fixes **CVE-YYYY-XXXXX** by upgrading <package> from X.X.X to Y.Y.Y.
EOF
)

gh pr create \
PR_URL=$(gh pr create \
--base <target-branch> \
--title "Security: Fix CVE-YYYY-XXXXX (<package-name>)" \
--body "$PR_BODY"
--body "$PR_BODY")

# Enable automerge if --automerge flag was passed
if [ "$AUTOMERGE" = "true" ]; then
gh pr merge --auto --squash "$PR_URL"
echo "✅ Automerge enabled on $PR_URL — will merge when checks pass"
fi
Comment thread
coderabbitai[bot] marked this conversation as resolved.
```
- Capture the PR URL from the command output
- Save PR URL to fix implementation report
Expand Down Expand Up @@ -1155,6 +1238,9 @@ EOF
- PR URL for the created pull request

- **Already Fixed Report**: `artifacts/cve-fixer/fixes/already-fixed-CVE-YYYY-XXXXX.md` (if CVE confirmed not present via both scan and package check)

- **Fix Failed Report**: `artifacts/cve-fixer/fixes/fix-failed-CVE-YYYY-XXXXX.md` (if post-fix re-scan still detects the CVE)
- Fix attempted, post-fix scan output, Jira comment added, manual review required
- CVE ID, repository, and scan evidence

- **VEX Justified Report**: `artifacts/cve-fixer/fixes/vex-justified-CVE-YYYY-XXXXX.md` (if auto-detected VEX justification added to Jira)
Expand Down Expand Up @@ -1222,6 +1308,12 @@ Fix multiple specific Jira issues:
/cve.fix RHOAIENG-4973 RHOAIENG-5821
```

Fix and enable automerge on all created PRs (merges automatically when checks pass):
```
/cve.fix --automerge
/cve.fix RHOAIENG-4973 --automerge
```
Comment thread
coderabbitai[bot] marked this conversation as resolved.

Fix with custom message:
```
/cve.fix Fix open CVEs found in latest scan
Expand Down
Loading