From 7fcb66f648eb58a790f992a21ad35336524cc9d2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 18 Nov 2026 16:32:17 +0100 Subject: [PATCH 1/3] test(test-app): add a sign-in sheet lab for the hosted web auth surface Present a real ASWebAuthenticationSession sheet from one fixture screen and read it in place. iOS hosts that sheet out of the app's process in com.apple.SafariViewService, so the sheet is the surface regular captures target while the app stays the accessibility primaryApp underneath it. The page comes from a fixture identity provider served over loopback, and it holds fixture values only, so the lane involves no real identity provider and no credential. The committed Maestro flow reads the sheet's own page: its title, and the Email, Password, and LOGIN controls. Driving past that point is left to the manual lane, because on iOS 27.0 the same steps alternate between passing and refusing the capture, which is the intermittency #4593 reports. Three refusals were observed there, all from the iOS snapshot engine's invariants, and the viewport one carries no retriable detail, so the step's own stability re-capture does not poll and the step aborts. Refs: #2449 Refs: #4593 --- examples/test-app/README.md | 45 ++++++++ examples/test-app/app/(tabs)/settings.tsx | 1 + examples/test-app/app/_layout.tsx | 1 + examples/test-app/app/auth-session-lab.tsx | 14 +++ .../maestro-ios/auth-session-sheet.yaml | 49 +++++++++ .../auth-session-lab/expo-module.config.json | 6 + .../ios/AuthSessionLab.podspec | 16 +++ .../ios/AuthSessionLabModule.swift | 86 +++++++++++++++ examples/test-app/scripts/serve-auth-idp.mjs | 74 +++++++++++++ examples/test-app/src/auth-idp-fixture.ts | 83 ++++++++++++++ examples/test-app/src/auth-session.ts | 31 ++++++ .../src/screens/AuthSessionLabScreen.tsx | 103 ++++++++++++++++++ .../test-app/src/screens/SettingsScreen.tsx | 12 ++ package.json | 1 + scripts/run-test-app-auth-session-lane.mjs | 78 +++++++++++++ 15 files changed, 600 insertions(+) create mode 100644 examples/test-app/app/auth-session-lab.tsx create mode 100644 examples/test-app/maestro-ios/auth-session-sheet.yaml create mode 100644 examples/test-app/modules/auth-session-lab/expo-module.config.json create mode 100644 examples/test-app/modules/auth-session-lab/ios/AuthSessionLab.podspec create mode 100644 examples/test-app/modules/auth-session-lab/ios/AuthSessionLabModule.swift create mode 100644 examples/test-app/scripts/serve-auth-idp.mjs create mode 100644 examples/test-app/src/auth-idp-fixture.ts create mode 100644 examples/test-app/src/auth-session.ts create mode 100644 examples/test-app/src/screens/AuthSessionLabScreen.tsx create mode 100644 scripts/run-test-app-auth-session-lane.mjs diff --git a/examples/test-app/README.md b/examples/test-app/README.md index c616b4000f..1ac17ac9b8 100644 --- a/examples/test-app/README.md +++ b/examples/test-app/README.md @@ -18,6 +18,7 @@ It is intentionally small, but each surface is dense with durable accessibility - `Settings`: switch rows, accordion content, loading and error states, retry flow, destructive-confirm modal - `Automation lab`: long-press, alert-result, app-event, app-state, appearance, orientation, permission-recovery, log canaries, a flattened (`accessible={true}`) text input, and an Apple Pay sheet hosted in `com.apple.PassbookUIService` - `WebView accessibility`: a deterministic semantic fixture plus live websites with varied HTML for native accessibility snapshot verification +- `Sign-in sheet lab`: a real `ASWebAuthenticationSession` sheet hosted out of process in `com.apple.SafariViewService`, opened against a loopback fixture identity provider (see [Sign-in sheet lab](#sign-in-sheet-lab)) - `Perf lab`: seeded JavaScript render problems for `react-devtools profile`, one per scenario (see [Perf lab](#perf-lab)) - `Settle lab`: timed effects with known final screens for `--settle` regression runs (an in-place counter; results 500 and 800 ms after an immediate `Run N` acknowledgement; a 750 ms fading overlay; two-stage transitions with and without a spinner; a toast that precedes navigation), reached by the `agent-device-test-app://settle-lab` deep link - `Heavy feed`: a Bluesky-shaped home feed whose accessibility tree is deeper than 65 levels (see [Heavy feed](#heavy-feed)) @@ -334,6 +335,50 @@ The stable ids are `heavy-feed-title`, `heavy-feed-liked-count`, `heavy-feed-las post `heavy-post-`, `heavy-post--like`, `-reply`, `-repost`, and `-more`. A like press updates `Liked posts: `, and a long press on a post sets `Last action: held post `. +## Sign-in sheet lab + +**Settings → Open sign-in sheet lab** (`open-auth-session-lab`, route `auth-session-lab`) presents a +real `ASWebAuthenticationSession` sheet. iOS hosts that sheet out of the app's process in +`com.apple.SafariViewService`, over this screen and with the app still the accessibility primaryApp, +so it is the committed fixture for reading and driving a hosted web sign-in sheet in place (#2438, +#2449). The native module is `modules/auth-session-lab`; nothing about the flow activates or +relaunches anything, which is what keeps the sheet alive. + +The sheet opens a page served over loopback by the fixture identity provider, so the flow involves +no real identity provider and no credential: `src/auth-idp-fixture.ts` owns the page and `Email`, +`Password`, and `LOGIN` are the vocabulary a lane asserts on. Submitting the fixture form navigates +to the app's own callback scheme, which ends the sheet and returns the app; `auth-session-status` +then reports `completed` and `auth-session-message` carries the callback URL. + +Run the lane with the sheet's page served by the same script that owns its lifecycle: + +```bash +pnpm test-app:maestro:auth:ios -- --udid "" +``` + +That starts `examples/test-app/scripts/serve-auth-idp.mjs`, runs +`examples/test-app/maestro-ios/auth-session-sheet.yaml` +through `agent-device test --maestro`, and stops the provider when the flow ends. Start the provider +yourself when you drive the sheet by hand, and add `--delay-ms ` to hold the loading page first, so +you can read the sheet while its page is still loading. The flow lives in `maestro-ios/` rather than +`maestro/` because the shared directory is also run on Android. + +The committed flow reads the sheet and stops at its form controls. Driving past that point is not +committed, because on iOS 27.0 the same steps alternate between passing and refusing the capture, +which is the intermittency #4593 reports. Fill the sheet's fields and submit it when you want that +state, and expect to see one of three capture refusals on the step that follows the first `inputText` +or the submit: `regular iOS snapshot presentation requires a valid viewport`, `regular iOS snapshot +node escaped its cumulative clip`, or `main thread execution timed out`. All three come from +`packages/capture-kit/src/ios-snapshot-engine/invariants.ts`, and the first carries no `retriable`, so +the step's own stability re-capture does not poll and the step aborts. A build of the fixture app +without the module shows `unavailable` in `auth-session-status` instead of opening a sheet. + +The app needs a build that includes the module: a development client (`pnpm test-app:ios`) or a +Release build (`pnpm --dir examples/test-app exec expo run:ios --configuration Release --device +generic --no-bundler`). It is a native change, so it produces one new fingerprinted build that +consumers then share. A build without it shows `unavailable` in `auth-session-status` instead of +opening a sheet. + ## Local Agent Device suites The repo includes two local suites for iterating on the fixture app: diff --git a/examples/test-app/app/(tabs)/settings.tsx b/examples/test-app/app/(tabs)/settings.tsx index e8e39b4796..a696104a95 100644 --- a/examples/test-app/app/(tabs)/settings.tsx +++ b/examples/test-app/app/(tabs)/settings.tsx @@ -18,6 +18,7 @@ export default function SettingsRoute() { onConfirmReset={state.resetLabState} onLoadDiagnostics={state.loadDiagnostics} onOpenAccessorySetup={() => router.push('/accessory-setup')} + onOpenAuthSessionLab={() => router.push('/auth-session-lab')} onOpenAutomationLab={() => router.push('/automation')} onOpenHeavyFeed={() => router.push('/heavy-feed')} onOpenInertSurface={() => router.push('/inert')} diff --git a/examples/test-app/app/_layout.tsx b/examples/test-app/app/_layout.tsx index 38ca0c0e9f..21589a906c 100644 --- a/examples/test-app/app/_layout.tsx +++ b/examples/test-app/app/_layout.tsx @@ -24,6 +24,7 @@ function RootLayoutContent() { > + diff --git a/examples/test-app/app/auth-session-lab.tsx b/examples/test-app/app/auth-session-lab.tsx new file mode 100644 index 0000000000..1f15e5143f --- /dev/null +++ b/examples/test-app/app/auth-session-lab.tsx @@ -0,0 +1,14 @@ +import { useRouter } from 'expo-router'; + +import { AppFrame } from '../src/components'; +import { AuthSessionLabScreen } from '../src/screens/AuthSessionLabScreen'; + +export default function AuthSessionLabRoute() { + const router = useRouter(); + + return ( + + router.back()} /> + + ); +} diff --git a/examples/test-app/maestro-ios/auth-session-sheet.yaml b/examples/test-app/maestro-ios/auth-session-sheet.yaml new file mode 100644 index 0000000000..4346b2cd3b --- /dev/null +++ b/examples/test-app/maestro-ios/auth-session-sheet.yaml @@ -0,0 +1,49 @@ +appId: com.callstack.agentdevicelab +name: Sign-in sheet +# Reads a real ASWebAuthenticationSession sheet, which iOS hosts out of process in +# com.apple.SafariViewService, while the app stays the foreground owner underneath it (#2449). The +# page comes from the fixture identity provider in src/auth-idp-fixture.ts, started by the lane script +# (`pnpm test-app:maestro:auth:ios`). It holds fixture values only, so no credential is involved. +# +# These assertions match the sheet's own page, which is what the runner's in-place read of the hosted +# surface has to keep producing (#2438). When that read regresses, or the sheet is not served, the +# first assertion below fails with the sheet's title missing. +# +# This flow reads the sheet and stops. Driving it further, with inputText or a submit, lands on the +# intermittent capture refusals #4593 reports; see examples/test-app/README.md for that sequence and +# the step-level signatures observed on iOS 27.0. +env: + # How long to wait for the sheet's page to serve the form. + AUTH_SHEET_TIMEOUT: '20000' +onFlowStart: + - launchApp: + clearState: true + - assertVisible: Agent Device Tester +--- +# Reaching the fixture screen: the Settings tab, then the lab's own entry. +- tapOn: + text: Settings +- scrollUntilVisible: + element: + id: open-auth-session-lab +- tapOn: + id: open-auth-session-lab +- assertVisible: Sign-in sheet lab +- assertVisible: + id: auth-session-open +# Opening the sheet. iOS presents it over the app, in its own process, so from here on a capture reads +# the sheet's surface rather than the app's and no app row can be asserted. +- tapOn: + id: auth-session-open +# The sheet's page is served by the fixture identity provider. This is the assertion that fails when +# the sheet is not served, so it carries the lane's timeout: an unserved sheet must fail here. +- extendedWaitUntil: + visible: Fixture sign-in + timeout: ${AUTH_SHEET_TIMEOUT} +# The hosted page's own controls, read in place. The form fields belong to the sheet, not the app. +- assertVisible: + text: Email +- assertVisible: + text: Password +- assertVisible: + text: LOGIN diff --git a/examples/test-app/modules/auth-session-lab/expo-module.config.json b/examples/test-app/modules/auth-session-lab/expo-module.config.json new file mode 100644 index 0000000000..5187edc63e --- /dev/null +++ b/examples/test-app/modules/auth-session-lab/expo-module.config.json @@ -0,0 +1,6 @@ +{ + "platforms": ["ios"], + "apple": { + "modules": ["AuthSessionLabModule"] + } +} diff --git a/examples/test-app/modules/auth-session-lab/ios/AuthSessionLab.podspec b/examples/test-app/modules/auth-session-lab/ios/AuthSessionLab.podspec new file mode 100644 index 0000000000..91d7ee9225 --- /dev/null +++ b/examples/test-app/modules/auth-session-lab/ios/AuthSessionLab.podspec @@ -0,0 +1,16 @@ +Pod::Spec.new do |s| + s.name = 'AuthSessionLab' + s.version = '1.0.0' + s.summary = 'ASWebAuthenticationSession fixture for Agent Device Tester' + s.description = s.summary + s.license = { :type => 'MIT' } + s.author = { 'Callstack' => 'opensource@callstack.com' } + s.homepage = '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/callstack/agent-device' + s.platforms = { :ios => '15.1' } + s.source = { :git => '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/callstack/agent-device.git' } + s.static_framework = true + + s.dependency 'ExpoModulesCore' + s.frameworks = 'AuthenticationServices', 'Foundation', 'UIKit' + s.source_files = '**/*.{h,m,mm,swift,hpp,cpp}' +end diff --git a/examples/test-app/modules/auth-session-lab/ios/AuthSessionLabModule.swift b/examples/test-app/modules/auth-session-lab/ios/AuthSessionLabModule.swift new file mode 100644 index 0000000000..669cf0bcee --- /dev/null +++ b/examples/test-app/modules/auth-session-lab/ios/AuthSessionLabModule.swift @@ -0,0 +1,86 @@ +import AuthenticationServices +import ExpoModulesCore +import UIKit + +// Presents a real sign-in sheet through ASWebAuthenticationSession. iOS hosts that sheet out of +// process in com.apple.SafariViewService, which makes this the #2449 fixture: the sheet is read and +// driven in place (#2438), the app stays the accessibility primaryApp while the sheet is up, and no +// step may activate or relaunch anything. +// +// The page itself is served by the fixture identity provider, not by the app: see +// `src/auth-idp-fixture.ts` for its content and `scripts/serve-auth-idp.mjs`, in this app's folder, +// for the server a lane starts. It holds fixture values only, so this flow needs no credentials. +// `startSignInAsync` resolves with the callback URL the sheet ended on, which is the observable end +// of the flow. +public final class AuthSessionLabModule: Module { + public func definition() -> ModuleDefinition { + Name("AuthSessionLab") + + AsyncFunction("startSignInAsync") { (url: String, callbackScheme: String, promise: Promise) in + AuthSessionLabController.shared.start(url: url, callbackScheme: callbackScheme, promise: promise) + }.runOnQueue(.main) + } +} + +private final class AuthSessionLabController: NSObject { + static let shared = AuthSessionLabController() + + private struct Session { + let controller: ASWebAuthenticationSession + let promise: Promise + } + + // One sheet at a time: two concurrent sessions would make which sheet answered ambiguous. + private var session: Session? + + func start(url: String, callbackScheme: String, promise: Promise) { + guard session == nil else { + promise.reject( + Exception( + name: "AuthSessionAlreadyPresented", + description: "A sign-in sheet is already presented." + ) + ) + return + } + + guard let url = URL(string: url), url.scheme != nil else { + promise.reject( + Exception(name: "InvalidAuthURL", description: "The sign-in URL is not a valid URL.") + ) + return + } + + let controller = ASWebAuthenticationSession(url: url, callbackURLScheme: callbackScheme) { + callbackURL, error in + guard let session = self.session else { return } + self.session = nil + if let callbackURL { + session.promise.resolve(callbackURL.absoluteString) + return + } + let sessionError = error as? ASWebAuthenticationSessionError + session.promise.reject( + Exception( + name: sessionError?.code == .canceledLogin ? "AuthSessionCanceled" : "AuthSessionFailed", + description: error?.localizedDescription ?? "The sign-in session failed." + ) + ) + } + + // Ephemeral so the sheet shares no cookies or website data with anything else on the device. + controller.prefersEphemeralWebBrowserSession = true + controller.presentationContextProvider = self + session = Session(controller: controller, promise: promise) + controller.start() + } +} + +extension AuthSessionLabController: ASWebAuthenticationPresentationContextProviding { + public func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor { + let windows = UIApplication.shared.connectedScenes + .compactMap { $0 as? UIWindowScene } + .flatMap(\.windows) + return windows.first(where: \.isKeyWindow) ?? ASPresentationAnchor() + } +} diff --git a/examples/test-app/scripts/serve-auth-idp.mjs b/examples/test-app/scripts/serve-auth-idp.mjs new file mode 100644 index 0000000000..99308bc74a --- /dev/null +++ b/examples/test-app/scripts/serve-auth-idp.mjs @@ -0,0 +1,74 @@ +#!/usr/bin/env node +// Serves the fixture identity provider page (#2449) over loopback for a lane. +// +// The sign-in sheet is opened by the app against this address, so the page travels through the real +// hosted SafariViewService surface and no external identity provider is involved. The page content +// lives in examples/test-app/src/auth-idp-fixture.ts, which is also what the Maestro flow asserts +// against. It holds fixture values only. +// +// node --experimental-strip-types examples/test-app/scripts/serve-auth-idp.mjs +// node --experimental-strip-types examples/test-app/scripts/serve-auth-idp.mjs --delay-ms 6000 +// +// `--host`, `--port`, and `--delay-ms` override the fixture identity provider's address and the time +// it holds the loading page. The lane starts this server; see scripts/run-test-app-auth-session-lane.mjs. +// +// Run it with `node --experimental-strip-types`, the repo's convention for a Node entry that imports +// TypeScript: the supported floor here is Node 22.12, where type stripping is still behind that flag. +import { createServer } from 'node:http'; +import path from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; + +const fixturePath = path.resolve( + path.dirname(fileURLToPath(import.meta.url)), + '..', + 'src', + 'auth-idp-fixture.ts', +); + +const args = process.argv.slice(2); +function readFlag(name, fallback) { + const index = args.indexOf(`--${name}`); + return index === -1 ? fallback : (args[index + 1] ?? fallback); +} + +const { AUTH_IDP_DEFAULT_PORT, AUTH_IDP_PATH, renderAuthIdpPage } = await import( + pathToFileURL(fixturePath).href +); + +const host = readFlag('host', '127.0.0.1'); +const port = Number(readFlag('port', String(AUTH_IDP_DEFAULT_PORT))); +const delayMs = Number(readFlag('delay-ms', '0')); + +let requests = 0; + +const server = createServer((request, response) => { + const url = new URL(request.url ?? '/', `http://${host}`); + if (url.pathname !== AUTH_IDP_PATH) { + response.writeHead(404, { 'content-type': 'text/plain' }); + response.end('not found\n'); + return; + } + + // Only the first request honours --delay-ms, so a lane can observe the sheet mid-load. A reload + // or a redirect must not sit in the loading state again. + const servedDelayMs = requests === 0 ? delayMs : 0; + const html = renderAuthIdpPage({ delayMs: servedDelayMs }); + requests += 1; + console.log(`[auth-idp] ${url.pathname} delayMs=${servedDelayMs}`); + response.writeHead(200, { + 'content-type': 'text/html; charset=utf-8', + 'content-length': Buffer.byteLength(html), + 'cache-control': 'no-store', + }); + response.end(html); +}); + +server.listen(port, host, () => { + console.log(`[auth-idp] http://${host}:${port}${AUTH_IDP_PATH} delayMs=${delayMs}`); +}); + +for (const signal of ['SIGINT', 'SIGTERM']) { + process.on(signal, () => { + server.close(() => process.exit(0)); + }); +} diff --git a/examples/test-app/src/auth-idp-fixture.ts b/examples/test-app/src/auth-idp-fixture.ts new file mode 100644 index 0000000000..d324325604 --- /dev/null +++ b/examples/test-app/src/auth-idp-fixture.ts @@ -0,0 +1,83 @@ +// The fixture identity provider for the sign-in sheet, and the single source of truth for the page +// the sheet shows. The content holds fixture values only: no credentials, no tokens, no client id. +// Submitting the form navigates to the app's own callback scheme, which is what ends the +// ASWebAuthenticationSession sheet and returns the app to the foreground. +// +// `scripts/serve-auth-idp.mjs` serves this page over loopback for a lane; the Maestro flow asserts +// against the same vocabulary. `delayMs` defers the real form, so a lane can observe the sheet while +// its page is still loading — the state #4593 reports from. + +export const AUTH_IDP_DEFAULT_PORT = 4593; + +export const AUTH_IDP_PATH = '/auth-idp'; + +export const AUTH_IDP_DEFAULT_URL = `http://127.0.0.1:${AUTH_IDP_DEFAULT_PORT}${AUTH_IDP_PATH}`; + +// The callback the fixture sheet ends on. `agent-device-test-app` is the scheme app.config.js +// registers and the one the session is opened with, so ASWebAuthenticationSession intercepts this +// navigation itself, ends the sheet, and hands the URL to the app. No route needs to serve it. +export const AUTH_IDP_FIXTURE_REDIRECT = + 'agent-device-test-app://auth-callback?code=fixture-code&state=fixture-state'; +// The words a lane asserts on. Keep the Maestro flow and this page changed together. +export const AUTH_IDP_TEXT = { + loading: 'Loading sign-in', + title: 'Fixture sign-in', + email: 'Email', + password: 'Password', + submit: 'LOGIN', +} as const; + +// The form submits natively to the callback scheme. ASWebAuthenticationSession intercepts a +// navigation to that scheme when the submit originates it, and ignores the same navigation when page +// script asks for it with `location.assign`, so a script-driven submit leaves the sheet open. Verified +// on iOS 27.0. +export function renderAuthIdpPage(options: { delayMs?: number } = {}): string { + const delayMs = options.delayMs ?? 0; + if (delayMs > 0) { + return ` + + + + ${AUTH_IDP_TEXT.loading} + + + +

