Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: Added scout & trivy scan to github workflow #37022

Merged
merged 4 commits into from
Oct 23, 2024

Conversation

sagar-qa007
Copy link
Contributor

@sagar-qa007 sagar-qa007 commented Oct 23, 2024

Description

Run trivy and scout scanner with image name

Fixes #37036

Automation

/ok-to-test tags="@tag.IDE"

🔍 Cypress test results

Tip

🟢 🟢 🟢 All cypress tests have passed! 🎉 🎉 🎉
Workflow run: https://github.com/appsmithorg/appsmith/actions/runs/11480586298
Commit: 5ebbcd3
Cypress dashboard.
Tags: @tag.IDE
Spec:


Wed, 23 Oct 2024 13:36:44 UTC

Communication

Should the DevRel and Marketing teams inform users about this change?

  • Yes
  • No

Summary by CodeRabbit

  • New Features

    • Introduced two new scripts for automated vulnerability scanning of Docker images: scout_vulnerabilities_data.sh and trivy_vulnerabilities_data.sh.
    • Added a GitHub Actions workflow to automate vulnerability scanning and update pull requests with results.
  • Bug Fixes

    • Improved error handling for missing environment variables in the new scripts.
  • Documentation

    • Added details on the new workflow and its steps for user reference.

Copy link
Contributor

coderabbitai bot commented Oct 23, 2024

Walkthrough

The pull request introduces two new scripts, scout_vulnerabilities_data.sh and trivy_vulnerabilities_data.sh, which automate vulnerability scanning for Docker images and manage results in a PostgreSQL database. Additionally, a new GitHub Actions workflow, test-vulnerabilities-data.yml, is created to facilitate these scans and update pull requests with the results. The scripts include error handling for environment variables, installation of necessary tools, and logic for processing and inserting vulnerability data into the database.

Changes

File Change Summary
scripts/scout_vulnerabilities_data.sh New script added to automate Docker image vulnerability checks using Docker Scout and insert results into PostgreSQL.
scripts/trivy_vulnerabilities_data.sh New script added to automate Docker image vulnerability checks using Trivy and manage results in PostgreSQL.
.github/workflows/test-vulnerabilities-data.yml New GitHub Actions workflow created to automate vulnerability scanning and PR updates with results.

Assessment against linked issues

