name: Security

on:
  push:
    branches: [main]
  pull_request:
    branches: [main]

jobs:
  security:
    name: Security check
    runs-on: ubuntu-latest
    steps:
      # Same external-URL checkout dance the fai/platform CI uses —
      # the runner's internal forgejo URL is not resolvable from
      # inside the DinD job container. See `reference_forgejo_ci_setup`
      # in the operator memory for the rationale.
      - name: Checkout via external URL
        run: |
          set -eu
          mkdir -p "$GITHUB_WORKSPACE"
          cd "$GITHUB_WORKSPACE"
          git init -q
          git remote add origin \
            "https://x-access-token:${GITHUB_TOKEN}@git.flemming.ws/${GITHUB_REPOSITORY}.git"
          # Fetch enough history that scanning back to the merge base
          # / origin/main yields a non-empty diff. depth=50 covers any
          # realistic PR; larger PRs still pass since the script
          # falls back to the root commit on missing base.
          git fetch --depth=50 origin "$GITHUB_SHA"
          git checkout -q FETCH_HEAD

      - name: Security check (secrets, confidentiality, banned phrases)
        # Same script `tools/security/check-staged.sh` the local
        # pre-commit hook runs — defense in depth, so a contributor
        # without `bash tools/install-hooks.sh` still cannot land
        # secrets or banned phrases on main.
        run: |
          set -eu
          BASE="origin/main"
          if [ -n "${GITHUB_BASE_REF:-}" ]; then
            git fetch --depth=50 origin "$GITHUB_BASE_REF"
            BASE="origin/$GITHUB_BASE_REF"
          fi
          bash tools/security/check-staged.sh ci "$BASE"

      - name: Security script self-test
        # Verifies every rule still trips on its tripwire — catches
        # the case where a refactor of the script silently weakens
        # a check.
        run: bash tools/security/test-check-staged.sh
