#!/usr/bin/env bash
# Smoke test: confirm the CVE-2025-1974 environment is up and ready.
# The exploiter and verifier run this first.
set -uo pipefail
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
export PATH="$HERE/bin:$PATH"
export KUBECONFIG="$HERE/kubeconfig"
KCTL="kubectl --kubeconfig=$KUBECONFIG"

AUTH_SECRET_NS=ingress-nginx
AUTH_SECRET_NAME=ingressnightmare-auth-ca

fail() { echo "SMOKE FAIL: $1"; exit 1; }

# 1. Cluster + controller up, pinned to the vulnerable version.
$KCTL -n ingress-nginx get deploy ingress-nginx-controller >/dev/null 2>&1 || fail "controller deployment missing"
IMG=$($KCTL -n ingress-nginx get deploy ingress-nginx-controller -o jsonpath='{.spec.template.spec.containers[0].image}')
echo "controller image: $IMG"
echo "$IMG" | grep -q "controller:v1.11.4" || fail "controller is not pinned to v1.11.4"
$KCTL -n ingress-nginx wait --for=condition=ready pod -l app.kubernetes.io/component=controller --timeout=60s >/dev/null 2>&1 || fail "controller pod not ready"

# 2. Admission webhook reachable, UNAUTHENTICATED, from the host pod-network position.
code=$(curl -sk -o /dev/null -w '%{http_code}' -X POST -H 'Content-Type: application/json' \
       --data '{}' https://127.0.0.1:8443/networking/v1/ingresses)
echo "webhook https://127.0.0.1:8443/networking/v1/ingresses -> HTTP $code"
[ "$code" = "400" ] || [ "$code" = "200" ] || fail "admission webhook not answering (HTTP $code)"

# 3. Ingress HTTP listener (fd-staging target) reachable with a LIVE upstream.
code=$(curl -s -o /dev/null -w '%{http_code}' -H 'Host: stage.local' http://127.0.0.1:8080/)
echo "ingress http://127.0.0.1:8080 (Host: stage.local) -> HTTP $code"
[ "$code" = "200" ] || fail "stage.local ingress did not return 200 (upstream may be dead -> fd-staging would break)"

# 4. Staging upstream has a live Endpoint (a prior-run fault was zero endpoints).
ep=$($KCTL -n ingress-nginx get endpoints stage-backend -o jsonpath='{.subsets[0].addresses[0].ip}' 2>/dev/null)
[ -n "$ep" ] || fail "stage-backend has no live Endpoint -> fd-staging body-read would 503"
echo "stage-backend live endpoint: $ep"

# 5. Referenceable auth-tls CA secret exists with key ca.crt (the render gate).
have=$($KCTL -n "$AUTH_SECRET_NS" get secret "$AUTH_SECRET_NAME" -o jsonpath='{.data.ca\.crt}' 2>/dev/null)
[ -n "$have" ] || fail "auth-tls secret ${AUTH_SECRET_NS}/${AUTH_SECRET_NAME} missing key ca.crt -> ssl_engine injection would be dropped"
echo "auth-tls secret present: ${AUTH_SECRET_NS}/${AUTH_SECRET_NAME} (key ca.crt) -> SECRET_REF for the exploit"

echo "SMOKE OK: environment is up; fd-staging surface, unauthenticated webhook, and referenceable auth-tls secret are live."