Objective Addressed Explanation
Run trivy and scout vulnerabilities scan in github action with image name (#37036)

Possibly related PRs

Suggested labels

skip-changelog

Suggested reviewers

  • sharat87
  • AnaghHegde

🎉 In the realm of code, new scripts arise,
Scanning for vulnerabilities, oh what a surprise!
With Docker and PostgreSQL, they dance in delight,
Automating checks, making security tight.
GitHub Actions join the fun, workflows in play,
Together they keep the bugs far away! 🚀


🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 9

🧹 Outside diff range and nitpick comments (2)
.github/workflows/test-vurnabilities-data.yml (1)

15-16: Update checkout action to latest version

The checkout action can be updated to v4 for latest features and security fixes.

- uses: actions/checkout@v3
+ uses: actions/checkout@v4
scripts/scout_vulnerabilities_data.sh (1)

98-98: Correct typo in log message

The message "Fetching passed data..." should be "Fetching past data..." to accurately describe the action.

Apply this diff to correct the typo:

-echo "Fetching passed data..."
+echo "Fetching past data..."
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 203b322 and 056ec0d.

📒 Files selected for processing (2)
  • .github/workflows/test-vurnabilities-data.yml (1 hunks)
  • scripts/scout_vulnerabilities_data.sh (1 hunks)
🧰 Additional context used
🪛 yamllint
.github/workflows/test-vurnabilities-data.yml

[error] 22-22: trailing spaces

(trailing-spaces)


[error] 27-27: trailing spaces

(trailing-spaces)


[error] 102-102: trailing spaces

(trailing-spaces)


[warning] 106-106: wrong indentation: expected 10 but found 12

(indentation)


[error] 109-109: trailing spaces

(trailing-spaces)


[error] 124-124: no new line character at the end of file

(new-line-at-end-of-file)

🪛 Shellcheck
scripts/scout_vulnerabilities_data.sh

[warning] 136-136: Declare and assign separately to avoid masking return values.

(SC2155)

🔇 Additional comments (2)
.github/workflows/test-vurnabilities-data.yml (1)

35-38: Review database credentials usage

Using Cypress database credentials for vulnerability tracking seems inappropriate. Consider:

  1. Creating dedicated credentials for vulnerability tracking
  2. Using a separate database instance for security data

Let's verify if these credentials are used elsewhere:

scripts/scout_vulnerabilities_data.sh (1)

117-117: Verify the correct column name 'vurn_id' in the database

The column name 'vurn_id' may be a typo. Please verify if it should be 'vuln_id' to match standard terminology.

Comment on lines 111 to 124
# Run Scout vulnerability data script
- name: Run Scout vulnerability data script
if: always()
env:
DB_HOST: ${{ secrets.CYPRESS_DB_HOST }}
DB_NAME: ${{ secrets.CYPRESS_DB_NAME }}
DB_USER: ${{ secrets.CYPRESS_DB_USER }}
DB_PWD: ${{ secrets.CYPRESS_DB_PWD }}
GITHUB_PR_ID: ${{ github.event.pull_request.number }}
GITHUB_PR_LINK: ${{ github.event.pull_request.html_url }}
GITHUB_RUN_ID: ${{ github.run_id }}
run: |
chmod +x scripts/scout_vulnerabilities_data.sh
./scripts/scout_vulnerabilities_data.sh "${{ inputs.image_name }}"
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Review PR environment variables usage

Since this is a manually triggered workflow (workflow_dispatch), the PR-related environment variables (GITHUB_PR_ID and GITHUB_PR_LINK) will be undefined as they're only available in PR-triggered workflows.

Consider:

  1. Making these variables optional in the script
  2. Adding appropriate checks in scout_vulnerabilities_data.sh
  3. Documenting when these variables will be available

Also, add a newline at the end of the file.

🧰 Tools
🪛 yamllint

[error] 124-124: no new line character at the end of file

(new-line-at-end-of-file)

Comment on lines 1 to 10
name: Run Vulnerability Data Script with Parameters and Update PR

on:
workflow_dispatch:
inputs:
image_name:
description: 'Docker image name to scan'
required: true
default: 'appsmith/appsmith-ce:release'

Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix typo in workflow filename

The workflow filename contains a typo: "vurnabilities" should be "vulnerabilities". This should be corrected for better maintainability.

Rename the file from:

- .github/workflows/test-vurnabilities-data.yml
+ .github/workflows/test-vulnerabilities-data.yml

Comment on lines 103 to 110
- name: Upload Vulnerability Data
uses: actions/upload-artifact@v3
with:
name: vulnerability-data
path: |
vulnerability_base_data.csv
vulnerability_base_data.txt

Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix YAML indentation

The path field indentation should be 10 spaces to match the YAML structure.

  with:
    name: vulnerability-data
-            path: |
-              vulnerability_base_data.csv
-              vulnerability_base_data.txt      
+    path: |
+      vulnerability_base_data.csv
+      vulnerability_base_data.txt
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
- name: Upload Vulnerability Data
uses: actions/upload-artifact@v3
with:
name: vulnerability-data
path: |
vulnerability_base_data.csv
vulnerability_base_data.txt
- name: Upload Vulnerability Data
uses: actions/upload-artifact@v3
with:
name: vulnerability-data
path: |
vulnerability_base_data.csv
vulnerability_base_data.txt
🧰 Tools
🪛 yamllint

[warning] 106-106: wrong indentation: expected 10 but found 12

(indentation)


[error] 109-109: trailing spaces

(trailing-spaces)

Comment on lines 82 to 85
[ -s "$CSV_OUTPUT_FILE" ] || echo "No vulnerabilities found for image: appsmith/appsmith-ce:release" > "$CSV_OUTPUT_FILE"

# Check if the CSV output file is empty
[ -s "$CSV_OUTPUT_FILE" ] || echo "No vulnerabilities found for image: $IMAGE" > "$CSV_OUTPUT_FILE"
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Consolidate redundant checks for empty output file

The checks at lines 82 and 85 are redundant and may overwrite each other's output. Combine them into a single check to ensure the correct message is displayed.

Apply this diff to fix the redundancy:

-[ -s "$CSV_OUTPUT_FILE" ] || echo "No vulnerabilities found for image: appsmith/appsmith-ce:release" > "$CSV_OUTPUT_FILE"

 [ -s "$CSV_OUTPUT_FILE" ] || echo "No vulnerabilities found for image: $IMAGE" > "$CSV_OUTPUT_FILE"
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
[ -s "$CSV_OUTPUT_FILE" ] || echo "No vulnerabilities found for image: appsmith/appsmith-ce:release" > "$CSV_OUTPUT_FILE"
# Check if the CSV output file is empty
[ -s "$CSV_OUTPUT_FILE" ] || echo "No vulnerabilities found for image: $IMAGE" > "$CSV_OUTPUT_FILE"
# Check if the CSV output file is empty
[ -s "$CSV_OUTPUT_FILE" ] || echo "No vulnerabilities found for image: $IMAGE" > "$CSV_OUTPUT_FILE"


local pr_id="$GITHUB_PR_ID"
local pr_link="$GITHUB_PR_LINK"
local created_date=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Separate declaration and assignment to avoid masking return values

Declaring and assigning created_date in the same command can mask return values. Separate the declaration and assignment as per ShellCheck SC2155.

Apply this diff to fix the issue:

-local created_date=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
+local created_date
+created_date=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
local created_date=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
local created_date
created_date=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
🧰 Tools
🪛 Shellcheck

[warning] 136-136: Declare and assign separately to avoid masking return values.

(SC2155)

scripts/scout_vulnerabilities_data.sh Show resolved Hide resolved
Comment on lines +144 to +147
priority=$(echo "$priority" | sed "s/'/''/g")
product=$(echo "$product" | sed "s/'/''/g")
scanner_tool=$(echo "$scanner_tool" | sed "s/'/''/g")

Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Escape all variables in SQL statements to prevent SQL injection

Variables like $comments, $owner, and $pod are not escaped and could contain special characters. Ensure all variables used in the SQL statement are properly escaped.

Apply this diff to enhance security:

     # Escape single quotes in vulnerability ID, product, and priority
     vurn_id=$(echo "$vurn_id" | sed "s/'/''/g")
     priority=$(echo "$priority" | sed "s/'/''/g")
     product=$(echo "$product" | sed "s/'/''/g")
     scanner_tool=$(echo "$scanner_tool" | sed "s/'/''/g")
+    comments=$(echo "$comments" | sed "s/'/''/g")
+    owner=$(echo "$owner" | sed "s/'/''/g")
+    pod=$(echo "$pod" | sed "s/'/''/g")
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
priority=$(echo "$priority" | sed "s/'/''/g")
product=$(echo "$product" | sed "s/'/''/g")
scanner_tool=$(echo "$scanner_tool" | sed "s/'/''/g")
priority=$(echo "$priority" | sed "s/'/''/g")
product=$(echo "$product" | sed "s/'/''/g")
scanner_tool=$(echo "$scanner_tool" | sed "s/'/''/g")
comments=$(echo "$comments" | sed "s/'/''/g")
owner=$(echo "$owner" | sed "s/'/''/g")
pod=$(echo "$pod" | sed "s/'/''/g")

Comment on lines +117 to +120
psql -t -c "SELECT vurn_id, product, scanner_tool, priority FROM vulnerability_tracking WHERE scanner_tool = 'SCOUT'" "postgresql://$DB_USER:$DB_PWD@$DB_HOST/$DB_NAME" | while IFS='|' read -r db_vurn_id db_product db_scanner_tool db_priority; do
existing_entries["$db_product,$db_scanner_tool,$db_vurn_id"]="$db_priority"
done

Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix variable scoping issue due to subshell in pipeline

The associative array existing_entries may not be populated correctly because the while loop runs in a subshell created by the pipe. Refactor the code to avoid this issue.

Apply this diff to fix the scoping issue:

-  psql -t -c "SELECT vurn_id, product, scanner_tool, priority FROM vulnerability_tracking WHERE scanner_tool = 'SCOUT'" "postgresql://$DB_USER:$DB_PWD@$DB_HOST/$DB_NAME" | while IFS='|' read -r db_vurn_id db_product db_scanner_tool db_priority; do
+  while IFS='|' read -r db_vurn_id db_product db_scanner_tool db_priority; do
     existing_entries["$db_product,$db_scanner_tool,$db_vurn_id"]="$db_priority"
-  done
+  done < <(psql -t -c "SELECT vurn_id, product, scanner_tool, priority FROM vulnerability_tracking WHERE scanner_tool = 'SCOUT'" "postgresql://$DB_USER:$DB_PWD@$DB_HOST/$DB_NAME")
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
psql -t -c "SELECT vurn_id, product, scanner_tool, priority FROM vulnerability_tracking WHERE scanner_tool = 'SCOUT'" "postgresql://$DB_USER:$DB_PWD@$DB_HOST/$DB_NAME" | while IFS='|' read -r db_vurn_id db_product db_scanner_tool db_priority; do
existing_entries["$db_product,$db_scanner_tool,$db_vurn_id"]="$db_priority"
done
while IFS='|' read -r db_vurn_id db_product db_scanner_tool db_priority; do
existing_entries["$db_product,$db_scanner_tool,$db_vurn_id"]="$db_priority"
done < <(psql -t -c "SELECT vurn_id, product, scanner_tool, priority FROM vulnerability_tracking WHERE scanner_tool = 'SCOUT'" "postgresql://$DB_USER:$DB_PWD@$DB_HOST/$DB_NAME")

@sagar-qa007 sagar-qa007 changed the title Do not merge : In progress : Added scout to github workflow chore : Added scout & trivy scan to github workflow Oct 23, 2024
yatinappsmith
yatinappsmith previously approved these changes Oct 23, 2024
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 9

🧹 Outside diff range and nitpick comments (4)
.github/workflows/test-vurnabilities-data.yml (1)

15-16: Update actions/checkout to v4.

The latest version includes performance improvements and security fixes.

- uses: actions/checkout@v3
+ uses: actions/checkout@v4
scripts/scout_vulnerabilities_data.sh (2)

12-15: Remove redundant variable assignments

The assignments on lines 12-15 are assigning variables to themselves, which is unnecessary unless there's a specific reason.


138-139: Replace hardcoded owner and pod with configurable variables

Currently, owner and pod are hardcoded values. Consider parameterizing these to make the script more flexible.

scripts/trivy_vulnerabilities_data.sh (1)

183-183: Make owner configurable instead of hardcoded

The owner is currently set to "John Doe". Consider making it configurable or deriving it from an environment variable or parameter.

Modify the line to:

-local owner="John Doe"
+local owner="${OWNER:-John Doe}"

This allows the script to use an OWNER environment variable if set, defaulting to "John Doe" otherwise.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 056ec0d and 23499d2.

📒 Files selected for processing (3)
  • .github/workflows/test-vurnabilities-data.yml (1 hunks)
  • scripts/scout_vulnerabilities_data.sh (1 hunks)
  • scripts/trivy_vulnerabilities_data.sh (1 hunks)
🧰 Additional context used
🪛 yamllint
.github/workflows/test-vurnabilities-data.yml

[error] 22-22: trailing spaces

(trailing-spaces)


[error] 27-27: trailing spaces

(trailing-spaces)


[error] 102-102: trailing spaces

(trailing-spaces)


[warning] 106-106: wrong indentation: expected 10 but found 12

(indentation)


[error] 109-109: trailing spaces

(trailing-spaces)


[error] 143-143: no new line character at the end of file

(new-line-at-end-of-file)


[error] 143-143: trailing spaces

(trailing-spaces)

🪛 Shellcheck
scripts/scout_vulnerabilities_data.sh

[warning] 135-135: Declare and assign separately to avoid masking return values.

(SC2155)

scripts/trivy_vulnerabilities_data.sh

[warning] 38-38: The surrounding quotes actually unquote this. Remove or escape them.

(SC2027)


[warning] 180-180: Declare and assign separately to avoid masking return values.

(SC2155)

🔇 Additional comments (1)
.github/workflows/test-vurnabilities-data.yml (1)

1-10: LGTM: Workflow configuration is well-structured.

The workflow configuration with manual trigger and Docker image input parameter is properly defined.

Comment on lines 111 to 126
# Run Scout vulnerability data script
- name: Run Scout vulnerability data script
if: always()
env:
DB_HOST: ${{ secrets.CYPRESS_DB_HOST }}
DB_NAME: ${{ secrets.CYPRESS_DB_NAME }}
DB_USER: ${{ secrets.CYPRESS_DB_USER }}
DB_PWD: ${{ secrets.CYPRESS_DB_PWD }}
run: |
chmod +x scripts/scout_vulnerabilities_data.sh
./scripts/scout_vulnerabilities_data.sh \
"${{ inputs.image_name }}" \
"${{ github.event.pull_request.number }}" \
"${{ github.event.pull_request.html_url }}" \
"${{ github.run_id }}"

Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add error handling for script execution.

The script execution should include error handling and status checks.

  run: |
    chmod +x scripts/scout_vulnerabilities_data.sh
-   ./scripts/scout_vulnerabilities_data.sh \
+   if ! ./scripts/scout_vulnerabilities_data.sh \
      "${{ inputs.image_name }}" \
      "${{ github.event.pull_request.number }}" \
      "${{ github.event.pull_request.html_url }}" \
-     "${{ github.run_id }}"
+     "${{ github.run_id }}"; then
+     echo "Scout vulnerability scan failed"
+     exit 1
+   fi
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
# Run Scout vulnerability data script
- name: Run Scout vulnerability data script
if: always()
env:
DB_HOST: ${{ secrets.CYPRESS_DB_HOST }}
DB_NAME: ${{ secrets.CYPRESS_DB_NAME }}
DB_USER: ${{ secrets.CYPRESS_DB_USER }}
DB_PWD: ${{ secrets.CYPRESS_DB_PWD }}
run: |
chmod +x scripts/scout_vulnerabilities_data.sh
./scripts/scout_vulnerabilities_data.sh \
"${{ inputs.image_name }}" \
"${{ github.event.pull_request.number }}" \
"${{ github.event.pull_request.html_url }}" \
"${{ github.run_id }}"
# Run Scout vulnerability data script
- name: Run Scout vulnerability data script
if: always()
env:
DB_HOST: ${{ secrets.CYPRESS_DB_HOST }}
DB_NAME: ${{ secrets.CYPRESS_DB_NAME }}
DB_USER: ${{ secrets.CYPRESS_DB_USER }}
DB_PWD: ${{ secrets.CYPRESS_DB_PWD }}
run: |
chmod +x scripts/scout_vulnerabilities_data.sh
if ! ./scripts/scout_vulnerabilities_data.sh \
"${{ inputs.image_name }}" \
"${{ github.event.pull_request.number }}" \
"${{ github.event.pull_request.html_url }}" \
"${{ github.run_id }}"; then
echo "Scout vulnerability scan failed"
exit 1
fi

Comment on lines 127 to 143
- name: Run Trivy vulnerability data script
if: always()
env:
DB_HOST: ${{ secrets.CYPRESS_DB_HOST }}
DB_NAME: ${{ secrets.CYPRESS_DB_NAME }}
DB_USER: ${{ secrets.CYPRESS_DB_USER }}
DB_PWD: ${{ secrets.CYPRESS_DB_PWD }}
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
echo "${{ secrets.GITHUB_TOKEN }}" | docker login ghcr.io -u "${{ github.actor }}" --password-stdin
chmod +x scripts/trivy_vulnerabilities_data.sh
./scripts/trivy_vulnerabilities_data.sh \
"${{ inputs.image_name }}" \
"${{ github.event.pull_request.number }}" \
"${{ github.event.pull_request.html_url }}" \
"${{ github.run_id }}"

Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Enhance Trivy scan reliability.

  1. Add error handling for Docker login and script execution
  2. Add newline at end of file
  run: |
-   echo "${{ secrets.GITHUB_TOKEN }}" | docker login ghcr.io -u "${{ github.actor }}" --password-stdin
+   if ! echo "${{ secrets.GITHUB_TOKEN }}" | docker login ghcr.io -u "${{ github.actor }}" --password-stdin; then
+     echo "Failed to login to GitHub Container Registry"
+     exit 1
+   fi
    chmod +x scripts/trivy_vulnerabilities_data.sh
-   ./scripts/trivy_vulnerabilities_data.sh \
+   if ! ./scripts/trivy_vulnerabilities_data.sh \
      "${{ inputs.image_name }}" \
      "${{ github.event.pull_request.number }}" \
      "${{ github.event.pull_request.html_url }}" \
-     "${{ github.run_id }}"
+     "${{ github.run_id }}"; then
+     echo "Trivy vulnerability scan failed"
+     exit 1
+   fi
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
- name: Run Trivy vulnerability data script
if: always()
env:
DB_HOST: ${{ secrets.CYPRESS_DB_HOST }}
DB_NAME: ${{ secrets.CYPRESS_DB_NAME }}
DB_USER: ${{ secrets.CYPRESS_DB_USER }}
DB_PWD: ${{ secrets.CYPRESS_DB_PWD }}
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
echo "${{ secrets.GITHUB_TOKEN }}" | docker login ghcr.io -u "${{ github.actor }}" --password-stdin
chmod +x scripts/trivy_vulnerabilities_data.sh
./scripts/trivy_vulnerabilities_data.sh \
"${{ inputs.image_name }}" \
"${{ github.event.pull_request.number }}" \
"${{ github.event.pull_request.html_url }}" \
"${{ github.run_id }}"
- name: Run Trivy vulnerability data script
if: always()
env:
DB_HOST: ${{ secrets.CYPRESS_DB_HOST }}
DB_NAME: ${{ secrets.CYPRESS_DB_NAME }}
DB_USER: ${{ secrets.CYPRESS_DB_USER }}
DB_PWD: ${{ secrets.CYPRESS_DB_PWD }}
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
if ! echo "${{ secrets.GITHUB_TOKEN }}" | docker login ghcr.io -u "${{ github.actor }}" --password-stdin; then
echo "Failed to login to GitHub Container Registry"
exit 1
fi
chmod +x scripts/trivy_vulnerabilities_data.sh
if ! ./scripts/trivy_vulnerabilities_data.sh \
"${{ inputs.image_name }}" \
"${{ github.event.pull_request.number }}" \
"${{ github.event.pull_request.html_url }}" \
"${{ github.run_id }}"; then
echo "Trivy vulnerability scan failed"
exit 1
fi
🧰 Tools
🪛 yamllint

[error] 143-143: no new line character at the end of file

(new-line-at-end-of-file)


[error] 143-143: trailing spaces

(trailing-spaces)

Comment on lines 32 to 102
- name: Fetch vulnerability data
id: vulnerability_data
env:
DB_HOST: ${{ secrets.CYPRESS_DB_HOST }}
DB_NAME: ${{ secrets.CYPRESS_DB_NAME }}
DB_USER: ${{ secrets.CYPRESS_DB_USER }}
DB_PWD: ${{ secrets.CYPRESS_DB_PWD }}
uses: actions/github-script@v7
with:
script: |
const { Pool } = require("pg");
const fs = require('fs');
const path = require('path');
const { DB_HOST, DB_NAME, DB_USER, DB_PWD } = process.env;

const pool = new Pool({
user: DB_USER,
host: DB_HOST,
database: DB_NAME,
password: DB_PWD,
port: 5432,
connectionTimeoutMillis: 60000,
});

(async () => {
const client = await pool.connect();
try {
// Fetch vurn_id, product, scanner_tool, and priority from the database
const result = await client.query(`SELECT vurn_id, product, scanner_tool, priority FROM vulnerability_tracking`);
console.log('Vulnerability Data:', result.rows);

// Extract relevant fields from the result
const extractedData = result.rows.map(({ vurn_id, product, scanner_tool, priority }) => ({
vurn_id,
product,
scanner_tool,
priority
}));
console.log('Extracted Vulnerability Data:', extractedData);

// Prepare CSV content
const csvContent = [
['vurn_id', 'product', 'scanner_tool', 'priority'], // Add priority column header
...extractedData.map(row => [row.vurn_id, row.product, row.scanner_tool, row.priority])
]
.map(e => e.join(',')) // Join columns
.join('\n'); // Join rows

// Write to CSV file in workspace
const csvFilePath = path.join(process.env.GITHUB_WORKSPACE, 'vulnerability_base_data.csv');
fs.writeFileSync(csvFilePath, csvContent);
console.log(`Data successfully written to ${csvFilePath}`);

// Prepare TXT content
const txtContent = extractedData
.map(row => `vurn_id: ${row.vurn_id}, product: ${row.product}, scanner_tool: ${row.scanner_tool}, priority: ${row.priority}`)
.join('\n'); // Join rows

// Write to TXT file in workspace
const txtFilePath = path.join(process.env.GITHUB_WORKSPACE, 'vulnerability_base_data.txt');
fs.writeFileSync(txtFilePath, txtContent);
console.log(`Data successfully written to ${txtFilePath}`);

client.release();
return extractedData; // Return the extracted data
} catch (err) {
console.error('Error fetching vulnerability data:', err);
client.release();
}
})();

Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Address potential database connection and I/O issues.

  1. Replace synchronous file operations with async versions
  2. Ensure pool is properly closed in all scenarios
  3. Add proper error propagation
- fs.writeFileSync(csvFilePath, csvContent);
+ await fs.promises.writeFile(csvFilePath, csvContent);

- fs.writeFileSync(txtFilePath, txtContent);
+ await fs.promises.writeFile(txtFilePath, txtContent);

  } catch (err) {
    console.error('Error fetching vulnerability data:', err);
    client.release();
+   throw err;
  } finally {
+   await pool.end();
  }

