#!/usr/bin/env bash
# Kubernetes RBAC auditor — finds overprivileged service accounts and risky bindings.
# Usage: bash scripts/k8s_rbac_audit.sh [--namespace NAMESPACE]
set -euo pipefail

NS="${1:---all-namespaces}"

echo "=== Cluster Role Bindings with cluster-admin ==="
kubectl get clusterrolebindings -o json | jq -r '
  .items[] | select(.roleRef.name == "cluster-admin") |
  "  \(.metadata.name) -> \(.subjects // [] | map("\(.kind)/\(.name) (\(.namespace // "cluster"))" ) | join(", "))"'

echo ""
echo "=== Service Accounts with Secrets ==="
kubectl get serviceaccounts $NS -o json | jq -r '
  .items[] | select(.secrets != null and (.secrets | length) > 0) |
  "  \(.metadata.namespace)/\(.metadata.name): \(.secrets | length) secret(s)"'

echo ""
echo "=== Pods Running as Privileged ==="
kubectl get pods $NS -o json | jq -r '
  .items[] | select(.spec.containers[]?.securityContext?.privileged == true) |
  "  \(.metadata.namespace)/\(.metadata.name)"'

echo ""
echo "=== Pods with Host Network ==="
kubectl get pods $NS -o json | jq -r '
  .items[] | select(.spec.hostNetwork == true) |
  "  \(.metadata.namespace)/\(.metadata.name)"'

echo ""
echo "=== Pods Mounting Docker Socket ==="
kubectl get pods $NS -o json | jq -r '
  .items[] | select(.spec.volumes[]?.hostPath?.path == "/var/run/docker.sock") |
  "  \(.metadata.namespace)/\(.metadata.name)"'
