Skip to content

fix(ios): require a caller token on the native schemes - #902

Merged
dcalhoun merged 7 commits into
trunkfrom
fix/ios-scheme-caller-token
Nov 13, 2026
Merged

dcalhoun merged 7 commits into
trunkfrom
fix/ios-scheme-caller-token

Conversation

@dcalhoun

@dcalhoun dcalhoun commented Nov 13, 2026 •

Copy link
Copy Markdown
Member

Description

Requires a per-session token on the iOS gbk-rest: and gbk-upload: URL schemes, so only the editor page can use them. Mirrors the token Android's loopback upload server already requires. Ref CMM-2462.

  • Native code generates one token per editor (SchemeCallerToken) and passes it to the page in GBKit, as restRelay.token and nativeUploadToken.
  • The page's fetch relay, XMLHttpRequest relay, and native upload requests send it as Relay-Authorization: Bearer <token>.
  • RestRelaySchemeHandler fails a request without it as a network error, before relaying. MediaUploadSchemeHandler answers 401 before routing. The relay never forwards the header to the site.
  • Updates "Who can use the schemes" in docs/code/media-uploads.md.

Testing instructions

Using the iOS demo app with the bundled editor (make build), on a self-hosted, an Atomic, and a Simple site:

  1. Open the editor; verify it loads, and the block inserter and patterns work.
  2. Upload an image, and a video large enough to send several chunks; cancel one upload part-way.
  3. On a Jetpack or Atomic site, add a VideoPress video (uploads over the XMLHttpRequest relay).
  4. Embed a X URL and a link to another WordPress post; verify both previews render.
  5. Repeat 1–2 with Lockdown Mode on.
  6. Verify none of the above shows "Could not get a valid response from the server" or "The request is not from the editor."

🤖 Generated with Claude Code

dcalhoun and others added 3 commits November 13, 2026 10:23
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
The "Who can use the schemes" section said neither scheme checks the
caller, which no longer holds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@github-actions github-actions Bot added the [Type] Bug An existing feature does not function as intended label Nov 13, 2026
@wpmobilebot

wpmobilebot commented Nov 13, 2026 •

Copy link
Copy Markdown

XCFramework Build

This PR's XCFramework is available for testing. Add the following to your Package.swift:

.package(url: "https://github.com/wordpress-mobile/GutenbergKit", branch: "pr-build/902")

Built from cdce298

@dcalhoun
dcalhoun marked this pull request as ready for review November 13, 2026 19:36

@jkmassel jkmassel left a comment

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 is pretty close – left a few suggestions, and #904 adds an additional test

Comment on lines +23 to +28
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()
}

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.

Comment on lines +40 to +52
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
}

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.

It's probably better to use a system-defined constant-time string comparison to ensure the compiler doesn't "helpfully" optimize it away on us:

Suggested change
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
}
let provided = Array(sent.utf8.dropFirst("Bearer ".count))
let expected = Array(value.utf8)
return provided.count == expected.count
&& timingsafe_bcmp(provided, expected, expected.count) == 0
}

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.

Comment on lines 127 to 132
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)

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.

A preflight can't carry the token, so with the check first, any OPTIONS request gets a 401 and the upload fails CORS. No preflight reaches the handler today, so this is harmless now, but answering the preflight first costs nothing:

Suggested change
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)
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.")

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 effa6e7.

jkmassel and others added 3 commits November 13, 2026 15:49
* 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.
SystemRandomNumberGenerator can't fail, which drops the precondition,
and timingsafe_bcmp can't be optimized into an early-exit comparison.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A CORS preflight never carries the token, so the upload scheme now
answers one before checking it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The prefix was matched by character but dropped by UTF-8 byte. Both
counts agree for "Bearer ", but doing both in UTF-8 keeps them in step.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@dcalhoun
dcalhoun merged commit 13e9259 into trunk Nov 13, 2026
23 checks passed
@dcalhoun
dcalhoun deleted the fix/ios-scheme-caller-token branch November 13, 2026 22:30
jkmassel added a commit that referenced this pull request Nov 16, 2026
A test that came in from trunk with #902 created an `EditorHTTPClient`
without an `authorizationScope`, which this branch made required. It now
builds the client from the test's own configuration, which scopes the
header to that site. The test only compiles for iOS, so the host build
missed it.
jkmassel added a commit that referenced this pull request Nov 16, 2026
…e app names (#757)

* fix!: send the Authorization header only to the site and the hosts the app names

The site's `Authorization` header was attached to every request the
editor made, whatever the host: iOS `EditorHTTPClient.configureRequest`,
Android `EditorHTTPClient.perform` and `download`, the manifest request
of Android's `org.wordpress.gutenberg.EditorAssetsLibrary`, and the web
editor's `tokenAuthMiddleware`. An asset on another party's host, or an
`apiFetch( { url } )` to another party's service, received the site's
credentials.

A request now carries the header when its origin (scheme, host and port)
is that of `siteURL` or `siteApiRoot`, or when it is over HTTPS and its
host matches an entry in the new `EditorConfiguration.authHeaderDomains`.
An entry is taken as written: `s0.wp.com` is that one host, and
`*.wp.com` is `wp.com` and every subdomain of it. The library infers
nothing about WordPress.com; both demo apps name `*.wp.com` and
`*.files.wordpress.com` for WordPress.com accounts.

The rule lives in `EditorAuthorizationScope` on iOS and Android and in
`isWithinAuthorizationScope` on the web, and `GBKitGlobal` carries
`authHeaderDomains` to the web editor. On the web, a request by `path`
is for the site's API and keeps the header; a request by `url` alone is
checked.

BREAKING CHANGE: both native `EditorHTTPClient` constructors take a
required `authorizationScope`. iOS gains
`EditorHTTPClient(configuration:)`, which derives it.

* fix: address review of the Authorization header scope

- Send every request without cookies when the app passes an `authHeader`,
  as trunk did, not only requests that carry the header. A request with
  credentials fails the CORS check against `Access-Control-Allow-Origin: *`,
  so on Android `apiFetch( { url } )` to public-api.wordpress.com failed.
- Treat a request by `namespace` and `endpoint` as one for the site's API.
  The root URL middleware turns them into a `path`, but runs after
  `tokenAuthMiddleware`, so these requests lost the header.
- Trim newlines from the names in `authHeaderDomains` on iOS, as Android
  and the web editor already do.
- Fix the `EditorHTTPClientDelegate` docs, which said native code never adds
  the site's credential to another host, and the `postType` examples, which
  passed a string.

* test(ios): build the relay test's client from its configuration

A test that came in from trunk with #902 created an `EditorHTTPClient`
without an `authorizationScope`, which this branch made required. It now
builds the client from the test's own configuration, which scopes the
header to that site. The test only compiles for iOS, so the host build
missed it.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

[Type] Bug An existing feature does not function as intended

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants