name: Trivy Scan (Repo)

on:
  workflow_dispatch:
  pull_request:
  push:
    branches:
      - 'main'
      - 'release/*'

concurrency:
  group: trivy_scan_${{ github.ref }}
  cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}

jobs:
  scan-repo-trivy:
    env:
      TRIVY_REPORT_PREFIX: trivy-report-concrete
      # used by aquasecurity/trivy-action
      TRIVY_DB_REPOSITORY: public.ecr.aws/aquasecurity/trivy-db:2
      TRIVY_JAVA_DB_REPOSITORY: public.ecr.aws/aquasecurity/trivy-java-db:1 
    runs-on: ubuntu-latest
    steps:
      - name: Checkout parent Repo
        uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
        with:
          submodules: true

      - name: Export DateTime
        run: |
          fullnumericdate=$(date +%Y%m%d%H%M%S)
          echo "DATE_FULL=$fullnumericdate" >> "$GITHUB_ENV"

      - name: Scan repo (json)
        uses: aquasecurity/trivy-action@18f2510ee396bbf400402947b394f2dd8c87dbb0 # 0.29.0
        with:
          scan-type: fs
          scanners: vuln,secret,misconfig
          scan-ref: ./
          format: json
          output: ${{ env.TRIVY_REPORT_PREFIX }}-${{ env.DATE_FULL }}.json

      - name: Scan repo (sarif)
        uses: aquasecurity/trivy-action@18f2510ee396bbf400402947b394f2dd8c87dbb0 # 0.29.0
        with:
          scan-type: fs
          scanners: vuln,secret,misconfig
          scan-ref: ./
          format: sarif
          output: ${{ env.TRIVY_REPORT_PREFIX }}-${{ env.DATE_FULL }}.sarif

      - name: Download Trivy HTML template
        run: |
            wget -q https://raw.githubusercontent.com/aquasecurity/trivy/main/contrib/html.tpl -P trivy_contrib/

      - name: Scan repo (html)
        uses: aquasecurity/trivy-action@18f2510ee396bbf400402947b394f2dd8c87dbb0 # 0.29.0
        with:
          scan-type: fs
          scanners: vuln,secret,misconfig
          scan-ref: ./
          format: template
          template: '@trivy_contrib/html.tpl'
          output: ${{ env.TRIVY_REPORT_PREFIX }}-${{ env.DATE_FULL }}.html

      - name: Upload scan results as artifacts
        uses: actions/upload-artifact@b4b15b8c7c6ac21ea08fcf65892d2ee8f75cf882 # v4.4.3
        with:
          name: ${{ env.TRIVY_REPORT_PREFIX }}-all-${{ env.DATE_FULL }}
          path: ${{ env.TRIVY_REPORT_PREFIX }}-${{ env.DATE_FULL }}.*

      - name: Upload Trivy scan results to GitHub Security tab
        uses: github/codeql-action/upload-sarif@dd7559424621a6dd0b32ababe9e4b271a87f78d2 # v3.27.6
        with:
          sarif_file: ${{ env.TRIVY_REPORT_PREFIX }}-${{ env.DATE_FULL }}.sarif
          category: sca-trivy-repo