Committable suggestion was skipped due to low confidence.

🧰 Tools
🪛 yamllint

[error] 102-102: trailing spaces

(trailing-spaces)

Comment on lines +51 to +54
if ! systemctl is-active --quiet docker; then
echo "Starting Docker..."
sudo systemctl start docker
fi
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve Docker daemon check for better compatibility

Using systemctl may not work on all systems. Consider checking if Docker is running by attempting to communicate with it directly.

Apply this diff to enhance the Docker check:

 if ! systemctl is-active --quiet docker; then
     echo "Starting Docker..."
     sudo systemctl start docker
 fi
+if ! docker info > /dev/null 2>&1; then
+    echo "Docker is not running. Please start Docker and try again."
+    exit 1
+fi

Committable suggestion was skipped due to low confidence.

Comment on lines +30 to +31
curl -fsSL https://raw.githubusercontent.com/docker/scout-cli/main/install.sh -o install-scout.sh
sh install-scout.sh &> install_scout_log.txt
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Check curl exit status before executing the script

Ensure that the curl command successfully downloads the script before attempting to execute it.

Apply this diff to enhance error handling:

 curl -fsSL https://raw.githubusercontent.com/docker/scout-cli/main/install.sh -o install-scout.sh
+if [ $? -ne 0 ]; then
+    echo "Failed to download Docker Scout install script."
+    ((attempts++))
+    sleep 2
+    continue
+fi
 sh install-scout.sh &> install_scout_log.txt

