From 6daafe329168e40b35802cb65766a0eab6c479a7 Mon Sep 17 00:00:00 2001 From: David Calhoun Date: Fri, 13 Nov 2026 10:23:46 -0500 Subject: [PATCH 1/7] fix: send the native scheme caller token from the page Native code will require a per-session token on the gbk-rest: and gbk-upload: schemes so only the editor page can use them (CMM-2462). The fetch relay, XHR relay, and native upload calls send it when GBKit provides one. Co-Authored-By: Claude Opus 5.5 --- src/utils/api-fetch-upload-scheme.test.js | 65 ++++++++++++++ src/utils/api-fetch.js | 100 ++++++++++++++-------- src/utils/bridge.js | 3 +- src/utils/fetch-relay.js | 10 +++ src/utils/fetch-relay.test.js | 38 ++++++++ src/utils/xhr-relay.js | 19 +++- src/utils/xhr-relay.test.js | 42 +++++++++ 7 files changed, 237 insertions(+), 40 deletions(-) diff --git a/src/utils/api-fetch-upload-scheme.test.js b/src/utils/api-fetch-upload-scheme.test.js index 4942fa47f..d712b1703 100644 --- a/src/utils/api-fetch-upload-scheme.test.js +++ b/src/utils/api-fetch-upload-scheme.test.js @@ -350,6 +350,71 @@ describe( 'nativeMediaUploadMiddleware over the native upload scheme', () => { } ); } ); + describe( 'caller token', () => { + const tokenHeader = ( request ) => + new Headers( request.init.headers ).get( 'Relay-Authorization' ); + + beforeEach( () => { + getGBKit.mockReturnValue( { + nativeUploadScheme: 'gbk-upload', + nativeUploadToken: 'caller-token', + } ); + } ); + + it( 'sends the token native code requires with every upload request', async () => { + const requests = installScheme(); + const file = new File( + [ new Uint8Array( NATIVE_UPLOAD_CHUNK_SIZE + 1 ) ], + 'a.jpg' + ); + + await nativeMediaUploadMiddleware( + makeOptions( file ), + makeNext() + ); + + expect( requests ).toHaveLength( 4 ); + for ( const request of requests ) { + expect( tokenHeader( request ) ).toBe( 'Bearer caller-token' ); + } + expect( + new Headers( requests[ 0 ].init.headers ).get( 'Content-Type' ) + ).toBe( 'application/json' ); + } ); + + it( 'sends it when cancelling a session', async () => { + const requests = installScheme( { + [ `/sessions/${ SESSION }/chunks` ]: () => + json( 409, { code: 'native_upload_offset_mismatch' } ), + } ); + + await nativeMediaUploadMiddleware( + makeOptions( new File( [ 'x' ], 'a.jpg' ) ), + makeNext() + ).catch( () => {} ); + + const cancel = requests.find( ( r ) => + r.path.endsWith( '/cancel' ) + ); + expect( tokenHeader( cancel ) ).toBe( 'Bearer caller-token' ); + } ); + + it( 'sends it with a media deletion', async () => { + const requests = installScheme( { + '/media/42/delete': () => json( 200, { deleted: true } ), + } ); + + await nativeMediaUploadMiddleware( + { method: 'DELETE', path: '/wp/v2/media/42' }, + makeNext() + ); + + expect( tokenHeader( requests[ 0 ] ) ).toBe( + 'Bearer caller-token' + ); + } ); + } ); + describe( 'transport selection and deletion', () => { it( 'prefers the scheme over a loopback server', async () => { getGBKit.mockReturnValue( { diff --git a/src/utils/api-fetch.js b/src/utils/api-fetch.js index dae0b958d..b8844a8d9 100644 --- a/src/utils/api-fetch.js +++ b/src/utils/api-fetch.js @@ -3,6 +3,7 @@ import { store as coreStore } from '@wordpress/core-data'; import { select } from '@wordpress/data'; import { __ } from '@wordpress/i18n'; import { getGBKit, getPostPath, getPostReference } from './bridge'; +import { CALLER_TOKEN_HEADER } from './fetch-relay'; import { info, warn, error as logError } from './logger'; import { ensureTrailingSlash, stripTrailingSlash } from './url'; @@ -328,7 +329,7 @@ export function nativeMediaUploadMiddleware( options, next ) { * @typedef {Object} NativeUploadTransport * @property {?string} schemeBase The base URL of the native upload scheme (iOS). * @property {?number} port The loopback upload server's port (Android). - * @property {?string} token The loopback upload server's token (Android). + * @property {?string} token The token native code requires on every request. */ /** @@ -343,7 +344,10 @@ export function nativeMediaUploadMiddleware( options, next ) { function nativeUploadTransport( gbkit ) { const { nativeUploadScheme, nativeUploadPort, nativeUploadToken } = gbkit; if ( nativeUploadScheme ) { - return { schemeBase: `${ nativeUploadScheme }://upload` }; + return { + schemeBase: `${ nativeUploadScheme }://upload`, + token: nativeUploadToken, + }; } if ( nativeUploadPort && nativeUploadToken ) { return { port: nativeUploadPort, token: nativeUploadToken }; @@ -392,7 +396,7 @@ function nativeMediaUpload( options, transport ) { const query = requestQuery( options.path ); const upload = transport.schemeBase - ? schemeUpload( options, file, query, transport.schemeBase ) + ? schemeUpload( options, file, query, transport ) : loopbackUpload( options, file, query, transport ); // Use the two-argument form of `.then()` so the rejection handler catches @@ -419,14 +423,23 @@ function loopbackUpload( options, file, query, { port, token } ) { ); return fetch( `http://localhost:${ port }/upload${ query }`, { method: 'POST', - headers: { - 'Relay-Authorization': `Bearer ${ token }`, - }, + headers: callerTokenHeader( token ), body: options.body, signal: options.signal, } ); } +/** + * The header that carries native code's caller token. Without it, native code + * refuses the request. + * + * @param {?string} token The token, from `GBKit`. + * @return {Object} The header, or none when the host gave no token. + */ +function callerTokenHeader( token ) { + return token ? { [ CALLER_TOKEN_HEADER ]: `Bearer ${ token }` } : {}; +} + /** * Sends an upload to iOS's native upload scheme. * @@ -442,20 +455,20 @@ function loopbackUpload( options, file, query, { port, token } ) { * REST relay, which holds the whole file in memory, enough to get the web view * killed over a large video. * - * @param {Object} options The api-fetch options. - * @param {File} file The file being uploaded. - * @param {string} query The request's query string. - * @param {string} schemeBase The native upload scheme's base URL. + * @param {Object} options The api-fetch options. + * @param {File} file The file being uploaded. + * @param {string} query The request's query string. + * @param {NativeUploadTransport} transport The native upload scheme's base URL and token. * @return {Promise} WordPress's response, or native code's refusal. */ -async function schemeUpload( options, file, query, schemeBase ) { +async function schemeUpload( options, file, query, transport ) { const { signal } = options; info( `Routing upload of ${ file.name } through the native upload scheme` ); let sessionId = null; try { - sessionId = await beginNativeUpload( schemeBase, file, signal ); + sessionId = await beginNativeUpload( transport, file, signal ); for ( let offset = 0; offset < file.size; @@ -465,15 +478,16 @@ async function schemeUpload( options, file, query, schemeBase ) { .slice( offset, offset + NATIVE_UPLOAD_CHUNK_SIZE ) .arrayBuffer(); await expectOk( - fetch( - `${ schemeBase }/sessions/${ sessionId }/chunks?offset=${ offset }`, + schemeFetch( + transport, + `/sessions/${ sessionId }/chunks?offset=${ offset }`, { method: 'POST', body: chunk, signal } ) ); } } catch ( sendError ) { if ( sessionId ) { - cancelNativeUpload( schemeBase, sessionId ); + cancelNativeUpload( transport, sessionId ); } if ( sendError instanceof Response && ! signal?.aborted ) { return sendError; @@ -482,7 +496,7 @@ async function schemeUpload( options, file, query, schemeBase ) { } return finishNativeUpload( - schemeBase, + transport, sessionId, uploadFields( options.body ), query, @@ -493,14 +507,14 @@ async function schemeUpload( options, file, query, schemeBase ) { /** * Starts a native upload session for `file` and returns its ID. * - * @param {string} schemeBase The native upload scheme's base URL. - * @param {File} file The file to upload. - * @param {?AbortSignal} signal Cancels the request. + * @param {NativeUploadTransport} transport The native upload scheme. + * @param {File} file The file to upload. + * @param {?AbortSignal} signal Cancels the request. * @return {Promise} The session ID. */ -async function beginNativeUpload( schemeBase, file, signal ) { +async function beginNativeUpload( transport, file, signal ) { const response = await expectOk( - fetch( `${ schemeBase }/sessions`, { + schemeFetch( transport, '/sessions', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify( { @@ -515,19 +529,35 @@ async function beginNativeUpload( schemeBase, file, signal ) { return id; } +/** + * Sends a request to iOS's native upload scheme, with the caller token native + * code requires. + * + * @param {NativeUploadTransport} transport The native upload scheme. + * @param {string} path The path below the scheme's base URL. + * @param {Object} init The request's options, as `fetch` takes them. + * @return {Promise} Native code's response. + */ +function schemeFetch( transport, path, init ) { + return fetch( `${ transport.schemeBase }${ path }`, { + ...init, + headers: { ...init.headers, ...callerTokenHeader( transport.token ) }, + } ); +} + /** * Asks native code to upload a session's file to WordPress, and returns * WordPress's response. * - * @param {string} schemeBase The native upload scheme's base URL. - * @param {string} sessionId The session to finish. - * @param {Array} fields The upload's form fields. - * @param {string} query The request's query string. - * @param {?AbortSignal} signal Cancels the upload. + * @param {NativeUploadTransport} transport The native upload scheme. + * @param {string} sessionId The session to finish. + * @param {Array} fields The upload's form fields. + * @param {string} query The request's query string. + * @param {?AbortSignal} signal Cancels the upload. * @return {Promise} WordPress's response, relayed. */ -function finishNativeUpload( schemeBase, sessionId, fields, query, signal ) { - return fetch( `${ schemeBase }/sessions/${ sessionId }/finish`, { +function finishNativeUpload( transport, sessionId, fields, query, signal ) { + return schemeFetch( transport, `/sessions/${ sessionId }/finish`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify( { fields, query } ), @@ -539,11 +569,11 @@ function finishNativeUpload( schemeBase, sessionId, fields, query, signal ) { * Abandons a native upload session, best effort: native code also sweeps idle * sessions, so a cancel that doesn't arrive only delays the cleanup. * - * @param {string} schemeBase The native upload scheme's base URL. - * @param {string} sessionId The session to abandon. + * @param {NativeUploadTransport} transport The native upload scheme. + * @param {string} sessionId The session to abandon. */ -function cancelNativeUpload( schemeBase, sessionId ) { - fetch( `${ schemeBase }/sessions/${ sessionId }/cancel`, { +function cancelNativeUpload( transport, sessionId ) { + schemeFetch( transport, `/sessions/${ sessionId }/cancel`, { method: 'POST', } ).catch( () => {} ); } @@ -689,7 +719,7 @@ function nativeMediaDelete( options, transport, next ) { ); const request = transport.schemeBase - ? fetch( `${ transport.schemeBase }/media/${ attachmentId }/delete`, { + ? schemeFetch( transport, `/media/${ attachmentId }/delete`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify( { query } ), @@ -699,9 +729,7 @@ function nativeMediaDelete( options, transport, next ) { `http://localhost:${ transport.port }/media/${ attachmentId }${ query }`, { method: 'DELETE', - headers: { - 'Relay-Authorization': `Bearer ${ transport.token }`, - }, + headers: callerTokenHeader( transport.token ), signal: options.signal, } ); diff --git a/src/utils/bridge.js b/src/utils/bridge.js index 62e0952dd..d3dbe930b 100644 --- a/src/utils/bridge.js +++ b/src/utils/bridge.js @@ -260,7 +260,7 @@ export function onNetworkRequest( requestData ) { * @property {boolean} [enableNetworkLogging] Enables logging of all network requests/responses to the native host via onNetworkRequest bridge method. * @property {string} [nativeUploadScheme] iOS: the URL scheme native media uploads are sent over. Takes precedence over the loopback server. * @property {number} [nativeUploadPort] Android: port the local HTTP server is listening on. If absent, the native upload override is not activated. - * @property {string} [nativeUploadToken] Android: per-session auth token for requests to the local upload server. + * @property {string} [nativeUploadToken] Per-session token every native upload request must carry: to the upload scheme (iOS) or the local upload server (Android). * @property {RestRelay} [restRelay] iOS: where native code relays the page's requests. If absent, requests go straight from the page. */ @@ -270,6 +270,7 @@ export function onNetworkRequest( requestData ) { * @typedef {Object} RestRelay * @property {string} endpoint The URL each request to another origin is sent to, with that request's URL in the `url` query parameter. * @property {boolean} [reportsRequests] Whether native code reports each relayed request to the host itself, so the page leaves it out of its network log. + * @property {string} [token] Per-session token every relayed request must carry. */ /** diff --git a/src/utils/fetch-relay.js b/src/utils/fetch-relay.js index 1193a3aed..59ccd241b 100644 --- a/src/utils/fetch-relay.js +++ b/src/utils/fetch-relay.js @@ -1,6 +1,9 @@ import { getGBKit } from './bridge'; import { debug } from './logger'; +/** The request header that carries the relay's caller token. */ +export const CALLER_TOKEN_HEADER = 'Relay-Authorization'; + /** * The relay wrapper for the host's configuration, or `null` when the host is * not running a relay. @@ -37,6 +40,10 @@ export function createRelayFetchWrapper() { * request goes, so which hosts get the site credential is decided here, on the * page. * + * Each relayed request carries `restRelay.token` in `CALLER_TOKEN_HEADER`. + * Native code refuses a request without it, so only callers that can read the + * page's `GBKit` can use the relay. + * * The relay wraps `fetch` rather than registering an api-fetch middleware or * fetch handler, either of which would replace api-fetch's own request building * and response parsing — the `data`-to-body serialization, the method override, @@ -78,6 +85,9 @@ export function createRelayFetch( next, { restRelay } ) { const headers = new Headers( request ? request.headers : init?.headers ); + if ( restRelay.token ) { + headers.set( CALLER_TOKEN_HEADER, `Bearer ${ restRelay.token }` ); + } // A `Request`'s body is read whole into an `ArrayBuffer`, the form // WebKit delivers to a scheme handler; see `bufferedBody`. const body = request diff --git a/src/utils/fetch-relay.test.js b/src/utils/fetch-relay.test.js index ae42615c1..08b593864 100644 --- a/src/utils/fetch-relay.test.js +++ b/src/utils/fetch-relay.test.js @@ -87,6 +87,35 @@ describe( 'createRelayFetch', () => { expect( init.credentials ).toBe( 'omit' ); } ); + it( 'sends the caller token native code requires, over any the caller set', async () => { + const relayFetchWithToken = createRelayFetch( next, { + restRelay: { ...REST_RELAY, token: 'caller-token' }, + } ); + + await relayFetchWithToken( + 'https://example.com/wp-json/wp/v2/posts', + { headers: { 'Relay-Authorization': 'Bearer guess' } } + ); + await relayFetchWithToken( + new Request( 'https://example.com/wp-json/wp/v2/users/me' ) + ); + + for ( const [ , init ] of next.mock.calls ) { + expect( + new Headers( init.headers ).get( 'Relay-Authorization' ) + ).toBe( 'Bearer caller-token' ); + } + } ); + + it( 'sends no caller token when the host gave none', async () => { + await relayFetch()( 'https://example.com/wp-json/wp/v2/posts' ); + + const init = next.mock.calls[ 0 ][ 1 ]; + expect( + new Headers( init.headers ).has( 'Relay-Authorization' ) + ).toBe( false ); + } ); + it( 'sends the whole URL, query and all', async () => { await relayFetch()( 'https://example.org/api?q=a%20b&tags=x,y' ); @@ -236,6 +265,15 @@ describe( 'createRelayFetch', () => { expect( next ).toHaveBeenCalledWith( input, undefined ); } + it( "a request to the page's own origin, without the caller token", async () => { + const url = `${ window.location.origin }/local.json`; + await createRelayFetch( next, { + restRelay: { ...REST_RELAY, token: 'caller-token' }, + } )( url ); + + expect( next ).toHaveBeenCalledWith( url, undefined ); + } ); + it( 'a request to native code itself', async () => { await expectPassthrough( 'gbk-upload://upload/sessions' ); await expectPassthrough( diff --git a/src/utils/xhr-relay.js b/src/utils/xhr-relay.js index c456cef8f..9219736bf 100644 --- a/src/utils/xhr-relay.js +++ b/src/utils/xhr-relay.js @@ -1,6 +1,11 @@ import { getGBKit } from './bridge'; import { debug, warn } from './logger'; -import { bufferedBody, isRelayed, relayURL } from './fetch-relay'; +import { + CALLER_TOKEN_HEADER, + bufferedBody, + isRelayed, + relayURL, +} from './fetch-relay'; /** * Marks the relaying `XMLHttpRequest` as ours. Registered globally so a second @@ -313,6 +318,14 @@ export function createRelayXMLHttpRequest( Base, { restRelay } ) { // listeners open the request again. this.#sent = true; + // Native code refuses a relayed request without it. + if ( restRelay.token ) { + super.setRequestHeader( + CALLER_TOKEN_HEADER, + `Bearer ${ restRelay.token }` + ); + } + if ( ! this.#async ) { if ( ! isReadBeforeSending( sent ) ) { for ( const type of this.#contentTypes ) { @@ -499,8 +512,8 @@ export function createRelayXMLHttpRequest( Base, { restRelay } ) { // empty body. this.#uploadSize = size === 0 ? undefined : size; if ( this.#uploadSize !== undefined ) { - // Hard to guess: any frame can reach the relay, and native code - // reports the name it is given to this page. + // Hard to guess: native code reports the name it is given to + // this page. this.#uploadID = crypto .getRandomValues( new Uint32Array( 4 ) ) .join( '-' ); diff --git a/src/utils/xhr-relay.test.js b/src/utils/xhr-relay.test.js index eae67d47e..52c91581d 100644 --- a/src/utils/xhr-relay.test.js +++ b/src/utils/xhr-relay.test.js @@ -510,6 +510,48 @@ describe( 'createRelayXMLHttpRequest', () => { } ); } ); + describe( 'caller token', () => { + const TokenRelayXMLHttpRequest = createRelayXMLHttpRequest( + FakeXMLHttpRequest, + { restRelay: { ...REST_RELAY, token: 'caller-token' } } + ); + const TOKEN_HEADER = [ 'Relay-Authorization', 'Bearer caller-token' ]; + + it( 'sends the token native code requires with a relayed request', () => { + const xhr = new TokenRelayXMLHttpRequest(); + xhr.open( 'GET', 'https://example.org/a' ); + xhr.send(); + + expect( xhr.headersSet() ).toEqual( [ TOKEN_HEADER ] ); + } ); + + it( 'sends it with a body read before sending', async () => { + const xhr = new TokenRelayXMLHttpRequest(); + xhr.open( 'POST', 'https://example.org/upload' ); + xhr.send( new NodeBlob( [ 'x' ] ) ); + await settle(); + + expect( xhr.headersSet() ).toContainEqual( TOKEN_HEADER ); + expect( xhr.callsTo( 'send' ) ).toHaveLength( 1 ); + } ); + + it( 'sends it with a synchronous request', () => { + const xhr = new TokenRelayXMLHttpRequest(); + xhr.open( 'POST', 'https://example.org/a', false ); + xhr.send( 'body' ); + + expect( xhr.headersSet() ).toEqual( [ TOKEN_HEADER ] ); + } ); + + it( "doesn't send it with a request that isn't relayed", () => { + const xhr = new TokenRelayXMLHttpRequest(); + xhr.open( 'GET', `${ window.location.origin }/local.json` ); + xhr.send(); + + expect( xhr.headersSet() ).toEqual( [] ); + } ); + } ); + describe( 'timeout', () => { it( 'tells native code the timeout, which WebKit does not apply', () => { const xhr = new RelayXMLHttpRequest(); From 2ea9f7b5bcd2b1485b198b6265f5262444b2f946 Mon Sep 17 00:00:00 2001 From: David Calhoun Date: Fri, 13 Nov 2026 10:29:50 -0500 Subject: [PATCH 2/7] fix(ios): require a caller token on the native schemes Require a per-session token, given only to the editor page in GBKit, on every gbk-rest: and gbk-upload: request. Mirrors Android's loopback upload server (CMM-2462). Co-Authored-By: Claude Opus 5.5 --- .../Sources/EditorViewController.swift | 25 ++++-- .../Media/MediaUploadSchemeHandler.swift | 18 +++- .../Sources/Media/RestRelay.swift | 17 ++-- .../Media/RestRelaySchemeHandler.swift | 25 +++++- .../Sources/Media/SchemeCallerToken.swift | 53 ++++++++++++ .../Sources/Model/GBKitGlobal.swift | 15 +++- ...itorViewControllerMediaTeardownTests.swift | 14 ++- .../Media/MediaUploadSchemeHandlerTests.swift | 86 +++++++++++++++++-- .../Media/RestRelayHandleTests.swift | 50 ++++++++--- .../Media/SchemeCallerTokenTests.swift | 45 ++++++++++ .../XMLHttpRequestRelayLifecycleTests.swift | 37 +++++--- .../Model/GBKitGlobalTests.swift | 26 ++++++ 12 files changed, 350 insertions(+), 61 deletions(-) create mode 100644 ios/Sources/GutenbergKit/Sources/Media/SchemeCallerToken.swift create mode 100644 ios/Tests/GutenbergKitTests/Media/SchemeCallerTokenTests.swift diff --git a/ios/Sources/GutenbergKit/Sources/EditorViewController.swift b/ios/Sources/GutenbergKit/Sources/EditorViewController.swift index 672ef647a..6a6d2b0fe 100644 --- a/ios/Sources/GutenbergKit/Sources/EditorViewController.swift +++ b/ios/Sources/GutenbergKit/Sources/EditorViewController.swift @@ -196,6 +196,8 @@ public final class EditorViewController: UIViewController, GutenbergEditorContro let mediaUploadSchemeHandler: MediaUploadSchemeHandler /// Relays the page's requests to other origins over `gbk-rest:`. let restRelaySchemeHandler: RestRelaySchemeHandler + /// The token both scheme handlers require. Given only to the editor page, in `GBKit`. + let schemeCallerToken = SchemeCallerToken() // MARK: - Private Properties (UI) @@ -321,19 +323,25 @@ public final class EditorViewController: UIViewController, GutenbergEditorContro config.setURLSchemeHandler(MediaFileSchemeHandler(), forURLScheme: MediaFileSchemeHandler.scheme) // The page sends the site's REST API requests here for native code to relay. - let relayHandler = RestRelaySchemeHandler(relay: RestRelay(configuration: configuration, observer: httpClient.delegate)) + let relayHandler = RestRelaySchemeHandler( + relay: RestRelay(configuration: configuration, observer: httpClient.delegate), + callerToken: schemeCallerToken + ) self.restRelaySchemeHandler = relayHandler config.setURLSchemeHandler(relayHandler, forURLScheme: RestRelaySchemeHandler.scheme) // Scheme handlers can only be registered before the web view exists, so the // upload handler is built here, from what the host handed over, even though the // page won't use it until it loads. - let uploadHandler = MediaUploadSchemeHandler(service: Self.makeMediaUploadService( - configuration: configuration, - httpClient: httpClient, - processor: mediaProcessor, - uploader: mediaUploader - )) + let uploadHandler = MediaUploadSchemeHandler( + service: Self.makeMediaUploadService( + configuration: configuration, + httpClient: httpClient, + processor: mediaProcessor, + uploader: mediaUploader + ), + callerToken: schemeCallerToken + ) self.mediaUploadSchemeHandler = uploadHandler config.setURLSchemeHandler(uploadHandler, forURLScheme: MediaUploadSchemeHandler.scheme) @@ -559,7 +567,8 @@ public final class EditorViewController: UIViewController, GutenbergEditorContro dependencies: dependencies, nativeUploadScheme: mediaUploadSchemeHandler.isEnabled ? MediaUploadSchemeHandler.scheme : nil, restRelayEndpoint: RestRelaySchemeHandler.endpoint, - restRelayReportsRequests: relayObserver != nil + restRelayReportsRequests: relayObserver != nil, + schemeCallerToken: schemeCallerToken.value ) return WKUserScript( source: Self.configurationScript(gbkitGlobal: try gbkitGlobal.toString()), diff --git a/ios/Sources/GutenbergKit/Sources/Media/MediaUploadSchemeHandler.swift b/ios/Sources/GutenbergKit/Sources/Media/MediaUploadSchemeHandler.swift index 4726ab648..2233c9772 100644 --- a/ios/Sources/GutenbergKit/Sources/Media/MediaUploadSchemeHandler.swift +++ b/ios/Sources/GutenbergKit/Sources/Media/MediaUploadSchemeHandler.swift @@ -19,9 +19,8 @@ import WebKit /// | `POST …/sessions//cancel` | — | `204` | /// | `POST …/media//delete` | JSON `{query}` | WordPress's response, verbatim | /// -/// The scheme doesn't check who is calling: every frame in the editor's web view can load -/// it, not only the editor page. Why that is left as it is: "Who can use the schemes" in -/// `docs/code/media-uploads.md`. +/// A request must carry the editor's ``SchemeCallerToken``. One without it gets a `401` +/// before it is routed, so it can't create, finish, or cancel a session, or delete media. /// /// Every response carries CORS headers: under Lockdown Mode WebKit enforces CORS on /// scheme responses too, and core's upload middleware reads @@ -36,13 +35,21 @@ final class MediaUploadSchemeHandler: NSObject, WKURLSchemeHandler { let store: MediaUploadSessionStore private var service: (any MediaUploading)? + /// The token every request must carry. + private let callerToken: SchemeCallerToken + /// Whether ``disable()`` has run, which nothing undoes. private var isDisabled = false private var active = ActiveSchemeTasks() - init(service: (any MediaUploading)?, store: MediaUploadSessionStore = MediaUploadSessionStore()) { + init( + service: (any MediaUploading)?, + callerToken: SchemeCallerToken, + store: MediaUploadSessionStore = MediaUploadSessionStore() + ) { self.service = service + self.callerToken = callerToken self.store = store super.init() // The handler is made with the editor, in the foreground: from here the shared @@ -117,6 +124,9 @@ final class MediaUploadSchemeHandler: NSObject, WKURLSchemeHandler { // MARK: - Routing private func response(to request: URLRequest) async -> SchemeResponse { + guard callerToken.authorizes(request) else { + return .error(401, code: "native_upload_unauthorized", message: "The request is not from the editor.") + } let route = Route(request) if case .preflight = route { return SchemeResponse(status: 204) diff --git a/ios/Sources/GutenbergKit/Sources/Media/RestRelay.swift b/ios/Sources/GutenbergKit/Sources/Media/RestRelay.swift index 49ea21693..5ffee5b3d 100644 --- a/ios/Sources/GutenbergKit/Sources/Media/RestRelay.swift +++ b/ios/Sources/GutenbergKit/Sources/Media/RestRelay.swift @@ -30,10 +30,9 @@ import OSLog /// /// ## Security /// -/// - The scheme doesn't check who is calling. Every frame in the editor's web -/// view can load it, including sandboxed frames that can't reach the page, -/// and the relay attaches the site credential to what they send to the -/// site's REST API. Why that is left as it is: "Who can use the schemes" in +/// - Only callers that can read the editor page's `GBKit` can use the scheme: +/// ``RestRelaySchemeHandler`` refuses a request without the editor's +/// ``SchemeCallerToken``. See "Who can use the schemes" in /// `docs/code/media-uploads.md`. /// - The relay adds the site credential only to a URL it builds itself, from /// the configured API root and the path below it. The page's URL is matched @@ -54,9 +53,9 @@ import OSLog /// credential to is decided on the page, before the request reaches the /// relay. Removing it here would protect nothing: the page already holds the /// credential, so it can send it anywhere. -/// - The relay reaches any `https` URL, so any frame in the web view can read -/// another host's response without CORS. Without Lockdown Mode the editor -/// page can do that anyway; a sandboxed frame couldn't before. +/// - The relay reaches any `https` URL, so a caller can read another host's +/// response without CORS. Without Lockdown Mode the editor page can do that +/// anyway. /// - A request for another host goes over `https`, or over plain `http` only to /// the site's own host. A device on the local network or this device itself /// can't present a valid certificate for another host's name, so a name @@ -560,12 +559,14 @@ struct RestRelay: Sendable { /// local page to the site (and WordPress rejects a `file://` origin — the /// exact problem the relay exists to solve); `cookie` is the page's, and /// the relay carries the site credential itself; `authorization` is set on - /// its own, by ``authorization(sentByCaller:toSiteAPI:)``. + /// its own, by ``authorization(sentByCaller:toSiteAPI:)``. The caller token is + /// for the relay alone. private static let requestHeadersToStrip: Set = [ "host", "connection", "content-length", "accept-encoding", "origin", "referer", "sec-fetch-site", "sec-fetch-mode", "sec-fetch-dest", "sec-fetch-user", "cookie", "authorization", + SchemeCallerToken.header.lowercased(), RestRelaySchemeHandler.timeoutHeader.lowercased(), RestRelaySchemeHandler.uploadHeader.lowercased(), ] diff --git a/ios/Sources/GutenbergKit/Sources/Media/RestRelaySchemeHandler.swift b/ios/Sources/GutenbergKit/Sources/Media/RestRelaySchemeHandler.swift index f1ee8ef23..581c31443 100644 --- a/ios/Sources/GutenbergKit/Sources/Media/RestRelaySchemeHandler.swift +++ b/ios/Sources/GutenbergKit/Sources/Media/RestRelaySchemeHandler.swift @@ -1,4 +1,5 @@ import Foundation +import OSLog import WebKit /// Serves ``RestRelay`` to the editor's page over a `gbk-rest:` URL scheme. @@ -6,6 +7,9 @@ import WebKit /// The page's `fetch` wrapper (`src/utils/fetch-relay.js`) rewrites a request for /// another origin to `gbk-rest://relay/fetch?url=`. This hands it to the /// relay and answers with what the server said. +/// +/// A request must carry the editor's ``SchemeCallerToken``. One without it fails as a +/// network failure would, before anything is relayed. @MainActor final class RestRelaySchemeHandler: NSObject, WKURLSchemeHandler { nonisolated static let scheme = "gbk-rest" @@ -45,15 +49,25 @@ final class RestRelaySchemeHandler: NSObject, WKURLSchemeHandler { /// relays for the configuration the page was given. var relay: RestRelay + /// The token every request must carry. + private let callerToken: SchemeCallerToken + private var active = ActiveSchemeTasks() /// The shortest time between two progress reports for one upload. private let uploadProgressInterval: Duration - /// - Parameter uploadProgressInterval: The shortest time between two progress - /// reports for one upload. A browser fires upload `progress` about every 50 ms. - init(relay: RestRelay, uploadProgressInterval: Duration = .milliseconds(50)) { + /// - Parameters: + /// - callerToken: The token every request must carry. + /// - uploadProgressInterval: The shortest time between two progress reports for + /// one upload. A browser fires upload `progress` about every 50 ms. + init( + relay: RestRelay, + callerToken: SchemeCallerToken, + uploadProgressInterval: Duration = .milliseconds(50) + ) { self.relay = relay + self.callerToken = callerToken self.uploadProgressInterval = uploadProgressInterval super.init() } @@ -87,6 +101,11 @@ final class RestRelaySchemeHandler: NSObject, WKURLSchemeHandler { reportUploadProgress: (@MainActor @Sendable (UploadProgress) -> Void)? = nil ) { let request = task.request + guard callerToken.authorizes(request) else { + Logger.restRelay.error("Refusing to relay a request without the editor's caller token") + task.didFailWithError(URLError(.userAuthenticationRequired)) + return + } let relay = relay active.start(task) { key in let onUploadProgress = reportUploadProgress.flatMap { diff --git a/ios/Sources/GutenbergKit/Sources/Media/SchemeCallerToken.swift b/ios/Sources/GutenbergKit/Sources/Media/SchemeCallerToken.swift new file mode 100644 index 000000000..971d2d8e5 --- /dev/null +++ b/ios/Sources/GutenbergKit/Sources/Media/SchemeCallerToken.swift @@ -0,0 +1,53 @@ +import Foundation +import Security + +/// A per-editor secret that a request to the native URL schemes must carry. +/// +/// Native code hands it to the editor page in `window.GBKit`, which is injected into +/// the main frame only. The page sends it in ``header`` on every `gbk-rest:` and +/// `gbk-upload:` request, and ``RestRelaySchemeHandler`` and +/// ``MediaUploadSchemeHandler`` refuse a request without it. A frame that can't read +/// the page's `GBKit` can't learn it, so it can't use the schemes. Mirrors the token +/// Android's loopback `HttpServer` requires. +/// +/// One token serves both schemes for the editor's lifetime. It is never stored. +struct SchemeCallerToken: Sendable { + /// The request header that carries the token, as `Bearer `. Android's + /// loopback server takes the same header. Never sent on to the site. + static let header = "Relay-Authorization" + + /// The token, as 64 lowercase hexadecimal characters. + let value: String + + /// A new random token. + init() { + var bytes = [UInt8](repeating: 0, count: 32) + let status = SecRandomCopyBytes(kSecRandomDefault, bytes.count, &bytes) + precondition(status == errSecSuccess, "Failed to generate a scheme caller token") + self.value = bytes.map { String(format: "%02x", $0) }.joined() + } + + init(value: String) { + self.value = value + } + + /// Whether `request` carries this token in ``header``. + func authorizes(_ request: URLRequest) -> Bool { + guard let sent = request.value(forHTTPHeaderField: Self.header), + sent.hasPrefix("Bearer ") else { + return false + } + return Self.constantTimeEqual(Array(sent.dropFirst("Bearer ".count).utf8), Array(value.utf8)) + } + + /// Compares in time that depends only on the expected token's length, so the time + /// a refusal takes doesn't reveal how much of a guess was right. + private static func constantTimeEqual(_ provided: [UInt8], _ expected: [UInt8]) -> Bool { + var difference = UInt8(provided.count == expected.count ? 0 : 1) + for index in expected.indices { + let byte = index < provided.count ? provided[index] : 0 + difference |= byte ^ expected[index] + } + return difference == 0 + } +} diff --git a/ios/Sources/GutenbergKit/Sources/Model/GBKitGlobal.swift b/ios/Sources/GutenbergKit/Sources/Model/GBKitGlobal.swift index acaa94a5c..7e0454a89 100644 --- a/ios/Sources/GutenbergKit/Sources/Model/GBKitGlobal.swift +++ b/ios/Sources/GutenbergKit/Sources/Model/GBKitGlobal.swift @@ -85,6 +85,10 @@ public struct GBKitGlobal: Sendable, Codable { /// the REST relay. let nativeUploadScheme: String? + /// The token the page sends with each request to ``nativeUploadScheme``. The same + /// name Android uses for its loopback upload server's token. + let nativeUploadToken: String? + /// Where the page sends its requests to other origins for native code to relay, or /// `nil` when they go straight from the page. let restRelay: RestRelayLocation? @@ -99,6 +103,9 @@ public struct GBKitGlobal: Sendable, Codable { /// page then leaves those requests out of its own network log, which would /// otherwise record each of them twice. let reportsRequests: Bool + + /// The token the page sends with each relayed request. + let token: String? } let editorSettings: JSON? @@ -120,12 +127,15 @@ public struct GBKitGlobal: Sendable, Codable { /// there is no site to relay for. /// - restRelayReportsRequests: Whether native code reports each relayed /// request to the host's ``EditorHTTPClientDelegate``. + /// - schemeCallerToken: The token the page sends to the upload scheme and the + /// REST relay, given to the page with each of them. public init( configuration: EditorConfiguration, dependencies: EditorDependencies, nativeUploadScheme: String? = nil, restRelayEndpoint: String? = nil, - restRelayReportsRequests: Bool = false + restRelayReportsRequests: Bool = false, + schemeCallerToken: String? = nil ) throws { self.siteURL = configuration.isOfflineModeEnabled ? nil : configuration.siteURL self.siteApiRoot = configuration.isOfflineModeEnabled ? nil : configuration.siteApiRoot @@ -149,8 +159,9 @@ public struct GBKitGlobal: Sendable, Codable { self.logLevel = configuration.logLevel.rawValue self.enableNetworkLogging = configuration.enableNetworkLogging self.nativeUploadScheme = nativeUploadScheme + self.nativeUploadToken = nativeUploadScheme == nil ? nil : schemeCallerToken self.restRelay = configuration.isOfflineModeEnabled ? nil : restRelayEndpoint.map { - RestRelayLocation(endpoint: $0, reportsRequests: restRelayReportsRequests) + RestRelayLocation(endpoint: $0, reportsRequests: restRelayReportsRequests, token: schemeCallerToken) } self.editorSettings = dependencies.editorSettings.jsonValue self.preloadData = try dependencies.preloadList?.build() diff --git a/ios/Tests/GutenbergKitTests/Media/EditorViewControllerMediaTeardownTests.swift b/ios/Tests/GutenbergKitTests/Media/EditorViewControllerMediaTeardownTests.swift index 1bf4fa42b..9291782a3 100644 --- a/ios/Tests/GutenbergKitTests/Media/EditorViewControllerMediaTeardownTests.swift +++ b/ios/Tests/GutenbergKitTests/Media/EditorViewControllerMediaTeardownTests.swift @@ -184,8 +184,11 @@ struct EditorViewControllerMediaTeardownTests: MakesTestFixtures { try await loadBlankPage(in: editor) _ = try await editor.webView.callAsyncJavaScript( - "try { await fetch(url); } catch {} return true;", - arguments: ["url": RestRelayHandleTests.relayURL(for: "http://127.0.0.1:1/wp-json/wp/v2/posts").absoluteString], + "try { await fetch(url, { headers: { 'Relay-Authorization': auth } }); } catch {} return true;", + arguments: [ + "url": RestRelayHandleTests.relayURL(for: "http://127.0.0.1:1/wp-json/wp/v2/posts").absoluteString, + "auth": "Bearer \(editor.schemeCallerToken.value)", + ], in: nil, contentWorld: .page ) @@ -400,11 +403,13 @@ struct EditorViewControllerMediaTeardownTests: MakesTestFixtures { let result = try await editor.webView.callAsyncJavaScript( """ const base = 'gbk-upload://upload'; + const headers = { 'Relay-Authorization': auth }; const bytes = new Uint8Array(size); for (let i = 0; i < size; i++) bytes[i] = i % 251; const file = new File([bytes], 'clip.bin', { type: 'application/octet-stream' }); const begin = await fetch(`${base}/sessions`, { method: 'POST', + headers, body: JSON.stringify({ filename: file.name, mimeType: file.type, size: file.size }), }); if (!begin.ok) return { beginStatus: begin.status }; @@ -412,11 +417,12 @@ struct EditorViewControllerMediaTeardownTests: MakesTestFixtures { const chunkSize = 4 * 1024 * 1024; for (let offset = 0; offset < file.size; offset += chunkSize) { const chunk = await file.slice(offset, offset + chunkSize).arrayBuffer(); - const response = await fetch(`${base}/sessions/${id}/chunks?offset=${offset}`, { method: 'POST', body: chunk }); + const response = await fetch(`${base}/sessions/${id}/chunks?offset=${offset}`, { method: 'POST', headers, body: chunk }); if (!response.ok) return { chunkStatus: response.status, offset }; } const finish = await fetch(`${base}/sessions/${id}/finish`, { method: 'POST', + headers, body: JSON.stringify({ fields: [{ name: 'post', value: '7' }], query: '?_embed' }), }); return { @@ -424,7 +430,7 @@ struct EditorViewControllerMediaTeardownTests: MakesTestFixtures { attachmentId: finish.headers.get('x-wp-upload-attachment-id'), }; """, - arguments: ["size": size], + arguments: ["size": size, "auth": "Bearer \(editor.schemeCallerToken.value)"], in: nil, contentWorld: .page ) diff --git a/ios/Tests/GutenbergKitTests/Media/MediaUploadSchemeHandlerTests.swift b/ios/Tests/GutenbergKitTests/Media/MediaUploadSchemeHandlerTests.swift index 3325c1457..26afbd2c4 100644 --- a/ios/Tests/GutenbergKitTests/Media/MediaUploadSchemeHandlerTests.swift +++ b/ios/Tests/GutenbergKitTests/Media/MediaUploadSchemeHandlerTests.swift @@ -10,6 +10,7 @@ struct MediaUploadSchemeHandlerTests { private func makeHandler(service: (any MediaUploading)?) -> MediaUploadSchemeHandler { MediaUploadSchemeHandler( service: service, + callerToken: .forTests, store: MediaUploadSessionStore( directory: FileManager.default.temporaryDirectory.appending(component: "scheme-tests-\(UUID().uuidString)") ) @@ -17,13 +18,16 @@ struct MediaUploadSchemeHandlerTests { } /// Starts a request and waits for the handler to answer it. + /// + /// - Parameter token: The caller token the request carries, or `nil` for none. @discardableResult private func send( _ handler: MediaUploadSchemeHandler, _ path: String, method: String = "POST", json: [String: Any]? = nil, - body: Data? = nil + body: Data? = nil, + token: SchemeCallerToken? = .forTests ) async throws -> FakeSchemeTask { var request = URLRequest(url: URL(string: "gbk-upload://upload\(path)")!) request.httpMethod = method @@ -32,7 +36,7 @@ struct MediaUploadSchemeHandlerTests { } else { request.httpBody = body } - let task = FakeSchemeTask(request: request) + let task = FakeSchemeTask(request: token.map { request.carrying($0) } ?? request) handler.start(task) await task.waitUntilAnswered() return task @@ -51,6 +55,7 @@ struct MediaUploadSchemeHandlerTests { let directory = FileManager.default.temporaryDirectory.appending(component: "scheme-tests-\(UUID().uuidString)") var handler: MediaUploadSchemeHandler? = MediaUploadSchemeHandler( service: ScriptedUploadService(), + callerToken: .forTests, store: MediaUploadSessionStore(directory: directory) ) _ = try await beginSession(try #require(handler), size: 10) @@ -65,6 +70,56 @@ struct MediaUploadSchemeHandlerTests { #expect(!FileManager.default.fileExists(atPath: directory.path(percentEncoded: false))) } + // MARK: - Caller token + + @Test("refuses a request without the caller token, without starting a session", arguments: [ + nil, SchemeCallerToken(value: "not-the-editors-token"), + ]) + func refusesBeginWithoutToken(token: SchemeCallerToken?) async throws { + let directory = FileManager.default.temporaryDirectory.appending(component: "scheme-tests-\(UUID().uuidString)") + defer { try? FileManager.default.removeItem(at: directory) } + let store = MediaUploadSessionStore(directory: directory) + let handler = MediaUploadSchemeHandler(service: ScriptedUploadService(), callerToken: .forTests, store: store) + + let begin = try await send( + handler, "/sessions", json: ["filename": "a.jpg", "mimeType": "image/jpeg", "size": 1], token: token + ) + + #expect(begin.status == 401) + #expect(begin.json["code"] as? String == "native_upload_unauthorized") + #expect(begin.header("Access-Control-Allow-Origin") == "*") + #expect(await store.sessionCount == 0) + } + + @Test("refuses to finish or cancel a session without the caller token") + func refusesFinishAndCancelWithoutToken() async throws { + let service = ScriptedUploadService() + let handler = makeHandler(service: service) + let id = try await beginSession(handler, size: 0) + + let finish = try await send(handler, "/sessions/\(id)/finish", json: [:], token: nil) + let cancel = try await send(handler, "/sessions/\(id)/cancel", token: nil) + + #expect(finish.status == 401) + #expect(cancel.status == 401) + #expect(service.calls.isEmpty) + // Neither touched the session, so the editor page can still finish it. + let finishedByPage = try await send(handler, "/sessions/\(id)/finish", json: [:]) + #expect(finishedByPage.status == 201) + #expect(service.calls.count == 1) + } + + @Test("refuses a media delete without the caller token") + func refusesDeleteWithoutToken() async throws { + let service = ScriptedUploadService() + let handler = makeHandler(service: service) + + let delete = try await send(handler, "/media/42/delete", json: ["query": ""], token: nil) + + #expect(delete.status == 401) + #expect(service.deletes.isEmpty) + } + // MARK: - Uploads from the page @Test("assembles chunks, finishes with the fields and query, and relays WordPress's answer") @@ -245,7 +300,7 @@ struct MediaUploadSchemeHandlerTests { var request = URLRequest(url: URL(string: "gbk-upload://upload/sessions/\(id)/finish")!) request.httpMethod = "POST" request.httpBody = Data("{}".utf8) - let finish = FakeSchemeTask(request: request) + let finish = FakeSchemeTask(request: request.carrying(.forTests)) handler.start(finish) await gate.waitUntilEntered() @@ -263,7 +318,7 @@ struct MediaUploadSchemeHandlerTests { let directory = FileManager.default.temporaryDirectory.appending(component: "scheme-tests-\(UUID().uuidString)") defer { try? FileManager.default.removeItem(at: directory) } let store = MediaUploadSessionStore(directory: directory) - let handler = MediaUploadSchemeHandler(service: ScriptedUploadService(), store: store) + let handler = MediaUploadSchemeHandler(service: ScriptedUploadService(), callerToken: .forTests, store: store) // With the store kept busy, the begin and then `disable()`'s clean-up queue up // behind it, which puts the clean-up ahead of the session the begin has yet to make. @@ -275,7 +330,7 @@ struct MediaUploadSchemeHandlerTests { var request = URLRequest(url: URL(string: "gbk-upload://upload/sessions")!) request.httpMethod = "POST" request.httpBody = try JSONSerialization.data(withJSONObject: ["filename": "clip.mp4", "mimeType": "video/mp4", "size": 10]) - let begin = FakeSchemeTask(request: request) + let begin = FakeSchemeTask(request: request.carrying(.forTests)) handler.start(begin) for _ in 0..<2 { await Task.yield() } @@ -306,7 +361,7 @@ struct MediaUploadSchemeHandlerTests { var request = URLRequest(url: URL(string: "gbk-upload://upload/sessions/\(id)/finish")!) request.httpMethod = "POST" request.httpBody = Data("{}".utf8) - let finish = FakeSchemeTask(request: request) + let finish = FakeSchemeTask(request: request.carrying(.forTests)) handler.start(finish) await gate.waitUntilEntered() @@ -349,6 +404,11 @@ final class FakeSchemeTask: NSObject, WKURLSchemeTask, @unchecked Sendable { self.request = request } + /// A task for `request` as the editor page sends it, carrying ``SchemeCallerToken/forTests``. + convenience init(fromEditor request: URLRequest) { + self.init(request: request.carrying(.forTests)) + } + func didReceive(_ response: URLResponse) { lock.withLock { _response = response } } func didReceive(_ data: Data) { lock.withLock { _body.append(data) } } func didFinish() { lock.withLock { _finished = true } } @@ -372,6 +432,20 @@ final class FakeSchemeTask: NSObject, WKURLSchemeTask, @unchecked Sendable { } } +extension SchemeCallerToken { + /// The token the tests' scheme handlers require. + static let forTests = SchemeCallerToken(value: "test-caller-token") +} + +extension URLRequest { + /// This request, carrying `token` as the editor page sends it. + func carrying(_ token: SchemeCallerToken) -> URLRequest { + var request = self + request.setValue("Bearer \(token.value)", forHTTPHeaderField: SchemeCallerToken.header) + return request + } +} + final class Flag: @unchecked Sendable { private let lock = NSLock() private var value = false diff --git a/ios/Tests/GutenbergKitTests/Media/RestRelayHandleTests.swift b/ios/Tests/GutenbergKitTests/Media/RestRelayHandleTests.swift index 147437316..72fe30260 100644 --- a/ios/Tests/GutenbergKitTests/Media/RestRelayHandleTests.swift +++ b/ios/Tests/GutenbergKitTests/Media/RestRelayHandleTests.swift @@ -298,11 +298,13 @@ struct RestRelayHandleTests { "Accept-Encoding": "gzip, deflate", "X-GBK-Relay-Timeout": "500", "X-GBK-Relay-Upload": "upload-1", + "Relay-Authorization": "Bearer test-caller-token", ]) for header in [ "Origin", "Referer", "Sec-Fetch-Site", "Sec-Fetch-Mode", "Cookie", "Connection", "X-GBK-Relay-Timeout", "X-GBK-Relay-Upload", + "Relay-Authorization", ] { #expect( exchange.upstream.value(forHTTPHeaderField: header) == nil, @@ -606,12 +608,31 @@ extension RestRelay.Response { @MainActor @Suite("RestRelaySchemeHandler") struct RestRelaySchemeHandlerTests { + @Test("refuses a request without the caller token, without relaying it", arguments: [ + nil, SchemeCallerToken(value: "not-the-editors-token"), + ]) + func refusesWithoutToken(token: SchemeCallerToken?) async throws { + let stubbed = StubURLProtocol.makeSession(stub: .init(body: Data("[]".utf8))) + defer { stubbed.finish() } + let handler = makeHandler(session: stubbed.session) + let request = URLRequest(url: RestRelayHandleTests.relayURL(for: "https://example.com/wp-json/wp/v2/users/me")) + let task = FakeSchemeTask(request: token.map { request.carrying($0) } ?? request) + + handler.start(task) + await task.waitUntilAnswered() + + #expect((task.failure as? URLError)?.code == .userAuthenticationRequired) + #expect(task.response == nil, "a response would reach the page as the site's own") + #expect(stubbed.recorder.request == nil, "the request reached the site") + #expect(handler.activeRequestCount == 0) + } + @Test("fails the page's request when the site can't be reached") func failsWhenSiteUnreachable() async throws { let stubbed = StubURLProtocol.makeSession(stub: .init(failure: URLError(.notConnectedToInternet))) defer { stubbed.finish() } let handler = makeHandler(session: stubbed.session) - let task = FakeSchemeTask(request: URLRequest(url: RestRelayHandleTests.relayURL(for: "https://example.com/wp-json/wp/v2/posts"))) + let task = FakeSchemeTask(fromEditor: URLRequest(url: RestRelayHandleTests.relayURL(for: "https://example.com/wp-json/wp/v2/posts"))) handler.start(task) await task.waitUntilAnswered() @@ -626,7 +647,7 @@ struct RestRelaySchemeHandlerTests { let stubbed = StubURLProtocol.makeSession(stub: .init()) defer { stubbed.finish() } let handler = makeHandler(session: stubbed.session) - let task = FakeSchemeTask(request: URLRequest(url: RestRelayHandleTests.relayURL(for: "https://example.com/wp-json/../wp-admin/"))) + let task = FakeSchemeTask(fromEditor: URLRequest(url: RestRelayHandleTests.relayURL(for: "https://example.com/wp-json/../wp-admin/"))) handler.start(task) await task.waitUntilAnswered() @@ -642,7 +663,7 @@ struct RestRelaySchemeHandlerTests { let stubbed = StubURLProtocol.makeSession(stub: .init(body: Data("[]".utf8))) defer { stubbed.finish() } let handler = makeHandler(session: stubbed.session) - let task = FakeSchemeTask(request: URLRequest(url: RestRelayHandleTests.relayURL(for: "https://example.com/wp-json/wp/v2/posts"))) + let task = FakeSchemeTask(fromEditor: URLRequest(url: RestRelayHandleTests.relayURL(for: "https://example.com/wp-json/wp/v2/posts"))) handler.start(task) handler.stop(task) @@ -670,7 +691,7 @@ struct RestRelaySchemeHandlerTests { )) defer { stubbed.finish() } let handler = makeHandler(session: stubbed.session) - let task = FakeSchemeTask(request: URLRequest(url: RestRelayHandleTests.relayURL(for: "https://example.com/wp-json/wpcom/v2/jetpack-ai-query"))) + let task = FakeSchemeTask(fromEditor: URLRequest(url: RestRelayHandleTests.relayURL(for: "https://example.com/wp-json/wpcom/v2/jetpack-ai-query"))) handler.start(task) try await waitUntil { !task.body.isEmpty } @@ -699,7 +720,7 @@ struct RestRelaySchemeHandlerTests { )) defer { stubbed.finish() } let handler = makeHandler(session: stubbed.session) - let task = FakeSchemeTask(request: URLRequest(url: RestRelayHandleTests.relayURL(for: "https://example.com/wp-json/wpcom/v2/jetpack-ai-query"))) + let task = FakeSchemeTask(fromEditor: URLRequest(url: RestRelayHandleTests.relayURL(for: "https://example.com/wp-json/wpcom/v2/jetpack-ai-query"))) handler.start(task) try await waitUntil { !task.body.isEmpty } @@ -730,7 +751,7 @@ struct RestRelaySchemeHandlerTests { // reached the handler. let observer = TaskEventRecorder() let handler = makeHandler(session: stubbed.session, observer: observer) - let task = FakeSchemeTask(request: URLRequest(url: RestRelayHandleTests.relayURL(for: "https://example.com/wp-json/wpcom/v2/jetpack-ai-query"))) + let task = FakeSchemeTask(fromEditor: URLRequest(url: RestRelayHandleTests.relayURL(for: "https://example.com/wp-json/wpcom/v2/jetpack-ai-query"))) handler.start(task) try await waitUntil { !task.body.isEmpty } @@ -755,7 +776,7 @@ struct RestRelaySchemeHandlerTests { )) defer { stubbed.finish() } let handler = makeHandler(session: stubbed.session) - let task = FakeSchemeTask(request: URLRequest(url: RestRelayHandleTests.relayURL(for: "https://example.com/wp-json/wpcom/v2/jetpack-ai-query"))) + let task = FakeSchemeTask(fromEditor: URLRequest(url: RestRelayHandleTests.relayURL(for: "https://example.com/wp-json/wpcom/v2/jetpack-ai-query"))) handler.start(task) try await waitUntil { !task.body.isEmpty } @@ -782,7 +803,7 @@ struct RestRelaySchemeHandlerTests { let handler = makeHandler(session: stubbed.session) var request = URLRequest(url: RestRelayHandleTests.relayURL(for: "https://example.com/wp-json/wpcom/v2/jetpack-ai-query")) request.setValue("100", forHTTPHeaderField: RestRelaySchemeHandler.timeoutHeader) - let task = FakeSchemeTask(request: request) + let task = FakeSchemeTask(fromEditor: request) handler.start(task) await task.waitUntilAnswered() @@ -801,7 +822,7 @@ struct RestRelaySchemeHandlerTests { let handler = makeHandler(session: stubbed.session) var request = URLRequest(url: RestRelayHandleTests.relayURL(for: "https://example.com/wp-json/wp/v2/posts")) request.setValue("60000", forHTTPHeaderField: RestRelaySchemeHandler.timeoutHeader) - let task = FakeSchemeTask(request: request) + let task = FakeSchemeTask(fromEditor: request) handler.start(task) await task.waitUntilAnswered() @@ -822,7 +843,7 @@ struct RestRelaySchemeHandlerTests { )) defer { stubbed.finish() } let handler = makeHandler(session: stubbed.session) - let task = FakeSchemeTask(request: URLRequest(url: RestRelayHandleTests.relayURL(for: "https://example.com/wp-json/wpcom/v2/jetpack-ai-query"))) + let task = FakeSchemeTask(fromEditor: URLRequest(url: RestRelayHandleTests.relayURL(for: "https://example.com/wp-json/wpcom/v2/jetpack-ai-query"))) handler.start(task) try await waitUntil { !task.body.isEmpty } @@ -849,7 +870,7 @@ struct RestRelaySchemeHandlerTests { let stubbed = StubURLProtocol.makeSession(stub: .init(headers: Self.eventStream, body: Data("one ".utf8), gate: gate, rest: Data("two".utf8))) defer { stubbed.finish() } let handler = makeHandler(session: stubbed.session, siteApiRoot: siteApiRoot) - let task = FakeSchemeTask(request: URLRequest(url: RestRelayHandleTests.relayURL(for: url))) + let task = FakeSchemeTask(fromEditor: URLRequest(url: RestRelayHandleTests.relayURL(for: url))) handler.start(task) try await waitUntil { !task.body.isEmpty } @@ -874,7 +895,7 @@ struct RestRelaySchemeHandlerTests { defer { server.stop() } let site = "http://127.0.0.1:\(server.port)" let handler = makeHandler(site: site, uploadProgressInterval: .zero) - let task = FakeSchemeTask(request: Self.uploadRequest(to: site, naming: "upload-1")) + let task = FakeSchemeTask(fromEditor: Self.uploadRequest(to: site, naming: "upload-1")) let reports = ProgressRecorder() handler.start(task) { reports.add($0) } @@ -900,7 +921,7 @@ struct RestRelaySchemeHandlerTests { defer { server.stop() } let site = "http://127.0.0.1:\(server.port)" let handler = makeHandler(site: site, uploadProgressInterval: .seconds(3600)) - let task = FakeSchemeTask(request: Self.uploadRequest(to: site, naming: "upload-1")) + let task = FakeSchemeTask(fromEditor: Self.uploadRequest(to: site, naming: "upload-1")) let reports = ProgressRecorder() handler.start(task) { reports.add($0) } @@ -920,7 +941,7 @@ struct RestRelaySchemeHandlerTests { defer { server.stop() } let site = "http://127.0.0.1:\(server.port)" let handler = makeHandler(site: site, uploadProgressInterval: .zero) - let task = FakeSchemeTask(request: Self.uploadRequest(to: site, naming: nil)) + let task = FakeSchemeTask(fromEditor: Self.uploadRequest(to: site, naming: nil)) let reports = ProgressRecorder() handler.start(task) { reports.add($0) } @@ -972,6 +993,7 @@ struct RestRelaySchemeHandlerTests { session: session, observer: observer ), + callerToken: .forTests, uploadProgressInterval: uploadProgressInterval ) } diff --git a/ios/Tests/GutenbergKitTests/Media/SchemeCallerTokenTests.swift b/ios/Tests/GutenbergKitTests/Media/SchemeCallerTokenTests.swift new file mode 100644 index 000000000..be1b9d50f --- /dev/null +++ b/ios/Tests/GutenbergKitTests/Media/SchemeCallerTokenTests.swift @@ -0,0 +1,45 @@ +import Foundation +import Testing + +@testable import GutenbergKit + +@Suite("SchemeCallerToken") +struct SchemeCallerTokenTests { + private let token = SchemeCallerToken(value: "0123456789abcdef") + + private func request(_ value: String?) -> URLRequest { + var request = URLRequest(url: URL(string: "gbk-rest://relay/fetch")!) + request.setValue(value, forHTTPHeaderField: SchemeCallerToken.header) + return request + } + + @Test("makes a different 64-character hex token each time") + func generatesRandomTokens() { + let first = SchemeCallerToken() + let second = SchemeCallerToken() + #expect(first.value.count == 64) + let isHex = first.value.allSatisfy { $0.isHexDigit } + #expect(isHex) + #expect(first.value != second.value) + } + + @Test("authorizes a request carrying the token") + func authorizesTheToken() { + #expect(token.authorizes(request("Bearer 0123456789abcdef"))) + } + + @Test("refuses a request without the exact token", arguments: [ + nil, + "", + "Bearer ", + "0123456789abcdef", + "Basic 0123456789abcdef", + "Bearer 0123456789abcdee", + "Bearer 0123456789abcde", + "Bearer 0123456789abcdef0", + "Bearer 0123456789ABCDEF", + ]) + func refusesOtherValues(value: String?) { + #expect(!token.authorizes(request(value))) + } +} diff --git a/ios/Tests/GutenbergKitTests/Media/XMLHttpRequestRelayLifecycleTests.swift b/ios/Tests/GutenbergKitTests/Media/XMLHttpRequestRelayLifecycleTests.swift index a71bba1d3..ecb2ba2db 100644 --- a/ios/Tests/GutenbergKitTests/Media/XMLHttpRequestRelayLifecycleTests.swift +++ b/ios/Tests/GutenbergKitTests/Media/XMLHttpRequestRelayLifecycleTests.swift @@ -139,13 +139,16 @@ private final class LifecyclePage { private init() async throws { server = try await LifecycleHTTPServer() - handler = RestRelaySchemeHandler(relay: RestRelay( - configuration: EditorConfigurationBuilder( - postType: .post, - siteURL: URL(string: server.origin)!, - siteApiRoot: URL(string: "\(server.origin)/wp-json/")! - ).build() - )) + handler = RestRelaySchemeHandler( + relay: RestRelay( + configuration: EditorConfigurationBuilder( + postType: .post, + siteURL: URL(string: server.origin)!, + siteApiRoot: URL(string: "\(server.origin)/wp-json/")! + ).build() + ), + callerToken: .forTests + ) let configuration = WKWebViewConfiguration() configuration.setURLSchemeHandler(handler, forURLScheme: RestRelaySchemeHandler.scheme) @@ -203,15 +206,25 @@ private final class LifecyclePage { } let source = root.appending(path: "src/utils") let modules = try ["fetch-relay.js", "xhr-relay.js"].map { name in - let lines = try String(contentsOf: source.appending(path: name), encoding: .utf8) - .components(separatedBy: "\n") - .filter { !$0.hasPrefix("import ") } - .map { $0.hasPrefix("export ") ? String($0.dropFirst("export ".count)) : $0 } + var lines: [String] = [] + var inImport = false + for line in try String(contentsOf: source.appending(path: name), encoding: .utf8) + .components(separatedBy: "\n") { + // An import can span several lines; it ends at the one with its `from`. + if line.hasPrefix("import ") { + inImport = true + } + if inImport { + inImport = !line.contains(" from ") + continue + } + lines.append(line.hasPrefix("export ") ? String(line.dropFirst("export ".count)) : line) + } return lines.joined(separator: "\n") } return """ (() => { - const restRelay = { endpoint: '\(RestRelaySchemeHandler.endpoint)' }; + const restRelay = { endpoint: '\(RestRelaySchemeHandler.endpoint)', token: '\(SchemeCallerToken.forTests.value)' }; const getGBKit = () => ( { restRelay } ); const debug = () => {}; const warn = () => {}; diff --git a/ios/Tests/GutenbergKitTests/Model/GBKitGlobalTests.swift b/ios/Tests/GutenbergKitTests/Model/GBKitGlobalTests.swift index ef9ca536e..c6f298c84 100644 --- a/ios/Tests/GutenbergKitTests/Model/GBKitGlobalTests.swift +++ b/ios/Tests/GutenbergKitTests/Model/GBKitGlobalTests.swift @@ -79,6 +79,32 @@ struct GBKitGlobalTests: MakesTestFixtures { #expect(try global.toString().contains(#""endpoint":"gbk-rest:\/\/relay\/fetch""#)) } + @Test("gives the page the caller token with the relay and the upload scheme") + func mapsCallerToken() throws { + let global = try GBKitGlobal( + configuration: makeConfiguration(), dependencies: makeDependencies(), + nativeUploadScheme: "gbk-upload", + restRelayEndpoint: "gbk-rest://relay/fetch", + schemeCallerToken: "abc123" + ) + #expect(global.restRelay?.token == "abc123") + #expect(global.nativeUploadToken == "abc123") + let json = try global.toString() + #expect(json.contains(#""nativeUploadToken":"abc123""#)) + #expect(json.contains(#""token":"abc123""#)) + } + + @Test("gives the page no upload token when native uploads are off") + func omitsUploadTokenWithoutScheme() throws { + let global = try GBKitGlobal( + configuration: makeConfiguration(), dependencies: makeDependencies(), + restRelayEndpoint: "gbk-rest://relay/fetch", + schemeCallerToken: "abc123" + ) + #expect(global.nativeUploadToken == nil) + #expect(global.restRelay?.token == "abc123") + } + @Test("offers no relay in offline mode, where there is no site") func omitsRelayOffline() throws { let global = try GBKitGlobal( From 98a0d01de0af94ef14903a0de164a15c648eaff7 Mon Sep 17 00:00:00 2001 From: David Calhoun Date: Fri, 13 Nov 2026 10:23:59 -0500 Subject: [PATCH 3/7] docs: describe the caller token on the native schemes The "Who can use the schemes" section said neither scheme checks the caller, which no longer holds. Co-Authored-By: Claude Opus 5.5 --- docs/code/media-uploads.md | 61 ++++++++++++++++---------------------- 1 file changed, 26 insertions(+), 35 deletions(-) diff --git a/docs/code/media-uploads.md b/docs/code/media-uploads.md index bc45d9c29..656b1a8e0 100644 --- a/docs/code/media-uploads.md +++ b/docs/code/media-uploads.md @@ -52,7 +52,7 @@ still held 170 MB after the 64 MB upload ended. A `WKURLSchemeHandler` in the editor's own web view. It has no socket, so iOS can't reclaim it when a suspended app's device idle-sleeps, which is what broke the loopback server -after an ordinary screen lock. It has no token either; see +after an ordinary screen lock. Like the loopback server, it requires a per-session token; see [Who can use the schemes](#who-can-use-the-schemes). WebKit hands a scheme handler only bodies it has buffered. Measured: @@ -156,48 +156,40 @@ byte for byte. ## Who can use the schemes -`gbk-upload:` and the REST relay's `gbk-rest:` don't check who is calling. A scheme -handler serves every frame in the editor's web view, not only the editor page, and native -code adds the site credential to what it sends to the site's REST API. So any frame can act -as the user through them. +A scheme handler serves every frame in the editor's web view, not only the editor page. So +`gbk-upload:` and the REST relay's `gbk-rest:` each require a per-session token, as +Android's loopback server does. Native code makes one token per editor (`SchemeCallerToken`) +and gives it to the page in `window.GBKit`, which is injected into the main frame only: as +`restRelay.token` for the relay, and as `nativeUploadToken` for uploads. The page sends it on +every request as `Relay-Authorization: Bearer `. WebKit sends a scheme handler no +preflight, so the header costs nothing. The relay never sends it on to the site. + +A request without the token is refused before native code acts on it. `gbk-rest:` fails it +as a network failure would, so it can't be mistaken for the site's own answer. `gbk-upload:` +answers `401` before routing, so it can't start, finish, or cancel a session, or delete +media. The editor's frames fall into two groups: -| Frames | Origin | Reads `window.GBKit` | -| -------------------------------------------------------- | ------------ | -------------------- | -| The editor page; embed previews | the editor's | yes | -| The Custom HTML preview; embeds from untrusted providers | `null` | no | +| Frames | Origin | Reads `window.GBKit` | Can use the schemes | +| -------------------------------------------------------- | ------------ | -------------------- | ------------------- | +| The editor page; embed previews | the editor's | yes | yes | +| The Custom HTML preview; embeds from untrusted providers | `null` | no | no | Gutenberg's `SandBox` runs embed previews with `allowSameOrigin`. Core reduces an embed from a provider it doesn't trust to a `sandbox="allow-scripts"` iframe. -The first group already has the credential through `GBKit.authHeader`, so the schemes give -it nothing new. The second group had no way to use the credential before the schemes, and -now it does. Measured on iOS 27.0 in the Simulator, with Lockdown Mode on and off: a -sandboxed `srcdoc` frame's `POST` through `gbk-rest:` reached the site with the credential, -and the frame read the reply. - -A check on each request would shut out the second group: - -- **A token** in `GBKit`, sent as a header. A frame that can't read `GBKit` can't send it. - WebKit sends a scheme handler no preflight, so the header costs nothing. -- **An `Origin` check** that allows only what the editor page sends: no `Origin` with - Lockdown Mode off, `file://` with it on. The second group's `fetch` says `null`. Loads - that send no `Origin`, such as an image or a navigation, still get through, but they are - `GET`s whose reply the frame can't read. - -Neither check reaches the first group. Code at the editor's origin can call the editor's own -functions, so nothing on the request tells it apart from the editor. Its scripts come from -the providers core trusts with their embed HTML (`wp_filter_oembed_result`), and they have -the same reach in wp-admin. - -Neither check is in place. It was left out of the scheme transports because it would close -the second group only, while the first stays as it was before the schemes. +The token doesn't reach the first group. Code at the editor's origin can call the editor's own +functions, so nothing on the request tells it apart from the editor. That group already has +the credential through `GBKit.authHeader`, so the schemes give it nothing new. Its scripts +come from the providers core trusts with their embed HTML (`wp_filter_oembed_result`), and +they have the same reach in wp-admin. Keeping the check to the token, rather than to the main +frame, also keeps same-origin scripts working if the editor's canvas moves into an iframe. The relay also sends requests for other hosts, so a plugin's call to its own service works under Lockdown Mode. The page sends every request for another origin to one URL, -`gbk-rest://relay/fetch?url=…`, and native code decides how to send it. That gives every -frame a response from any `https` URL without CORS. Plain `http` goes only to the site's own +`gbk-rest://relay/fetch?url=…`, and native code decides how to send it. That gives the +editor page a response from any `https` URL without CORS. Plain `http` goes only to the site's own host — the API root's or the site URL's — on any port. Any other `http` request gets a `426` before anything is sent. A device on the local network, or this device itself, can't present a valid certificate for another host's name, so a name pointed at one fails before anything @@ -211,8 +203,7 @@ builds from the configured root. It never removes or replaces an `Authorization` sent, wherever the request goes, even when that is the site credential. Which hosts get the site credential is the page's decision, made before the request reaches native code: removing it there would protect nothing, because the page already holds the credential and -can send it anywhere. Without Lockdown Mode the editor page can already read those responses; -the second group couldn't. +can send it anywhere. Without Lockdown Mode the editor page can already read those responses. ### Where a relayed request differs from the browser's From effa6e7e834f50a9afa72fe6d2087aded1cf3646 Mon Sep 17 00:00:00 2001 From: Jeremy Massel <1123407+jkmassel@users.noreply.github.com> Date: Fri, 13 Nov 2026 14:49:23 -0600 Subject: [PATCH 4/7] test(ios): check a sandboxed frame can't use the native schemes (#904) * test(ios): check a sandboxed frame can't use the native schemes Loads the editor's real GBKit script into a page with a `sandbox="allow-scripts"` frame. The frame can't read GBKit, the upload scheme answers it with a 401, and the relay never sends its request. The editor page, using the token from GBKit, gets through both. `buildEditorConfiguration(dependencies:)` is no longer private, so the test installs the same script the editor does, `forMainFrameOnly` and all. * fix(ios): answer an upload preflight without the caller token A browser's CORS preflight never carries the request's own headers, so with the token check first, a preflight got a 401 and the upload would fail CORS. No preflight reaches the handler today, but answering it first costs nothing: it only returns CORS headers. The preflight test now sends no token, as a browser does, so it fails if the check moves back in front. --- .../Sources/EditorViewController.swift | 2 +- .../Media/MediaUploadSchemeHandler.swift | 6 +- ...itorViewControllerMediaTeardownTests.swift | 88 +++++++++++++++++++ .../Media/MediaUploadSchemeHandlerTests.swift | 3 +- 4 files changed, 94 insertions(+), 5 deletions(-) diff --git a/ios/Sources/GutenbergKit/Sources/EditorViewController.swift b/ios/Sources/GutenbergKit/Sources/EditorViewController.swift index 6a6d2b0fe..afee73343 100644 --- a/ios/Sources/GutenbergKit/Sources/EditorViewController.swift +++ b/ios/Sources/GutenbergKit/Sources/EditorViewController.swift @@ -561,7 +561,7 @@ public final class EditorViewController: UIViewController, GutenbergEditorContro /// scripts run. This ensures the editor JavaScript has access to all configuration data /// when it initializes. /// - private func buildEditorConfiguration(dependencies: EditorDependencies) throws -> WKUserScript { + func buildEditorConfiguration(dependencies: EditorDependencies) throws -> WKUserScript { let gbkitGlobal = try GBKitGlobal( configuration: self.configuration, dependencies: dependencies, diff --git a/ios/Sources/GutenbergKit/Sources/Media/MediaUploadSchemeHandler.swift b/ios/Sources/GutenbergKit/Sources/Media/MediaUploadSchemeHandler.swift index 2233c9772..a49839980 100644 --- a/ios/Sources/GutenbergKit/Sources/Media/MediaUploadSchemeHandler.swift +++ b/ios/Sources/GutenbergKit/Sources/Media/MediaUploadSchemeHandler.swift @@ -124,13 +124,13 @@ final class MediaUploadSchemeHandler: NSObject, WKURLSchemeHandler { // MARK: - Routing private func response(to request: URLRequest) async -> SchemeResponse { - guard callerToken.authorizes(request) else { - return .error(401, code: "native_upload_unauthorized", message: "The request is not from the editor.") - } let route = Route(request) if case .preflight = route { return SchemeResponse(status: 204) } + guard callerToken.authorizes(request) else { + return .error(401, code: "native_upload_unauthorized", message: "The request is not from the editor.") + } guard let service else { return Self.unavailable } diff --git a/ios/Tests/GutenbergKitTests/Media/EditorViewControllerMediaTeardownTests.swift b/ios/Tests/GutenbergKitTests/Media/EditorViewControllerMediaTeardownTests.swift index 9291782a3..f9a1c5761 100644 --- a/ios/Tests/GutenbergKitTests/Media/EditorViewControllerMediaTeardownTests.swift +++ b/ios/Tests/GutenbergKitTests/Media/EditorViewControllerMediaTeardownTests.swift @@ -197,6 +197,94 @@ struct EditorViewControllerMediaTeardownTests: MakesTestFixtures { #expect(recorder.events.last == "failed") } + // MARK: - Who can use the schemes + + @MainActor + @Test("a sandboxed frame can't read the caller token, so both schemes refuse it") + func sandboxedFrameIsRefused() async throws { + // Nothing listens on port 1, so a relayed request fails at once. The relay still + // reports it to the host's delegate, which is how the test tells a request that + // was relayed from one refused before it. + let configuration = EditorConfigurationBuilder( + postType: .post, + siteURL: URL(string: "http://127.0.0.1:1")!, + siteApiRoot: URL(string: "http://127.0.0.1:1/wp-json/")! + ) + .setAuthHeader("Bearer test-token") + .build() + let recorder = TaskEventRecorder() + let editor = EditorViewController( + configuration: configuration, + mediaUploader: InertUploader(), + httpClient: EditorHTTPClient(urlSession: URLSession.shared, authHeader: "Bearer test-token", delegate: recorder) + ) + defer { editor.stopMediaHandling() } + // The script the editor itself installs, so the test covers which frames get `GBKit`. + let dependencies = EditorDependencies(editorSettings: .undefined, assetBundle: .empty, preloadList: nil) + editor.webView.configuration.userContentController.addUserScript( + try editor.buildEditorConfiguration(dependencies: dependencies) + ) + try await loadBlankPage(in: editor) + let relayURL = RestRelayHandleTests.relayURL(for: "http://127.0.0.1:1/wp-json/wp/v2/users/me").absoluteString + + let frame = try #require(try await editor.webView.callAsyncJavaScript( + """ + const script = `(async () => { + const result = { origin: self.origin, hasOwnGBKit: 'GBKit' in window }; + try { result.parentGBKit = typeof parent.GBKit; } catch (e) { result.parentGBKit = e.name; } + try { await fetch(relayURL); } catch {} + const upload = await fetch('gbk-upload://upload/sessions', { + method: 'POST', + body: JSON.stringify({ filename: 'a.jpg', mimeType: 'image/jpeg', size: 1 }), + }); + result.uploadStatus = upload.status; + parent.postMessage(result, '*'); + })();`; + const iframe = document.createElement('iframe'); + iframe.sandbox = 'allow-scripts'; + iframe.srcdoc = `