name: Docker Security Scan

on:
  schedule:
    - cron: "0 2 * * *" # Daily at 2 AM UTC
  workflow_dispatch:
  workflow_run:
    workflows: ["Docker Release to Github"]
    types: [completed]

permissions:
  contents: read
  packages: read
  security-events: write

jobs:
  scan:
    name: Vulnerability Scan
    runs-on: ubuntu-latest
    timeout-minutes: 30
    steps:
      - name: Harden the runner
        uses: step-security/harden-runner@ec9f2d5744a09debf3a187a3f4f675c53b671911 # v2.13.0
        with:
          egress-policy: audit

      - name: Checkout (for SARIF fingerprinting only)
        uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
        with:
          fetch-depth: 1

      - name: Determine ref and commit for upload
        id: gitref
        shell: bash
        env:
          EVENT_NAME: ${{ github.event_name }}
          HEAD_BRANCH: ${{ github.event.workflow_run.head_branch }}
          HEAD_SHA: ${{ github.event.workflow_run.head_sha }}
        run: |
          set -euo pipefail
          if [[ "${EVENT_NAME}" == "workflow_run" ]]; then
            echo "ref=refs/heads/${HEAD_BRANCH}" >> "$GITHUB_OUTPUT"
            echo "sha=${HEAD_SHA}" >> "$GITHUB_OUTPUT"
          else
            echo "ref=${GITHUB_REF}" >> "$GITHUB_OUTPUT"
            echo "sha=${GITHUB_SHA}" >> "$GITHUB_OUTPUT"
          fi
      - name: Log in to GitHub Container Registry
        uses: docker/login-action@184bdaa0721073962dff0199f1fb9940f07167d1 # v3.5.0
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Run Trivy vulnerability scanner
        uses: aquasecurity/trivy-action@dc5a429b52fcf669ce959baa2c2dd26090d2a6c4 # v0.32.0
        with:
          image-ref: "ghcr.io/${{ github.repository }}:latest"
          format: "sarif"
          output: "trivy-results.sarif"
          severity: "CRITICAL,HIGH,MEDIUM,LOW"

      - name: Upload Trivy scan results to GitHub Security tab
        uses: github/codeql-action/upload-sarif@a4e1a019f5e24960714ff6296aee04b736cbc3cf # v3.29.6
        if: ${{ always() }}
        with:
          sarif_file: "trivy-results.sarif"
          ref: ${{ steps.gitref.outputs.ref }}
          sha: ${{ steps.gitref.outputs.sha }}
          category: "trivy-container-scan"
