#!/usr/bin/env bash
# POC runner: loads the malicious MV3 extension and captures the sandboxed
# page's committed origin from console output.
#
# Usage: ./run.sh [extension-dir]   (defaults to ./extension)
set -u

CHROME="${CHROME:-/chromium/chromium/src/out/asan/chrome}"
HERE="$(cd "$(dirname "$0")" && pwd)"
EXT_DIR="${1:-$HERE/extension}"
PROFILE="$(mktemp -d /tmp/chrome-poc-profile.XXXXXX)"
LOG="$HERE/chrome.log"

echo "[*] Chrome:    $CHROME"
echo "[*] Extension: $EXT_DIR"
echo "[*] Profile:   $PROFILE"
echo "[*] Log:       $LOG"

# Suppress LSAN noise on shutdown — this is a logic bug, not a memory bug.
export ASAN_OPTIONS="${ASAN_OPTIONS:-detect_leaks=0:detect_odr_violation=0}"

"$CHROME" \
  --no-first-run --no-default-browser-check --no-sandbox \
  --disable-gpu \
  --user-data-dir="$PROFILE" \
  --enable-logging=stderr --v=0 \
  --load-extension="$EXT_DIR" \
  about:blank >"$LOG" 2>&1 &
PID=$!

# Wait up to 30s for the sandboxed page to log its origin.
for i in $(seq 1 30); do
  sleep 1
  if grep -q 'CSP-VT-' "$LOG" 2>/dev/null; then
    sleep 1  # let any trailing output flush
    break
  fi
done

kill -TERM "$PID" 2>/dev/null
wait "$PID" 2>/dev/null
rm -rf "$PROFILE" 2>/dev/null || true

echo
echo "===== Relevant log lines ====="
grep -E 'CSP-VT-|content_security_policy|Failed to load extension|Extension error|manifest' "$LOG" || true
echo "=============================="
echo

if grep -q 'CSP-VT-POC.*VULNERABLE' "$LOG"; then
  echo "[+] BYPASS CONFIRMED: sandboxed page committed with non-opaque chrome-extension:// origin."
  exit 0
elif grep -q 'CSP-VT-POC.*SECURE' "$LOG"; then
  echo "[-] No bypass: sandboxed page has opaque origin (bug fixed or not triggered)."
  exit 1
elif grep -q 'CSP-VT-CONTROL' "$LOG"; then
  echo "[i] Control extension output captured (see above)."
  exit 0
else
  echo "[!] No POC marker found in log. Dumping tail:"
  tail -n 80 "$LOG"
  exit 2
fi
