Skip to content

Commit 9bc5740

Browse files
wpfleger96Duncan
andauthored
fix(mobile): stop notification extension sending cookies to Builderlab (#9741)
Builderlab's hosts set Cloudflare's `__cf_bm` cookie on every response. The notification extension's sessions are `.ephemeral`, which keeps an in-memory cookie store, so after the first response every later request to Builderlab sends the cookie back. The NIP-FI assertion issuer refuses any request carrying a `Cookie` header with 401 `session_required`, so the extension's assertions fail and notifications from communities that require NIP-FI fall back to "Open Buzz to view this message". - `BuzzRelayAssertionIssuer` now turns off cookie storage and sending (`httpCookieStorage = nil`, `httpShouldSetCookies = false`) on the configuration it uses for both the identity-binding check and the assertion request, whatever session it is given. - The extension's per-notification relay session gets the same settings, since the relay is also a Builderlab host. - The issuer gains a `startDownload` seam, matching `BuzzNotificationAvatarLoader`'s, and a `BuzzPushKitTests` test checks that the assertion request carries no `Cookie` header after the identity check's response sets one. Signed-off-by: Will Pfleger <wpfleger@block.xyz> Co-authored-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz>
1 parent d9c3f4e commit 9bc5740

3 files changed

Lines changed: 79 additions & 11 deletions

File tree

‎mobile/ios/BuzzPushKit/Sources/BuzzPushKit/BuzzRelayAssertionIssuer.swift‎

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,8 @@ public final class BuzzRelayAssertionIssuer: @unchecked Sendable {
9999

100100
private let loadSession: () -> BuzzOrganizationSession?
101101
private let loadHostedSession: () -> BuzzOrganizationSession?
102-
private let session: URLSession
102+
/// Cookieless: the issuer refuses any request that carries a cookie, and its hosts set one.
103+
private let configuration: URLSessionConfiguration
103104
private let now: () -> Date
104105
/// Monotonic seconds, for local deadlines a wall-clock change cannot move.
105106
private let uptime: () -> TimeInterval
@@ -114,6 +115,14 @@ public final class BuzzRelayAssertionIssuer: @unchecked Sendable {
114115
private var bound: Set<String> = []
115116
/// Hosted relays that have challenged for NIP-FI evidence in this process.
116117
private var challengedRelays: Set<String> = []
118+
/// The network transfer; tests substitute it to observe each request and its configuration.
119+
var startDownload:
120+
(URLRequest, URLSessionConfiguration, Int, @escaping (Result<Data, Error>) -> Void) -> Void =
121+
{ request, configuration, maximumBytes, completion in
122+
BuzzNotificationDownload.start(
123+
request: request, configuration: configuration, maximumBytes: maximumBytes,
124+
completion: completion)
125+
}
117126

118127
public init(
119128
session: URLSession,
@@ -122,7 +131,10 @@ public final class BuzzRelayAssertionIssuer: @unchecked Sendable {
122131
now: @escaping () -> Date = Date.init,
123132
uptime: @escaping () -> TimeInterval = { ProcessInfo.processInfo.systemUptime }
124133
) {
125-
self.session = session
134+
let configuration = session.configuration
135+
configuration.httpCookieStorage = nil
136+
configuration.httpShouldSetCookies = false
137+
self.configuration = configuration
126138
self.loadSession = loadSession
127139
self.loadHostedSession = loadHostedSession
128140
self.now = now
@@ -267,10 +279,7 @@ public final class BuzzRelayAssertionIssuer: @unchecked Sendable {
267279
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
268280
request.setValue(organization.origin, forHTTPHeaderField: "Origin")
269281
request.setValue(organization.credential, forHTTPHeaderField: "X-BB-Session-Credential")
270-
BuzzNotificationDownload.start(
271-
request: request, configuration: session.configuration,
272-
maximumBytes: Self.maximumResponseBytes
273-
) { [self] result in
282+
startDownload(request, configuration, Self.maximumResponseBytes) { [self] result in
274283
guard case .success(let data) = result,
275284
let value = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
276285
value["error"] == nil || value["error"] is NSNull
@@ -324,10 +333,7 @@ public final class BuzzRelayAssertionIssuer: @unchecked Sendable {
324333
request.setValue(auth, forHTTPHeaderField: "Authorization")
325334
// Sampled before the request, so time in flight counts against the token's life.
326335
let requestStart = uptime()
327-
BuzzNotificationDownload.start(
328-
request: request, configuration: session.configuration,
329-
maximumBytes: Self.maximumResponseBytes
330-
) { [self] result in
336+
startDownload(request, configuration, Self.maximumResponseBytes) { [self] result in
331337
guard case .success(let data) = result,
332338
let value = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
333339
let token = value["assertion"] as? String, !token.isEmpty,

‎mobile/ios/BuzzPushKit/Tests/BuzzPushKitTests/BuzzRelayAssertionLifetimeTests.swift‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,64 @@ final class BuzzRelayAssertionLifetimeTests: XCTestCase {
5050
XCTAssertEqual(mints, 2, "an assertion that expired during sleep must be replaced")
5151
}
5252

53+
/// The issuer refuses any request with a cookie, and its hosts set Cloudflare's `__cf_bm` on
54+
/// every response, so a cookie set on the identity check must never reach the mint.
55+
func testIssuerRequestsCarryNoCookieAfterAResponseSetsOne() throws {
56+
let wall = 1_800_000_000
57+
let issuer = BuzzRelayAssertionIssuer(
58+
session: URLSession(configuration: .ephemeral), loadSession: { nil },
59+
loadHostedSession: {
60+
BuzzOrganizationSession(
61+
origin: "https://app.example", credential: "hosted-credential", relayHosts: [],
62+
relayDomains: ["communities.example"], communityDomain: "communities.example")
63+
},
64+
now: { Date(timeIntervalSince1970: TimeInterval(wall)) })
65+
// A stand-in for the loading system's cookie handling: it stores each response's cookies
66+
// and sends them back, unless the configuration turns cookies off.
67+
let jar = HTTPCookieStorage.sharedCookieStorage(forGroupContainerIdentifier: UUID().uuidString)
68+
var sent: [URLRequest] = []
69+
issuer.startDownload = { request, configuration, _, completion in
70+
var request = request
71+
if configuration.httpCookieStorage != nil, configuration.httpShouldSetCookies {
72+
let cookies = jar.cookies(for: request.url!) ?? []
73+
HTTPCookie.requestHeaderFields(with: cookies).forEach {
74+
request.setValue($0.value, forHTTPHeaderField: $0.key)
75+
}
76+
}
77+
sent.append(request)
78+
if configuration.httpCookieStorage != nil {
79+
jar.setCookies(
80+
HTTPCookie.cookies(
81+
withResponseHeaderFields: [
82+
"Set-Cookie": "__cf_bm=token; Domain=app.example; Path=/; Secure; HttpOnly"
83+
], for: request.url!),
84+
for: request.url!, mainDocumentURL: nil)
85+
}
86+
let identity = ["identity": ["pubkey_hex": BuzzPushNotificationResolverTests.ownPubkey]]
87+
let assertion: [String: Any] = [
88+
"assertion": "e30.eyJpYXQiOjE4MDAwMDAwMDB9.c2ln",
89+
"nostr_pubkey": BuzzPushNotificationResolverTests.ownPubkey, "expires_at": wall + 300,
90+
]
91+
let isIdentityCheck = request.url?.path == "/api/goose/v1/buzz/nostr-identities/current"
92+
completion(Result {
93+
try JSONSerialization.data(withJSONObject: isIdentityCheck ? identity : assertion)
94+
})
95+
}
96+
let done = expectation(description: "assertion")
97+
issuer.header(
98+
relayURL: URL(string: "https://team.communities.example")!,
99+
privateKeyHex: BuzzPushNotificationResolverTests.privateKey, challenged: true
100+
) { result in
101+
XCTAssertNotNil(result)
102+
done.fulfill()
103+
}
104+
wait(for: [done], timeout: 3)
105+
XCTAssertEqual(sent.map(\.url?.path), [
106+
"/api/goose/v1/buzz/nostr-identities/current", "/api/goose/v1/buzz/identity/assertions",
107+
])
108+
XCTAssertEqual(sent.map { $0.value(forHTTPHeaderField: "Cookie") }, [nil, nil])
109+
}
110+
53111
func testDeadlineWithPhoneClock120SecondsSlowOrFast() {
54112
// Issuer: iat 10_000, exp 10_180. Request sent at uptime 1_000, answered at once.
55113
func deadline(wall: Int) -> TimeInterval {

‎mobile/ios/NotificationService/NotificationService.swift‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -160,7 +160,11 @@ final class NotificationService: UNNotificationServiceExtension {
160160
// Only a resolved message offers Reply; the extension sets it below.
161161
content.categoryIdentifier = ""
162162

163-
let session = URLSession(configuration: .ephemeral)
163+
let configuration = URLSessionConfiguration.ephemeral
164+
// The relay's hosts set a Cloudflare cookie the extension must never send back.
165+
configuration.httpCookieStorage = nil
166+
configuration.httpShouldSetCookies = false
167+
let session = URLSession(configuration: configuration)
164168
self.session = session
165169
let resolver = makeResolver(session: session)
166170
self.resolver = resolver

0 commit comments

Comments
 (0)