diff --git a/mobile/lib/shared/hosted/bounded_http_response.dart b/mobile/lib/shared/hosted/bounded_http_response.dart index 607d5d22b0..c4ce978603 100644 --- a/mobile/lib/shared/hosted/bounded_http_response.dart +++ b/mobile/lib/shared/hosted/bounded_http_response.dart @@ -4,14 +4,16 @@ import 'package:http/http.dart' as http; import '../http/app_http_client.dart'; -/// One deadline covers headers and the bounded body. Abort only this request, -/// leaving the shared client usable for sign-out and subsequent attempts. +/// One deadline, [timeout], covers headers and the bounded body. Abort only +/// this request, leaving the shared client usable for sign-out and subsequent +/// attempts. /// [onHeaders] sees the response as soon as its headers arrive, before the /// body is read, even if reading the body then fails. Future boundedHttpResponse( http.Client client, http.Request source, { int maxBytes = 65536, + Duration timeout = const Duration(seconds: 30), void Function(http.BaseResponse headers)? onHeaders, }) async { final abort = Completer(); @@ -55,7 +57,7 @@ Future boundedHttpResponse( } try { - return await read().timeout(const Duration(seconds: 30)); + return await read().timeout(timeout); } on TimeoutException { noteHttpDeadline(request); rethrow; diff --git a/mobile/lib/shared/push/android_push_authority.dart b/mobile/lib/shared/push/android_push_authority.dart index 11d7e86966..44e8aebc91 100644 --- a/mobile/lib/shared/push/android_push_authority.dart +++ b/mobile/lib/shared/push/android_push_authority.dart @@ -192,7 +192,13 @@ class AndroidPushAuthority { } } final grant = await _pointOrigin(relayOrigin, relayPubkey); - await _revokeUnreferencedDelegations(desiredRelays()); + // This origin counts as desired even before the caller's list shows + // it, but only while it is still wanted: an opt-out that landed + // during the delegation must see that delegation revoked. + await _revokeUnreferencedDelegations({ + ...desiredRelays(), + if (stillWanted()) relayOrigin, + }); return grant; } } on _EnrollmentNoLongerWanted { @@ -355,7 +361,7 @@ class AndroidPushAuthority { final handle = response['installation_handle']; final expiresAt = response['expires_at']; if (handle is! String || expiresAt is! int) { - throw const FormatException( + throw const AndroidPushGatewayResponseInvalid( 'Push gateway returned a malformed installation.', ); } @@ -563,7 +569,9 @@ class AndroidPushAuthority { ); final endpointGrant = response['endpoint_grant']; if (endpointGrant is! String || endpointGrant.isEmpty) { - throw const FormatException('Push gateway returned a malformed grant.'); + throw const AndroidPushGatewayResponseInvalid( + 'Push gateway returned a malformed grant.', + ); } state = await _load(); final granted = delegation.copyWith( @@ -686,7 +694,7 @@ class AndroidPushAuthority { final id = response['challenge_id']; final text = response['challenge']; if (id is! String || text is! String) { - throw const FormatException( + throw const AndroidPushGatewayResponseInvalid( 'Push gateway returned a malformed challenge.', ); } diff --git a/mobile/lib/shared/push/android_push_gateway.dart b/mobile/lib/shared/push/android_push_gateway.dart index 4d7d39e17d..8551c06cc7 100644 --- a/mobile/lib/shared/push/android_push_gateway.dart +++ b/mobile/lib/shared/push/android_push_gateway.dart @@ -2,6 +2,7 @@ import 'dart:convert'; import 'package:http/http.dart' as http; +import '../hosted/bounded_http_response.dart'; import '../http/app_http_client.dart'; /// The gateway answered with a refusal. Signed installation calls answer every @@ -29,6 +30,13 @@ class AndroidPushGatewayRejection implements Exception { String toString() => 'Push gateway refused $route: $status ${code ?? ''}'; } +/// The gateway answered with something the app cannot read: no JSON object, +/// or one missing a field the call needs. Unlike a refusal, this points at a +/// gateway or protocol defect, so it is reported to diagnostics. +class AndroidPushGatewayResponseInvalid extends FormatException { + const AndroidPushGatewayResponseInvalid(super.message); +} + /// One round trip to the gateway's JSON API. class AndroidPushGatewayClient { AndroidPushGatewayClient({ @@ -42,19 +50,35 @@ class AndroidPushGatewayClient { final http.Client _client; /// Posts [body] to [route] and returns the JSON object answered with - /// [expectedStatus]. Transport failures propagate unchanged. + /// [expectedStatus]. Transport failures propagate unchanged. At [timeout] + /// the request is aborted, not just abandoned, so a retry never races a + /// copy of itself still on its way to the gateway. Future> post( String route, Map body, { int expectedStatus = 200, }) async { - final response = await _client - .post( - baseUrl.resolve(route), - headers: const {'content-type': 'application/json'}, - body: jsonEncode(body), - ) - .timeout(timeout); + final http.Response response; + int? status; + try { + response = await boundedHttpResponse( + _client, + http.Request('POST', baseUrl.resolve(route)) + ..headers['content-type'] = 'application/json' + ..body = jsonEncode(body), + timeout: timeout, + onHeaders: (headers) => status = headers.statusCode, + ); + } on FormatException catch (error) { + // The only one a bounded read throws: a body over its limit. A refusal + // keeps its status, so an oversized 503 still reads as transient. + if (status case final status? when status != expectedStatus) { + throw AndroidPushGatewayRejection(route, status, null); + } + throw AndroidPushGatewayResponseInvalid( + 'Push gateway answered $route unreadably: ${error.message}', + ); + } final decoded = _object(response.bodyBytes); if (response.statusCode != expectedStatus) { throw AndroidPushGatewayRejection( @@ -64,7 +88,7 @@ class AndroidPushGatewayClient { ); } if (decoded == null) { - throw FormatException( + throw AndroidPushGatewayResponseInvalid( 'Push gateway answered $route without a JSON object.', ); } diff --git a/mobile/lib/shared/push/push_bridge.dart b/mobile/lib/shared/push/push_bridge.dart index fcc6e0d4a4..b36f868196 100644 --- a/mobile/lib/shared/push/push_bridge.dart +++ b/mobile/lib/shared/push/push_bridge.dart @@ -461,6 +461,15 @@ Future enrollBuzzPush( } on AndroidPushAttestationUnavailable catch (error) { pushUnavailableReason.value = error.reason; rethrow; + } on AndroidPushGatewayResponseInvalid catch (error, stackTrace) { + // As on iOS, only a reply the app cannot read is reported; refusals and + // transport failures are routine. + diagnostics.reportError( + error, + stackTrace, + operation: DiagnosticOperation.pushGatewayResponse, + ); + rethrow; } if (enrolled == null) return null; grant = _grantOf(enrolled); diff --git a/mobile/test/features/settings/android_notifications_test.dart b/mobile/test/features/settings/android_notifications_test.dart index 9442513514..6efc28390d 100644 --- a/mobile/test/features/settings/android_notifications_test.dart +++ b/mobile/test/features/settings/android_notifications_test.dart @@ -387,6 +387,69 @@ void main() { await unmount(tester); }); + testWidgets('turning push off while it delegates ends the attempt quietly', ( + tester, + ) async { + fcmDeviceToken.value = 'test-fcm-token'; + addTearDown(() => fcmDeviceToken.value = null); + final failures = []; + final print = debugPrint; + debugPrint = (message, {wrapWidth}) { + if (message != null && message.contains('bootstrap failed')) { + failures.add(message); + } + }; + final gateway = FakePushGateway( + nowSeconds: () => DateTime.now().millisecondsSinceEpoch ~/ 1000, + ); + final delegated = Completer(); + gateway.holdResponseFor['/v1/delegations'] = delegated.future; + final session = _Connected(); + final descriptorGate = Completer(); + await pumpBootstrap( + tester, + platform: TargetPlatform.android, + relayUrl: 'https://relay.example', + enabled: true, + session: session, + gateway: gateway, + descriptorGate: descriptorGate.future, + subscriptions: [ + BuzzPushSubscription( + filter: BuzzPushFilter(kinds: const [9], pTags: ['a' * 64]), + notificationClass: 'default', + ), + ], + ); + descriptorGate.complete(); + await tester.pump(); + await tester.pump(); + expect(gateway.bodiesFor('/v1/delegations'), hasLength(1)); + + // The gateway accepted the delegation; the opt-out lands before the phone + // hears back. + final container = ProviderScope.containerOf( + tester.element(find.byType(BuzzPushBootstrap)), + ); + await container + .read(communityListProvider.notifier) + .setPushNotificationsEnabled( + container.read(communityListProvider).value!.single.id, + false, + ); + delegated.complete(); + await tester.pumpAndSettle(); + + // No lease is published, the new delegation is revoked, and the attempt + // ends as cancelled rather than failing into a retry. + expect(session.leases.where((lease) => lease['active'] == true), isEmpty); + expect(gateway.installations.values.single.revokedDelegations, isNotEmpty); + // Foundation checks its debug variables before teardowns run. + debugPrint = print; + expect(failures, isEmpty); + await unmount(tester); + }); + testWidgets('resuming while the relay reconnects refreshes the FCM token', ( tester, ) async { diff --git a/mobile/test/helpers/android_push_fakes.dart b/mobile/test/helpers/android_push_fakes.dart index 3b15914eff..ca771fb9c3 100644 --- a/mobile/test/helpers/android_push_fakes.dart +++ b/mobile/test/helpers/android_push_fakes.dart @@ -89,10 +89,16 @@ class FakePushGateway { /// Routes that answer with this status instead of acting. final failWith = {}; + /// Pad [failWith] answers past the client's 64 KiB read limit. + bool oversizeFailures = false; + /// Routes whose next call is refused like an expired challenge: answered /// `not_authorized` without acting. final refuseOnce = {}; + /// Routes whose next response waits for the future after the gateway acted. + final holdResponseFor = >{}; + /// Refuse attestations like a gateway that does not trust this phone. bool refuseAttestation = false; @@ -106,9 +112,15 @@ class FakePushGateway { final body = jsonDecode(request.body) as Map; requests.add((route: route, body: body)); final status = failWith[route]; - if (status != null) return _json(status, {'error': 'unavailable'}); + if (status != null) { + return _json(status, { + 'error': 'unavailable', + if (oversizeFailures) 'padding': 'x' * 65537, + }); + } if (refuseOnce.remove(route)) return _notAuthorized(); final response = _handle(route, body); + await holdResponseFor.remove(route); if (loseResponseFor.remove(route)) { throw http.ClientException('connection lost'); } diff --git a/mobile/test/shared/push/android_push_authority_test.dart b/mobile/test/shared/push/android_push_authority_test.dart index dac1ab5d0f..4891997d80 100644 --- a/mobile/test/shared/push/android_push_authority_test.dart +++ b/mobile/test/shared/push/android_push_authority_test.dart @@ -149,20 +149,32 @@ void main() { test( 'an unavailable gateway keeps the journal and a refusal clears it', () async { - gateway.failWith['/v1/installations'] = 503; - await expectLater( - enroll(), - throwsA( - isA().having( - (e) => e.isTransient, - 'transient', - true, + // Even when the refusal's body is too large to read. + for (final oversized in [false, true]) { + gateway + ..oversizeFailures = oversized + ..failWith['/v1/installations'] = 503; + await expectLater( + enroll(), + throwsA( + isA().having( + (e) => e.isTransient, + 'transient', + true, + ), ), - ), - ); - expect(store.value, contains('pendingEnrollment')); - expect(keystore.key, isNotNull); - gateway.failWith.remove('/v1/installations'); + ); + expect(store.value, contains('pendingEnrollment')); + expect(keystore.key, isNotNull); + } + + gateway.failWith['/v1/installations'] = 403; + await expectLater(enroll(), throwsA(isA())); + expect(keystore.key, isNull); + expect(store.value, isNot(contains('pendingEnrollment'))); + gateway + ..oversizeFailures = false + ..failWith.remove('/v1/installations'); gateway.refuseAttestation = true; await expectLater( @@ -501,6 +513,36 @@ void main() { }, ); + test( + 'the enrolling relay keeps its delegation before the caller lists it', + () async { + // A community's relay may not be in the desired list yet when its first + // enrollment finishes; while it is still wanted, its new delegation is + // not swept. + final grant = (await authority.enroll( + relayOrigin: _relayA, + relayPubkey: _keyA, + endpoint: 'token-1', + stillWanted: () => true, + desiredRelays: () => {}, + ))!; + final installation = gateway.installations.values.single; + expect(installation.revokedDelegations, isEmpty); + expect(grant.generation, 1); + + // An opt-out that lands while the next delegation is in flight sees + // that delegation revoked by the same sweep. + await authority.enroll( + relayOrigin: _relayB, + relayPubkey: _keyB, + endpoint: 'token-1', + stillWanted: () => gateway.bodiesFor('/v1/delegations').length < 2, + desiredRelays: () => {_relayA}, + ); + expect(installation.revokedDelegations, {'$_keyB/1'}); + }, + ); + test('an opt-out after enrollment creates no delegation', () async { final enrolling = authority.enroll( relayOrigin: _relayA, diff --git a/mobile/test/shared/push/push_bridge_android_test.dart b/mobile/test/shared/push/push_bridge_android_test.dart index 3f8ea594b4..535406fbfc 100644 --- a/mobile/test/shared/push/push_bridge_android_test.dart +++ b/mobile/test/shared/push/push_bridge_android_test.dart @@ -1,11 +1,19 @@ +import 'dart:async'; +import 'dart:convert'; + +import 'package:buzz/shared/diagnostics/diagnostic_reporter.dart'; import 'package:buzz/shared/push/android_push_authority.dart'; +import 'package:buzz/shared/push/android_push_gateway.dart'; import 'package:buzz/shared/push/android_push_keystore.dart'; import 'package:buzz/shared/push/push_bridge.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart' as http; +import 'package:http/testing.dart'; import '../../helpers/android_push_fakes.dart'; +import '../../helpers/recording_diagnostics.dart'; const _channel = MethodChannel('buzz/push_registration'); @@ -189,6 +197,66 @@ void main() { expect(pushUnavailableReason.value, isNotNull); }); + test('only a gateway reply the app cannot read is reported', () async { + debugDefaultTargetPlatformOverride = TargetPlatform.android; + fcmDeviceToken.value = 'fcm-token'; + final diagnostics = RecordingDiagnostics(); + + Future enroll() => enrollBuzzPush( + 'wss://relay.example/', + 'https://gateway.example/', + relayOrigin: 'wss://relay.example', + relayPubkey: 'a' * 64, + desiredRelays: () => {'wss://relay.example'}, + diagnostics: diagnostics, + ).then((_) {}); + + for (final (reply, reported) in [ + // A refusal and gateway trouble are routine. + (http.Response(jsonEncode({'error': 'unavailable'}), 503), false), + // Even when the refusal's body is too large to read. + (http.Response('x' * 65537, 503), false), + // A challenge with no fields, and a body that is not JSON, are not. + (http.Response(jsonEncode({}), 200), true), + (http.Response('', 200), true), + (http.Response('x' * 65537, 200), true), + ]) { + diagnostics.errors.clear(); + debugAndroidPushAuthority = AndroidPushAuthority( + keystore: FakeAndroidKeystore(), + gateway: AndroidPushGatewayClient( + baseUrl: Uri.parse('https://push.example'), + client: MockClient((_) async => reply), + ), + store: _MemoryStore(), + sleep: (_) async {}, + ); + await expectLater(enroll(), throwsA(anything)); + expect(diagnostics.errors, [ + if (reported) + ( + AndroidPushGatewayResponseInvalid, + DiagnosticOperation.pushGatewayResponse, + ), + ], reason: '${reply.statusCode} ${reply.body.length} bytes'); + } + }); + + test('a gateway call that times out is aborted, not abandoned', () async { + final aborted = Completer(); + final gateway = AndroidPushGatewayClient( + baseUrl: Uri.parse('https://push.example'), + timeout: const Duration(milliseconds: 10), + client: _HangingClient(aborted), + ); + + await expectLater( + gateway.post('/v1/installations/challenges', {'v': 1}), + throwsA(isA()), + ); + await aborted.future.timeout(const Duration(seconds: 1)); + }); + test('enrolling without a token fails loudly', () async { debugDefaultTargetPlatformOverride = TargetPlatform.android; @@ -214,3 +282,19 @@ class _MemoryStore implements AndroidPushStateStore { @override Future write(String? next) async => value = next; } + +/// Never answers, and completes [aborted] when the request's abort trigger +/// fires. +class _HangingClient extends http.BaseClient { + _HangingClient(this.aborted); + + final Completer aborted; + + @override + Future send(http.BaseRequest request) { + final trigger = (request as http.Abortable).abortTrigger; + if (trigger == null) throw StateError('the request is not abortable'); + trigger.then((_) => aborted.complete()); + return Completer().future; + } +} diff --git a/mobile/test/shared/push/push_bridge_test.dart b/mobile/test/shared/push/push_bridge_test.dart index beb3fc6634..5bff882310 100644 --- a/mobile/test/shared/push/push_bridge_test.dart +++ b/mobile/test/shared/push/push_bridge_test.dart @@ -180,6 +180,25 @@ void main() { }, ); + test('a community that opted out enrolls nothing', () async { + debugDefaultTargetPlatformOverride = TargetPlatform.iOS; + final methods = []; + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(_channel, (call) async { + methods.add(call.method); + return null; + }); + + final grant = await enrollBuzzPush( + 'wss://relay.example/', + 'https://gateway.example/', + stillWanted: () => false, + ); + + expect(grant, isNull); + expect(methods, isEmpty); + }); + test('a gateway reply the app cannot read is reported and still fails ' 'enrollment', () async { debugDefaultTargetPlatformOverride = TargetPlatform.iOS;