name: "Audit dependencies"
on:
  push:
    paths:
      # Run if workflow changes
      - .github/workflows/audit.yml
      # Run on changed dependencies
      - "**/Cargo.toml"
      - "**/Cargo.lock"
  pull_request:
    paths:
      # Run if workflow changes
      - .github/workflows/audit.yml
      # Run on changed dependencies
      - "**/Cargo.toml"
      - "**/Cargo.lock"
  # Rerun periodically to pick up new advisories (weekly instead of daily)
  schedule:
    - cron: "0 6 * * 1" # Monday at 6 AM UTC
  # Run manually
  workflow_dispatch:

# Security: Define minimal required permissions
permissions:
  actions: read
  contents: read
  issues: write
  security-events: write

jobs:
  audit:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2

      - name: Install Rust toolchain
        uses: actions-rust-lang/setup-rust-toolchain@2b1f5e9b395427c92ee4e3331786ca3c37afe2d7 # v1.16.0
        with:
          cache: true
          # toolchain, components, etc. are specified in rust-toolchain.toml

      - name: Cache audit database
        uses: actions/cache@9255dc7a253b0ccc959486e2bca901246202afeb # v5.0.1
        with:
          path: ~/.cargo/advisory-db
          key: advisory-db-${{ github.ref_name }}-v1
          restore-keys: advisory-db-

      - name: Install cargo-audit
        run: cargo install --locked cargo-audit

      - name: Run cargo audit
        run: |
          set +e
          cargo audit --format sarif > audit-results.sarif
          sarif_status=$?
          cargo audit --json > audit-results.json
          json_status=$?
          # Show human-readable output as well
          cargo audit
          terminal_status=$?

          if [ "$sarif_status" -ne 0 ]; then
            exit "$sarif_status"
          fi
          if [ "$json_status" -ne 0 ]; then
            exit "$json_status"
          fi
          exit "$terminal_status"
        continue-on-error: true

      - name: Upload audit SARIF results
        if: always()
        uses: github/codeql-action/upload-sarif@95e58e9a2cdfd71adc6e0353d5c52f41a045d225 # v4
        with:
          sarif_file: audit-results.sarif
          category: "cargo-audit"
          wait-for-processing: true

      - name: Upload audit results
        uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0
        if: always()
        with:
          name: audit-results
          path: |
            audit-results.json
            audit-results.sarif
