Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 27 additions & 35 deletions docs/code/media-uploads.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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 <token>`. 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
Expand All @@ -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

Expand Down
27 changes: 18 additions & 9 deletions ios/Sources/GutenbergKit/Sources/EditorViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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()),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,9 @@ import WebKit
/// | `POST …/sessions/<id>/cancel` | — | `204` |
/// | `POST …/media/<attachmentId>/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
Expand All @@ -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
Expand Down Expand Up @@ -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
}
Expand Down
17 changes: 9 additions & 8 deletions ios/Sources/GutenbergKit/Sources/Media/RestRelay.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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<String> = [
"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(),
]
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
import Foundation
import OSLog
import WebKit

/// Serves ``RestRelay`` to the editor's page over a `gbk-rest:` URL scheme.
///
/// The page's `fetch` wrapper (`src/utils/fetch-relay.js`) rewrites a request for
/// another origin to `gbk-rest://relay/fetch?url=<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"
Expand Down Expand Up @@ -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()
}
Expand Down Expand Up @@ -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 {
Expand Down
44 changes: 44 additions & 0 deletions ios/Sources/GutenbergKit/Sources/Media/SchemeCallerToken.swift
Original file line number Diff line number Diff line change
@@ -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 <token>`. 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()
}
Comment on lines +22 to +26

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should be infallible as written, but to avoid the precondition (which looks a little scary), WDYT about using the infallible-by-contract SystemRandomNumberGenerator? With it, import Security on line 2 can go too.

Suggested change
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() {
var generator = SystemRandomNumberGenerator()
let words = (0..<4).map { _ in generator.next() } // 4 × UInt64 = 256 bits
self.value = words.map { String(format: "%016llx", $0) }.joined()
}

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 60356b3.


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
}
}
Loading
Loading