diff --git a/mobile/ios/BuzzPushKit/Sources/BuzzPushKit/BuzzRelayAssertionIssuer.swift b/mobile/ios/BuzzPushKit/Sources/BuzzPushKit/BuzzRelayAssertionIssuer.swift index 4de52d6fda..41c791a6ab 100644 --- a/mobile/ios/BuzzPushKit/Sources/BuzzPushKit/BuzzRelayAssertionIssuer.swift +++ b/mobile/ios/BuzzPushKit/Sources/BuzzPushKit/BuzzRelayAssertionIssuer.swift @@ -99,7 +99,8 @@ public final class BuzzRelayAssertionIssuer: @unchecked Sendable { private let loadSession: () -> BuzzOrganizationSession? private let loadHostedSession: () -> BuzzOrganizationSession? - private let session: URLSession + /// Cookieless: the issuer refuses any request that carries a cookie, and its hosts set one. + private let configuration: URLSessionConfiguration private let now: () -> Date /// Monotonic seconds, for local deadlines a wall-clock change cannot move. private let uptime: () -> TimeInterval @@ -114,6 +115,14 @@ public final class BuzzRelayAssertionIssuer: @unchecked Sendable { private var bound: Set = [] /// Hosted relays that have challenged for NIP-FI evidence in this process. private var challengedRelays: Set = [] + /// The network transfer; tests substitute it to observe each request and its configuration. + var startDownload: + (URLRequest, URLSessionConfiguration, Int, @escaping (Result) -> Void) -> Void = + { request, configuration, maximumBytes, completion in + BuzzNotificationDownload.start( + request: request, configuration: configuration, maximumBytes: maximumBytes, + completion: completion) + } public init( session: URLSession, @@ -122,7 +131,10 @@ public final class BuzzRelayAssertionIssuer: @unchecked Sendable { now: @escaping () -> Date = Date.init, uptime: @escaping () -> TimeInterval = { ProcessInfo.processInfo.systemUptime } ) { - self.session = session + let configuration = session.configuration + configuration.httpCookieStorage = nil + configuration.httpShouldSetCookies = false + self.configuration = configuration self.loadSession = loadSession self.loadHostedSession = loadHostedSession self.now = now @@ -267,10 +279,7 @@ public final class BuzzRelayAssertionIssuer: @unchecked Sendable { request.setValue("application/json", forHTTPHeaderField: "Content-Type") request.setValue(organization.origin, forHTTPHeaderField: "Origin") request.setValue(organization.credential, forHTTPHeaderField: "X-BB-Session-Credential") - BuzzNotificationDownload.start( - request: request, configuration: session.configuration, - maximumBytes: Self.maximumResponseBytes - ) { [self] result in + startDownload(request, configuration, Self.maximumResponseBytes) { [self] result in guard case .success(let data) = result, let value = try? JSONSerialization.jsonObject(with: data) as? [String: Any], value["error"] == nil || value["error"] is NSNull @@ -324,10 +333,7 @@ public final class BuzzRelayAssertionIssuer: @unchecked Sendable { request.setValue(auth, forHTTPHeaderField: "Authorization") // Sampled before the request, so time in flight counts against the token's life. let requestStart = uptime() - BuzzNotificationDownload.start( - request: request, configuration: session.configuration, - maximumBytes: Self.maximumResponseBytes - ) { [self] result in + startDownload(request, configuration, Self.maximumResponseBytes) { [self] result in guard case .success(let data) = result, let value = try? JSONSerialization.jsonObject(with: data) as? [String: Any], let token = value["assertion"] as? String, !token.isEmpty, diff --git a/mobile/ios/BuzzPushKit/Tests/BuzzPushKitTests/BuzzRelayAssertionLifetimeTests.swift b/mobile/ios/BuzzPushKit/Tests/BuzzPushKitTests/BuzzRelayAssertionLifetimeTests.swift index 72be56629c..774c24aa85 100644 --- a/mobile/ios/BuzzPushKit/Tests/BuzzPushKitTests/BuzzRelayAssertionLifetimeTests.swift +++ b/mobile/ios/BuzzPushKit/Tests/BuzzPushKitTests/BuzzRelayAssertionLifetimeTests.swift @@ -50,6 +50,64 @@ final class BuzzRelayAssertionLifetimeTests: XCTestCase { XCTAssertEqual(mints, 2, "an assertion that expired during sleep must be replaced") } + /// The issuer refuses any request with a cookie, and its hosts set Cloudflare's `__cf_bm` on + /// every response, so a cookie set on the identity check must never reach the mint. + func testIssuerRequestsCarryNoCookieAfterAResponseSetsOne() throws { + let wall = 1_800_000_000 + let issuer = BuzzRelayAssertionIssuer( + session: URLSession(configuration: .ephemeral), loadSession: { nil }, + loadHostedSession: { + BuzzOrganizationSession( + origin: "https://app.example", credential: "hosted-credential", relayHosts: [], + relayDomains: ["communities.example"], communityDomain: "communities.example") + }, + now: { Date(timeIntervalSince1970: TimeInterval(wall)) }) + // A stand-in for the loading system's cookie handling: it stores each response's cookies + // and sends them back, unless the configuration turns cookies off. + let jar = HTTPCookieStorage.sharedCookieStorage(forGroupContainerIdentifier: UUID().uuidString) + var sent: [URLRequest] = [] + issuer.startDownload = { request, configuration, _, completion in + var request = request + if configuration.httpCookieStorage != nil, configuration.httpShouldSetCookies { + let cookies = jar.cookies(for: request.url!) ?? [] + HTTPCookie.requestHeaderFields(with: cookies).forEach { + request.setValue($0.value, forHTTPHeaderField: $0.key) + } + } + sent.append(request) + if configuration.httpCookieStorage != nil { + jar.setCookies( + HTTPCookie.cookies( + withResponseHeaderFields: [ + "Set-Cookie": "__cf_bm=token; Domain=app.example; Path=/; Secure; HttpOnly" + ], for: request.url!), + for: request.url!, mainDocumentURL: nil) + } + let identity = ["identity": ["pubkey_hex": BuzzPushNotificationResolverTests.ownPubkey]] + let assertion: [String: Any] = [ + "assertion": "e30.eyJpYXQiOjE4MDAwMDAwMDB9.c2ln", + "nostr_pubkey": BuzzPushNotificationResolverTests.ownPubkey, "expires_at": wall + 300, + ] + let isIdentityCheck = request.url?.path == "/api/goose/v1/buzz/nostr-identities/current" + completion(Result { + try JSONSerialization.data(withJSONObject: isIdentityCheck ? identity : assertion) + }) + } + let done = expectation(description: "assertion") + issuer.header( + relayURL: URL(string: "https://team.communities.example")!, + privateKeyHex: BuzzPushNotificationResolverTests.privateKey, challenged: true + ) { result in + XCTAssertNotNil(result) + done.fulfill() + } + wait(for: [done], timeout: 3) + XCTAssertEqual(sent.map(\.url?.path), [ + "/api/goose/v1/buzz/nostr-identities/current", "/api/goose/v1/buzz/identity/assertions", + ]) + XCTAssertEqual(sent.map { $0.value(forHTTPHeaderField: "Cookie") }, [nil, nil]) + } + func testDeadlineWithPhoneClock120SecondsSlowOrFast() { // Issuer: iat 10_000, exp 10_180. Request sent at uptime 1_000, answered at once. func deadline(wall: Int) -> TimeInterval { diff --git a/mobile/ios/NotificationService/NotificationService.swift b/mobile/ios/NotificationService/NotificationService.swift index 76a46a1726..f3cb14c544 100644 --- a/mobile/ios/NotificationService/NotificationService.swift +++ b/mobile/ios/NotificationService/NotificationService.swift @@ -160,7 +160,11 @@ final class NotificationService: UNNotificationServiceExtension { // Only a resolved message offers Reply; the extension sets it below. content.categoryIdentifier = "" - let session = URLSession(configuration: .ephemeral) + let configuration = URLSessionConfiguration.ephemeral + // The relay's hosts set a Cloudflare cookie the extension must never send back. + configuration.httpCookieStorage = nil + configuration.httpShouldSetCookies = false + let session = URLSession(configuration: configuration) self.session = session let resolver = makeResolver(session: session) self.resolver = resolver