name: Secrets Scanner

on:
  push:
    branches: [main, develop]
  pull_request:
    branches: [main, develop]
  schedule:
    - cron: '0 6 * * *'   # daily at 06:00 UTC
  workflow_dispatch:

permissions:
  contents: read
  security-events: write
  pull-requests: write

jobs:
  gitleaks:
    name: Gitleaks — git history scan
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0   # full history so gitleaks can scan all commits

      - name: Run Gitleaks
        uses: gitleaks/gitleaks-action@v2
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          GITLEAKS_LICENSE: ${{ secrets.GITLEAKS_LICENSE }}   # only needed for org/enterprise repos
        with:
          args: detect --source . --redact --exit-code 1

  trufflehog:
    name: TruffleHog — entropy + pattern scan
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Run TruffleHog
        uses: trufflesecurity/trufflehog@main
        with:
          path: ./
          base: ${{ github.event.repository.default_branch }}
          head: HEAD
          extra_args: --only-verified

  detect-secrets:
    name: detect-secrets — baseline diff
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-python@v5
        with:
          python-version: '3.12'

      - name: Install detect-secrets
        run: pip install detect-secrets

      - name: Scan for new secrets
        run: |
          # If a .secrets.baseline exists, audit against it
          if [ -f .secrets.baseline ]; then
            detect-secrets audit .secrets.baseline --diff
          else
            detect-secrets scan --all-files > .secrets.baseline
            echo "No baseline found — created one. Commit .secrets.baseline to enable diff mode."
            # Fail if anything was detected
            python -c "
          import json, sys
          with open('.secrets.baseline') as f:
              baseline = json.load(f)
          results = baseline.get('results', {})
          total = sum(len(v) for v in results.values())
          if total > 0:
              print(f'Found {total} potential secret(s). Review .secrets.baseline.')
              sys.exit(1)
          "
          fi

      - name: Upload baseline
        if: always()
        uses: actions/upload-artifact@v4
        with:
          name: secrets-baseline
          path: .secrets.baseline

  comment-on-pr:
    name: PR Comment on Findings
    runs-on: ubuntu-latest
    needs: [gitleaks, trufflehog, detect-secrets]
    if: failure() && github.event_name == 'pull_request'
    steps:
      - uses: actions/github-script@v7
        with:
          script: |
            github.rest.issues.createComment({
              issue_number: context.issue.number,
              owner: context.repo.owner,
              repo: context.repo.repo,
              body: [
                '## ⚠️ Secrets Scan Failed',
                '',
                'One or more secrets scanners detected potential credentials in this PR.',
                '',
                '**Do not merge until secrets are removed from the branch history.**',
                '',
                'Steps to remediate:',
                '1. Rotate any exposed credentials immediately.',
                '2. Remove the secret from code and all commits (`git filter-repo` or BFG).',
                '3. Re-run this workflow to confirm clean.',
                '',
                `[View scan details](${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }})`
              ].join('\n')
            })
