name: Scan for vulnerabilities using Trivy

# Use `yarn run trivy-*` to run them locally

on:
  push:
    branches:
      - main
  pull_request:
    types: [opened, synchronize, reopened]

jobs:
  build_and_scan:
    runs-on: [self-hosted, cicd]
    permissions:
      contents: read
      security-events: write
    steps:
      - name: Checkout code
        uses: actions/checkout@v5

      - name: "Run Trivy vuln scanner, fs mode"
        uses: aquasecurity/trivy-action@v0.36.0
        with:
          scan-type: 'fs'
          scan-ref: '.'
          format: 'sarif'
          output: './trivy-results-fs.sarif'

      - name: Upload Trivy scan results, fs mode, to GitHub Security tab
        uses: github/codeql-action/upload-sarif@v4
        if: always()
        with:
          sarif_file: './trivy-results-fs.sarif'
          category: trivy-v2-fs

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3

      - name: Add IMAGE_TAG_SHORT_SHA env property with commit short sha
        run: echo "IMAGE_TAG_SHORT_SHA=aulaapp/${{ github.event.repository.name }}:$(git rev-parse --short HEAD)" >> $GITHUB_ENV

      - name: Build and tag Docker image
        run: docker build -t $IMAGE_TAG_SHORT_SHA .

      - name: "Run Trivy vuln scanner, image mode"
        uses: aquasecurity/trivy-action@v0.36.0
        with:
          image-ref: ${{ env.IMAGE_TAG_SHORT_SHA }}
          format: 'sarif'
          output: './trivy-results-image.sarif'
          skip-setup-trivy: true

      - name: Upload Trivy scan results, image mode, to GitHub Security tab
        uses: github/codeql-action/upload-sarif@v4
        if: always()
        with:
          sarif_file: './trivy-results-image.sarif'
          category: trivy-v2-image
