diff --git a/desktop/src/testing/nativeReviewSemanticProbe.test.mjs b/desktop/src/testing/nativeReviewSemanticProbe.test.mjs new file mode 100644 index 00000000000..ebcd22c1da0 --- /dev/null +++ b/desktop/src/testing/nativeReviewSemanticProbe.test.mjs @@ -0,0 +1,33 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { clipFrameToViewport } from "./nativeReviewSemanticProbe.ts"; + +const viewport = { width: 1440, height: 792 }; + +test("a frame wholly inside the viewport is unchanged", () => { + const frame = { x: 11, y: 297, width: 260, height: 32 }; + assert.deepEqual(clipFrameToViewport(frame, viewport), frame); +}); + +test("a frame that overflows the viewport is clipped to its visible part", () => { + assert.deepEqual( + clipFrameToViewport({ x: 1400, y: 700, width: 100, height: 200 }, viewport), + { x: 1400, y: 700, width: 40, height: 92 }, + ); + assert.deepEqual( + clipFrameToViewport({ x: -20, y: -10, width: 100, height: 50 }, viewport), + { x: 0, y: 0, width: 80, height: 40 }, + ); +}); + +test("a frame wholly outside the viewport has no visible part", () => { + // The visually hidden 1px elements UI libraries park at -1px. + assert.equal( + clipFrameToViewport({ x: -1, y: -1, width: 1, height: 1 }, viewport), + undefined, + ); + assert.equal( + clipFrameToViewport({ x: 0, y: 800, width: 10, height: 10 }, viewport), + undefined, + ); +}); diff --git a/desktop/src/testing/nativeReviewSemanticProbe.ts b/desktop/src/testing/nativeReviewSemanticProbe.ts index c264898fea7..665c5c4456b 100644 --- a/desktop/src/testing/nativeReviewSemanticProbe.ts +++ b/desktop/src/testing/nativeReviewSemanticProbe.ts @@ -35,6 +35,26 @@ function accessibleName(element: HTMLElement): string | undefined { ); } +type Frame = SemanticNode["frame"]; + +/** + * The part of `frame` inside the viewport, or undefined when none of it is + * visible. The harness rejects a whole snapshot if any node leaves the + * viewport, so a visually hidden 1px element at -1px, or a list that overflows + * the window, must be clipped or skipped here rather than poison every update. + */ +export function clipFrameToViewport( + frame: Frame, + viewport: { width: number; height: number }, +): Frame | undefined { + const left = Math.max(frame.x, 0); + const top = Math.max(frame.y, 0); + const right = Math.min(frame.x + frame.width, viewport.width); + const bottom = Math.min(frame.y + frame.height, viewport.height); + if (right <= left || bottom <= top) return undefined; + return { x: left, y: top, width: right - left, height: bottom - top }; +} + function snapshot(): SemanticNode[] { const nodes: SemanticNode[] = []; for (const candidate of document.querySelectorAll( @@ -62,6 +82,12 @@ function snapshot(): SemanticNode[] { ? candidate.innerText.replace(/\r\n?/g, "\n").replace(/\n$/, "") : undefined; if (!id && !role && !name) continue; + const viewport = { width: window.innerWidth, height: window.innerHeight }; + const frame = clipFrameToViewport( + { x: rect.x, y: rect.y, width: rect.width, height: rect.height }, + viewport, + ); + if (!frame) continue; nodes.push({ ...(id ? { id } : {}), ...(role ? { role } : {}), @@ -72,16 +98,8 @@ function snapshot(): SemanticNode[] { !candidate.hasAttribute("disabled") && candidate.getAttribute("aria-disabled") !== "true", focused: candidate === document.activeElement, - frame: { - x: rect.x, - y: rect.y, - width: rect.width, - height: rect.height, - }, - viewport: { - width: window.innerWidth, - height: window.innerHeight, - }, + frame, + viewport, }); } return nodes; diff --git a/scripts/start-isolated-test-relay.sh b/scripts/start-isolated-test-relay.sh index b737a73ea9c..8d7a3b1ec5f 100755 --- a/scripts/start-isolated-test-relay.sh +++ b/scripts/start-isolated-test-relay.sh @@ -22,6 +22,11 @@ # # Teardown (safe — scoped to our project only): # docker compose -p buzz-harness -f docker-compose.harness.yml down -v +# +# Hosts without Docker (e.g. a managed macOS VM): set BUZZ_HARNESS_NATIVE_SERVICES=1 +# and BUZZ_HARNESS_STATE_DIR after Postgres/Redis/MinIO were started on the ports above +# by tools/native-review/bin/setup-macos-vm, which also creates the media bucket and +# marks the state dir and database so the schema reset below can be checked. # ============================================================================= set -euo pipefail @@ -69,12 +74,21 @@ ok() { echo -e "${GREEN}[isolated-relay]${NC} $*"; } err() { echo -e "${RED}[isolated-relay]${NC} $*" >&2; } # ── Backing services (scoped to buzz-harness only) ─────────────────────────── -log "Bringing up backing services (project=${PROJECT})..." -docker compose -p "${PROJECT}" -f "${COMPOSE_FILE}" up -d +NATIVE_SERVICES="${BUZZ_HARNESS_NATIVE_SERVICES:-0}" +if [[ "${NATIVE_SERVICES}" == "1" ]]; then + log "Using natively-run backing services on :${PG_PORT}/:${REDIS_PORT}/:${MINIO_PORT} (no Docker)..." +else + log "Bringing up backing services (project=${PROJECT})..." + docker compose -p "${PROJECT}" -f "${COMPOSE_FILE}" up -d +fi wait_pg() { for _ in $(seq 1 60); do - if docker compose -p "${PROJECT}" -f "${COMPOSE_FILE}" exec -T postgres \ + if [[ "${NATIVE_SERVICES}" == "1" ]]; then + if pg_isready -h localhost -p "${PG_PORT}" -U buzz >/dev/null 2>&1; then + ok "Postgres ready"; return 0 + fi + elif docker compose -p "${PROJECT}" -f "${COMPOSE_FILE}" exec -T postgres \ pg_isready -U buzz >/dev/null 2>&1; then ok "Postgres ready"; return 0 fi @@ -86,13 +100,29 @@ wait_pg # ── Schema + partitions ────────────────────────────────────────────────────── export PGPASSWORD=buzz_dev -psql_h() { docker compose -p "${PROJECT}" -f "${COMPOSE_FILE}" exec -T postgres \ - psql -U buzz -d buzz -v ON_ERROR_STOP=1 "$@"; } +psql_h() { + if [[ "${NATIVE_SERVICES}" == "1" ]]; then + psql -h localhost -p "${PG_PORT}" -U buzz -d buzz -v ON_ERROR_STOP=1 "$@" + else + docker compose -p "${PROJECT}" -f "${COMPOSE_FILE}" exec -T postgres \ + psql -U buzz -d buzz -v ON_ERROR_STOP=1 "$@" + fi +} log "Resetting isolated database and applying schema..." -# This database belongs only to the buzz-harness Compose project. Reset it on -# every launch so stale partitions/events from an earlier proof cannot alter -# schema planning or test results. +# This database is the harness's own: the buzz-harness Compose project's, or, with +# BUZZ_HARNESS_NATIVE_SERVICES=1, the Postgres that setup-macos-vm started. Reset it +# on every launch so stale partitions/events from an earlier proof cannot alter +# schema planning or test results. Natively run, the port is not ours by +# construction, so refuse to drop anything unless the server is demonstrably the +# harness's (its data directory, a marker file and a marker on the database). +if [[ "${NATIVE_SERVICES}" == "1" ]]; then + [[ -n "${BUZZ_HARNESS_STATE_DIR:-}" ]] \ + || { err "BUZZ_HARNESS_NATIVE_SERVICES=1 needs BUZZ_HARNESS_STATE_DIR (set by setup-macos-vm); refusing to reset a database."; exit 1; } + "${REPO_ROOT}/tools/native-review/bin/check-harness-database" \ + --state-dir "${BUZZ_HARNESS_STATE_DIR}" --port "${PG_PORT}" --db buzz --user buzz \ + || { err "Postgres on :${PG_PORT} is not the harness database; refusing to reset it."; exit 1; } +fi psql_h -c "DROP SCHEMA public CASCADE; CREATE SCHEMA public;" export PGSCHEMA_PLAN_HOST=localhost PGSCHEMA_PLAN_PORT=${PG_PORT} export PGSCHEMA_PLAN_DB=buzz PGSCHEMA_PLAN_USER=buzz PGSCHEMA_PLAN_PASSWORD=buzz_dev @@ -141,8 +171,9 @@ if command -v lsof >/dev/null 2>&1 && lsof -nP -iTCP:"${RELAY_MAIN}" -sTCP:LISTE exit 1 fi log "Starting relay in tmux session '${TMUX_SESSION}' on :${RELAY_MAIN} (health :${RELAY_HEALTH}, metrics :${RELAY_METRICS})..." +RELAY_DATABASE_URL="postgres://buzz:buzz_dev@localhost:${PG_PORT}/buzz" # sadscan:disable np.postgres.1 -- public dev fixture from docker-compose.harness.yml tmux new-session -d -s "${TMUX_SESSION}" "cd '${REPO_ROOT}' && env \ - DATABASE_URL=postgres://buzz:buzz_dev@localhost:${PG_PORT}/buzz \ + DATABASE_URL=${RELAY_DATABASE_URL} \ REDIS_URL=redis://localhost:${REDIS_PORT} \ RELAY_URL=ws://localhost:${RELAY_MAIN} \ BUZZ_BIND_ADDR=0.0.0.0:${RELAY_MAIN} \ @@ -163,7 +194,11 @@ for _ in $(seq 1 30); do ok "Relay live — BUZZ_E2E_RELAY_URL=http://localhost:${RELAY_MAIN}" ok "Logs: ${RELAY_LOG} Attach: tmux attach -t ${TMUX_SESSION}" ok "Stop relay: tmux kill-session -t ${TMUX_SESSION}" - ok "Full teardown: docker compose -p ${PROJECT} -f ${COMPOSE_FILE} down -v" + if [[ "${NATIVE_SERVICES}" == "1" ]]; then + ok "Backing services run natively under ${BUZZ_HARNESS_STATE_DIR} (stop them with pg_ctl, redis-cli shutdown and the pid in minio.pid)" + else + ok "Full teardown: docker compose -p ${PROJECT} -f ${COMPOSE_FILE} down -v" + fi exit 0 fi sleep 1 diff --git a/tools/native-review/README.md b/tools/native-review/README.md index 9b1ba136cdf..0d1ab099f69 100644 --- a/tools/native-review/README.md +++ b/tools/native-review/README.md @@ -65,6 +65,68 @@ or VM for untrusted changes. xcrun simctl list devices available ``` +### Headless macOS VM without Docker + +A cloud or CI Mac usually has a GUI session (Accessibility and Screen Recording +work) but no Docker, so `scripts/start-isolated-test-relay.sh` cannot start its +Compose stack. `tools/native-review/bin/setup-macos-vm` is the idempotent +one-shot for that machine: + +```bash +tools/native-review/bin/setup-macos-vm # services, relay, prefetch, prompt +. ~/.buzz-native-review/env.sh # PATH + SHERPA_ONNX_ARCHIVE_DIR +just native-review-desktop tools/native-review/desktop/composer-keyboard.yaml +``` + +It installs `postgresql@17`, `redis`, `ffmpeg` and `tmux` with Homebrew; builds a +pinned MinIO with `go install` (release binaries may be unreachable); runs +Postgres/Redis/MinIO natively on the harness ports (5471/6471/9471) under +`~/.buzz-native-review`; creates the `buzz-media` bucket with a SigV4 `curl`; +starts the isolated relay with `BUZZ_HARNESS_NATIVE_SERVICES=1`; prefetches the +`sherpa-onnx` archive (a TLS-intercepting proxy breaks that crate's rustls +downloader with `UnknownIssuer`, so the build reads `SHERPA_ONNX_ARCHIVE_DIR` +instead); and answers the one-time macOS "Local Network" (Allow) and "Microphone" +(Don't Allow) prompts through the same Accessibility-trusted driver +(`bin/answer-first-run-prompts`). Unanswered, the microphone prompt freezes the +app's web view. + +What it does not do: grant Accessibility or Screen Recording (the invoking +process needs them; `review-native doctor --require-permissions` checks), install +Homebrew, Go or Xcode, or set up iOS (CocoaPods mirrors, simulators). If your +network cannot reach pub.dev, export `PUB_HOSTED_URL` before running the setup +script and `review-ios`; the iOS runner passes it through. + +The driver moves the review window onto the main display and waits for WebKit's +accessibility tree before the first locator. It moves the same window the harness +reports (matched by frame, never "the first window"), reads the frame back, fails +the run if the window is not wholly on the main display, and records the +before/after frames in the receipt (`provenance.initial_window.placement`). A VM +with a second display otherwise opens the app there, where the web view exposes no +accessibility children. + +If the app cannot take focus because a first-run macOS privacy prompt is up, the +driver (`answer-privacy-prompt`) answers it, but only when it can positively +identify the prompt, and otherwise leaves it alone and says why. All of these must +hold: the window belongs to the macOS system prompt agent (bundle id +`com.apple.UserNotificationCenter`, executable under `/System/Library/CoreServices`); +it is a system alert (`AXWindow`/`AXSystemDialog`, not a sheet or a document +window); its text parses as a microphone, camera or Local Network prompt; the app +it names is one of this run's own processes (the driver's ancestry, the process +macOS holds responsible for the driver, which is what a prompt names and which +survives a detached launch, the app under review, or a trigger child passed with +`--expect`); and exactly one button carries +the expected title. It declines microphone and camera access (a review never needs +them) and allows Local Network. A prompt from any other app, a sheet, or an alert +from another process is never touched. + +`setup-macos-vm` refuses to run outside a virtual machine +(`kern.hv_vmm_present` must be 1) unless `--allow-non-vm` is passed. It marks its +state directory and database as the harness's own, uses a pidfile for each service +it starts, and refuses to reuse a port that is open but not its own. The relay +script refuses to run `DROP SCHEMA` in native-services mode unless +`bin/check-harness-database` confirms the server runs from the harness data +directory and the database carries the harness marker. + ## Run existing journeys ```bash diff --git a/tools/native-review/bin/answer-first-run-prompts b/tools/native-review/bin/answer-first-run-prompts new file mode 100755 index 00000000000..d6c58541752 --- /dev/null +++ b/tools/native-review/bin/answer-first-run-prompts @@ -0,0 +1,74 @@ +#!/usr/bin/env bash +# Answer the one-time macOS privacy prompts a fresh VM shows the first time the +# process that launches a review touches the local network or the microphone. +# Left unanswered they freeze the reviewed app's web view or steal focus from it. +# Best effort: each prompt is triggered by a tiny child process (a Bonjour browse, +# a one-second audio capture) and answered through the same Accessibility-trusted +# driver the harness uses. The answers are remembered per launching process, so +# this only has to succeed once. Exits 0 when a prompt was answered or never +# appeared; nonzero only if the driver could not run. +# +# The driver presses a button only when it can positively identify the window as +# the system's own privacy alert (owned by the system prompt agent, a system +# dialog) that names a process of this run: this script's ancestry, the reviewed +# app, or the trigger it launched here. Anything else is left alone and logged. +# +# Local Network -> Allow +# Microphone -> Don't Allow (a review never records audio) +set -euo pipefail +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +DRIVER="${BUZZ_NATIVE_REVIEW_DRIVER:-$SCRIPT_DIR/swift/.build/release/buzz-native-driver}" +if [[ ! -x "$DRIVER" ]]; then + swift build -c release --package-path "$SCRIPT_DIR/swift" >/dev/null +fi + +# Stop a trigger child. A process blocked on an unanswered privacy prompt can ignore +# SIGTERM, so escalate rather than wait on it forever. +stop_trigger() { + kill "$1" 2>/dev/null || true + for _ in 1 2 3 4 5 6; do kill -0 "$1" 2>/dev/null || break; sleep 0.5; done + kill -9 "$1" 2>/dev/null || true + wait "$1" 2>/dev/null || true +} + +# answer LABEL TRIGGER_NAME COMMAND... +# Starts the trigger, then answers whatever prompt the driver can positively identify +# as this run's own. The log line carries the prompt text that was actually answered, +# which may be an earlier trigger's prompt that was still on screen. +answer() { + local label="$1" trigger_name="$2" + shift 2 + "$@" >/dev/null 2>&1 & + local trigger=$! + local pressed=0 skipped="" failed="" + for _ in $(seq 1 20); do + if ! reply="$("$DRIVER" answer-privacy-prompt --expect "$trigger_name" 2>&1)"; then + failed="$reply" + elif grep -Eq '"answered" ?: ?true' <<<"$reply"; then + pressed=1 + echo "[answer-first-run-prompts] while triggering $label, answered: $reply" + break + elif grep -Eq '"skipped" ?: ?\[ ?"' <<<"$reply"; then + skipped="$reply" + fi + sleep 0.5 + done + stop_trigger "$trigger" + if ((pressed)); then + : + elif [[ -n "$skipped" ]]; then + echo "[answer-first-run-prompts] $label: a window was left alone because it could not be identified as this run's prompt: $skipped" + elif [[ -n "$failed" ]]; then + echo "[answer-first-run-prompts] $label: the driver could not run: $failed" + else + echo "[answer-first-run-prompts] $label: no prompt appeared (already answered, or not needed)" + fi +} + +answer "Local Network" dns-sd dns-sd -B _services._dns-sd._udp local. +if command -v ffmpeg >/dev/null 2>&1; then + answer "Microphone" ffmpeg \ + ffmpeg -hide_banner -loglevel error -f avfoundation -i ":0" -t 1 -f null - +else + echo "[answer-first-run-prompts] Microphone: ffmpeg not installed, skipping" +fi diff --git a/tools/native-review/bin/check-harness-database b/tools/native-review/bin/check-harness-database new file mode 100755 index 00000000000..da981e920de --- /dev/null +++ b/tools/native-review/bin/check-harness-database @@ -0,0 +1,45 @@ +#!/usr/bin/env bash +# Exit 0 only when the Postgres on the harness port is demonstrably the one that +# setup-macos-vm created, so a schema reset can never land on a database that +# belongs to someone else. Checks, all of which must hold: +# * the server's data_directory is the state dir's own postgres directory; +# * the state dir carries the harness marker file; +# * the database carries the harness marker as its comment. +# Fails closed: if any of it cannot be read (wrong password, no server), it +# refuses. Used by setup-macos-vm and scripts/start-isolated-test-relay.sh. +# +# check-harness-database --state-dir DIR [--port 5471] [--db buzz] [--user buzz] +# PSQL overrides the psql binary; PGPASSWORD defaults to the public dev constant. +set -euo pipefail + +MARKER="buzz-native-review-harness" +MARKER_FILE=".buzz-native-review-harness" +STATE_DIR="" PORT=5471 DB=buzz USER_NAME=buzz +while [[ $# -gt 0 ]]; do + case "$1" in + --state-dir) STATE_DIR="$2"; shift 2 ;; + --port) PORT="$2"; shift 2 ;; + --db) DB="$2"; shift 2 ;; + --user) USER_NAME="$2"; shift 2 ;; + *) echo "unknown option: $1" >&2; exit 2 ;; + esac +done +refuse() { printf '[check-harness-database] REFUSING: %s\n' "$*" >&2; exit 1; } +[[ -n "$STATE_DIR" ]] || refuse "no --state-dir given" +[[ -d "$STATE_DIR/postgres" ]] || refuse "$STATE_DIR/postgres does not exist" +[[ -f "$STATE_DIR/$MARKER_FILE" ]] || refuse "$STATE_DIR is not a harness state dir (no $MARKER_FILE)" + +PSQL="${PSQL:-psql}" +export PGPASSWORD="${PGPASSWORD:-buzz_dev}" +query() { "$PSQL" -h 127.0.0.1 -p "$PORT" -U "$USER_NAME" -d postgres -qtAc "$1" 2>/dev/null; } + +data_dir="$(query 'SHOW data_directory')" || refuse "cannot read data_directory from the server on :$PORT" +[[ -n "$data_dir" && -d "$data_dir" ]] || refuse "server on :$PORT reports an unreadable data directory" +actual="$(cd "$data_dir" && pwd -P)" +expected="$(cd "$STATE_DIR/postgres" && pwd -P)" +[[ "$actual" == "$expected" ]] || refuse "server on :$PORT runs from $actual, not the harness data dir $expected" + +comment="$(query "SELECT shobj_description(oid, 'pg_database') FROM pg_database WHERE datname = '$DB'")" \ + || refuse "cannot read database $DB" +[[ "$comment" == "$MARKER" ]] || refuse "database $DB on :$PORT is not marked as the harness database" +echo "[check-harness-database] :$PORT database $DB is the harness database ($expected)" diff --git a/tools/native-review/bin/setup-macos-vm b/tools/native-review/bin/setup-macos-vm new file mode 100755 index 00000000000..b34e509bfbb --- /dev/null +++ b/tools/native-review/bin/setup-macos-vm @@ -0,0 +1,234 @@ +#!/usr/bin/env bash +# One-time (idempotent) setup so `review-native run` works on a macOS VM +# (a headless cloud Mac). +# +# What that machine lacks, and what this script does about it: +# * No Docker (a VM without nested virtualization): runs the +# isolated relay's Postgres, Redis and MinIO natively on the harness ports +# (5471 / 6471 / 9471) and creates the media bucket. +# * No ffmpeg: installs it (video-share.mp4 finalization needs it). +# * A TLS-intercepting proxy that sherpa-onnx-sys's build script (rustls with +# bundled roots) rejects with `UnknownIssuer`: prefetches the archive with +# curl and exports SHERPA_ONNX_ARCHIVE_DIR. The download base defaults to the +# project's GitHub releases; set SHERPA_ONNX_DOWNLOAD_BASE to fetch the same +# path layout through a caching mirror instead. +# * pub.dev blocked (iOS/Flutter only): when PUB_HOSTED_URL is set in the +# environment running this script, it is recorded in env.sh so a later +# review-ios run receives the mirror. No mirror URL is hard-coded here. +# * One-time macOS "Local Network" and "Microphone" prompts for the process that launches +# the run: triggers each and answers it through the Accessibility-trusted native driver +# (best effort, see README). +# +# Safety: it refuses to run outside a virtual machine (kern.hv_vmm_present must be 1) +# unless --allow-non-vm is passed, because it starts services on fixed ports and the +# relay script resets the harness database. Every service it starts is identified by +# a pidfile under the state dir; a port that is already open but not ours is never +# reused, and the schema reset is refused unless Postgres is the one started here +# (see check-harness-database). +# +# Nothing here copies, creates or prints a secret. The Postgres/MinIO +# credentials are the public dev constants already hard-coded in +# docker-compose.harness.yml and review_native.fixture_environment. +# +# Usage: +# tools/native-review/bin/setup-macos-vm [--state-dir DIR] [--no-relay] +# [--skip-prompts] [--allow-non-vm] +# . "$STATE_DIR/env.sh" # then: tools/native-review/bin/review-native run ... +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(cd "$SCRIPT_DIR/../../.." && pwd)" + +STATE_DIR="${BUZZ_NATIVE_REVIEW_STATE_DIR:-$HOME/.buzz-native-review}" +START_RELAY=1 +ANSWER_PROMPTS=1 +ALLOW_NON_VM=0 +while [[ $# -gt 0 ]]; do + case "$1" in + --state-dir) STATE_DIR="$2"; shift 2 ;; + --no-relay) START_RELAY=0; shift ;; + --skip-prompts) ANSWER_PROMPTS=0; shift ;; + --allow-non-vm) ALLOW_NON_VM=1; shift ;; + -h|--help) sed -n '2,/^set -euo/p' "${BASH_SOURCE[0]}" | sed '$d' | sed 's/^# \{0,1\}//'; exit 0 ;; + *) echo "unknown option: $1" >&2; exit 2 ;; + esac +done + +# Harness constants (docker-compose.harness.yml, start-isolated-test-relay.sh). +PG_PORT=5471 +REDIS_PORT=6471 +MINIO_PORT=9471 +MINIO_CONSOLE_PORT=9472 +DEV_USER=buzz_dev +DEV_SECRET=buzz_dev_secret +DB_USER=buzz +DB_PASS=buzz_dev +DB_NAME=buzz +BUCKET=buzz-media +# dl.min.io may be unreachable from a locked-down VM; build a pinned upstream commit instead. +MINIO_REF="${MINIO_REF:-7aac2a2c5b7c}" + +log() { printf '[setup-macos-vm] %s\n' "$*"; } +die() { printf '[setup-macos-vm] ERROR: %s\n' "$*" >&2; exit 1; } + +[[ "$(uname -s)" == "Darwin" && "$(uname -m)" == "arm64" ]] || die "this script is for Apple-silicon macOS" +# Refuse outside a VM before touching anything. kern.hv_vmm_present is 1 under +# Apple's Virtualization framework (Tart, ec2-macos workstations); hw.model is +# VirtualMac2,1 there too. +vmm_present="$(sysctl -n kern.hv_vmm_present 2>/dev/null || echo 0)" +if [[ "$vmm_present" != "1" ]]; then + ((ALLOW_NON_VM)) || die "refusing to run: this does not look like a virtual machine (kern.hv_vmm_present=$vmm_present, hw.model=$(sysctl -n hw.model 2>/dev/null || echo unknown)). It starts services on fixed local ports and resets a database; pass --allow-non-vm if you really mean to run it here." + log "WARNING: not a VM (kern.hv_vmm_present=$vmm_present); continuing because --allow-non-vm was given" +fi +command -v brew >/dev/null || die "Homebrew is required" +command -v go >/dev/null || die "Go is required to build MinIO (brew install go)" +mkdir -p "$STATE_DIR"/{logs,sherpa} "$HOME/.local/bin" +# Marks this directory (and everything under it) as the harness's own. +printf 'buzz-native-review-harness\n' > "$STATE_DIR/.buzz-native-review-harness" +BREW_PREFIX="$(brew --prefix)" + +port_open() { (exec 3<>"/dev/tcp/127.0.0.1/$1") 2>/dev/null; } +listener_pids() { lsof -nP -iTCP:"$1" -sTCP:LISTEN -t 2>/dev/null | sort -u | tr '\n' ' ' | sed 's/ $//'; } +# An open port is ours only when its sole listener is the pid recorded in the pidfile +# this script's own service wrote. Anything else is someone else's: never use it. +require_ours() { + local name="$1" port="$2" pidfile="$3" want + want="$(head -1 "$pidfile" 2>/dev/null || true)" + if [[ -z "$want" || "$(listener_pids "$port")" != "$want" ]]; then + die "$name port :$port is already in use by something this script did not start (listener pid: $(listener_pids "$port")); refusing to use it. Stop it or free the port." + fi +} +wait_port() { + local name="$1" port="$2" + for _ in $(seq 1 60); do port_open "$port" && return 0; sleep 1; done + die "$name did not open :$port (see $STATE_DIR/logs)" +} + +# -- 1. brew packages ------------------------------------------------------- +need=() +for formula in postgresql@17 redis ffmpeg tmux; do + brew list --formula "$formula" >/dev/null 2>&1 || need+=("$formula") +done +if ((${#need[@]})); then + log "brew install ${need[*]}" + HOMEBREW_NO_AUTO_UPDATE=1 brew install "${need[@]}" +fi +PG_BIN="$BREW_PREFIX/opt/postgresql@17/bin" +REDIS_SERVER="$BREW_PREFIX/opt/redis/bin/redis-server" +export PATH="$PG_BIN:$HOME/.local/bin:$PATH" + +# -- 2. MinIO --------------------------------------------------------------- +MINIO_BIN="$HOME/.local/bin/minio" +if [[ ! -x "$MINIO_BIN" ]]; then + log "go install github.com/minio/minio@$MINIO_REF" + GOBIN="$HOME/.local/bin" go install "github.com/minio/minio@$MINIO_REF" +fi + +# -- 3. Postgres on :5471 --------------------------------------------------- +PGDATA="$STATE_DIR/postgres" +if [[ ! -f "$PGDATA/PG_VERSION" ]]; then + log "initdb $PGDATA" + pwfile="$(mktemp)"; printf '%s\n' "$DB_PASS" > "$pwfile" + "$PG_BIN/initdb" -D "$PGDATA" -U "$DB_USER" --auth=scram-sha-256 --pwfile="$pwfile" -E UTF8 >/dev/null + rm -f "$pwfile" +fi +if port_open "$PG_PORT"; then + require_ours postgres "$PG_PORT" "$PGDATA/postmaster.pid" +else + log "starting postgres on :$PG_PORT" + "$PG_BIN/pg_ctl" -D "$PGDATA" -l "$STATE_DIR/logs/postgres.log" \ + -o "-p $PG_PORT -c listen_addresses=127.0.0.1 -c unix_socket_directories=$STATE_DIR" -w start >/dev/null +fi +export PGPASSWORD="$DB_PASS" +if ! psql -h 127.0.0.1 -p "$PG_PORT" -U "$DB_USER" -d postgres -qtAc \ + "SELECT 1 FROM pg_database WHERE datname='$DB_NAME'" | grep -q 1; then + log "createdb $DB_NAME" + createdb -h 127.0.0.1 -p "$PG_PORT" -U "$DB_USER" "$DB_NAME" +fi +# The cluster is the one initdb'd under the state dir above, so this database is ours: +# mark it, then prove it. The relay script runs the same check before it resets the schema. +psql -h 127.0.0.1 -p "$PG_PORT" -U "$DB_USER" -d postgres -qc \ + "COMMENT ON DATABASE $DB_NAME IS 'buzz-native-review-harness'" +"$SCRIPT_DIR/check-harness-database" --state-dir "$STATE_DIR" --port "$PG_PORT" --db "$DB_NAME" --user "$DB_USER" \ + || die "Postgres on :$PG_PORT is not the harness database" + +# -- 4. Redis on :6471 ------------------------------------------------------ +if port_open "$REDIS_PORT"; then + require_ours redis "$REDIS_PORT" "$STATE_DIR/redis/redis.pid" +else + log "starting redis on :$REDIS_PORT" + mkdir -p "$STATE_DIR/redis" + "$REDIS_SERVER" --port "$REDIS_PORT" --bind 127.0.0.1 --dir "$STATE_DIR/redis" \ + --pidfile "$STATE_DIR/redis/redis.pid" \ + --save "" --daemonize yes --logfile "$STATE_DIR/logs/redis.log" >/dev/null + wait_port redis "$REDIS_PORT" +fi + +# -- 5. MinIO on :9471 + bucket --------------------------------------------- +if port_open "$MINIO_PORT"; then + require_ours minio "$MINIO_PORT" "$STATE_DIR/minio.pid" +else + log "starting minio on :$MINIO_PORT" + mkdir -p "$STATE_DIR/minio" + MINIO_ROOT_USER="$DEV_USER" MINIO_ROOT_PASSWORD="$DEV_SECRET" \ + nohup "$MINIO_BIN" server "$STATE_DIR/minio" --address "127.0.0.1:$MINIO_PORT" \ + --console-address "127.0.0.1:$MINIO_CONSOLE_PORT" \ + > "$STATE_DIR/logs/minio.log" 2>&1 < /dev/null & + echo $! > "$STATE_DIR/minio.pid" + wait_port minio "$MINIO_PORT" +fi +# Create the media bucket with a SigV4-signed PUT (no `mc` needed). 200 = created, +# 409 = already ours. +empty_sha="e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" +status="$(curl -s -o /dev/null -w '%{http_code}' -X PUT \ + --aws-sigv4 "aws:amz:us-east-1:s3" --user "$DEV_USER:$DEV_SECRET" \ + -H "x-amz-content-sha256: $empty_sha" "http://127.0.0.1:$MINIO_PORT/$BUCKET")" +case "$status" in 200|409) log "bucket $BUCKET ready (HTTP $status)" ;; *) die "bucket create failed (HTTP $status)" ;; esac + +# -- 6. sherpa-onnx archive (rustls cannot verify a TLS-intercepting proxy) -------- +sherpa_version="$(awk '/^name = "sherpa-onnx-sys"$/ {getline; gsub(/[^0-9.]/, "", $0); print; exit}' "$REPO_ROOT/Cargo.lock")" +[[ -n "$sherpa_version" ]] || die "could not read sherpa-onnx-sys version from Cargo.lock" +sherpa_archive="sherpa-onnx-v${sherpa_version}-osx-arm64-static-lib.tar.bz2" +if [[ ! -s "$STATE_DIR/sherpa/$sherpa_archive" ]] || ! bzip2 -t "$STATE_DIR/sherpa/$sherpa_archive" 2>/dev/null; then + log "downloading $sherpa_archive" + sherpa_url="${SHERPA_ONNX_DOWNLOAD_BASE:-https://github.com/k2-fsa/sherpa-onnx/releases/download}/v${sherpa_version}/${sherpa_archive}" + log "curl -fsSL --retry 3 $sherpa_url" + sherpa_status="$(curl -fsSL --retry 3 -o "$STATE_DIR/sherpa/$sherpa_archive.part" -w '%{http_code}' "$sherpa_url")" \ + || die "could not download $sherpa_url" + log "HTTP $sherpa_status, $(wc -c < "$STATE_DIR/sherpa/$sherpa_archive.part" | tr -d ' ') bytes" + bzip2 -t "$STATE_DIR/sherpa/$sherpa_archive.part" || die "sherpa archive is not valid bzip2" + mv "$STATE_DIR/sherpa/$sherpa_archive.part" "$STATE_DIR/sherpa/$sherpa_archive" +fi + +# -- 7. environment file ---------------------------------------------------- +cat > "$STATE_DIR/env.sh" <> "$STATE_DIR/env.sh" +fi + +# -- 8. isolated relay (native services, no Docker) ------------------------- +if ((START_RELAY)); then + if port_open 3030; then + # Only the relay this script's relay script started (a tmux session of that name) is ours. + tmux has-session -t dawn-relay 2>/dev/null \ + || die "port :3030 is in use by something that is not the harness relay; refusing to use it" + log "relay already listening on :3030" + else + log "starting isolated relay (first build takes several minutes)" + # shellcheck disable=SC1091 + ( cd "$REPO_ROOT" && . bin/activate-hermit >/dev/null \ + && BUZZ_HARNESS_NATIVE_SERVICES=1 BUZZ_HARNESS_STATE_DIR="$STATE_DIR" RELAY_LOG="$STATE_DIR/logs/relay.log" \ + SHERPA_ONNX_ARCHIVE_DIR="$STATE_DIR/sherpa" ./scripts/start-isolated-test-relay.sh ) + fi +fi + +# -- 9. macOS first-run privacy prompts -------------------------------------- +if ((ANSWER_PROMPTS)); then + "$SCRIPT_DIR/answer-first-run-prompts" || log "first-run prompts not answered automatically; see README" +fi + +log "done. Next: . \"$STATE_DIR/env.sh\" && tools/native-review/bin/review-native doctor --require-permissions" diff --git a/tools/native-review/ios_review.py b/tools/native-review/ios_review.py index 0f2c86c1302..2d09b6b65cf 100755 --- a/tools/native-review/ios_review.py +++ b/tools/native-review/ios_review.py @@ -37,6 +37,8 @@ SUBPROCESS_ENV_ALLOWLIST = { "PATH", "HOME", "TMPDIR", "LANG", "LC_ALL", "SHELL", "USER", "LOGNAME", "TERM", "__CF_USER_TEXT_ENCODING", "DEVELOPER_DIR", + # Package-mirror override for hosts that cannot reach pub.dev directly. + "PUB_HOSTED_URL", } diff --git a/tools/native-review/review_native.py b/tools/native-review/review_native.py index 2c6f70e22b4..20e7d7246dc 100755 --- a/tools/native-review/review_native.py +++ b/tools/native-review/review_native.py @@ -6,6 +6,7 @@ import dataclasses import datetime as dt import hashlib +import hmac import http.server import json import math @@ -329,8 +330,17 @@ def provenance() -> dict[str, Any]: } +# Host-build settings the Rust build needs on machines behind a TLS-intercepting +# proxy (sherpa-onnx-sys's build script cannot verify it and reads a prefetched +# archive instead). They reach host tooling (include_home=True) but never the +# reviewed app, and secret-shaped names are still dropped. +HOST_BUILD_PASSTHROUGH = {"SHERPA_ONNX_ARCHIVE_DIR", "SHERPA_ONNX_LIB_DIR"} + + def scrubbed_environment(*, include_home: bool = False) -> dict[str, str]: keep = {"PATH", "TMPDIR", "LANG", "LC_ALL", "SHELL", "USER", "LOGNAME", "TERM", "__CF_USER_TEXT_ENCODING"} + if include_home: + keep |= HOST_BUILD_PASSTHROUGH env = {key: value for key, value in os.environ.items() if key in keep and not SECRET_NAME.search(key)} env["HOME"] = os.environ.get("HOME", "") if include_home else "" # isolated per run unless tooling needs host caches return env @@ -434,7 +444,7 @@ def close(self) -> None: def doctor(require_permissions: bool = False) -> dict[str, Any]: checks: list[dict[str, Any]] = [] checks.append({"name": "platform", "ok": sys.platform == "darwin", "detail": sys.platform}) - for command in ("swift", "xcrun", "git"): + for command in ("swift", "xcrun", "git", "ffmpeg"): path = shutil.which(command) checks.append({"name": command, "ok": path is not None, "detail": path or "not found"}) checks.append({"name": "repository", "ok": (ROOT / "desktop/src-tauri/tauri.conf.json").is_file(), "detail": str(ROOT)}) @@ -445,7 +455,7 @@ def doctor(require_permissions: bool = False) -> dict[str, Any]: checks.extend(native.get("checks", [])) except (HarnessError, subprocess.SubprocessError, json.JSONDecodeError) as exc: checks.append({"name": "native-driver", "ok": False, "detail": str(exc)}) - hard_names = {"platform", "swift", "xcrun", "git", "repository", "native-driver-build"} + hard_names = {"platform", "swift", "xcrun", "git", "ffmpeg", "repository", "native-driver-build"} failed = [c for c in checks if not c.get("ok") and (require_permissions or c.get("name") in hard_names)] result = {"ok": not failed, "checks": checks} print(json.dumps(result, indent=2)) @@ -540,8 +550,14 @@ def do_OPTIONS(self) -> None: # noqa: N802 - BaseHTTPRequestHandler API self.end_headers() def do_POST(self) -> None: # noqa: N802 - BaseHTTPRequestHandler API - if self.path != "/snapshot" or self.headers.get("X-Buzz-Native-Review-Token") != token: - self.send_response(404 if self.path != "/snapshot" else 401) + target = urllib.parse.urlsplit(self.path) + # The page publishes with navigator.sendBeacon, which cannot set request + # headers, so the token travels in the probe URL's query; the header is + # still accepted for other clients. + supplied = (urllib.parse.parse_qs(target.query).get("token") or + [self.headers.get("X-Buzz-Native-Review-Token") or ""])[0] + if target.path != "/snapshot" or not hmac.compare_digest(supplied.encode(), token.encode()): + self.send_response(404 if target.path != "/snapshot" else 401) self.end_headers() return raw_length = self.headers.get("Content-Length") @@ -572,7 +588,8 @@ def log_message(self, _format: str, *_args: Any) -> None: server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) server.daemon_threads = True threading.Thread(target=server.serve_forever, daemon=True).start() - return server, f"http://127.0.0.1:{server.server_port}/snapshot" + query = urllib.parse.urlencode({"token": token}) + return server, f"http://127.0.0.1:{server.server_port}/snapshot?{query}" def build_native_review_app(isolation: dict[str, str]) -> pathlib.Path: @@ -672,6 +689,50 @@ def wait_for_visible_window(driver: Driver, process: subprocess.Popen[str], time raise HarnessError(f"timed out after {timeout_seconds:g}s waiting for visible native window: {detail}") +def wait_for_interactive_window(driver: Driver, process: subprocess.Popen[str], + timeout_seconds: float = 30) -> dict[str, Any]: + """Show the window, move it onto the main display, and wait for WebKit's AX tree. + + A fresh macOS VM can open the app on a secondary display whose WKWebView exposes + no accessibility children, so locators would never match. Placement is idempotent + (a window already on the main display is left alone). + """ + status = wait_for_visible_window(driver, process, timeout_seconds) + deadline = time.monotonic() + timeout_seconds + while True: + # A first-run macOS privacy prompt freezes the web view until answered. + driver.request("answer_privacy_prompt") + # The accessibility window can lag the compositor's by a moment. + try: + placement = driver.request("place_window") + if not placement.get("verified", True): + raise HarnessError( + f"window placement was not verified: before {placement.get('before')}, " + f"after {placement.get('after')}") + break + except HarnessError as error: + if "no accessibility window" not in str(error): + raise + if process.poll() is not None: + raise HarnessError("Tauri exited while waiting for its accessibility window") from error + if time.monotonic() >= deadline: + raise + time.sleep(0.1) + while True: + driver.request("answer_privacy_prompt") + if driver.request("web_ready").get("ready"): + break + if process.poll() is not None: + raise HarnessError("Tauri exited while waiting for web content accessibility") + if time.monotonic() >= deadline: + raise HarnessError( + f"timed out after {timeout_seconds:g}s waiting for web content accessibility " + f"(window status: {status})") + time.sleep(0.1) + placed = driver.request("window_status") + return {**placed, "moved": bool(placement.get("moved")), "placement": placement} + + def locate_required(driver: Driver, locators: list[dict[str, str]], timeout_ms: int) -> dict[str, Any]: """Wait for a semantic target to materialize, then return the locator used.""" deadline = time.monotonic() + timeout_ms / 1000 @@ -792,7 +853,7 @@ def run_journey(path: pathlib.Path, relay_url: str, output_root: pathlib.Path, driver = Driver(build_driver(), app_pid, run_dir / "state" / "semantic.json") sampler = ProcessSampler(app_pid) sampler.start() - receipt["provenance"]["initial_window"] = wait_for_visible_window(driver, process) + receipt["provenance"]["initial_window"] = wait_for_interactive_window(driver, process) if journey["record"]["video"] == "window": video = run_dir / "video.mp4" driver.request("record_start", path=str(video)) diff --git a/tools/native-review/swift/Sources/BuzzNativeDriver/main.swift b/tools/native-review/swift/Sources/BuzzNativeDriver/main.swift index 6a4ae5ec837..1ea11bc9d1b 100644 --- a/tools/native-review/swift/Sources/BuzzNativeDriver/main.swift +++ b/tools/native-review/swift/Sources/BuzzNativeDriver/main.swift @@ -3,6 +3,7 @@ import ApplicationServices import AVFoundation import CoreGraphics import Foundation +import Darwin import BuzzNativeDriverSupport struct Locator: Codable { @@ -192,8 +193,10 @@ func describe(_ element: AXUIElement, locator: Locator) -> ElementDescription { focused: boolAttribute(element, kAXFocusedAttribute), frame: frameAttribute(element)) } -func semanticContentBounds(pid: pid_t) -> CGRect? { +func semanticContentBounds(pid: pid_t, messagingTimeout: Float? = nil) -> CGRect? { let app = AXUIElementCreateApplication(pid) + // An app frozen behind a privacy prompt would otherwise stall every query. + if let messagingTimeout { AXUIElementSetMessagingTimeout(app, messagingTimeout) } enableWebViewAccessibility(app) let webArea = find(accessibilityRoots(app: app, pid: pid), locator: Locator(id: nil, role: "web-area", name: nil)) guard let frame = webArea.flatMap(frameAttribute) else { return nil } @@ -286,6 +289,60 @@ func windowStatus(pid: pid_t) -> [String: Any] { } } +/// Move the window the harness reports (`windowInfo`, the largest on-screen one) +/// onto the main display when it opened elsewhere (a fresh VM can have a second +/// display left of the main one, where WKWebView exposes no accessibility tree). +/// The accessibility window moved is the one whose frame matches the reported +/// window, never "the first"; the result is read back from the window server and +/// the call fails unless the reported window ends up wholly on the main display. +func placeWindowOnMainDisplay(app: AXUIElement, pid: pid_t) throws -> [String: Any] { + let (windowID, reported) = try windowInfo(pid: pid) + let windows = (attribute(app, kAXWindowsAttribute) as? [AXUIElement]) ?? [] + let frames = windows.map { window -> CGRect in + guard let frame = frameAttribute(window) else { return .null } + return CGRect(x: frame.x, y: frame.y, width: frame.width, height: frame.height) + } + guard let index = matchingWindowIndex(frames: frames, reported: reported) else { + throw DriverError.message("no accessibility window to place matches the reported window \(windowID) at \(reported)") + } + let window = windows[index] + let mainDisplay = CGDisplayBounds(CGMainDisplayID()) + var moved = false + if let target = placementOnMainDisplay(window: reported, mainDisplay: mainDisplay) { + var size = target.size + var origin = target.origin + guard let sizeValue = AXValueCreate(.cgSize, &size), let originValue = AXValueCreate(.cgPoint, &origin) else { + throw DriverError.message("could not encode window placement") + } + // Size first so the window cannot be clamped against the display it is leaving. + guard AXUIElementSetAttributeValue(window, kAXSizeAttribute as CFString, sizeValue) == .success, + AXUIElementSetAttributeValue(window, kAXPositionAttribute as CFString, originValue) == .success else { + throw DriverError.message("accessibility refused to move the window; grant Accessibility to the invoking process") + } + moved = true + } + // Read it back from the window server, the same source the harness reports from. + var after = reported + var verified = false + for _ in 0..<20 { + if let (_, current) = try? windowInfo(pid: pid) { after = current } + verified = windowIsOnMainDisplay(after, mainDisplay: mainDisplay) + if verified { break } + Thread.sleep(forTimeInterval: 0.1) + } + guard verified else { + throw DriverError.message("window \(windowID) is at \(after) after placement, not wholly on the main display \(mainDisplay)") + } + func rect(_ value: CGRect) -> [String: Double] { + ["x": value.minX, "y": value.minY, "width": value.width, "height": value.height] + } + return [ + "ok": true, "moved": moved, "verified": true, "window_id": windowID, + "before": rect(reported), "after": rect(after), "main_display": rect(mainDisplay), + "accessibility_windows": windows.count, + ] +} + func captureWindow(pid: pid_t, path: String) throws { let (windowID, bounds) = try windowInfo(pid: pid) guard let image = CGWindowListCreateImage(bounds, .optionIncludingWindow, windowID, [.boundsIgnoreFraming, .bestResolution]) else { @@ -497,6 +554,8 @@ func ensureTargetFrontmost(pid: pid_t) async throws { throw DriverError.message("target app is no longer running") } if NSWorkspace.shared.frontmostApplication?.processIdentifier != pid { + // A first-run macOS privacy prompt keeps focus until answered. + _ = answerPrivacyPrompt(target: pid) running.activate(options: [.activateIgnoringOtherApps]) } let deadline = ContinuousClock.now.advanced(by: .seconds(2)) @@ -550,12 +609,132 @@ func postText(_ text: String, pid: pid_t) throws { } } +/// Names a privacy prompt may legitimately use for this review: the processes in +/// the driver's own ancestry (macOS names the responsible process, such as the +/// agent that launched the run, or an interpreter), the reviewed app, and any +/// `extra` names the caller launched on purpose (a trigger child). +/// The process macOS holds responsible for `pid`: the one a privacy prompt names. It is +/// fixed when the process is spawned, so unlike the parent chain it survives the +/// launcher exiting (a review started detached, for example under nohup). The symbol is +/// private to libSystem, so it is looked up at run time and its absence only narrows +/// what counts as this review's own process. +func responsiblePid(for pid: pid_t) -> pid_t? { + typealias Function = @convention(c) (pid_t) -> pid_t + guard let symbol = dlsym(UnsafeMutableRawPointer(bitPattern: -2), "responsibility_get_pid_responsible_for_pid") else { return nil } + let responsible = unsafeBitCast(symbol, to: Function.self)(pid) + return responsible > 1 && responsible != pid ? responsible : nil +} + +func reviewProcessNames(target: pid_t?, extra: [String]) -> [String] { + var names = Set(extra) + func add(pid: pid_t) { + var path = [CChar](repeating: 0, count: 4096) + if proc_pidpath(pid, &path, UInt32(path.count)) > 0 { + let url = URL(fileURLWithPath: String(cString: path)) + names.insert(url.lastPathComponent) + for component in url.pathComponents where component.hasSuffix(".app") { + names.insert(String(component.dropLast(4))) + } + } + var name = [CChar](repeating: 0, count: 256) + if proc_name(pid, &name, UInt32(name.count)) > 0 { names.insert(String(cString: name)) } + if let app = NSRunningApplication(processIdentifier: pid) { + if let localized = app.localizedName { names.insert(localized) } + } + } + var pid = getpid() + var hops = 0 + while pid > 1 && hops < 32 { + add(pid: pid) + var info = proc_bsdinfo() + guard proc_pidinfo(pid, PROC_PIDTBSDINFO, 0, &info, Int32(MemoryLayout.size)) > 0 else { break } + pid = pid_t(info.pbi_ppid) + hops += 1 + } + if let responsible = responsiblePid(for: getpid()) { add(pid: responsible) } + if let target { add(pid: target) } + names.remove("") + return Array(names) +} + +/// Every on-screen window owned by the system prompt agent, as the decision +/// function sees it, with its accessibility element. Scans only that owner, never +/// the reviewed app or anyone else. +func systemPromptWindows() -> [(PromptWindow, AXUIElement)] { + let owners = Set(((CGWindowListCopyWindowInfo([.optionOnScreenOnly], kCGNullWindowID) as? [[String: Any]]) ?? []) + .compactMap { $0[kCGWindowOwnerPID as String] as? Int32 }) + var windows: [(PromptWindow, AXUIElement)] = [] + for pid in owners where pid != getpid() { + guard let running = NSRunningApplication(processIdentifier: pid), + running.bundleIdentifier == systemPromptBundleID else { continue } + let app = AXUIElementCreateApplication(pid) + for window in (attribute(app, kAXWindowsAttribute) as? [AXUIElement]) ?? [] { + windows.append((promptWindow(window, owner: running), window)) + } + } + return windows +} + +func promptWindow(_ window: AXUIElement, owner: NSRunningApplication) -> PromptWindow { + var queue = [window] + var texts: [String] = [] + var buttons: [String] = [] + var visited = 0 + while !queue.isEmpty && visited < 200 { + let current = queue.removeFirst() + visited += 1 + if normalizedRole(elementRole(current)) == "button" { + if let name = elementName(current) { buttons.append(name) } + } else if let text = stringAttribute(current, [kAXValueAttribute]) { + texts.append(text) + } + queue.append(contentsOf: children(current)) + } + return PromptWindow( + ownerBundleID: owner.bundleIdentifier, + ownerExecutablePath: owner.executableURL?.path, + role: stringAttribute(window, [kAXRoleAttribute]), + subrole: stringAttribute(window, [kAXSubroleAttribute]), + texts: texts, + buttons: buttons) +} + +/// Answer a pending first-run macOS privacy prompt, but only one that is positively +/// the system's own alert naming a process of this review (see +/// `decidePrivacyPrompt`). Returns what was done; a skipped window is reported with +/// its reason and nothing is pressed. +func answerPrivacyPrompt(target: pid_t? = nil, extraNames: [String] = []) -> [String: Any] { + let expected = reviewProcessNames(target: target, extra: extraNames) + var skipped: [String] = [] + for (candidate, element) in systemPromptWindows() { + switch decidePrivacyPrompt(candidate, expectedApps: expected) { + case .skip(let reason): + skipped.append(reason) + case .press(let title): + var queue = [element] + var visited = 0 + while !queue.isEmpty && visited < 200 { + let current = queue.removeFirst() + visited += 1 + if normalizedRole(elementRole(current)) == "button", let name = elementName(current), + normalizedButtonTitle(name) == normalizedButtonTitle(title) { + let pressed = AXUIElementPerformAction(current, kAXPressAction as CFString) == .success + return ["ok": true, "answered": pressed, "button": title, "prompt": candidate.texts.first ?? ""] + } + queue.append(contentsOf: children(current)) + } + skipped.append("could not find the \(title) button to press") + } + } + return ["ok": true, "answered": false, "skipped": skipped] +} + @main struct BuzzNativeDriver { static func main() async { do { let arguments = Array(CommandLine.arguments.dropFirst()) - guard let command = arguments.first else { throw DriverError.message("usage: buzz-native-driver doctor | serve --pid PID") } + guard let command = arguments.first else { throw DriverError.message("usage: buzz-native-driver doctor | serve --pid PID | answer-privacy-prompt [--expect NAME]...") } if command == "doctor" { let accessibility = AXIsProcessTrusted() let screen = CGPreflightScreenCaptureAccess() @@ -567,6 +746,22 @@ struct BuzzNativeDriver { ]]) return } + if command == "answer-privacy-prompt" { + // answer-privacy-prompt [--expect NAME]...: NAME is a process the caller launched + // on purpose to raise the prompt (for example dns-sd or ffmpeg). + var extra: [String] = [] + var rest = Array(arguments.dropFirst()) + while !rest.isEmpty { + guard rest.count >= 2, rest[0] == "--expect" else { + throw DriverError.message("usage: buzz-native-driver answer-privacy-prompt [--expect NAME]...") + } + extra.append(rest[1]) + rest.removeFirst(2) + } + guard AXIsProcessTrusted() else { throw DriverError.message("Accessibility permission is not granted") } + response(answerPrivacyPrompt(extraNames: extra)) + return + } guard command == "serve", (arguments.count == 3 || arguments.count == 5), arguments[1] == "--pid", let pid = pid_t(arguments[2]) else { throw DriverError.message("usage: buzz-native-driver serve --pid PID [--semantic-snapshot PATH]") } @@ -696,6 +891,12 @@ struct BuzzNativeDriver { } else { throw DriverError.message("unsupported action: \(type)") } } response(["ok": true]) + case "place_window": + response(try placeWindowOnMainDisplay(app: app, pid: pid)) + case "answer_privacy_prompt": + response(answerPrivacyPrompt(target: pid)) + case "web_ready": + response(["ok": true, "ready": semanticContentBounds(pid: pid, messagingTimeout: 1.5) != nil]) case "window_status": response(windowStatus(pid: pid)) case "snapshot": diff --git a/tools/native-review/swift/Sources/BuzzNativeDriverSupport/DriverSupport.swift b/tools/native-review/swift/Sources/BuzzNativeDriverSupport/DriverSupport.swift index 2697e678f11..b820cb906e8 100644 --- a/tools/native-review/swift/Sources/BuzzNativeDriverSupport/DriverSupport.swift +++ b/tools/native-review/swift/Sources/BuzzNativeDriverSupport/DriverSupport.swift @@ -41,3 +41,135 @@ public func makeScrollEvent(deltaY: Int32, targetFrame: CGRect) -> CGEvent? { event.location = CGPoint(x: targetFrame.midX, y: targetFrame.midY) return event } + +/// Where to put a window so it sits wholly on the main display, centered, below +/// the menu bar. Returns nil when it is already there. A window larger than the +/// usable area is shrunk to fit. +public func placementOnMainDisplay(window: CGRect, mainDisplay: CGRect, menuBarHeight: CGFloat = 30) -> CGRect? { + let usable = CGRect(x: mainDisplay.minX, y: mainDisplay.minY + menuBarHeight, + width: mainDisplay.width, height: mainDisplay.height - menuBarHeight) + if usable.contains(window) { return nil } + let size = CGSize(width: min(window.width, usable.width), height: min(window.height, usable.height)) + return CGRect(x: usable.midX - size.width / 2, y: usable.midY - size.height / 2, + width: size.width, height: size.height) +} + +public enum PrivacyPromptKind: Equatable, Sendable { case microphone, camera, localNetwork } + +public struct PrivacyPrompt: Equatable, Sendable { + public var kind: PrivacyPromptKind + public var appName: String + public init(kind: PrivacyPromptKind, appName: String) { + self.kind = kind + self.appName = appName + } +} + +/// What the driver can see of a candidate prompt window: who owns it, what kind +/// of accessibility window it is, and the text and buttons inside it. +public struct PromptWindow: Equatable, Sendable { + public var ownerBundleID: String? + public var ownerExecutablePath: String? + public var role: String? + public var subrole: String? + public var texts: [String] + public var buttons: [String] + public init(ownerBundleID: String?, ownerExecutablePath: String?, role: String?, + subrole: String?, texts: [String], buttons: [String]) { + self.ownerBundleID = ownerBundleID + self.ownerExecutablePath = ownerExecutablePath + self.role = role + self.subrole = subrole + self.texts = texts + self.buttons = buttons + } +} + +public enum PromptDecision: Equatable, Sendable { + case press(String) + case skip(String) +} + +/// The process macOS draws its privacy (TCC) prompts with. Observed on a macOS 26 +/// VM: the alert is an `AXWindow` with subrole `AXSystemDialog`, owned by this +/// bundle, running from the sealed system volume. +public let systemPromptBundleID = "com.apple.UserNotificationCenter" +public let systemPromptExecutablePrefix = "/System/Library/CoreServices/UserNotificationCenter.app/" + +/// Read the kind of prompt and the app it names (the first quoted name) from the +/// alert's text. nil when the text is not a known privacy prompt. +public func parsePrivacyPrompt(texts: [String]) -> PrivacyPrompt? { + let text = texts.joined(separator: " ") + let lowered = text.lowercased() + let kind: PrivacyPromptKind + if lowered.contains("would like to access the microphone") { + kind = .microphone + } else if lowered.contains("would like to access the camera") { + kind = .camera + } else if lowered.contains("to find devices on local networks") { + kind = .localNetwork + } else { + return nil + } + let quotes: Set = ["\u{201C}", "\u{201D}", "\""] + let characters = Array(text) + guard let open = characters.firstIndex(where: { quotes.contains($0) }), + let close = characters[(open + 1)...].firstIndex(where: { quotes.contains($0) }) else { return nil } + let name = String(characters[(open + 1).. PromptDecision { + guard window.ownerBundleID == systemPromptBundleID else { + return .skip("window is not owned by the system prompt agent (owner: \(window.ownerBundleID ?? "unknown"))") + } + guard let executable = window.ownerExecutablePath, + URL(fileURLWithPath: executable).standardizedFileURL.path.hasPrefix(systemPromptExecutablePrefix) else { + return .skip("window owner does not run from the system prompt agent's path") + } + guard window.role == "AXWindow", window.subrole == "AXSystemDialog" else { + return .skip("window is not a system dialog (role: \(window.role ?? "none"), subrole: \(window.subrole ?? "none"))") + } + guard let prompt = parsePrivacyPrompt(texts: window.texts) else { + return .skip("window text is not a known privacy prompt") + } + let names = Set(expectedApps.map { $0.lowercased() }) + guard names.contains(prompt.appName.lowercased()) else { + return .skip("prompt names \"\(prompt.appName)\", which is not a process of this review") + } + let wanted = prompt.kind == .localNetwork ? "Allow" : "Don't Allow" + let matching = window.buttons.filter { normalizedButtonTitle($0) == normalizedButtonTitle(wanted) } + guard matching.count == 1 else { + return .skip("expected exactly one \"\(wanted)\" button, found \(matching.count)") + } + return .press(wanted) +} + +/// The index of the accessibility window whose frame is the window the harness +/// reports (within `tolerance` points), or nil. Never falls back to another window. +public func matchingWindowIndex(frames: [CGRect], reported: CGRect, tolerance: CGFloat = 2) -> Int? { + frames.firstIndex { frame in + abs(frame.minX - reported.minX) <= tolerance && abs(frame.minY - reported.minY) <= tolerance + && abs(frame.width - reported.width) <= tolerance && abs(frame.height - reported.height) <= tolerance + } +} + +/// True when the window sits wholly on the main display below the menu bar. +public func windowIsOnMainDisplay(_ window: CGRect, mainDisplay: CGRect) -> Bool { + placementOnMainDisplay(window: window, mainDisplay: mainDisplay) == nil +} + +/// A button title with typographic apostrophes folded to plain ones, so +/// "Don\u{2019}t Allow" (what macOS draws) matches "Don't Allow" (what people type). +public func normalizedButtonTitle(_ title: String) -> String { + title.replacingOccurrences(of: "\u{2019}", with: "'") +} diff --git a/tools/native-review/swift/Tests/BuzzNativeDriverSupportTests/DriverSupportTests.swift b/tools/native-review/swift/Tests/BuzzNativeDriverSupportTests/DriverSupportTests.swift index b69700a19be..4743b6dcc68 100644 --- a/tools/native-review/swift/Tests/BuzzNativeDriverSupportTests/DriverSupportTests.swift +++ b/tools/native-review/swift/Tests/BuzzNativeDriverSupportTests/DriverSupportTests.swift @@ -31,3 +31,136 @@ import Testing #expect(event.location == CGPoint(x: 100, y: 110)) } + +@Test func windowOnSecondaryDisplayMovesToCenterOfMainDisplay() throws { + let main = CGRect(x: 0, y: 0, width: 1440, height: 900) + let window = CGRect(x: -1016, y: 36, width: 1008, height: 726) + + let target = try #require(placementOnMainDisplay(window: window, mainDisplay: main)) + + #expect(target.size == window.size) + #expect(main.contains(target)) + #expect(target.midX == main.midX) +} + +@Test func windowAlreadyOnMainDisplayIsLeftAlone() { + let main = CGRect(x: 0, y: 0, width: 1440, height: 900) + + #expect(placementOnMainDisplay(window: CGRect(x: 100, y: 80, width: 1008, height: 726), mainDisplay: main) == nil) +} + +@Test func windowUnderTheMenuBarOrPartlyOffscreenIsMoved() { + let main = CGRect(x: 0, y: 0, width: 1440, height: 900) + + #expect(placementOnMainDisplay(window: CGRect(x: 100, y: 0, width: 800, height: 600), mainDisplay: main) != nil) + #expect(placementOnMainDisplay(window: CGRect(x: 1000, y: 100, width: 800, height: 600), mainDisplay: main) != nil) +} + +@Test func oversizedWindowIsShrunkToFitMainDisplay() throws { + let main = CGRect(x: 0, y: 0, width: 1024, height: 768) + let window = CGRect(x: -2000, y: 0, width: 1800, height: 1200) + + let target = try #require(placementOnMainDisplay(window: window, mainDisplay: main)) + + #expect(main.contains(target)) + #expect(target.width <= main.width && target.height <= main.height) +} + +// The real prompt, as the VM's accessibility tree shows it. +private func systemPrompt( + text: String = "\u{201C}LauncherHost\u{201D} would like to access the Microphone.", + buttons: [String] = ["Help", "Don\u{2019}t Allow", "Allow"], + bundleID: String? = "com.apple.UserNotificationCenter", + executable: String? = "/System/Library/CoreServices/UserNotificationCenter.app/Contents/MacOS/UserNotificationCenter", + role: String? = "AXWindow", + subrole: String? = "AXSystemDialog" +) -> PromptWindow { + PromptWindow(ownerBundleID: bundleID, ownerExecutablePath: executable, role: role, + subrole: subrole, texts: [text, ""], buttons: buttons) +} + +@Test func promptTextNamesTheKindAndTheApp() { + #expect(parsePrivacyPrompt(texts: ["\u{201C}LauncherHost\u{201D} would like to access the Microphone."]) + == PrivacyPrompt(kind: .microphone, appName: "LauncherHost")) + #expect(parsePrivacyPrompt(texts: ["\"Terminal\" would like to access the Camera."]) + == PrivacyPrompt(kind: .camera, appName: "Terminal")) + #expect(parsePrivacyPrompt(texts: ["Allow \u{201C}Python\u{201D} to find devices on local networks?", "This will allow the app to discover"]) + == PrivacyPrompt(kind: .localNetwork, appName: "Python")) + #expect(parsePrivacyPrompt(texts: ["Do you want to save changes? Allow"]) == nil) + #expect(parsePrivacyPrompt(texts: ["would like to access the Microphone."]) == nil) +} + +@Test func theRealMicrophonePromptIsDeclinedWhenItNamesAProcessOfTheReview() { + #expect(decidePrivacyPrompt(systemPrompt(), expectedApps: ["LauncherHost", "Buzz Native Review"]) == .press("Don't Allow")) +} + +@Test func theRealLocalNetworkPromptIsAllowedWhenItNamesAProcessOfTheReview() { + let prompt = systemPrompt(text: "Allow \u{201C}Python\u{201D} to find devices on local networks?", + buttons: ["Don\u{2019}t Allow", "Allow"]) + #expect(decidePrivacyPrompt(prompt, expectedApps: ["python"]) == .press("Allow")) +} + +@Test func aPromptNamingAnotherAppIsNeverAnswered() { + guard case .skip(let reason) = decidePrivacyPrompt(systemPrompt(text: "\u{201C}Zoom\u{201D} would like to access the Microphone."), + expectedApps: ["LauncherHost", "Buzz Native Review"]) else { + Issue.record("answered a prompt for another app"); return + } + #expect(reason.contains("Zoom")) +} + +@Test func aWindowNotOwnedBySystemPromptAgentIsNeverAnswered() { + // Same words, same buttons, wrong owner: a web page or app drawing a lookalike. + for impostor in [ + systemPrompt(bundleID: "com.apple.Safari"), + systemPrompt(bundleID: nil), + systemPrompt(executable: "/Users/someone/UserNotificationCenter.app/Contents/MacOS/UserNotificationCenter"), + systemPrompt(executable: nil), + systemPrompt(executable: "/System/Library/CoreServices/../../../tmp/evil"), + ] { + guard case .skip = decidePrivacyPrompt(impostor, expectedApps: ["LauncherHost"]) else { + Issue.record("answered a window the system prompt agent does not own: \(impostor)"); continue + } + } +} + +@Test func aWindowThatIsNotASystemAlertIsNeverAnswered() { + for other in [systemPrompt(role: "AXSheet"), systemPrompt(subrole: "AXStandardWindow"), systemPrompt(subrole: nil), systemPrompt(role: nil)] { + guard case .skip = decidePrivacyPrompt(other, expectedApps: ["LauncherHost"]) else { + Issue.record("answered a window that is not a system dialog: \(other)"); continue + } + } +} + +@Test func aPromptWithoutTheExpectedButtonOrWithDuplicatesIsNotAnswered() { + guard case .skip = decidePrivacyPrompt(systemPrompt(buttons: ["Help", "Allow"]), expectedApps: ["LauncherHost"]) else { + Issue.record("pressed a missing button"); return + } + guard case .skip = decidePrivacyPrompt(systemPrompt(buttons: ["Don\u{2019}t Allow", "Don't Allow"]), expectedApps: ["LauncherHost"]) else { + Issue.record("pressed an ambiguous button"); return + } +} + +@Test func anEmptyExpectedSetNeverMatches() { + guard case .skip = decidePrivacyPrompt(systemPrompt(), expectedApps: []) else { + Issue.record("answered with nothing to identify the app by"); return + } +} + +@Test func theReportedWindowIsTheOneThatMoves() { + let reported = CGRect(x: -1016, y: 36, width: 1008, height: 726) + let others = [CGRect(x: 40, y: 40, width: 300, height: 200), CGRect(x: -1015, y: 36, width: 1008, height: 726)] + #expect(matchingWindowIndex(frames: others, reported: reported) == 1) + #expect(matchingWindowIndex(frames: [CGRect(x: 40, y: 40, width: 300, height: 200)], reported: reported) == nil) + #expect(matchingWindowIndex(frames: [], reported: reported) == nil) +} + +@Test func aMovedWindowIsVerifiedOnlyWhenItIsWhollyOnTheMainDisplay() { + let main = CGRect(x: 0, y: 0, width: 1440, height: 900) + #expect(windowIsOnMainDisplay(CGRect(x: 100, y: 80, width: 1008, height: 726), mainDisplay: main)) + #expect(!windowIsOnMainDisplay(CGRect(x: -1016, y: 36, width: 1008, height: 726), mainDisplay: main)) +} + +@Test func buttonTitlesCompareIgnoringTypographicApostrophes() { + #expect(normalizedButtonTitle("Don\u{2019}t Allow") == normalizedButtonTitle("Don't Allow")) + #expect(normalizedButtonTitle("Allow") != normalizedButtonTitle("Don't Allow")) +} diff --git a/tools/native-review/tests/test_harness_guards.py b/tools/native-review/tests/test_harness_guards.py new file mode 100644 index 00000000000..b21825008b5 --- /dev/null +++ b/tools/native-review/tests/test_harness_guards.py @@ -0,0 +1,178 @@ +"""The setup and relay scripts must never act on a machine, port or database that +is not the harness's own. These run the real shell scripts against stub binaries.""" +import os +import pathlib +import stat +import subprocess +import tempfile +import unittest + +TOOL = pathlib.Path(__file__).parents[1] +REPO = TOOL.parents[1] +CHECK = TOOL / "bin/check-harness-database" +SETUP = TOOL / "bin/setup-macos-vm" +RELAY = REPO / "scripts/start-isolated-test-relay.sh" + +# A psql that answers from environment variables and records every statement. +STUB_PSQL = """#!/bin/bash +sql="" +while [[ $# -gt 0 ]]; do + case "$1" in -c|-qtAc|-qc) sql="$2"; shift 2 ;; *) shift ;; esac +done +echo "$sql" >> "$STUB_LOG" +case "$sql" in + # Stop the relay script right after the reset: nothing after it may run in a test. + *"DROP SCHEMA"*) exit 3 ;; + "SHOW data_directory") [[ -n "${STUB_DATA_DIR:-}" ]] && echo "$STUB_DATA_DIR" || exit 2 ;; + *shobj_description*) [[ -n "${STUB_COMMENT+x}" ]] && echo "$STUB_COMMENT" ;; +esac +exit 0 +""" + + +def write_exe(path: pathlib.Path, body: str) -> None: + path.write_text(body) + path.chmod(path.stat().st_mode | stat.S_IXUSR) + + +class Sandbox(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + root = pathlib.Path(self.tmp.name).resolve() + self.stubs = root / "stubs" + self.stubs.mkdir() + self.state = root / "state" + (self.state / "postgres").mkdir(parents=True) + self.foreign = root / "foreign-postgres" + self.foreign.mkdir() + self.log = root / "psql.log" + self.log.write_text("") + write_exe(self.stubs / "psql", STUB_PSQL) + + def mark_state(self): + (self.state / ".buzz-native-review-harness").write_text("buzz-native-review-harness\n") + + def env(self, **extra): + env = { + "PATH": f"{self.stubs}:/usr/bin:/bin", + "HOME": self.tmp.name, + "STUB_LOG": str(self.log), + } + env.update(extra) + return env + + def run_script(self, args, **extra): + return subprocess.run(args, env=self.env(**extra), capture_output=True, text=True, timeout=60) + + def statements(self): + return self.log.read_text() + + +class CheckHarnessDatabaseTests(Sandbox): + def check(self, **extra): + return self.run_script([str(CHECK), "--state-dir", str(self.state)], **extra) + + def test_accepts_the_harness_database(self): + self.mark_state() + result = self.check(STUB_DATA_DIR=str(self.state / "postgres"), STUB_COMMENT="buzz-native-review-harness") + self.assertEqual(result.returncode, 0, result.stderr) + + def test_refuses_a_server_running_from_another_data_directory(self): + self.mark_state() + result = self.check(STUB_DATA_DIR=str(self.foreign), STUB_COMMENT="buzz-native-review-harness") + self.assertEqual(result.returncode, 1) + self.assertIn("not the harness data dir", result.stderr) + + def test_refuses_an_unmarked_database(self): + self.mark_state() + for comment in ("", "someone else's database"): + result = self.check(STUB_DATA_DIR=str(self.state / "postgres"), STUB_COMMENT=comment) + self.assertEqual(result.returncode, 1, comment) + self.assertIn("not marked", result.stderr) + + def test_refuses_without_the_state_dir_marker_file(self): + result = self.check(STUB_DATA_DIR=str(self.state / "postgres"), STUB_COMMENT="buzz-native-review-harness") + self.assertEqual(result.returncode, 1) + self.assertIn("not a harness state dir", result.stderr) + + def test_refuses_when_the_server_cannot_be_read(self): + self.mark_state() + result = self.check(STUB_COMMENT="buzz-native-review-harness") # no data dir: psql fails + self.assertEqual(result.returncode, 1) + self.assertIn("cannot read data_directory", result.stderr) + + def test_refuses_without_a_state_dir(self): + result = self.run_script([str(CHECK)]) + self.assertEqual(result.returncode, 1) + + +class SetupVmGuardTests(Sandbox): + def setUp(self): + super().setUp() + write_exe(self.stubs / "uname", '#!/bin/bash\n[[ "$1" == "-m" ]] && echo arm64 || echo Darwin\n') + + def sysctl(self, vmm: str): + write_exe(self.stubs / "sysctl", f'#!/bin/bash\n[[ "$2" == "kern.hv_vmm_present" ]] && echo {vmm} || echo Mac15,9\n') + + def setup(self, *flags): + return self.run_script([str(SETUP), "--state-dir", str(self.state), *flags]) + + def test_refuses_outside_a_vm_before_touching_anything(self): + self.sysctl("0") + result = self.setup() + self.assertEqual(result.returncode, 1) + self.assertIn("does not look like a virtual machine", result.stderr) + self.assertFalse((self.state / ".buzz-native-review-harness").exists()) + + def test_allow_non_vm_is_an_explicit_opt_in(self): + self.sysctl("0") + result = self.setup("--allow-non-vm") + self.assertIn("continuing because --allow-non-vm", result.stdout) + self.assertNotIn("does not look like a virtual machine", result.stderr) + self.assertIn("Homebrew is required", result.stderr) # got past the guard, stopped at the stubbed PATH + + def test_a_vm_passes_the_guard(self): + self.sysctl("1") + result = self.setup() + self.assertNotIn("virtual machine", result.stderr) + self.assertIn("Homebrew is required", result.stderr) + + +class RelayResetGuardTests(Sandbox): + def relay(self, **extra): + write_exe(self.stubs / "pg_isready", "#!/bin/bash\nexit 0\n") + return self.run_script([str(RELAY)], BUZZ_HARNESS_NATIVE_SERVICES="1", **extra) + + def assertNoReset(self, result): + self.assertNotEqual(result.returncode, 0) + self.assertNotIn("DROP SCHEMA", self.statements()) + + def test_native_mode_without_a_state_dir_never_drops(self): + result = self.relay(STUB_DATA_DIR=str(self.state / "postgres"), STUB_COMMENT="buzz-native-review-harness") + self.assertNoReset(result) + self.assertIn("BUZZ_HARNESS_STATE_DIR", result.stderr) + + def test_native_mode_against_a_foreign_postgres_never_drops(self): + self.mark_state() + result = self.relay(BUZZ_HARNESS_STATE_DIR=str(self.state), STUB_DATA_DIR=str(self.foreign), + STUB_COMMENT="buzz-native-review-harness") + self.assertNoReset(result) + self.assertIn("refusing to reset", result.stderr) + + def test_native_mode_against_an_unmarked_database_never_drops(self): + self.mark_state() + result = self.relay(BUZZ_HARNESS_STATE_DIR=str(self.state), STUB_DATA_DIR=str(self.state / "postgres"), + STUB_COMMENT="") + self.assertNoReset(result) + + def test_the_harness_database_is_reset(self): + self.mark_state() + result = self.relay(BUZZ_HARNESS_STATE_DIR=str(self.state), STUB_DATA_DIR=str(self.state / "postgres"), + STUB_COMMENT="buzz-native-review-harness") + self.assertIn("DROP SCHEMA", self.statements()) + self.assertEqual(result.returncode, 3) # the stub aborts the script at the reset + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/native-review/tests/test_ios_review.py b/tools/native-review/tests/test_ios_review.py index c08f1b438e8..8f49fb49de2 100644 --- a/tools/native-review/tests/test_ios_review.py +++ b/tools/native-review/tests/test_ios_review.py @@ -102,6 +102,13 @@ def test_flutter_environment_scrubs_host_credentials(self): for name in sentinels: self.assertNotIn(name, environment) + def test_flutter_environment_keeps_pub_mirror_but_not_credentials(self): + host = {"PUB_HOSTED_URL": "https://pub.example.org/api", "PUB_TOKEN": "secret"} + with mock.patch.dict(ios_review.os.environ, host, clear=False): + environment = ios_review.flutter_environment() + self.assertEqual(environment["PUB_HOSTED_URL"], "https://pub.example.org/api") + self.assertNotIn("PUB_TOKEN", environment) + def test_flutter_environment_carries_private_proceed_url(self): environment = ios_review.flutter_environment("http://127.0.0.1:1/proceed/token") self.assertEqual(environment["BUZZ_NATIVE_REVIEW_PROCEED_URL"], "http://127.0.0.1:1/proceed/token") diff --git a/tools/native-review/tests/test_review_native.py b/tools/native-review/tests/test_review_native.py index 720628168e1..a7cce4f3131 100644 --- a/tools/native-review/tests/test_review_native.py +++ b/tools/native-review/tests/test_review_native.py @@ -5,6 +5,8 @@ import re import tempfile import unittest +import urllib.error +import urllib.request from unittest import mock MODULE_PATH = pathlib.Path(__file__).parents[1] / "review_native.py" @@ -502,7 +504,7 @@ def test_journey_body_interruption_runs_all_cleanup(self): mock.patch.object(review_native, "build_driver", return_value=pathlib.Path("driver")), \ mock.patch.object(review_native, "Driver", return_value=driver), \ mock.patch.object(review_native, "ProcessSampler", return_value=sampler), \ - mock.patch.object(review_native, "wait_for_visible_window", return_value={"visible": True}), \ + mock.patch.object(review_native, "wait_for_interactive_window", return_value={"visible": True}), \ mock.patch.object(review_native, "capture_step", return_value={}), \ mock.patch.object(review_native, "terminate_and_reap", return_value=[]) as reap, \ mock.patch.object(review_native, "cleanup_review_state") as cleanup: @@ -549,7 +551,7 @@ def test_journey_cleanup_survives_driver_interruption(self): mock.patch.object(review_native, "build_driver", return_value=pathlib.Path("driver")), \ mock.patch.object(review_native, "Driver", return_value=driver), \ mock.patch.object(review_native, "ProcessSampler", return_value=sampler), \ - mock.patch.object(review_native, "wait_for_visible_window", return_value={"visible": True}), \ + mock.patch.object(review_native, "wait_for_interactive_window", return_value={"visible": True}), \ mock.patch.object(review_native, "wait_expectation"), \ mock.patch.object(review_native, "capture_step", return_value={}), \ mock.patch.object(review_native, "terminate_and_reap", return_value=[]) as reap, \ @@ -615,6 +617,217 @@ def test_visible_window_fails_if_app_exits(self): review_native.wait_for_visible_window(driver, process, timeout_seconds=1) driver.request.assert_not_called() + def test_host_toolchain_overrides_reach_builds_but_not_the_reviewed_app(self): + overrides = {"SHERPA_ONNX_ARCHIVE_DIR": "/opt/archives", "SHERPA_ONNX_LIB_DIR": "/opt/sherpa/lib"} + with mock.patch.dict(review_native.os.environ, overrides, clear=False): + build = review_native.scrubbed_environment(include_home=True) + app = review_native.scrubbed_environment() + for name, value in overrides.items(): + self.assertEqual(build[name], value) + self.assertNotIn(name, app) + + def test_secret_shaped_toolchain_names_are_still_dropped(self): + with mock.patch.dict(review_native.os.environ, {"SHERPA_ONNX_ARCHIVE_TOKEN": "x"}, clear=False): + self.assertNotIn("SHERPA_ONNX_ARCHIVE_TOKEN", + review_native.scrubbed_environment(include_home=True)) + + def test_interactive_window_is_placed_then_waits_for_web_accessibility(self): + driver = mock.Mock() + process = mock.Mock() + process.poll.return_value = None + driver.request.side_effect = [ + {"ok": True, "visible": True, "window_id": 7}, + {"ok": True, "answered": False}, + {"ok": True, "moved": True, "verified": True, "window_id": 7, + "before": {"x": -1016, "y": 36, "width": 1008, "height": 726}, + "after": {"x": 40, "y": 60, "width": 1008, "height": 726}}, + {"ok": True, "answered": False}, + {"ok": True, "ready": False}, + {"ok": True, "answered": True}, + {"ok": True, "ready": True}, + {"ok": True, "visible": True, "window_id": 7, "bounds": {"x": 40, "y": 60}}, + ] + with mock.patch.object(review_native.time, "sleep"): + status = review_native.wait_for_interactive_window(driver, process, timeout_seconds=5) + self.assertEqual([call.args[0] for call in driver.request.call_args_list], + ["window_status", "answer_privacy_prompt", "place_window", + "answer_privacy_prompt", "web_ready", + "answer_privacy_prompt", "web_ready", "window_status"]) + self.assertTrue(status["moved"]) + self.assertEqual(status["bounds"]["x"], 40) + # The receipt records what was moved and where it ended up. + self.assertTrue(status["placement"]["verified"]) + self.assertEqual(status["placement"]["before"]["x"], -1016) + self.assertEqual(status["placement"]["after"]["x"], 40) + + def test_interactive_window_fails_when_placement_is_not_verified(self): + driver = mock.Mock() + process = mock.Mock() + process.poll.return_value = None + driver.request.side_effect = [ + {"ok": True, "visible": True, "window_id": 7}, + {"ok": True, "answered": False}, + {"ok": True, "moved": True, "verified": False, + "before": {"x": -1016, "y": 36, "width": 1008, "height": 726}, + "after": {"x": -1016, "y": 36, "width": 1008, "height": 726}}, + ] + with mock.patch.object(review_native.time, "sleep"): + with self.assertRaisesRegex(review_native.HarnessError, "not verified"): + review_native.wait_for_interactive_window(driver, process, timeout_seconds=5) + + def test_interactive_window_waits_for_the_accessibility_window_to_exist(self): + driver = mock.Mock() + process = mock.Mock() + process.poll.return_value = None + driver.request.side_effect = [ + {"ok": True, "visible": True, "window_id": 7}, + {"ok": True, "answered": False}, + review_native.HarnessError("no accessibility window to place"), + {"ok": True, "answered": False}, + review_native.HarnessError("no accessibility window to place"), + {"ok": True, "answered": False}, + {"ok": True, "moved": False}, + {"ok": True, "answered": False}, + {"ok": True, "ready": True}, + {"ok": True, "visible": True, "window_id": 7, "bounds": {"x": 40, "y": 60}}, + ] + with mock.patch.object(review_native.time, "sleep"): + status = review_native.wait_for_interactive_window(driver, process, timeout_seconds=5) + self.assertEqual([call.args[0] for call in driver.request.call_args_list], + ["window_status", "answer_privacy_prompt", "place_window", + "answer_privacy_prompt", "place_window", "answer_privacy_prompt", + "place_window", "answer_privacy_prompt", "web_ready", "window_status"]) + self.assertFalse(status["moved"]) + + def test_interactive_window_does_not_hide_other_placement_errors(self): + driver = mock.Mock() + process = mock.Mock() + process.poll.return_value = None + driver.request.side_effect = [ + {"ok": True, "visible": True, "window_id": 7}, + {"ok": True, "answered": False}, + review_native.HarnessError("Accessibility permission is not granted"), + ] + with mock.patch.object(review_native.time, "sleep"): + with self.assertRaisesRegex(review_native.HarnessError, "Accessibility permission"): + review_native.wait_for_interactive_window(driver, process, timeout_seconds=5) + + def test_interactive_window_reports_missing_web_accessibility(self): + driver = mock.Mock() + process = mock.Mock() + process.poll.return_value = None + + def respond(command, **_): + return {"ok": True, "visible": True, "ready": False, "moved": False} + + driver.request.side_effect = respond + with mock.patch.object(review_native.time, "sleep"): + with self.assertRaisesRegex(review_native.HarnessError, "web content accessibility"): + review_native.wait_for_interactive_window(driver, process, timeout_seconds=0.05) + + def test_journey_runs_after_the_window_is_interactive(self): + journey = { + "flow": "interactive_order", + "record": {"video": "off", "screenshots": False, "accessibility": False}, + "steps": [{"name": "wait", "act": {"type": "wait", "duration_ms": 0}, + "expect": {"focused": False}}], + "cleanup": {"terminate_app": True, "remove_state": True}, + } + events = [] + process = mock.Mock(pid=42) + driver = mock.Mock() + driver.request.side_effect = lambda command, **_: events.append(command) or {"ok": True} + sampler = mock.Mock() + sampler.finish.return_value = {"sample_count": 0} + with tempfile.TemporaryDirectory() as directory: + output_root = pathlib.Path(directory) / "output" + fixture = {"secret_path": str(pathlib.Path(directory) / "identity.key")} + app_binary = pathlib.Path(directory) / "buzz-desktop" + app_binary.write_bytes(b"binary") + journey_path = pathlib.Path(directory) / "journey.yaml" + journey_path.write_text("fixture") + with mock.patch.object(review_native, "load_journey", return_value=journey), \ + mock.patch.object(review_native, "provenance", return_value={"head_sha": "a" * 40}), \ + mock.patch.object(review_native, "machine_fingerprint", return_value={}), \ + mock.patch.object(review_native, "doctor", return_value={"ok": True}), \ + mock.patch.object(review_native, "prepare_fixture", return_value=fixture), \ + mock.patch.object(review_native, "semantic_probe_server", return_value=(mock.Mock(), "probe")), \ + mock.patch.object(review_native, "build_and_launch", return_value=(process, app_binary, 42)), \ + mock.patch.object(review_native, "build_driver", return_value=pathlib.Path("driver")), \ + mock.patch.object(review_native, "Driver", return_value=driver), \ + mock.patch.object(review_native, "ProcessSampler", return_value=sampler), \ + mock.patch.object(review_native, "wait_for_interactive_window", + side_effect=lambda *a, **k: events.append("interactive") or {"visible": True}), \ + mock.patch.object(review_native, "wait_expectation"), \ + mock.patch.object(review_native, "capture_step", return_value={}), \ + mock.patch.object(review_native, "terminate_and_reap", return_value=[]), \ + mock.patch.object(review_native, "cleanup_review_state"): + review_native.run_journey(journey_path, "ws://127.0.0.1:3030", output_root) + self.assertEqual(events[0], "interactive") + self.assertLess(events.index("interactive"), events.index("act")) + + def test_doctor_requires_ffmpeg_for_shareable_evidence(self): + with mock.patch.object(review_native.shutil, "which", + side_effect=lambda name: None if name == "ffmpeg" else f"/usr/bin/{name}"), \ + mock.patch.object(review_native, "build_driver", return_value=pathlib.Path("driver")), \ + mock.patch.object(review_native, "run", + return_value=mock.Mock(stdout='{"checks": []}', stderr="")), \ + mock.patch("builtins.print"): + result = review_native.doctor() + self.assertFalse(result["ok"]) + self.assertIn("ffmpeg", [c["name"] for c in result["checks"] if not c["ok"]]) + + +class SemanticProbeServerTests(unittest.TestCase): + NODE = {"id": "message-composer", "role": "textbox", "name": "Message", "value": "", + "scrollY": 0, "enabled": True, "focused": False, + "frame": {"x": 1, "y": 2, "width": 3, "height": 4}, + "viewport": {"width": 100, "height": 100}} + + def post(self, url, body=None, headers=None): + # navigator.sendBeacon sends a plain POST and cannot add request headers. + request = urllib.request.Request( + url, data=json.dumps(body if body is not None else [self.NODE]).encode(), + headers={"Content-Type": "text/plain;charset=UTF-8", **(headers or {})}, method="POST") + try: + with urllib.request.urlopen(request, timeout=5) as response: + return response.status + except urllib.error.HTTPError as error: + error.close() + return error.code + + def serve(self): + directory = tempfile.TemporaryDirectory() + self.addCleanup(directory.cleanup) + path = pathlib.Path(directory.name) / "semantic.json" + server, url = review_native.semantic_probe_server(path, "s3cret-token") + self.addCleanup(server.server_close) + self.addCleanup(server.shutdown) + return path, url + + def test_probe_url_carries_the_token_so_a_beacon_is_accepted(self): + path, url = self.serve() + self.assertIn("token=s3cret-token", url) + self.assertEqual(self.post(url), 204) + self.assertEqual(json.loads(path.read_text())[0]["id"], "message-composer") + + def test_beacon_without_or_with_the_wrong_token_is_rejected(self): + path, url = self.serve() + base = url.split("?")[0] + self.assertEqual(self.post(base), 401) + self.assertEqual(self.post(base + "?token=nope"), 401) + self.assertFalse(path.exists()) + + def test_header_token_is_still_accepted(self): + path, url = self.serve() + base = url.split("?")[0] + self.assertEqual(self.post(base, headers={"X-Buzz-Native-Review-Token": "s3cret-token"}), 204) + self.assertTrue(path.exists()) + + def test_unknown_path_is_not_found(self): + _, url = self.serve() + self.assertEqual(self.post(url.replace("/snapshot", "/other")), 404) + class PerformanceTests(unittest.TestCase): MACHINE = {"host_id_sha256": "f" * 64, "system": "Darwin", "release": "test", "machine": "arm64", "cpu": "test"}