Committable suggestion was skipped due to low confidence.

Comment on lines +161 to +163
psql -t -c "SELECT vurn_id, product, scanner_tool, priority FROM vulnerability_tracking WHERE scanner_tool = 'TRIVY'" "postgresql://$DB_USER:$DB_PWD@$DB_HOST/$DB_NAME" | while IFS='|' read -r db_vurn_id db_product db_scanner_tool db_priority; do
existing_entries["$db_product,$db_scanner_tool,$db_vurn_id"]="$db_priority"
done
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Correct typo from vurn_id to vuln_id

The term vurn_id seems to be a typo. It should be vuln_id to accurately represent "vulnerability ID." Update the variable names and database fields accordingly.

Apply these changes:

-SELECT vurn_id, product, scanner_tool, priority FROM vulnerability_tracking WHERE scanner_tool = 'TRIVY'
+SELECT vuln_id, product, scanner_tool, priority FROM vulnerability_tracking WHERE scanner_tool = 'TRIVY'

Update variable names and the insert statement:

-echo "INSERT INTO vulnerability_tracking (product, scanner_tool, vurn_id, priority, pr_id, pr_link, github_run_id, created_date, update_date, comments, owner, pod) VALUES ('$product', '$scanner_tool', '$vurn_id', '$priority', '$pr_id', '$pr_link', '$GITHUB_RUN_ID', '$created_date', '$update_date', '$comments', '$owner', '$pod');" >> "$query_file"
+echo "INSERT INTO vulnerability_tracking (product, scanner_tool, vuln_id, priority, pr_id, pr_link, github_run_id, created_date, update_date, comments, owner, pod) VALUES ('$product', '$scanner_tool', '$vuln_id', '$priority', '$pr_id', '$pr_link', '$GITHUB_RUN_ID', '$created_date', '$update_date', '$comments', '$owner', '$pod');" >> "$query_file"

