# Filename: .github/workflows/kingfisher-secrets-scan.yaml

name: Scan for leaked secrets using Kingfisher

on:
  push:
  pull_request:
  workflow_dispatch:

concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

jobs:
  kingfisher-secrets-scan:
    runs-on: ubuntu-latest
    name: Kingfisher Secrets Scan

    steps:
      - name: Checkout Code
        uses: actions/checkout@v6

      - name: Get Kingfisher version and arch
        id: get_version_arch
        run: |
          VERSION=$(curl -s https://api.github.com/repos/mongodb/kingfisher/releases/latest | jq -r '.tag_name')

          if [ -z "$VERSION" ] || [ "$VERSION" = "null" ]; then
            echo "Warning: Could not get latest Kingfisher version, falling back to v1.54.0"
            VERSION="v1.54.0"
          fi

          echo "version=$VERSION" >> $GITHUB_OUTPUT

          ARCH_RAW=$(arch)
          if [ "$ARCH_RAW" = "x86_64" ]; then
            ARCH="x64"
          elif [ "$ARCH_RAW" = "aarch64" ]; then
            ARCH="arm64"
          else
            echo "Unsupported architecture: $ARCH_RAW"
            exit 1
          fi
          echo "arch=$ARCH" >> $GITHUB_OUTPUT
          cat $GITHUB_OUTPUT

      - name: Cache kingfisher binary
        id: cache
        uses: actions/cache@v4
        with:
          path: /usr/local/bin
          key: ${{ runner.os }}-kingfisher-${{ steps.get_version_arch.outputs.version }}-${{ steps.get_version_arch.outputs.arch }}
          restore-keys: |
            ${{ runner.os }}-kingfisher-${{ steps.get_version_arch.outputs.arch }}

      - name: Install kingfisher if cache missed
        if: steps.cache.outputs.cache-hit != 'true'
        run: |
          VERSION="${{ steps.get_version_arch.outputs.version }}"
          ARCH="${{ steps.get_version_arch.outputs.arch }}"
          URL="https://github.com/mongodb/kingfisher/releases/download/${VERSION}/kingfisher-linux-${ARCH}.tgz"
          
          echo "Downloading Kingfisher ${VERSION} from $URL"
          curl -sL $URL | tar -xz -C /usr/local/bin kingfisher
          chmod +x /usr/local/bin/kingfisher

      - name: Run Kingfisher scan
        run: |
          kingfisher scan -n -r ${{ github.workspace }} \
            --exclude .git \
            --exclude '**/composer.lock' \
            --exclude '**/package-lock.json' \
            --exclude '**/yarn.lock'