# =============================================================================
# REUSABLE WORKFLOW: Security Scanning Suite
# PURPOSE: Run security scans (audit, OSV) and generate SBOM
# USAGE: Called by PR and main workflows for security validation
# OUTPUTS: Security findings uploaded to GitHub Security tab, SBOM artifact
# NOTE: CodeQL has its own dedicated workflow (codeql.yml) for better integration
# =============================================================================

name: Reusable Security

on:
  workflow_call:
    inputs:
      node-version:
        description: 'Node.js version (should match package.json engines.node)'
        type: string
        default: '22' # UPDATE: When upgrading Node.js
      pnpm-version:
        description: 'pnpm version (should match package.json packageManager)'
        type: string
        default: '10.17.0' # UPDATE: When upgrading pnpm
      run-osv-scan:
        description: 'Run OSV scanner for dependency vulnerabilities'
        type: boolean
        default: true

# SECURITY: Required permissions for security scanning
permissions:
  actions: read # Read workflow metadata
  contents: read # Read source code
  security-events: write # Upload security findings

# EXAMPLE USAGE:
# jobs:
#   security:
#     uses: ./.github/workflows/reusable-security.yml
#     with:
#       run-osv-scan: true

jobs:
  audit:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v4
        with:
          fetch-depth: 0 # Full history for accurate analysis

      # =============================================================================
      # ENVIRONMENT SETUP
      # Required for SBOM generation and dependency analysis
      # =============================================================================

      - name: Install pnpm
        uses: pnpm/action-setup@v4
        with:
          version: ${{ inputs.pnpm-version }}
          run_install: false
          standalone: true

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: ${{ inputs.node-version }}
          cache: pnpm # Cache dependencies for speed

      - name: Install dependencies
        # Dependencies needed for accurate SBOM generation
        run: pnpm install --frozen-lockfile

      - name: Security audit
        # Check for known vulnerabilities in dependencies
        # FAILS IF: Critical vulnerabilities found
        # To fix: Run 'pnpm update' or add overrides in package.json
        run: pnpm audit --audit-level critical

  osv-scan:
    if: inputs.run-osv-scan
    uses: google/osv-scanner-action/.github/workflows/osv-scanner-reusable.yml@v2.2.1
    with:
      # Scan entire project including all manifests (package.json, pnpm-lock.yaml)
      scan-args: |-
        ./
    permissions:
      security-events: write # Required to upload findings to Security tab
      actions: read
      contents: read