${AUTH_IDP_TEXT.loading}

+ + +`; + } + + return ` + + + + ${AUTH_IDP_TEXT.title} + + + +

${AUTH_IDP_TEXT.title}

+
+ + + +
+ + +`; +} diff --git a/examples/test-app/src/auth-session.ts b/examples/test-app/src/auth-session.ts new file mode 100644 index 0000000000..71bfcc14f3 --- /dev/null +++ b/examples/test-app/src/auth-session.ts @@ -0,0 +1,31 @@ +import { Platform } from 'react-native'; +import { requireOptionalNativeModule } from 'expo-modules-core'; + +// The callback scheme the fixture registers in app.config.js. A real IdP redirect lands here, so +// the sheet closing with a callback to this scheme is the observable end of the flow. +export const AUTH_SESSION_CALLBACK_SCHEME = 'agent-device-test-app'; + +type AuthSessionLabModule = { + startSignInAsync(url: string, callbackScheme: string): Promise; +}; + +const authSessionLab = + Platform.OS === 'ios' + ? requireOptionalNativeModule('AuthSessionLab') + : null; + +export function isAuthSessionLabAvailable(): boolean { + return authSessionLab !== null; +} + +/** + * Opens the system sign-in sheet for `url` and resolves with the callback URL the fixture IdP + * redirected to. Rejects when the sheet is canceled or fails. + */ +export async function startFixtureSignInSession(url: string): Promise { + if (!authSessionLab) { + throw new Error('Rebuild the iOS development client to include AuthSessionLab.'); + } + + return authSessionLab.startSignInAsync(url, AUTH_SESSION_CALLBACK_SCHEME); +} diff --git a/examples/test-app/src/screens/AuthSessionLabScreen.tsx b/examples/test-app/src/screens/AuthSessionLabScreen.tsx new file mode 100644 index 0000000000..617d312596 --- /dev/null +++ b/examples/test-app/src/screens/AuthSessionLabScreen.tsx @@ -0,0 +1,103 @@ +import { useState } from 'react'; +import { ScrollView, StyleSheet, Text } from 'react-native'; + +import { AUTH_IDP_DEFAULT_URL } from '../auth-idp-fixture'; +import { isAuthSessionLabAvailable, startFixtureSignInSession } from '../auth-session'; +import { ActionButton, InlineBadge, ScreenTitle, SectionCard } from '../components'; +import { useAppColors, type AppColors } from '../theme'; + +type SheetStatus = 'idle' | 'presenting' | 'completed' | 'canceled' | 'error' | 'unavailable'; + +function initialStatus(): SheetStatus { + return isAuthSessionLabAvailable() ? 'idle' : 'unavailable'; +} + +export function AuthSessionLabScreen(props: { onBack: () => void }) { + const colors = useAppColors(); + const styles = createStyles(colors); + const [status, setStatus] = useState(initialStatus); + const [message, setMessage] = useState('Ready to open the system sign-in sheet.'); + + async function openSheet() { + setStatus('presenting'); + setMessage('Sign-in sheet requested.'); + + try { + const callbackUrl = await startFixtureSignInSession(AUTH_IDP_DEFAULT_URL); + setStatus('completed'); + setMessage(`Signed in: ${callbackUrl}`); + } catch (error) { + const canceled = error instanceof Error && error.name === 'AuthSessionCanceled'; + setStatus(canceled ? 'canceled' : 'error'); + setMessage(error instanceof Error ? error.message : String(error)); + } + } + + return ( + + + + + + {AUTH_IDP_DEFAULT_URL} + + + iOS hosts the sheet in com.apple.SafariViewService, over this screen and outside the + app's process. + + + + + void openSheet()} testID="auth-session-open" /> + + {status} + + {status === 'presenting' ? : null} + + {message} + + + + + + ); +} + +function createStyles(colors: AppColors) { + return StyleSheet.create({ + content: { + gap: 16, + padding: 20, + }, + url: { + color: colors.text, + fontFamily: 'Menlo', + fontSize: 13, + }, + body: { + color: colors.textSoft, + fontSize: 14, + }, + status: { + color: colors.text, + fontSize: 16, + fontWeight: '600', + }, + }); +} diff --git a/examples/test-app/src/screens/SettingsScreen.tsx b/examples/test-app/src/screens/SettingsScreen.tsx index bd5be5dbb4..6f9658bc5d 100644 --- a/examples/test-app/src/screens/SettingsScreen.tsx +++ b/examples/test-app/src/screens/SettingsScreen.tsx @@ -19,6 +19,7 @@ export interface SettingsScreenProps { onConfirmReset: () => void; onLoadDiagnostics: () => void; onOpenAccessorySetup: () => void; + onOpenAuthSessionLab: () => void; onOpenAutomationLab: () => void; onOpenHeavyFeed: () => void; onOpenInertSurface: () => void; @@ -110,6 +111,17 @@ export function SettingsScreen(props: SettingsScreenProps) { /> + + + + { + const fail = (message) => reject(new Error(message)); + const timeout = setTimeout(() => fail('did not print its listen line within 15s'), 15_000); + const onData = (chunk) => { + if (!chunk.includes('[auth-idp] http')) return; + clearTimeout(timeout); + idp.stdout.removeListener('data', onData); + resolve(); + }; + idp.stdout.on('data', onData); + idp.once('error', (error) => { + clearTimeout(timeout); + fail(error.message); + }); + idp.once('exit', (code) => { + clearTimeout(timeout); + fail(`exited with code ${String(code)} before it started`); + }); +}) + .then(() => { + // The flow runs through `spawnSync`, so this loop cannot keep reading the IdP while it runs. The + // IdP logs one line per request, and a pipe nobody reads fills up and blocks the IdP, which would + // stall the sheet's own fetch. `resume()` puts the stream in flowing mode and discards the output. + idp.stdout.resume(); + const suite = spawnSync( + process.execPath, + [ + path.join(repoRoot, 'scripts', 'run-test-app-maestro-suite.mjs'), + '--flow-dir', + flowDir, + '--platform', + 'ios', + ...passthrough, + ], + { cwd: repoRoot, stdio: 'inherit' }, + ); + process.exitCode = suite.signal ? 1 : (suite.status ?? 1); + }) + .catch((error) => { + console.error( + `[auth-session-lane] fixture identity provider ${error instanceof Error ? error.message : String(error)}`, + ); + process.exitCode = 1; + }) + .finally(() => { + if (idp.exitCode === null && !idp.killed) idp.kill('SIGTERM'); + }); From e551b09a852760a4c89ccb9ed9b7d6891d7cd0c5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 18 Nov 2026 17:05:56 +0100 Subject: [PATCH 2/3] fix(test-app): drain the auth fixture provider during the Maestro lane --- examples/test-app/README.md | 8 +- scripts/__tests__/auth-session-lane.test.ts | 132 ++++++++++++++ scripts/run-test-app-auth-session-lane.mjs | 183 +++++++++++++------- scripts/run-test-app-maestro-suite.mjs | 18 +- vitest.config.ts | 1 + 5 files changed, 272 insertions(+), 70 deletions(-) create mode 100644 scripts/__tests__/auth-session-lane.test.ts diff --git a/examples/test-app/README.md b/examples/test-app/README.md index 1ac17ac9b8..3bfe7a3990 100644 --- a/examples/test-app/README.md +++ b/examples/test-app/README.md @@ -358,10 +358,10 @@ pnpm test-app:maestro:auth:ios -- --udid "" That starts `examples/test-app/scripts/serve-auth-idp.mjs`, runs `examples/test-app/maestro-ios/auth-session-sheet.yaml` -through `agent-device test --maestro`, and stops the provider when the flow ends. Start the provider -yourself when you drive the sheet by hand, and add `--delay-ms ` to hold the loading page first, so -you can read the sheet while its page is still loading. The flow lives in `maestro-ios/` rather than -`maestro/` because the shared directory is also run on Android. +through `agent-device test --maestro`. The launcher stops the provider when the flow ends or you +cancel the lane. Start the provider yourself when you drive the sheet by hand. Add `--delay-ms ` +to hold the loading page so you can read the sheet while its page is still loading. The flow lives +in `maestro-ios/` rather than `maestro/` because the shared directory is also run on Android. The committed flow reads the sheet and stops at its form controls. Driving past that point is not committed, because on iOS 27.0 the same steps alternate between passing and refusing the capture, diff --git a/scripts/__tests__/auth-session-lane.test.ts b/scripts/__tests__/auth-session-lane.test.ts new file mode 100644 index 0000000000..e41e7ec6d2 --- /dev/null +++ b/scripts/__tests__/auth-session-lane.test.ts @@ -0,0 +1,132 @@ +import assert from 'node:assert/strict'; +import { spawn } from 'node:child_process'; +import { once } from 'node:events'; +import fs from 'node:fs'; +import path from 'node:path'; +import { expect, test } from 'vitest'; +import { mkdtempForTestSync } from '@agent-device/test-kit'; + +function fixture(provider: string, cli: string) { + const root = fs.realpathSync(mkdtempForTestSync('agent-device-auth-lane-')); + for (const dir of [ + 'scripts', + 'bin', + 'examples/test-app/scripts', + 'examples/test-app/maestro-ios', + ]) { + fs.mkdirSync(path.join(root, dir), { recursive: true }); + } + for (const name of ['run-test-app-auth-session-lane.mjs', 'run-test-app-maestro-suite.mjs']) { + fs.copyFileSync(path.join(import.meta.dirname, '..', name), path.join(root, 'scripts', name)); + } + for (const name of ['auth-session-sheet.yaml', 'unrelated.yaml']) { + fs.writeFileSync(path.join(root, 'examples/test-app/maestro-ios', name), ''); + } + const prelude = "import fs from 'node:fs';\n"; + fs.writeFileSync( + path.join(root, 'examples/test-app/scripts/serve-auth-idp.mjs'), + prelude + provider, + ); + fs.writeFileSync(path.join(root, 'bin/agent-device.mjs'), prelude + cli); + + const child = spawn( + process.execPath, + ['scripts/run-test-app-auth-session-lane.mjs', '--', '--udid', 'fixture'], + { cwd: root, stdio: ['ignore', 'ignore', 'pipe'] }, + ); + let stderr = ''; + child.stderr.setEncoding('utf8').on('data', (chunk) => { + stderr += chunk; + }); + const exit = once(child, 'close'); + return { + root, + child, + exit, + stderr: () => stderr, + marker: (name: string) => fs.existsSync(path.join(root, name)), + }; +} + +const ready = ` + fs.writeSync(1, '[auth-idp] http://fixture\\n'); + process.on('SIGTERM', () => { + fs.writeFileSync('provider-stopped', ''); + process.exit(0); + }); +`; + +test('the selected auth flow can finish while the provider writes more than a pipe buffer', async () => { + const lane = fixture( + ready + + ` + const pump = setInterval(() => { + if (!fs.existsSync('cli-started')) return; + clearInterval(pump); + const chunk = Buffer.alloc(65536, 120); + for (let i = 0; i < 128; i++) fs.writeSync(1, chunk); + fs.writeFileSync('provider-drained', ''); + }, 10); + setTimeout(() => process.exit(9), 5000); + `, + ` + fs.writeFileSync('argv', JSON.stringify(process.argv.slice(2))); + fs.writeFileSync('cli-started', ''); + const probe = setInterval(() => { + if (fs.existsSync('provider-drained')) process.exit(0); + }, 10); + setTimeout(() => { console.error('provider pipe did not drain'); process.exit(7); }, 3000); + `, + ); + assert.deepEqual(await lane.exit, [0, null], lane.stderr()); + assert.equal(lane.marker('provider-stopped'), true); + assert.deepEqual(JSON.parse(fs.readFileSync(path.join(lane.root, 'argv'), 'utf8')), [ + '--session', + 'test-app-maestro', + 'test', + path.join(lane.root, 'examples/test-app/maestro-ios/auth-session-sheet.yaml'), + '--maestro', + '--platform', + 'ios', + '--udid', + 'fixture', + ]); +}); + +test('an early provider failure prevents the suite from starting', async () => { + const lane = fixture('process.exit(3);', "fs.writeFileSync('cli-started', '');"); + assert.deepEqual(await lane.exit, [1, null], lane.stderr()); + assert.equal(lane.marker('cli-started'), false); +}); + +test('a failed suite stops the provider', async () => { + const lane = fixture(ready + 'setTimeout(() => process.exit(9), 5000);', 'process.exit(7);'); + assert.deepEqual(await lane.exit, [1, null], lane.stderr()); + assert.equal(lane.marker('provider-stopped'), true); +}); + +test.skipIf(process.platform === 'win32')( + 'cancellation stops the provider and the suite CLI', + async () => { + const lane = fixture( + ready + 'setTimeout(() => process.exit(9), 5000);', + ` + process.on('SIGTERM', () => { + fs.writeFileSync('cli-stopped', ''); + process.exit(0); + }); + fs.writeFileSync('cli-started', ''); + setTimeout(() => process.exit(8), 5000); + `, + ); + try { + await expect.poll(() => lane.marker('cli-started')).toBe(true); + } finally { + lane.child.kill('SIGTERM'); + } + assert.deepEqual(await lane.exit, [1, null], lane.stderr()); + assert.equal(lane.marker('provider-stopped'), true); + assert.equal(lane.marker('cli-stopped'), true); + }, + 8000, +); diff --git a/scripts/run-test-app-auth-session-lane.mjs b/scripts/run-test-app-auth-session-lane.mjs index 61ec2dc449..9927a06e67 100644 --- a/scripts/run-test-app-auth-session-lane.mjs +++ b/scripts/run-test-app-auth-session-lane.mjs @@ -1,78 +1,139 @@ #!/usr/bin/env node -// Runs the sign-in sheet lane: the fixture identity provider plus the Maestro flow that drives the -// ASWebAuthenticationSession sheet through it (#2449). -// -// pnpm test-app:maestro:auth:ios -// -// The identity provider is a separate process because the sheet's page is fetched by the hosted -// SafariViewService surface over the host's loopback interface, not by the app. This script owns -// that process: it starts before the flow, and the flow's exit — pass or fail — stops it. -// -// The flow needs a fixture app built with the AuthSessionLab module (examples/test-app/README.md). +// Run the read-only ASWebAuthenticationSession flow against the loopback fixture provider (#2449). // Pass extra agent-device arguments after `--`. -import { spawn, spawnSync } from 'node:child_process'; +import { spawn } from 'node:child_process'; import path from 'node:path'; import process from 'node:process'; +import { createInterface } from 'node:readline'; +import { setTimeout as delay } from 'node:timers/promises'; import { fileURLToPath } from 'node:url'; const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); -const flowDir = path.join(repoRoot, 'examples', 'test-app', 'maestro-ios'); +const flow = path.join(repoRoot, 'examples', 'test-app', 'maestro-ios', 'auth-session-sheet.yaml'); const idpScript = path.join(repoRoot, 'examples', 'test-app', 'scripts', 'serve-auth-idp.mjs'); +const suiteScript = path.join(repoRoot, 'scripts', 'run-test-app-maestro-suite.mjs'); const passthroughIndex = process.argv.indexOf('--'); const passthrough = passthroughIndex === -1 ? [] : process.argv.slice(passthroughIndex + 1); +const cleanupTimeoutMs = 5_000; -const idp = spawn(process.execPath, ['--experimental-strip-types', idpScript], { - cwd: repoRoot, - stdio: ['ignore', 'pipe', 'inherit'], -}); -idp.stdout.setEncoding('utf8'); +function watchChild(child, name) { + return new Promise((resolve, reject) => { + child.on('error', (error) => reject(new Error(`${name}: ${error.message}`))); + child.once('exit', (code, signal) => resolve({ code, signal })); + }); +} -// The IdP prints its listen line before it can serve the sheet. Waiting for that line keeps a slow -// start from being reported as an unserved sheet inside the flow. -await new Promise((resolve, reject) => { - const fail = (message) => reject(new Error(message)); - const timeout = setTimeout(() => fail('did not print its listen line within 15s'), 15_000); - const onData = (chunk) => { - if (!chunk.includes('[auth-idp] http')) return; - clearTimeout(timeout); - idp.stdout.removeListener('data', onData); - resolve(); - }; - idp.stdout.on('data', onData); - idp.once('error', (error) => { +async function waitForProvider(idp, exit) { + const lines = createInterface({ input: idp.stdout }); + let timeout; + try { + await Promise.race([ + new Promise((resolve, reject) => { + lines.on('line', (line) => { + if (line.startsWith('[auth-idp] http')) resolve(); + }); + lines.once('close', () => reject(new Error('provider stdout closed before readiness'))); + lines.once('error', reject); + timeout = setTimeout(() => reject(new Error('provider was not ready within 15s')), 15_000); + }), + exit.then(({ code, signal }) => { + throw new Error(`provider exited before readiness (${signal ?? code})`); + }), + ]); + } finally { clearTimeout(timeout); - fail(error.message); - }); - idp.once('exit', (code) => { + lines.close(); + idp.stdout.resume(); + } +} + +function signalSuite(child, signal) { + if (!child.pid) return false; + if (process.platform === 'win32') { + return child.exitCode === null && child.signalCode === null && child.kill(signal); + } + try { + process.kill(-child.pid, signal); + return true; + } catch (error) { + if (error.code === 'ESRCH') return false; + throw error; + } +} + +async function stopSuite(child, exit, signal) { + if (!signalSuite(child, signal)) return; + const deadline = Date.now() + cleanupTimeoutMs; + // The suite runner can exit before its agent-device child on cancellation. + while (signalSuite(child, 0)) { + if (Date.now() >= deadline) { + signalSuite(child, 'SIGKILL'); + break; + } + await delay(25); + } + await exit.catch(() => {}); +} + +async function stopProvider(child, exit, signal) { + if (!child.pid || child.exitCode !== null || child.signalCode !== null) return; + child.kill(signal); + const timeout = setTimeout(() => child.kill('SIGKILL'), cleanupTimeoutMs); + try { + await exit.catch(() => {}); + } finally { clearTimeout(timeout); - fail(`exited with code ${String(code)} before it started`); + } +} + +async function runLane() { + let suite; + let suiteExit; + let signal; + const { promise: cancellation, resolve: finishCancellation } = Promise.withResolvers(); + function cancel(received) { + signal ??= received; + finishCancellation(); + } + process.on('SIGINT', cancel); + process.on('SIGTERM', cancel); + const idp = spawn(process.execPath, ['--experimental-strip-types', idpScript], { + cwd: repoRoot, + stdio: ['ignore', 'pipe', 'inherit'], }); -}) - .then(() => { - // The flow runs through `spawnSync`, so this loop cannot keep reading the IdP while it runs. The - // IdP logs one line per request, and a pipe nobody reads fills up and blocks the IdP, which would - // stall the sheet's own fetch. `resume()` puts the stream in flowing mode and discards the output. - idp.stdout.resume(); - const suite = spawnSync( + const idpExit = watchChild(idp, 'fixture identity provider'); + try { + await Promise.race([waitForProvider(idp, idpExit), cancellation]); + if (signal) return 1; + // Keep the event loop draining the provider pipe while the suite runs. + suite = spawn( process.execPath, - [ - path.join(repoRoot, 'scripts', 'run-test-app-maestro-suite.mjs'), - '--flow-dir', - flowDir, - '--platform', - 'ios', - ...passthrough, - ], - { cwd: repoRoot, stdio: 'inherit' }, + [suiteScript, '--platform', 'ios', '--flow', flow, '--', ...passthrough], + { cwd: repoRoot, stdio: 'inherit', detached: process.platform !== 'win32' }, ); - process.exitCode = suite.signal ? 1 : (suite.status ?? 1); - }) - .catch((error) => { - console.error( - `[auth-session-lane] fixture identity provider ${error instanceof Error ? error.message : String(error)}`, - ); - process.exitCode = 1; - }) - .finally(() => { - if (idp.exitCode === null && !idp.killed) idp.kill('SIGTERM'); - }); + suiteExit = watchChild(suite, 'Maestro suite'); + const result = await Promise.race([ + suiteExit, + cancellation, + idpExit.then(({ code, signal }) => { + throw new Error(`provider exited during the suite (${signal ?? code})`); + }), + ]); + return result?.code ?? 1; + } catch (error) { + console.error(`[auth-session-lane] ${error.message}`); + return 1; + } finally { + try { + await Promise.all([ + stopProvider(idp, idpExit, signal ?? 'SIGTERM'), + suite && stopSuite(suite, suiteExit, signal ?? 'SIGTERM'), + ]); + } finally { + process.off('SIGINT', cancel); + process.off('SIGTERM', cancel); + } + } +} + +process.exitCode = await runLane(); diff --git a/scripts/run-test-app-maestro-suite.mjs b/scripts/run-test-app-maestro-suite.mjs index e2b4796070..68b486b68c 100644 --- a/scripts/run-test-app-maestro-suite.mjs +++ b/scripts/run-test-app-maestro-suite.mjs @@ -11,6 +11,7 @@ const options = { platform: 'ios', session: 'test-app-maestro', flowDir: path.join(repoRoot, 'examples', 'test-app', 'maestro'), + flow: undefined, close: false, passthrough: [], }; @@ -36,6 +37,11 @@ for (let index = 2; index < process.argv.length; index += 1) { index += 1; continue; } + if (arg === '--flow' && process.argv[index + 1]) { + options.flow = path.resolve(process.argv[index + 1]); + index += 1; + continue; + } if (arg === '--close') { options.close = true; continue; @@ -43,11 +49,13 @@ for (let index = 2; index < process.argv.length; index += 1) { options.passthrough.push(arg); } -const flows = fs - .readdirSync(options.flowDir) - .filter((entry) => entry.endsWith('.yaml') || entry.endsWith('.yml')) - .sort() - .map((entry) => path.join(options.flowDir, entry)); +const flows = options.flow + ? [options.flow] + : fs + .readdirSync(options.flowDir) + .filter((entry) => entry.endsWith('.yaml') || entry.endsWith('.yml')) + .sort() + .map((entry) => path.join(options.flowDir, entry)); if (flows.length === 0) { console.error(`No Maestro flows found in ${options.flowDir}`); diff --git a/vitest.config.ts b/vitest.config.ts index 0335d9caac..77dacc6226 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -151,6 +151,7 @@ export default defineConfig({ // The tooling send over real loopback daemons: in-process, no device. 'scripts/lib/recorded-daemon.test.ts', 'scripts/__tests__/vitest-slow-test-reporter.test.ts', + 'scripts/__tests__/auth-session-lane.test.ts', // Artifact guards assert on Swift sources, package.json, workflows, docs and examples rather // than on a module under src. 'test/repo-guards/*.test.ts', From 806f73c8c7c3d16214d6aad2faa3435d6c51243e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 18 Nov 2026 17:35:18 +0100 Subject: [PATCH 3/3] refactor(test-app): run the auth fixture server in the lane --- examples/test-app/README.md | 25 +++-- .../maestro-ios/auth-session-sheet.yaml | 21 +---- examples/test-app/scripts/serve-auth-idp.mjs | 94 +++++-------------- examples/test-app/src/auth-idp-fixture.ts | 18 +--- examples/test-app/src/auth-idp-server.mjs | 46 +++++++++ package.json | 2 +- scripts/__tests__/auth-session-lane.test.ts | 83 +++++----------- scripts/run-test-app-auth-session-lane.mjs | 69 ++------------ 8 files changed, 121 insertions(+), 237 deletions(-) create mode 100644 examples/test-app/src/auth-idp-server.mjs diff --git a/examples/test-app/README.md b/examples/test-app/README.md index 3bfe7a3990..7edda45d3e 100644 --- a/examples/test-app/README.md +++ b/examples/test-app/README.md @@ -356,22 +356,27 @@ Run the lane with the sheet's page served by the same script that owns its lifec pnpm test-app:maestro:auth:ios -- --udid "" ``` -That starts `examples/test-app/scripts/serve-auth-idp.mjs`, runs -`examples/test-app/maestro-ios/auth-session-sheet.yaml` -through `agent-device test --maestro`. The launcher stops the provider when the flow ends or you -cancel the lane. Start the provider yourself when you drive the sheet by hand. Add `--delay-ms ` -to hold the loading page so you can read the sheet while its page is still loading. The flow lives -in `maestro-ios/` rather than `maestro/` because the shared directory is also run on Android. +The launcher starts the provider at `127.0.0.1:4593` and runs +`examples/test-app/maestro-ios/auth-session-sheet.yaml` through `agent-device test --maestro`. When +the flow ends or you cancel it, the launcher closes the provider. + +To drive the sheet by hand and see its loading state, start the provider from the repo root: + +```bash +node --experimental-strip-types examples/test-app/scripts/serve-auth-idp.mjs --delay-ms 6000 +``` + +Omit `--delay-ms` to show the form immediately. The committed flow reads the sheet and stops at its form controls. Driving past that point is not committed, because on iOS 27.0 the same steps alternate between passing and refusing the capture, which is the intermittency #4593 reports. Fill the sheet's fields and submit it when you want that state, and expect to see one of three capture refusals on the step that follows the first `inputText` or the submit: `regular iOS snapshot presentation requires a valid viewport`, `regular iOS snapshot -node escaped its cumulative clip`, or `main thread execution timed out`. All three come from -`packages/capture-kit/src/ios-snapshot-engine/invariants.ts`, and the first carries no `retriable`, so -the step's own stability re-capture does not poll and the step aborts. A build of the fixture app -without the module shows `unavailable` in `auth-session-status` instead of opening a sheet. +node escaped its cumulative clip`, or `main thread execution timed out`. The first two come from +`packages/capture-kit/src/ios-snapshot-engine/invariants.ts`. The XCTest runner reports the third, which +`packages/apple-runner/src/runner-failure-diagnostics.ts` classifies. The viewport refusal carries no +`retriable` flag, so the step aborts during stability re-capture. The app needs a build that includes the module: a development client (`pnpm test-app:ios`) or a Release build (`pnpm --dir examples/test-app exec expo run:ios --configuration Release --device diff --git a/examples/test-app/maestro-ios/auth-session-sheet.yaml b/examples/test-app/maestro-ios/auth-session-sheet.yaml index 4346b2cd3b..9539eed2fa 100644 --- a/examples/test-app/maestro-ios/auth-session-sheet.yaml +++ b/examples/test-app/maestro-ios/auth-session-sheet.yaml @@ -1,26 +1,14 @@ appId: com.callstack.agentdevicelab name: Sign-in sheet -# Reads a real ASWebAuthenticationSession sheet, which iOS hosts out of process in -# com.apple.SafariViewService, while the app stays the foreground owner underneath it (#2449). The -# page comes from the fixture identity provider in src/auth-idp-fixture.ts, started by the lane script -# (`pnpm test-app:maestro:auth:ios`). It holds fixture values only, so no credential is involved. -# -# These assertions match the sheet's own page, which is what the runner's in-place read of the hosted -# surface has to keep producing (#2438). When that read regresses, or the sheet is not served, the -# first assertion below fails with the sheet's title missing. -# -# This flow reads the sheet and stops. Driving it further, with inputText or a submit, lands on the -# intermittent capture refusals #4593 reports; see examples/test-app/README.md for that sequence and -# the step-level signatures observed on iOS 27.0. +# Read SafariViewService in place while the app remains the accessibility primaryApp (#2438). +# Stop before typing or submitting, which can encounter the capture refusals in #4593. env: - # How long to wait for the sheet's page to serve the form. AUTH_SHEET_TIMEOUT: '20000' onFlowStart: - launchApp: clearState: true - assertVisible: Agent Device Tester --- -# Reaching the fixture screen: the Settings tab, then the lab's own entry. - tapOn: text: Settings - scrollUntilVisible: @@ -31,16 +19,11 @@ onFlowStart: - assertVisible: Sign-in sheet lab - assertVisible: id: auth-session-open -# Opening the sheet. iOS presents it over the app, in its own process, so from here on a capture reads -# the sheet's surface rather than the app's and no app row can be asserted. - tapOn: id: auth-session-open -# The sheet's page is served by the fixture identity provider. This is the assertion that fails when -# the sheet is not served, so it carries the lane's timeout: an unserved sheet must fail here. - extendedWaitUntil: visible: Fixture sign-in timeout: ${AUTH_SHEET_TIMEOUT} -# The hosted page's own controls, read in place. The form fields belong to the sheet, not the app. - assertVisible: text: Email - assertVisible: diff --git a/examples/test-app/scripts/serve-auth-idp.mjs b/examples/test-app/scripts/serve-auth-idp.mjs index 99308bc74a..7aeff817e6 100644 --- a/examples/test-app/scripts/serve-auth-idp.mjs +++ b/examples/test-app/scripts/serve-auth-idp.mjs @@ -1,74 +1,24 @@ #!/usr/bin/env node -// Serves the fixture identity provider page (#2449) over loopback for a lane. -// -// The sign-in sheet is opened by the app against this address, so the page travels through the real -// hosted SafariViewService surface and no external identity provider is involved. The page content -// lives in examples/test-app/src/auth-idp-fixture.ts, which is also what the Maestro flow asserts -// against. It holds fixture values only. -// -// node --experimental-strip-types examples/test-app/scripts/serve-auth-idp.mjs -// node --experimental-strip-types examples/test-app/scripts/serve-auth-idp.mjs --delay-ms 6000 -// -// `--host`, `--port`, and `--delay-ms` override the fixture identity provider's address and the time -// it holds the loading page. The lane starts this server; see scripts/run-test-app-auth-session-lane.mjs. -// -// Run it with `node --experimental-strip-types`, the repo's convention for a Node entry that imports -// TypeScript: the supported floor here is Node 22.12, where type stripping is still behind that flag. -import { createServer } from 'node:http'; -import path from 'node:path'; -import { fileURLToPath, pathToFileURL } from 'node:url'; - -const fixturePath = path.resolve( - path.dirname(fileURLToPath(import.meta.url)), - '..', - 'src', - 'auth-idp-fixture.ts', -); - -const args = process.argv.slice(2); -function readFlag(name, fallback) { - const index = args.indexOf(`--${name}`); - return index === -1 ? fallback : (args[index + 1] ?? fallback); -} - -const { AUTH_IDP_DEFAULT_PORT, AUTH_IDP_PATH, renderAuthIdpPage } = await import( - pathToFileURL(fixturePath).href -); - -const host = readFlag('host', '127.0.0.1'); -const port = Number(readFlag('port', String(AUTH_IDP_DEFAULT_PORT))); -const delayMs = Number(readFlag('delay-ms', '0')); - -let requests = 0; - -const server = createServer((request, response) => { - const url = new URL(request.url ?? '/', `http://${host}`); - if (url.pathname !== AUTH_IDP_PATH) { - response.writeHead(404, { 'content-type': 'text/plain' }); - response.end('not found\n'); - return; - } - - // Only the first request honours --delay-ms, so a lane can observe the sheet mid-load. A reload - // or a redirect must not sit in the loading state again. - const servedDelayMs = requests === 0 ? delayMs : 0; - const html = renderAuthIdpPage({ delayMs: servedDelayMs }); - requests += 1; - console.log(`[auth-idp] ${url.pathname} delayMs=${servedDelayMs}`); - response.writeHead(200, { - 'content-type': 'text/html; charset=utf-8', - 'content-length': Buffer.byteLength(html), - 'cache-control': 'no-store', - }); - response.end(html); -}); - -server.listen(port, host, () => { - console.log(`[auth-idp] http://${host}:${port}${AUTH_IDP_PATH} delayMs=${delayMs}`); -}); - -for (const signal of ['SIGINT', 'SIGTERM']) { - process.on(signal, () => { - server.close(() => process.exit(0)); - }); +import { AUTH_IDP_DEFAULT_URL } from '../src/auth-idp-fixture.ts'; +import { startAuthIdpServer } from '../src/auth-idp-server.mjs'; + +const [flag, value, ...rest] = process.argv.slice(2); +const delayMs = Number(value ?? 0); +if ( + flag !== undefined && + (flag !== '--delay-ms' || + !value?.trim() || + !Number.isFinite(delayMs) || + delayMs < 0 || + rest.length) +) { + console.error( + 'Usage: node --experimental-strip-types examples/test-app/scripts/serve-auth-idp.mjs [--delay-ms ]', + ); + process.exitCode = 1; +} else { + const provider = await startAuthIdpServer({ delayMs }); + console.log(`[auth-idp] ${AUTH_IDP_DEFAULT_URL} delayMs=${delayMs}`); + process.once('SIGINT', () => provider.close()); + process.once('SIGTERM', () => provider.close()); } diff --git a/examples/test-app/src/auth-idp-fixture.ts b/examples/test-app/src/auth-idp-fixture.ts index d324325604..c70727e649 100644 --- a/examples/test-app/src/auth-idp-fixture.ts +++ b/examples/test-app/src/auth-idp-fixture.ts @@ -1,21 +1,9 @@ -// The fixture identity provider for the sign-in sheet, and the single source of truth for the page -// the sheet shows. The content holds fixture values only: no credentials, no tokens, no client id. -// Submitting the form navigates to the app's own callback scheme, which is what ends the -// ASWebAuthenticationSession sheet and returns the app to the foreground. -// -// `scripts/serve-auth-idp.mjs` serves this page over loopback for a lane; the Maestro flow asserts -// against the same vocabulary. `delayMs` defers the real form, so a lane can observe the sheet while -// its page is still loading — the state #4593 reports from. - export const AUTH_IDP_DEFAULT_PORT = 4593; export const AUTH_IDP_PATH = '/auth-idp'; export const AUTH_IDP_DEFAULT_URL = `http://127.0.0.1:${AUTH_IDP_DEFAULT_PORT}${AUTH_IDP_PATH}`; -// The callback the fixture sheet ends on. `agent-device-test-app` is the scheme app.config.js -// registers and the one the session is opened with, so ASWebAuthenticationSession intercepts this -// navigation itself, ends the sheet, and hands the URL to the app. No route needs to serve it. export const AUTH_IDP_FIXTURE_REDIRECT = 'agent-device-test-app://auth-callback?code=fixture-code&state=fixture-state'; // The words a lane asserts on. Keep the Maestro flow and this page changed together. @@ -27,10 +15,8 @@ export const AUTH_IDP_TEXT = { submit: 'LOGIN', } as const; -// The form submits natively to the callback scheme. ASWebAuthenticationSession intercepts a -// navigation to that scheme when the submit originates it, and ignores the same navigation when page -// script asks for it with `location.assign`, so a script-driven submit leaves the sheet open. Verified -// on iOS 27.0. +// On iOS 27.0 the sheet intercepts native form submission to the callback scheme. +// Redirecting from page script with `location.assign` leaves the sheet open. export function renderAuthIdpPage(options: { delayMs?: number } = {}): string { const delayMs = options.delayMs ?? 0; if (delayMs > 0) { diff --git a/examples/test-app/src/auth-idp-server.mjs b/examples/test-app/src/auth-idp-server.mjs new file mode 100644 index 0000000000..33d0605a1a --- /dev/null +++ b/examples/test-app/src/auth-idp-server.mjs @@ -0,0 +1,46 @@ +import { once } from 'node:events'; +import { createServer } from 'node:http'; +import { AUTH_IDP_DEFAULT_URL, AUTH_IDP_PATH, renderAuthIdpPage } from './auth-idp-fixture.ts'; + +export async function startAuthIdpServer({ delayMs = 0 } = {}) { + let nextDelayMs = delayMs; + const server = createServer((request, response) => { + if (request.url?.split('?', 1)[0] !== AUTH_IDP_PATH) { + response.writeHead(404, { 'content-type': 'text/plain' }); + response.end('not found\n'); + return; + } + + const html = renderAuthIdpPage({ delayMs: nextDelayMs }); + nextDelayMs = 0; + response.writeHead(200, { + 'content-type': 'text/html; charset=utf-8', + 'content-length': Buffer.byteLength(html), + 'cache-control': 'no-store', + }); + response.end(html); + }); + + const url = new URL(AUTH_IDP_DEFAULT_URL); + const startup = new AbortController(); + const timeout = setTimeout( + () => startup.abort(new Error('provider was not ready within 15s')), + 15_000, + ); + try { + server.listen({ host: url.hostname, port: Number(url.port), signal: startup.signal }); + await once(server, 'listening', { signal: startup.signal }); + } finally { + clearTimeout(timeout); + } + + let closed; + return { + close() { + return (closed ??= new Promise((resolve, reject) => { + server.close((error) => (error ? reject(error) : resolve())); + server.closeAllConnections(); + })); + }, + }; +} diff --git a/package.json b/package.json index acddcfcb03..ee69ece4de 100644 --- a/package.json +++ b/package.json @@ -199,7 +199,7 @@ "test-app:maestro": "node scripts/run-test-app-maestro-suite.mjs", "test-app:maestro:ios": "pnpm test-app:maestro --platform ios", "test-app:maestro:android": "pnpm test-app:maestro --platform android", - "test-app:maestro:auth:ios": "node scripts/run-test-app-auth-session-lane.mjs", + "test-app:maestro:auth:ios": "node --experimental-strip-types scripts/run-test-app-auth-session-lane.mjs", "test": "pnpm test:unit", "test:unit": "vitest run --project unit-core --project apple-runner --project fuzz-worker", "test:maestro-compat": "vitest run --project unit-core packages/maestro src/compat/__tests__/replay-input.test.ts", diff --git a/scripts/__tests__/auth-session-lane.test.ts b/scripts/__tests__/auth-session-lane.test.ts index e41e7ec6d2..0739528b3a 100644 --- a/scripts/__tests__/auth-session-lane.test.ts +++ b/scripts/__tests__/auth-session-lane.test.ts @@ -3,17 +3,12 @@ import { spawn } from 'node:child_process'; import { once } from 'node:events'; import fs from 'node:fs'; import path from 'node:path'; -import { expect, test } from 'vitest'; +import { expect, onTestFinished, test } from 'vitest'; import { mkdtempForTestSync } from '@agent-device/test-kit'; -function fixture(provider: string, cli: string) { +function fixture(cli: string) { const root = fs.realpathSync(mkdtempForTestSync('agent-device-auth-lane-')); - for (const dir of [ - 'scripts', - 'bin', - 'examples/test-app/scripts', - 'examples/test-app/maestro-ios', - ]) { + for (const dir of ['scripts', 'bin', 'examples/test-app/src', 'examples/test-app/maestro-ios']) { fs.mkdirSync(path.join(root, dir), { recursive: true }); } for (const name of ['run-test-app-auth-session-lane.mjs', 'run-test-app-maestro-suite.mjs']) { @@ -23,15 +18,27 @@ function fixture(provider: string, cli: string) { fs.writeFileSync(path.join(root, 'examples/test-app/maestro-ios', name), ''); } const prelude = "import fs from 'node:fs';\n"; - fs.writeFileSync( - path.join(root, 'examples/test-app/scripts/serve-auth-idp.mjs'), - prelude + provider, + const source = path.join(import.meta.dirname, '../../examples/test-app/src'); + const fixtureDir = path.join(root, 'examples/test-app/src'); + fs.copyFileSync( + path.join(source, 'auth-idp-server.mjs'), + path.join(fixtureDir, 'auth-idp-server.mjs'), ); + const page = fs.readFileSync(path.join(source, 'auth-idp-fixture.ts'), 'utf8'); + const ephemeralPage = page.replace('AUTH_IDP_DEFAULT_PORT = 4593', 'AUTH_IDP_DEFAULT_PORT = 0'); + assert.notEqual(ephemeralPage, page); + fs.writeFileSync(path.join(fixtureDir, 'auth-idp-fixture.ts'), ephemeralPage); fs.writeFileSync(path.join(root, 'bin/agent-device.mjs'), prelude + cli); const child = spawn( process.execPath, - ['scripts/run-test-app-auth-session-lane.mjs', '--', '--udid', 'fixture'], + [ + '--experimental-strip-types', + 'scripts/run-test-app-auth-session-lane.mjs', + '--', + '--udid', + 'fixture', + ], { cwd: root, stdio: ['ignore', 'ignore', 'pipe'] }, ); let stderr = ''; @@ -39,6 +46,9 @@ function fixture(provider: string, cli: string) { stderr += chunk; }); const exit = once(child, 'close'); + onTestFinished(async () => { + if (child.kill('SIGKILL')) await exit; + }); return { root, child, @@ -48,38 +58,9 @@ function fixture(provider: string, cli: string) { }; } -const ready = ` - fs.writeSync(1, '[auth-idp] http://fixture\\n'); - process.on('SIGTERM', () => { - fs.writeFileSync('provider-stopped', ''); - process.exit(0); - }); -`; - -test('the selected auth flow can finish while the provider writes more than a pipe buffer', async () => { - const lane = fixture( - ready + - ` - const pump = setInterval(() => { - if (!fs.existsSync('cli-started')) return; - clearInterval(pump); - const chunk = Buffer.alloc(65536, 120); - for (let i = 0; i < 128; i++) fs.writeSync(1, chunk); - fs.writeFileSync('provider-drained', ''); - }, 10); - setTimeout(() => process.exit(9), 5000); - `, - ` - fs.writeFileSync('argv', JSON.stringify(process.argv.slice(2))); - fs.writeFileSync('cli-started', ''); - const probe = setInterval(() => { - if (fs.existsSync('provider-drained')) process.exit(0); - }, 10); - setTimeout(() => { console.error('provider pipe did not drain'); process.exit(7); }, 3000); - `, - ); +test('the lane runs only the sign-in sheet flow and closes its fixture server', async () => { + const lane = fixture("fs.writeFileSync('argv', JSON.stringify(process.argv.slice(2)));"); assert.deepEqual(await lane.exit, [0, null], lane.stderr()); - assert.equal(lane.marker('provider-stopped'), true); assert.deepEqual(JSON.parse(fs.readFileSync(path.join(lane.root, 'argv'), 'utf8')), [ '--session', 'test-app-maestro', @@ -93,23 +74,10 @@ test('the selected auth flow can finish while the provider writes more than a pi ]); }); -test('an early provider failure prevents the suite from starting', async () => { - const lane = fixture('process.exit(3);', "fs.writeFileSync('cli-started', '');"); - assert.deepEqual(await lane.exit, [1, null], lane.stderr()); - assert.equal(lane.marker('cli-started'), false); -}); - -test('a failed suite stops the provider', async () => { - const lane = fixture(ready + 'setTimeout(() => process.exit(9), 5000);', 'process.exit(7);'); - assert.deepEqual(await lane.exit, [1, null], lane.stderr()); - assert.equal(lane.marker('provider-stopped'), true); -}); - test.skipIf(process.platform === 'win32')( - 'cancellation stops the provider and the suite CLI', + 'cancellation closes the fixture server and stops the suite CLI', async () => { const lane = fixture( - ready + 'setTimeout(() => process.exit(9), 5000);', ` process.on('SIGTERM', () => { fs.writeFileSync('cli-stopped', ''); @@ -125,7 +93,6 @@ test.skipIf(process.platform === 'win32')( lane.child.kill('SIGTERM'); } assert.deepEqual(await lane.exit, [1, null], lane.stderr()); - assert.equal(lane.marker('provider-stopped'), true); assert.equal(lane.marker('cli-stopped'), true); }, 8000, diff --git a/scripts/run-test-app-auth-session-lane.mjs b/scripts/run-test-app-auth-session-lane.mjs index 9927a06e67..4313cffb16 100644 --- a/scripts/run-test-app-auth-session-lane.mjs +++ b/scripts/run-test-app-auth-session-lane.mjs @@ -2,51 +2,20 @@ // Run the read-only ASWebAuthenticationSession flow against the loopback fixture provider (#2449). // Pass extra agent-device arguments after `--`. import { spawn } from 'node:child_process'; +import { once } from 'node:events'; import path from 'node:path'; import process from 'node:process'; -import { createInterface } from 'node:readline'; import { setTimeout as delay } from 'node:timers/promises'; import { fileURLToPath } from 'node:url'; +import { startAuthIdpServer } from '../examples/test-app/src/auth-idp-server.mjs'; const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); const flow = path.join(repoRoot, 'examples', 'test-app', 'maestro-ios', 'auth-session-sheet.yaml'); -const idpScript = path.join(repoRoot, 'examples', 'test-app', 'scripts', 'serve-auth-idp.mjs'); const suiteScript = path.join(repoRoot, 'scripts', 'run-test-app-maestro-suite.mjs'); const passthroughIndex = process.argv.indexOf('--'); const passthrough = passthroughIndex === -1 ? [] : process.argv.slice(passthroughIndex + 1); const cleanupTimeoutMs = 5_000; -function watchChild(child, name) { - return new Promise((resolve, reject) => { - child.on('error', (error) => reject(new Error(`${name}: ${error.message}`))); - child.once('exit', (code, signal) => resolve({ code, signal })); - }); -} - -async function waitForProvider(idp, exit) { - const lines = createInterface({ input: idp.stdout }); - let timeout; - try { - await Promise.race([ - new Promise((resolve, reject) => { - lines.on('line', (line) => { - if (line.startsWith('[auth-idp] http')) resolve(); - }); - lines.once('close', () => reject(new Error('provider stdout closed before readiness'))); - lines.once('error', reject); - timeout = setTimeout(() => reject(new Error('provider was not ready within 15s')), 15_000); - }), - exit.then(({ code, signal }) => { - throw new Error(`provider exited before readiness (${signal ?? code})`); - }), - ]); - } finally { - clearTimeout(timeout); - lines.close(); - idp.stdout.resume(); - } -} - function signalSuite(child, signal) { if (!child.pid) return false; if (process.platform === 'win32') { @@ -75,18 +44,8 @@ async function stopSuite(child, exit, signal) { await exit.catch(() => {}); } -async function stopProvider(child, exit, signal) { - if (!child.pid || child.exitCode !== null || child.signalCode !== null) return; - child.kill(signal); - const timeout = setTimeout(() => child.kill('SIGKILL'), cleanupTimeoutMs); - try { - await exit.catch(() => {}); - } finally { - clearTimeout(timeout); - } -} - async function runLane() { + let provider; let suite; let suiteExit; let signal; @@ -97,36 +56,24 @@ async function runLane() { } process.on('SIGINT', cancel); process.on('SIGTERM', cancel); - const idp = spawn(process.execPath, ['--experimental-strip-types', idpScript], { - cwd: repoRoot, - stdio: ['ignore', 'pipe', 'inherit'], - }); - const idpExit = watchChild(idp, 'fixture identity provider'); try { - await Promise.race([waitForProvider(idp, idpExit), cancellation]); + provider = await startAuthIdpServer(); if (signal) return 1; - // Keep the event loop draining the provider pipe while the suite runs. suite = spawn( process.execPath, [suiteScript, '--platform', 'ios', '--flow', flow, '--', ...passthrough], { cwd: repoRoot, stdio: 'inherit', detached: process.platform !== 'win32' }, ); - suiteExit = watchChild(suite, 'Maestro suite'); - const result = await Promise.race([ - suiteExit, - cancellation, - idpExit.then(({ code, signal }) => { - throw new Error(`provider exited during the suite (${signal ?? code})`); - }), - ]); - return result?.code ?? 1; + suiteExit = once(suite, 'exit'); + const result = await Promise.race([suiteExit, cancellation]); + return result?.[0] ?? 1; } catch (error) { console.error(`[auth-session-lane] ${error.message}`); return 1; } finally { try { await Promise.all([ - stopProvider(idp, idpExit, signal ?? 'SIGTERM'), + provider?.close(), suite && stopSuite(suite, suiteExit, signal ?? 'SIGTERM'), ]); } finally {