Repository navigation
fix(ios): require a caller token on the native schemes - #902
Conversation
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>
XCFramework BuildThis PR's XCFramework is available for testing. Add the following to your .package(url: "https://github.com/wordpress-mobile/GutenbergKit", branch: "pr-build/902")Built from cdce298 |
| 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() | ||
| } |
There was a problem hiding this comment.
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.
| 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() | |
| } |
| 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 | ||
| } |
There was a problem hiding this comment.
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:
| 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 | |
| } |
| 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) |
There was a problem hiding this comment.
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:
| 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.") |
* 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>
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.
…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.
Description
Requires a per-session token on the iOS
gbk-rest:andgbk-upload:URL schemes, so only the editor page can use them. Mirrors the token Android's loopback upload server already requires. Ref CMM-2462.SchemeCallerToken) and passes it to the page inGBKit, asrestRelay.tokenandnativeUploadToken.fetchrelay,XMLHttpRequestrelay, and native upload requests send it asRelay-Authorization: Bearer <token>.RestRelaySchemeHandlerfails a request without it as a network error, before relaying.MediaUploadSchemeHandleranswers401before routing. The relay never forwards the header to the site.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:XMLHttpRequestrelay).🤖 Generated with Claude Code