#!/usr/bin/env bash
# registry-outage.sh on|off - make ghcr.io unreachable from pods (Kyverno included) by
# answering its name with 192.0.2.1, an address reserved for documentation that routes
# nowhere (RFC 5737), in the cluster's CoreDNS. The node's own container runtime does not
# use CoreDNS, so image pulls by the kubelet are not affected: this cuts off the verifier only.
#
# DNS alone is not enough. Kyverno keeps its HTTPS connections to the registry open and
# reuses them, so it never asks for the name again. The second half drops forwarded (pod)
# traffic to GitHub's 140.82.112.0/20 inside the kind node; node-originated traffic goes
# through OUTPUT, not FORWARD, and is left alone.
NODE=supply-chain-control-plane
NET=140.82.112.0/20
set -euo pipefail
cm="$(kubectl -n kube-system get configmap coredns -o jsonpath='{.data.Corefile}')"
clean="$(printf '%s\n' "$cm" | sed '/# lab-outage-start/,/# lab-outage-end/d')"
case "$1" in
  on)  new="$(printf '%s\n' "$clean" | awk '{print} /^\.:53 \{/{print "    # lab-outage-start\n    hosts {\n        192.0.2.1 ghcr.io pkg-containers.githubusercontent.com\n        fallthrough\n    }\n    # lab-outage-end"}')" ;;
  off) new="$clean" ;;
esac
kubectl -n kube-system create configmap coredns --from-literal=Corefile="$new" --dry-run=client -o yaml | kubectl apply -f - >/dev/null
kubectl -n kube-system rollout restart deployment/coredns >/dev/null
kubectl -n kube-system rollout status deployment/coredns --timeout=120s >/dev/null
docker exec "$NODE" iptables -D FORWARD -d "$NET" -j DROP 2>/dev/null || true
[ "$1" = on ] && docker exec "$NODE" iptables -I FORWARD -d "$NET" -j DROP
echo "registry outage: $1"
