diff --git a/docs/code/media-uploads.md b/docs/code/media-uploads.md index bc45d9c29..2f5cbec06 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,41 @@ 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`, so it can't start, finish, or cancel a session, or delete media. A CORS +preflight never carries the token, so `gbk-upload:` answers one with its CORS headers alone, +as Android's loopback server does. 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 +204,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 diff --git a/ios/Sources/GutenbergKit/Sources/EditorViewController.swift b/ios/Sources/GutenbergKit/Sources/EditorViewController.swift index 672ef647a..afee73343 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) @@ -553,13 +561,14 @@ 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, 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..05feb56ad 100644 --- a/ios/Sources/GutenbergKit/Sources/Media/MediaUploadSchemeHandler.swift +++ b/ios/Sources/GutenbergKit/Sources/Media/MediaUploadSchemeHandler.swift @@ -19,9 +19,9 @@ 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`, +/// so it can't create, finish, or cancel a session, or delete media. A CORS preflight, +/// which never carries the token, gets only CORS headers. /// /// Every response carries CORS headers: under Lockdown Mode WebKit enforces CORS on /// scheme responses too, and core's upload middleware reads @@ -36,13 +36,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 @@ -121,6 +129,9 @@ final class MediaUploadSchemeHandler: NSObject, WKURLSchemeHandler { 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/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..79852e0d2 --- /dev/null +++ b/ios/Sources/GutenbergKit/Sources/Media/SchemeCallerToken.swift @@ -0,0 +1,44 @@ +import Foundation + +/// 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 generator = SystemRandomNumberGenerator() + let words = (0..<4).map { _ in generator.next() } // 4 × UInt64 = 256 bits + self.value = words.map { String(format: "%016llx", $0) }.joined() + } + + init(value: String) { + self.value = value + } + + /// Whether `request` carries this token in ``header``. + func authorizes(_ request: URLRequest) -> Bool { + let prefix = "Bearer ".utf8 + guard let sent = request.value(forHTTPHeaderField: Self.header)?.utf8, + sent.starts(with: prefix) else { + return false + } + let provided = Array(sent.dropFirst(prefix.count)) + let expected = Array(value.utf8) + return provided.count == expected.count + && timingsafe_bcmp(provided, expected, expected.count) == 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..f9a1c5761 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 ) @@ -194,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 = `