Skip to content

Commit 0636d21

Browse files
browstudio
andauthored
feat(mobile): report push gateway replies the app cannot read (#9806)
Reports push gateway replies the app cannot read, the last explicit error report from [the diagnostic reporting spec](https://github.com/block/buzz/blob/main/docs/mobile-diagnostic-reporting.md) still missing. The gateway is called from native code (`BuzzDevPushEnrollmentDriver`), and Dart used to see every native failure as one code. Native now fails with its own `gateway_response_invalid` code when a reply does not match the gateway's protocol (bad JSON, a 2xx status other than the one the gateway sends for that call, or a challenge, installation or delegation reply with missing or invalid fields), carrying no text from the reply. Dart reports that as a push gateway response error and rethrows as before. - **Not reported:** status mismatches (including 4xx and 5xx), timeouts and offline failures, which the spec counts as routine; local-state failures such as an App Attest key mismatch; and a plausible challenge that has already expired by the device's clock, since a phone whose clock runs fast would otherwise report on every retry. An expiry no real challenge could have (zero, negative or a relative TTL) is still reported. Local enrollment logs keep the fixed name of the failing route. - **Attribution:** the report goes through the signing member, so an enrollment that finishes after a community switch names no one else. ## Validation - `push_bridge_test.dart`: an unreadable reply is reported once and enrollment still fails; routine native codes report nothing. - `BuzzDevPushEnrollmentDriverTests`: bad JSON and an unexpected 2xx fail as an unreadable reply; a 503 stays a status mismatch; a plausible but expired challenge is not an unreadable reply, while an expiry of 0, -1 or 300 is. - `notification_toggle_test.dart`: an unreadable reply during the notification journey files one report while the member matches and none after it changes. Full-app run on an iPhone 17 Pro simulator at 6de2998: startup and session restore, channel list, opening a channel, sending, Settings and the notifications toggle, and background and foreground. With the gateway pointed at a local server that answers 200 with HTML, enrollment failed with `gateway_response_invalid`, retries backed off, and the app stayed usable. Not covered: receiving a real push. --------- Signed-off-by: Tom Brow <tomb@block.xyz> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
1 parent ec1b786 commit 0636d21

8 files changed

Lines changed: 262 additions & 11 deletions

File tree

‎docs/mobile-diagnostic-reporting.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# Mobile diagnostic reporting
22

3-
Status: step one in progress. Implemented: the reporting module and explicit error reports (for push, the relay's capability descriptor; push gateway replies are not reported yet). Still to come: networking counts.
3+
Status: step one in progress. Implemented: the reporting module and explicit error reports (for push, the relay's capability descriptor and the push gateway's replies). Still to come: networking counts.
44

55
Terminology is defined in [CONTEXT.md](../CONTEXT.md#mobile-builds). The decisions behind this spec are in [ADR 0007](adr/0007-diagnostic-reporting-follows-the-destination.md) and [ADR 0008](adr/0008-sentry-for-mobile-diagnostic-reporting.md).
66

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

Lines changed: 29 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,10 @@ public enum BuzzDevPushEnrollmentError: Error, LocalizedError, Equatable {
9595
case invalidRelayURL
9696
case invalidRelayDescriptor
9797
case invalidResponse(route: String)
98+
/// A gateway reply whose body does not decode, or whose fields fail
99+
/// validation. Unlike `invalidResponse`, which also covers unreadable local
100+
/// enrollment state, this one means the gateway's contract drifted.
101+
case invalidGatewayResponse(route: String)
98102
case unexpectedStatus(route: String, expected: Int, actual: Int, body: String)
99103
case randomGenerationFailed(Int32)
100104
case appAttestUnsupported
@@ -109,7 +113,7 @@ public enum BuzzDevPushEnrollmentError: Error, LocalizedError, Equatable {
109113
return "The relay URL must be a ws or wss origin."
110114
case .invalidRelayDescriptor:
111115
return "NIP-11 must contain exactly one valid current push key."
112-
case .invalidResponse(let route):
116+
case .invalidResponse(let route), .invalidGatewayResponse(let route):
113117
return "The response from \(route) did not match the closed push protocol."
114118
case .unexpectedStatus(let route, let expected, let actual, let body):
115119
return "The response from \(route) was HTTP \(actual), expected \(expected): \(body)"
@@ -342,6 +346,8 @@ public final class BuzzDevPushEnrollmentDriver {
342346
/// starts this far in the past, so a fast clock neither signs a `not_before` the gateway
343347
/// has not reached nor an `expires_at` beyond its maximum lifetime.
344348
static let clockSkewAllowanceSeconds: Int64 = 120
349+
/// 2025-01-01T00:00:00Z. No challenge the gateway issues can expire before this.
350+
static let earliestPlausibleChallengeExpiry: Int64 = 1_735_689_600
345351
private let installationIdBytes: () throws -> Data
346352

347353
/// Creates a driver backed by Apple's App Attest service and persists the
@@ -863,9 +869,19 @@ public final class BuzzDevPushEnrollmentDriver {
863869
)
864870
guard let id = UUID(uuidString: response.challengeId),
865871
response.challengeId == id.uuidString.lowercased(),
866-
Self.isBase64URLChallenge(response.challenge),
867-
response.expiresAt > Int64(now().timeIntervalSince1970)
872+
Self.isBase64URLChallenge(response.challenge)
868873
else {
874+
throw BuzzDevPushEnrollmentError.invalidGatewayResponse(route: "v1/installations/challenges")
875+
}
876+
// The gateway issues an absolute Unix time, so a value below any real date
877+
// (zero, negative, a relative TTL) is contract drift whatever this phone's
878+
// clock says.
879+
guard response.expiresAt >= Self.earliestPlausibleChallengeExpiry else {
880+
throw BuzzDevPushEnrollmentError.invalidGatewayResponse(route: "v1/installations/challenges")
881+
}
882+
// A plausible expiry that already looks expired usually means the phone's
883+
// clock runs fast, not that the gateway broke its contract.
884+
guard response.expiresAt > Int64(now().timeIntervalSince1970) else {
869885
throw BuzzDevPushEnrollmentError.invalidResponse(route: "v1/installations/challenges")
870886
}
871887
return Challenge(id: id, value: response.challenge)
@@ -896,7 +912,7 @@ public final class BuzzDevPushEnrollmentDriver {
896912
response.endpointEpoch == Self.endpointEpoch,
897913
response.expiresAt == expiresAt
898914
else {
899-
throw BuzzDevPushEnrollmentError.invalidResponse(route: "v1/installations")
915+
throw BuzzDevPushEnrollmentError.invalidGatewayResponse(route: "v1/installations")
900916
}
901917
return installation
902918
}
@@ -927,7 +943,7 @@ public final class BuzzDevPushEnrollmentDriver {
927943
)
928944
)
929945
guard !response.endpointGrant.isEmpty, response.endpointGrant.utf8.count <= 4_096 else {
930-
throw BuzzDevPushEnrollmentError.invalidResponse(route: "v1/delegations")
946+
throw BuzzDevPushEnrollmentError.invalidGatewayResponse(route: "v1/delegations")
931947
}
932948
return response.endpointGrant
933949
}
@@ -972,11 +988,18 @@ public final class BuzzDevPushEnrollmentDriver {
972988
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
973989
request.httpBody = try JSONEncoder().encode(body)
974990
let (data, response) = try await session.data(for: request)
991+
// The gateway answers each route with exactly one success status, so any
992+
// other 2xx means its contract drifted rather than a routine refusal.
993+
if let http = response as? HTTPURLResponse, (200..<300).contains(http.statusCode),
994+
http.statusCode != expectedStatus
995+
{
996+
throw BuzzDevPushEnrollmentError.invalidGatewayResponse(route: route)
997+
}
975998
try Self.expectStatus(response, data: data, route: route, expected: expectedStatus)
976999
do {
9771000
return try JSONDecoder().decode(Response.self, from: data)
9781001
} catch {
979-
throw BuzzDevPushEnrollmentError.invalidResponse(route: route)
1002+
throw BuzzDevPushEnrollmentError.invalidGatewayResponse(route: route)
9801003
}
9811004
}
9821005

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

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1308,6 +1308,92 @@ final class BuzzDevPushEnrollmentDriverTests: XCTestCase {
13081308
}
13091309
}
13101310

1311+
func testMalformedGatewayReplyIsContractDrift() async throws {
1312+
let error = try await challengeFailure { request in
1313+
let response = HTTPURLResponse(
1314+
url: request.url!, statusCode: 200, httpVersion: "HTTP/1.1",
1315+
headerFields: ["Content-Type": "application/json"])!
1316+
return (response, Data("not json".utf8))
1317+
}
1318+
XCTAssertEqual(error, .invalidGatewayResponse(route: "v1/installations/challenges"))
1319+
}
1320+
1321+
func testUnexpectedGatewaySuccessStatusIsContractDrift() async throws {
1322+
let error = try await challengeFailure { request in
1323+
Self.response(request, status: 201, json: Self.challengeJSON(expiresAt: Self.expiresAt))
1324+
}
1325+
XCTAssertEqual(error, .invalidGatewayResponse(route: "v1/installations/challenges"))
1326+
}
1327+
1328+
func testGatewayRefusalIsRoutineStatusMismatch() async throws {
1329+
let error = try await challengeFailure { request in
1330+
Self.response(request, status: 503, json: ["error": "unavailable"])
1331+
}
1332+
XCTAssertEqual(
1333+
error,
1334+
.unexpectedStatus(
1335+
route: "v1/installations/challenges", expected: 200, actual: 503,
1336+
body: "{\"error\":\"unavailable\"}"))
1337+
}
1338+
1339+
func testExpiredLookingChallengeFromFastClockIsNotContractDrift() async throws {
1340+
// The gateway issued gateway-now + 300; this phone runs more than 300 s ahead.
1341+
let error = try await challengeFailure(
1342+
now: { Date(timeIntervalSince1970: TimeInterval(Self.now + 300 + 60)) }
1343+
) { request in
1344+
Self.response(request, status: 200, json: Self.challengeJSON(expiresAt: Self.now + 300))
1345+
}
1346+
XCTAssertEqual(error, .invalidResponse(route: "v1/installations/challenges"))
1347+
}
1348+
1349+
func testImplausibleChallengeExpiryIsContractDriftWhateverTheClockSays() async throws {
1350+
// Zero, negative and a relative TTL cannot come from the gateway's absolute now + 300.
1351+
for expiresAt: Int64 in [0, -1, 300] {
1352+
let error = try await challengeFailure { request in
1353+
Self.response(request, status: 200, json: Self.challengeJSON(expiresAt: expiresAt))
1354+
}
1355+
XCTAssertEqual(
1356+
error, .invalidGatewayResponse(route: "v1/installations/challenges"),
1357+
"expires_at \(expiresAt)")
1358+
}
1359+
}
1360+
1361+
private func challengeFailure(
1362+
now: (() -> Date)? = nil,
1363+
_ gateway: @escaping (URLRequest) -> (HTTPURLResponse, Data)
1364+
) async throws -> BuzzDevPushEnrollmentError {
1365+
let driver =
1366+
if let now {
1367+
try makeDriver(store: MemoryGrantStore(), appAttest: RecordingAppAttest(), now: now)
1368+
} else {
1369+
try makeDriver(store: MemoryGrantStore(), appAttest: RecordingAppAttest())
1370+
}
1371+
URLProtocolStub.handler = { request in
1372+
if request.httpMethod == "GET" {
1373+
return Self.response(
1374+
request,
1375+
status: 200,
1376+
json: [
1377+
"self": Self.relayPubkey,
1378+
"push": ["keys": [["pubkey": Self.relayPubkey, "current": true]]],
1379+
]
1380+
)
1381+
}
1382+
return gateway(request)
1383+
}
1384+
do {
1385+
_ = try await driver.enroll(deviceToken: Data([1]), relayURL: Self.relayURL)
1386+
} catch let error as BuzzDevPushEnrollmentError {
1387+
return error
1388+
}
1389+
XCTFail("Expected enrollment to fail at the challenge")
1390+
throw CancellationError()
1391+
}
1392+
1393+
private static func challengeJSON(expiresAt: Int64) -> [String: Any] {
1394+
["challenge_id": firstChallengeId, "challenge": challenge, "expires_at": expiresAt]
1395+
}
1396+
13111397
private func makeDriver(
13121398
gatewayBaseURL: URL = BuzzDevPushEnrollmentDriverTests.gatewayURL,
13131399
store: BuzzPushEndpointGrantStore,

‎mobile/ios/Runner/AppDelegate.swift‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -861,6 +861,19 @@ import os.log
861861
relayURL: relayURL
862862
)
863863
await MainActor.run { result(record.flutterArguments) }
864+
} catch BuzzDevPushEnrollmentError.invalidGatewayResponse(let route) {
865+
// Its own code, with no text from the reply, so Dart can report
866+
// contract drift without parsing messages. The details are only the
867+
// fixed route label, so local logs still tell the routes apart.
868+
await MainActor.run {
869+
result(
870+
FlutterError(
871+
code: "gateway_response_invalid",
872+
message: "The push gateway sent a response the app cannot read.",
873+
details: route
874+
)
875+
)
876+
}
864877
} catch {
865878
await MainActor.run {
866879
result(

‎mobile/lib/shared/push/push_bootstrap.dart‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import 'package:hooks_riverpod/hooks_riverpod.dart';
77

88
import '../community/community.dart';
99
import '../community/community_provider.dart';
10+
import '../diagnostics/diagnostic_reporter.dart';
1011
import '../relay/relay_provider.dart';
1112
import '../relay/relay_session.dart';
1213
import '../relay/signed_event_relay.dart';
@@ -559,6 +560,12 @@ class _BuzzPushLifecycle extends HookConsumerWidget {
559560
Env.pushGatewayUrl,
560561
communitiesForSnapshotRefresh:
561562
ref.read(communityListProvider).value ?? [community],
563+
// Enrollment can finish after a community switch, when reports already
564+
// name the next member.
565+
diagnostics: SignerDiagnosticReporter(
566+
ref.read(diagnosticReporterProvider),
567+
signer: memberPubkey,
568+
),
562569
);
563570
// Relay lease replacement and gateway delegation are independent state
564571
// machines. Subscription changes advance only the kind-30350 generation;

‎mobile/lib/shared/push/push_bridge.dart‎

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,16 @@ import 'package:flutter/services.dart';
66

77
import '../community/community.dart';
88
import '../deeplink/deep_link.dart';
9+
import '../diagnostics/diagnostic_reporter.dart';
910
import '../relay/relay_provider.dart';
1011
import 'push_snapshot.dart';
1112

1213
const _channel = MethodChannel('buzz/push');
1314

15+
/// The code native enrollment fails with when the push gateway's reply does
16+
/// not match its protocol.
17+
const _gatewayResponseInvalid = 'gateway_response_invalid';
18+
1419
/// Latest APNs registration state, including callbacks replayed by iOS after
1520
/// the Flutter method channel attaches.
1621
final apnsDeviceToken = ValueNotifier<String?>(null);
@@ -307,11 +312,27 @@ Future<BuzzPushEndpointGrant> enrollBuzzPush(
307312
String relayUrl,
308313
String gatewayUrl, {
309314
List<Community>? communitiesForSnapshotRefresh,
315+
DiagnosticReporter diagnostics = const NoopDiagnosticReporter(),
310316
}) async {
311-
final raw = await _channel.invokeMapMethod<dynamic, dynamic>('enrollPush', {
312-
'relayUrl': relayUrl,
313-
'gatewayUrl': gatewayUrl,
314-
});
317+
final Map<dynamic, dynamic>? raw;
318+
try {
319+
raw = await _channel.invokeMapMethod<dynamic, dynamic>('enrollPush', {
320+
'relayUrl': relayUrl,
321+
'gatewayUrl': gatewayUrl,
322+
});
323+
} on PlatformException catch (error, stackTrace) {
324+
// The gateway is called from native code. It has its own code for a reply
325+
// the app cannot read; every other failure (offline, refused, expired,
326+
// server errors) is routine and not reported.
327+
if (error.code == _gatewayResponseInvalid) {
328+
diagnostics.reportError(
329+
error,
330+
stackTrace,
331+
operation: DiagnosticOperation.pushGatewayResponse,
332+
);
333+
}
334+
rethrow;
335+
}
315336
if (raw == null) {
316337
throw StateError('Native push enrollment returned no grant.');
317338
}

‎mobile/test/features/settings/notification_toggle_test.dart‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import 'package:buzz/shared/push/dev_push_lease.dart';
1010
import 'package:buzz/shared/push/push_bootstrap.dart';
1111
import 'package:buzz/shared/push/push_lease_revocation_outbox.dart';
1212
import 'package:buzz/shared/crypto/nip44.dart';
13+
import 'package:buzz/shared/diagnostics/diagnostic_reporter.dart';
1314
import 'package:buzz/shared/relay/nostr_models.dart';
1415
import 'package:buzz/shared/relay/signed_event_relay.dart';
1516
import 'package:buzz/shared/push/push_bridge.dart';
@@ -128,6 +129,7 @@ void main() {
128129
}
129130
await storage.saveActiveId(community.id);
130131

132+
final reports = _RecordingDiagnostics();
131133
final cleanup = Completer<void>();
132134
final showingSettings = ValueNotifier(true);
133135
addTearDown(showingSettings.dispose);
@@ -172,6 +174,7 @@ void main() {
172174
discoveries++;
173175
return _descriptor;
174176
}),
177+
diagnosticReporterProvider.overrideWithValue(reports),
175178
appLifecycleProvider.overrideWith(_Lifecycle.new),
176179
],
177180
child: BuzzPushBootstrap(
@@ -307,6 +310,28 @@ void main() {
307310
await tester.pumpAndSettle();
308311
expect(discoveries, 5);
309312
expect(tester.widget<Switch>(find.byType(Switch)).onChanged, isNotNull);
313+
// A gateway reply the app cannot read is reported while the signing
314+
// member is still the reported member, and not after a community switch.
315+
messenger.setMockMethodCallHandler(
316+
nativePush,
317+
(call) async => switch (call.method) {
318+
'enrollPush' => throw PlatformException(
319+
code: 'gateway_response_invalid',
320+
),
321+
'startRegistration' ||
322+
'syncPushSnapshot' ||
323+
'takePendingNotificationResponse' => null,
324+
_ => throw StateError('Unexpected native call ${call.method}'),
325+
},
326+
);
327+
reports.member = nostr.Keys('1' * 64).public;
328+
apnsDeviceToken.value = 'test-apns-token-2';
329+
await tester.pumpAndSettle();
330+
expect(reports.operations, [DiagnosticOperation.pushGatewayResponse]);
331+
reports.member = 'e' * 64;
332+
apnsDeviceToken.value = 'test-apns-token-3';
333+
await tester.pumpAndSettle();
334+
expect(reports.operations, hasLength(1));
310335
expect(tester.takeException(), isNull);
311336
await tester.pumpWidget(const SizedBox.shrink());
312337
await tester.pumpAndSettle();
@@ -316,6 +341,23 @@ void main() {
316341
}
317342
}
318343

344+
class _RecordingDiagnostics extends NoopDiagnosticReporter {
345+
final operations = <DiagnosticOperation>[];
346+
347+
@override
348+
String? member;
349+
350+
@override
351+
void reportError(
352+
Object error,
353+
StackTrace? stackTrace, {
354+
required DiagnosticOperation operation,
355+
}) {
356+
operations.add(operation);
357+
super.reportError(error, stackTrace, operation: operation);
358+
}
359+
}
360+
319361
class _Lifecycle extends AppLifecycleNotifier {
320362
@override
321363
AppLifecycleState build() => AppLifecycleState.resumed;

0 commit comments

Comments
 (0)