name: report-on-vulnerabilities
on:
  workflow_dispatch: {}
  schedule:
    - cron: '23 2 * * *' # Every day at 02:23
env:
  REGISTRY: ghcr.io
  IMAGE_NAME: ${{ github.repository }}
jobs:
  scan:
    runs-on: ubuntu-20.04
    permissions:
      contents: read
    outputs:
      results: ${{ steps.parse-results.outputs.results }}
    steps:
    - name: Scan for vulnerabilities
      uses: aquasecurity/trivy-action@1f0aa582c8c8f5f7639610d6d38baddfea4fdcee # v0.8.0 (Trivy v0.34.0)
      with: 
        image-ref: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest
        format: json
        ignore-unfixed: false
        severity: HIGH,CRITICAL
        output: scan.json

    - name: Parse scan results
      id: parse-results
      continue-on-error: true
      run: |
        VULNS=$(cat scan.json | jq '.Results[] | has("Vulnerabilities")')
        if echo $VULNS | grep -q 'true'; then
          echo "Vulnerabilities found, creating issue"
          echo "results=$(cat scan.json)" >> $GITHUB_OUTPUT
        else
          echo "No vulnerabilities found, halting"
          echo "results=nothing" >> $GITHUB_OUTPUT
        fi

    - name: Upload vulnerability scan report
      uses: actions/upload-artifact@0b7f8abb1508181956e8e162db84b466c27e18ce # v3.1.2
      if: contains(steps.parse-results.outputs.results, 'SchemaVersion')
      with:
        name: scan.json
        path: scan.json
        if-no-files-found: error

  open-issue:
    runs-on: ubuntu-latest
    if: contains(needs.scan.outputs.results, 'SchemaVersion')
    needs: scan
    steps:
      - name: Checkout
        uses: actions/checkout@8f4b7f84864484a7bf31766abe9204da3cbe65b3 # v3.5.0
      - name: Setup build env
        uses: ./.github/actions/setup-build-env
      - name: Download scan
        uses: actions/download-artifact@9bc31d5ccc31df68ecc42ccf4149144866c47d8a # v3.0.2
        with:
          name: scan.json
      - name: Set scan output
        id: set-scan-output
        run: echo "results=$(cat scan.json)" >> $GITHUB_OUTPUT
      - uses: JasonEtco/create-an-issue@e27dddc79c92bc6e4562f268fffa5ed752639abd # v2.9.1
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          RESULTS: ${{ steps.set-scan-output.outputs.results }}
        with:
          filename: .github/VULN_TEMPLATE.md