Ensure all instances of vurn_id are updated throughout the script.

Also applies to: 165-196, 193-193


local pr_id="$GITHUB_PR_ID"
local pr_link="$GITHUB_PR_LINK"
local created_date=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Avoid masking return values by separating declaration and assignment

Declaring and assigning local created_date in the same line can mask return values in some shells. Separate the declaration and assignment for better compatibility.

Here’s the corrected code:

-local created_date=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
+local created_date
+created_date=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
local created_date=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
local created_date
created_date=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
🧰 Tools
🪛 Shellcheck

[warning] 180-180: Declare and assign separately to avoid masking return values.

(SC2155)


# Fetch the latest release dynamically instead of hardcoding
TRIVY_VERSION=$(curl -s https://api.github.com/repos/aquasecurity/trivy/releases/latest | grep '"tag_name"' | sed -E 's/.*"v([^"]+)".*/\1/')
TRIVY_URL="https://github.com/aquasecurity/trivy/releases/download/v$TRIVY_VERSION/trivy_"$TRIVY_VERSION"_Linux-64bit.tar.gz"
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix unintentional unquoting in TRIVY_URL assignment

The mixing of quotes in this line can lead to unexpected behavior due to unintentional unquoting. Update the assignment to ensure the variable is correctly quoted.

Apply this fix:

-TRIVY_URL="https://github.com/aquasecurity/trivy/releases/download/v$TRIVY_VERSION/trivy_"$TRIVY_VERSION"_Linux-64bit.tar.gz"
+TRIVY_URL="https://github.com/aquasecurity/trivy/releases/download/v${TRIVY_VERSION}/trivy_${TRIVY_VERSION}_Linux-64bit.tar.gz"
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
TRIVY_URL="https://github.com/aquasecurity/trivy/releases/download/v$TRIVY_VERSION/trivy_"$TRIVY_VERSION"_Linux-64bit.tar.gz"
TRIVY_URL="https://github.com/aquasecurity/trivy/releases/download/v${TRIVY_VERSION}/trivy_${TRIVY_VERSION}_Linux-64bit.tar.gz"
🧰 Tools
🪛 Shellcheck

[warning] 38-38: The surrounding quotes actually unquote this. Remove or escape them.

(SC2027)

Comment on lines +161 to +164
psql -t -c "SELECT vurn_id, product, scanner_tool, priority FROM vulnerability_tracking WHERE scanner_tool = 'TRIVY'" "postgresql://$DB_USER:$DB_PWD@$DB_HOST/$DB_NAME" | while IFS='|' read -r db_vurn_id db_product db_scanner_tool db_priority; do
existing_entries["$db_product,$db_scanner_tool,$db_vurn_id"]="$db_priority"
done

Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance parsing of existing database entries

When reading existing entries from the database, special characters could disrupt parsing. Use a delimiter less likely to appear in the data.

Update the psql command to use a tab delimiter:

-psql -t -c "SELECT vuln_id, product, scanner_tool, priority FROM vulnerability_tracking WHERE scanner_tool = 'TRIVY'" "postgresql://$DB_USER:$DB_PWD@$DB_HOST/$DB_NAME" | while IFS='|' read -r db_vuln_id db_product db_scanner_tool db_priority; do
+psql -A -F $'\t' -t -c "SELECT vuln_id, product, scanner_tool, priority FROM vulnerability_tracking WHERE scanner_tool = 'TRIVY'" "postgresql://$DB_USER:$DB_PWD@$DB_HOST/$DB_NAME" | while IFS=$'\t' read -r db_vuln_id db_product db_scanner_tool db_priority; do

This reduces the risk of parsing errors due to unexpected characters in the data.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
psql -t -c "SELECT vurn_id, product, scanner_tool, priority FROM vulnerability_tracking WHERE scanner_tool = 'TRIVY'" "postgresql://$DB_USER:$DB_PWD@$DB_HOST/$DB_NAME" | while IFS='|' read -r db_vurn_id db_product db_scanner_tool db_priority; do
existing_entries["$db_product,$db_scanner_tool,$db_vurn_id"]="$db_priority"
done
psql -A -F $'\t' -t -c "SELECT vurn_id, product, scanner_tool, priority FROM vulnerability_tracking WHERE scanner_tool = 'TRIVY'" "postgresql://$DB_USER:$DB_PWD@$DB_HOST/$DB_NAME" | while IFS=$'\t' read -r db_vurn_id db_product db_scanner_tool db_priority; do
existing_entries["$db_product,$db_scanner_tool,$db_vurn_id"]="$db_priority"
done

@sagar-qa007 sagar-qa007 added the ok-to-test Required label for CI label Oct 23, 2024
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 4

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 23499d2 and 5ebbcd3.

📒 Files selected for processing (1)
  • .github/workflows/test-vulnerabilities-data.yml (1 hunks)
🧰 Additional context used
🪛 yamllint
.github/workflows/test-vulnerabilities-data.yml

[error] 22-22: trailing spaces

(trailing-spaces)


[error] 27-27: trailing spaces

(trailing-spaces)


[error] 102-102: trailing spaces

(trailing-spaces)


[error] 109-109: trailing spaces

(trailing-spaces)


[error] 143-143: no new line character at the end of file

(new-line-at-end-of-file)


[error] 143-143: trailing spaces

(trailing-spaces)

🔇 Additional comments (2)
.github/workflows/test-vulnerabilities-data.yml (2)

103-109: LGTM!

The artifact upload is properly configured and uses the latest version of the action.

🧰 Tools
🪛 yamllint

[error] 109-109: trailing spaces

(trailing-spaces)


111-142: ⚠️ Potential issue

Enhance security and reliability of vulnerability scans

Several improvements needed:

  1. Separate database credentials for each scanner
  2. Add timeout limits
  3. Validate scan results

Apply these changes:

   - name: Run Scout vulnerability data script
     if: always()
+    timeout-minutes: 30
     env:
-      DB_HOST: ${{ secrets.CYPRESS_DB_HOST }}
+      DB_HOST: ${{ secrets.SCOUT_DB_HOST }}
     # ... rest of env vars ...

   - name: Run Trivy vulnerability data script
     if: always()
+    timeout-minutes: 30
     env:
-      DB_HOST: ${{ secrets.CYPRESS_DB_HOST }}
+      DB_HOST: ${{ secrets.TRIVY_DB_HOST }}
     # ... rest of env vars ...

uses: actions/setup-node@v3
with:
node-version: '20'

Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix YAML formatting issues

Remove trailing spaces and add newline at end of file.

# Remove trailing spaces from lines 22, 27, 102, 109
# Add newline at end of file (line 143)

Also applies to: 27-27, 102-102, 109-109, 143-143

🧰 Tools
🪛 yamllint

[error] 22-22: trailing spaces

(trailing-spaces)


jobs:
run-and-update-pr:
runs-on: ubuntu-latest
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Pin Ubuntu version for stability

Using ubuntu-latest may lead to unexpected issues when GitHub updates the runner image.

-    runs-on: ubuntu-latest
+    runs-on: ubuntu-22.04
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
runs-on: ubuntu-latest
runs-on: ubuntu-22.04

Comment on lines +3 to +9
on:
workflow_dispatch:
inputs:
image_name:
description: 'Docker image name to scan'
required: true
default: 'appsmith/appsmith-ce:release'
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add validation for Docker image name format

Consider adding a pattern validation to ensure the image_name follows Docker naming conventions.

 inputs:
   image_name:
     description: 'Docker image name to scan'
     required: true
     default: 'appsmith/appsmith-ce:release'
+    pattern: '^[a-z0-9]+(?:[._-][a-z0-9]+)*\/[a-z0-9]+(?:[._-][a-z0-9]+)*(?::[a-z0-9]+(?:[._-][a-z0-9]+)*)?$'
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
on:
workflow_dispatch:
inputs:
image_name:
description: 'Docker image name to scan'
required: true
default: 'appsmith/appsmith-ce:release'
on:
workflow_dispatch:
inputs:
image_name:
description: 'Docker image name to scan'
required: true
default: 'appsmith/appsmith-ce:release'
pattern: '^[a-z0-9]+(?:[._-][a-z0-9]+)*\/[a-z0-9]+(?:[._-][a-z0-9]+)*(?::[a-z0-9]+(?:[._-][a-z0-9]+)*)?$'

Comment on lines +56 to +101
(async () => {
const client = await pool.connect();
try {
// Fetch vurn_id, product, scanner_tool, and priority from the database
const result = await client.query(`SELECT vurn_id, product, scanner_tool, priority FROM vulnerability_tracking`);
console.log('Vulnerability Data:', result.rows);

// Extract relevant fields from the result
const extractedData = result.rows.map(({ vurn_id, product, scanner_tool, priority }) => ({
vurn_id,
product,
scanner_tool,
priority
}));
console.log('Extracted Vulnerability Data:', extractedData);

// Prepare CSV content
const csvContent = [
['vurn_id', 'product', 'scanner_tool', 'priority'], // Add priority column header
...extractedData.map(row => [row.vurn_id, row.product, row.scanner_tool, row.priority])
]
.map(e => e.join(',')) // Join columns
.join('\n'); // Join rows

// Write to CSV file in workspace
const csvFilePath = path.join(process.env.GITHUB_WORKSPACE, 'vulnerability_base_data.csv');
fs.writeFileSync(csvFilePath, csvContent);
console.log(`Data successfully written to ${csvFilePath}`);

// Prepare TXT content
const txtContent = extractedData
.map(row => `vurn_id: ${row.vurn_id}, product: ${row.product}, scanner_tool: ${row.scanner_tool}, priority: ${row.priority}`)
.join('\n'); // Join rows

// Write to TXT file in workspace
const txtFilePath = path.join(process.env.GITHUB_WORKSPACE, 'vulnerability_base_data.txt');
fs.writeFileSync(txtFilePath, txtContent);
console.log(`Data successfully written to ${txtFilePath}`);

client.release();
return extractedData; // Return the extracted data
} catch (err) {
console.error('Error fetching vulnerability data:', err);
client.release();
}
})();
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Critical: Fix resource leaks and error handling

Several issues need attention:

  1. The pool is never closed, leading to connection leaks
  2. Large result sets could cause memory issues
  3. Errors are logged but not propagated, potentially hiding failures

Apply these fixes:

 (async () => {
   const client = await pool.connect();
   try {
     // Fetch vurn_id, product, scanner_tool, and priority from the database
-    const result = await client.query(`SELECT vurn_id, product, scanner_tool, priority FROM vulnerability_tracking`);
+    const result = await client.query(`
+      SELECT vurn_id, product, scanner_tool, priority 
+      FROM vulnerability_tracking 
+      LIMIT 1000
+    `);
     // ... rest of the code ...
     client.release();
     return extractedData;
   } catch (err) {
     console.error('Error fetching vulnerability data:', err);
     client.release();
+    throw err;
   } finally {
+    await pool.end();
   }
 })();
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
(async () => {
const client = await pool.connect();
try {
// Fetch vurn_id, product, scanner_tool, and priority from the database
const result = await client.query(`SELECT vurn_id, product, scanner_tool, priority FROM vulnerability_tracking`);
console.log('Vulnerability Data:', result.rows);
// Extract relevant fields from the result
const extractedData = result.rows.map(({ vurn_id, product, scanner_tool, priority }) => ({
vurn_id,
product,
scanner_tool,
priority
}));
console.log('Extracted Vulnerability Data:', extractedData);
// Prepare CSV content
const csvContent = [
['vurn_id', 'product', 'scanner_tool', 'priority'], // Add priority column header
...extractedData.map(row => [row.vurn_id, row.product, row.scanner_tool, row.priority])
]
.map(e => e.join(',')) // Join columns
.join('\n'); // Join rows
// Write to CSV file in workspace
const csvFilePath = path.join(process.env.GITHUB_WORKSPACE, 'vulnerability_base_data.csv');
fs.writeFileSync(csvFilePath, csvContent);
console.log(`Data successfully written to ${csvFilePath}`);
// Prepare TXT content
const txtContent = extractedData
.map(row => `vurn_id: ${row.vurn_id}, product: ${row.product}, scanner_tool: ${row.scanner_tool}, priority: ${row.priority}`)
.join('\n'); // Join rows
// Write to TXT file in workspace
const txtFilePath = path.join(process.env.GITHUB_WORKSPACE, 'vulnerability_base_data.txt');
fs.writeFileSync(txtFilePath, txtContent);
console.log(`Data successfully written to ${txtFilePath}`);
client.release();
return extractedData; // Return the extracted data
} catch (err) {
console.error('Error fetching vulnerability data:', err);
client.release();
}
})();
(async () => {
const client = await pool.connect();
try {
// Fetch vurn_id, product, scanner_tool, and priority from the database
const result = await client.query(`
SELECT vurn_id, product, scanner_tool, priority
FROM vulnerability_tracking
LIMIT 1000
`);
console.log('Vulnerability Data:', result.rows);
// Extract relevant fields from the result
const extractedData = result.rows.map(({ vurn_id, product, scanner_tool, priority }) => ({
vurn_id,
product,
scanner_tool,
priority
}));
console.log('Extracted Vulnerability Data:', extractedData);
// Prepare CSV content
const csvContent = [
['vurn_id', 'product', 'scanner_tool', 'priority'], // Add priority column header
...extractedData.map(row => [row.vurn_id, row.product, row.scanner_tool, row.priority])
]
.map(e => e.join(',')) // Join columns
.join('\n'); // Join rows
// Write to CSV file in workspace
const csvFilePath = path.join(process.env.GITHUB_WORKSPACE, 'vulnerability_base_data.csv');
fs.writeFileSync(csvFilePath, csvContent);
console.log(`Data successfully written to ${csvFilePath}`);
// Prepare TXT content
const txtContent = extractedData
.map(row => `vurn_id: ${row.vurn_id}, product: ${row.product}, scanner_tool: ${row.scanner_tool}, priority: ${row.priority}`)
.join('\n'); // Join rows
// Write to TXT file in workspace
const txtFilePath = path.join(process.env.GITHUB_WORKSPACE, 'vulnerability_base_data.txt');
fs.writeFileSync(txtFilePath, txtContent);
console.log(`Data successfully written to ${txtFilePath}`);
client.release();
return extractedData; // Return the extracted data
} catch (err) {
console.error('Error fetching vulnerability data:', err);
client.release();
throw err;
} finally {
await pool.end();
}
})();

@sagar-qa007 sagar-qa007 added ok-to-test Required label for CI and removed ok-to-test Required label for CI labels Oct 23, 2024
@sagar-qa007 sagar-qa007 changed the title chore : Added scout & trivy scan to github workflow chore: Added scout & trivy scan to github workflow Oct 23, 2024
@github-actions github-actions bot added the skip-changelog Adding this label to a PR prevents it from being listed in the changelog label Oct 23, 2024
@sagar-qa007 sagar-qa007 merged commit 915b602 into release Oct 23, 2024
58 of 60 checks passed
@sagar-qa007 sagar-qa007 deleted the chore/vurnailityworkflow branch October 23, 2024 14:31
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
ok-to-test Required label for CI skip-changelog Adding this label to a PR prevents it from being listed in the changelog
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants