name: Diagnose SSH access to liderra.ru

# Цель: понять, почему dev-IP 89.144.17.119 не пускают по SSH.
# Запускается вручную: gh workflow run ssh-diagnose.yml -f dev_ip=89.144.17.119
# Ничего не меняет на проде — только читает состояние fail2ban / iptables / sshd /
# auth.log.
#
# Использует тот же LIDERRA_SSH_KEY что и deploy.yml.

on:
  workflow_dispatch:
    inputs:
      dev_ip:
        description: 'IP который нужно проверить на блок (по умолчанию 89.144.17.119)'
        required: true
        default: '89.144.17.119'
        type: string

jobs:
  diagnose:
    runs-on: ubuntu-latest
    timeout-minutes: 5

    env:
      LIDERRA_HOST: 111.88.246.137
      LIDERRA_USER: ubuntu
      DEV_IP: ${{ github.event.inputs.dev_ip }}

    steps:
      - name: Setup SSH key
        run: |
          mkdir -p ~/.ssh
          echo "${{ secrets.LIDERRA_SSH_KEY }}" > ~/.ssh/liderra_deploy
          chmod 600 ~/.ssh/liderra_deploy
          ssh-keyscan -H ${{ env.LIDERRA_HOST }} >> ~/.ssh/known_hosts 2>/dev/null

      - name: Run diagnostic queries on prod
        run: |
          ssh -i ~/.ssh/liderra_deploy ${{ env.LIDERRA_USER }}@${{ env.LIDERRA_HOST }} \
            "DEV_IP='${DEV_IP}' bash -s" <<'REMOTE' | tee /tmp/diagnose.log
            set +e
            echo "=== 1. fail2ban status (sshd jail) ==="
            sudo fail2ban-client status sshd 2>&1 | head -30 || echo "fail2ban not available"

            echo
            echo "=== 2. Is ${DEV_IP} currently banned by fail2ban? ==="
            sudo fail2ban-client get sshd banip 2>&1 | grep -F "${DEV_IP}" || echo "NOT IN fail2ban banlist"

            echo
            echo "=== 3. Recent fail2ban actions for ${DEV_IP} (last 50 lines) ==="
            sudo grep -F "${DEV_IP}" /var/log/fail2ban.log 2>/dev/null | tail -50 || echo "no fail2ban log entries"

            echo
            echo "=== 4. iptables INPUT rules referencing ${DEV_IP} or :22 ==="
            sudo iptables -L INPUT -n -v --line-numbers 2>&1 | grep -E "(${DEV_IP}|dpt:22|tcp dpt:ssh|f2b)" || echo "no specific INPUT rules"

            echo
            echo "=== 5. iptables chains containing fail2ban (f2b-*) ==="
            sudo iptables -L -n 2>&1 | grep -E "^Chain (f2b|INPUT)" | head -10

            echo
            echo "=== 6. Full f2b-sshd chain (entries banning IPs) ==="
            sudo iptables -L f2b-sshd -n -v --line-numbers 2>&1 | head -40 || echo "no f2b-sshd chain"

            echo
            echo "=== 7. Recent SSH failed attempts from ${DEV_IP} (last 30 lines auth.log) ==="
            sudo grep -F "${DEV_IP}" /var/log/auth.log 2>/dev/null | tail -30 || echo "no auth.log entries"

            echo
            echo "=== 8. Active sshd config: AllowUsers / DenyUsers / Match blocks ==="
            sudo grep -E "^(AllowUsers|DenyUsers|AllowGroups|DenyGroups|Match)" /etc/ssh/sshd_config 2>&1 || true
            sudo ls /etc/ssh/sshd_config.d/ 2>&1
            sudo grep -E "^(AllowUsers|DenyUsers|AllowGroups|DenyGroups|Match)" /etc/ssh/sshd_config.d/*.conf 2>/dev/null || echo "no relevant entries in sshd_config.d"

            echo
            echo "=== 9. hosts.deny / hosts.allow ==="
            echo "--- /etc/hosts.deny ---"
            sudo cat /etc/hosts.deny 2>/dev/null | grep -v '^#' | grep -v '^$' || echo "(empty)"
            echo "--- /etc/hosts.allow ---"
            sudo cat /etc/hosts.allow 2>/dev/null | grep -v '^#' | grep -v '^$' || echo "(empty)"

            echo
            echo "=== 10. ufw status (если используется) ==="
            sudo ufw status verbose 2>&1 | head -20 || echo "ufw not active"

            echo
            echo "=== 11. nftables ruleset (если активен) ==="
            sudo nft list ruleset 2>&1 | head -40 || echo "nftables not active"

            echo
            echo "=== 12. Last 5 successful SSH logins (who logged in last) ==="
            last -n 5 ubuntu 2>&1 | head -10

            echo
            echo "=== 13. Full content of /etc/ssh/sshd_config.d/01-claude.conf ==="
            sudo cat /etc/ssh/sshd_config.d/01-claude.conf 2>&1 | head -80

            echo
            echo "=== 14. nftables full ruleset (f2b-table content) ==="
            sudo nft list ruleset 2>&1 | head -120

            echo
            echo "=== 15. journalctl ssh.service last 30min ==="
            sudo journalctl -u ssh.service --since="30 minutes ago" --no-pager 2>&1 | tail -40

            echo
            echo "=== 16. /etc/fail2ban/jail.d/ content ==="
            sudo ls -la /etc/fail2ban/jail.d/ 2>&1
            echo "--- whitelist-dev.conf ---"
            sudo cat /etc/fail2ban/jail.d/whitelist-dev.conf 2>&1 || echo "(missing)"
            echo "--- jail.local ---"
            sudo cat /etc/fail2ban/jail.local 2>&1 | head -40 || echo "(missing)"

            echo
            echo "=== 17. recidive jail (if any — long-term ban) ==="
            sudo fail2ban-client status recidive 2>&1 | head -20 || echo "no recidive jail"
            sudo fail2ban-client get recidive banip 2>&1 | grep -F "${DEV_IP}" || echo "NOT IN recidive"

            echo
            echo "=== DONE ==="
          REMOTE

      - name: Print summary
        if: always()
        run: |
          {
            echo "## SSH diagnostic for $DEV_IP → $LIDERRA_HOST"
            echo
            echo '```'
            cat /tmp/diagnose.log 2>/dev/null || echo "(no log captured)"
            echo '```'
          } >> "$GITHUB_STEP_SUMMARY"

      - name: Cleanup SSH key
        if: always()
        run: rm -f ~/.ssh/liderra_deploy
