fix(mobile): Android push follow-ups from enrollment review (#9892)

Follow-ups from the review of #9811 (Android push enrollment): the
review items that were safe to leave for after merge.

- **A timed-out gateway call is now aborted.** The 15 s timeout used to
abandon the POST while it kept running, so a retry could race the
original request at the gateway. The gateway client now sends through
`boundedHttpResponse`, which aborts the request at the deadline (and
caps the reply size).
- **An Android gateway reply the app can't read is reported to
diagnostics,** as #9806 does for iOS. Malformed replies (no JSON object,
missing fields, or an oversized reply with the expected status) throw
`AndroidPushGatewayResponseInvalid`, which `enrollBuzzPush` reports
under the push gateway operation. Refusals and transport failures stay
unreported, and a refusal keeps its status even when its body is over
the cap.
- **The delegation sweep after enrollment keeps the enrolling relay
while it is still wanted.** It now sweeps with the desired relays plus
the enrolling origin, but only while `stillWanted()` holds, so an
opt-out that landed during the delegation still sees that delegation
revoked.
- **Tests for two paths that had none:** an opt-out that lands while the
gateway answers the delegation ends the attempt quietly (no lease,
delegation revoked, no failure retry), and an opted-out iOS community
enrolls nothing.

Two other items from the review, both Codex findings on an earlier head
of #9811 (reusing a revoked grant after a lost re-delegation; deleting a
key after a lost renewal), were already fixed and tested before #9811
merged, so nothing changes here for them.

### Validation

Added tests:
- [the enrolling relay keeps its delegation before the caller lists
it](157d6d4759/mobile/test/shared/push/android_push_authority_test.dart):
the sweep keeps a still-wanted relay that the desired list doesn't show
yet, and revokes a delegation whose community opted out while it was in
flight.
- [turning push off while it delegates ends the attempt
quietly](157d6d4759/mobile/test/features/settings/android_notifications_test.dart):
production bootstrap, opt-out while the delegation response is held.
- [only a gateway reply the app cannot read is
reported](157d6d4759/mobile/test/shared/push/push_bridge_android_test.dart)
and [a gateway call that times out is aborted, not
abandoned](157d6d4759/mobile/test/shared/push/push_bridge_android_test.dart).
- [a community that opted out enrolls
nothing](157d6d4759/mobile/test/shared/push/push_bridge_test.dart)
(iOS).
- [an unavailable gateway keeps the journal and a refusal clears
it](157d6d4759/mobile/test/shared/push/android_push_authority_test.dart):
now also with refusal bodies over the 64 KiB cap.

Each test was checked to fail with its guard removed.

No device or full-app run: every change is on the Android push gateway
path (which needs a gateway-configured Android build) or is a test, and
the behavior changed is timeout, malformed-reply and race handling that
the tests above drive directly against the production authority and
bootstrap.

### Regressions

- iOS is unchanged apart from the new test; the abort and diagnostics
changes are Android-only code.
- `boundedHttpResponse` gains an optional `timeout` that defaults to its
old 30 s, so existing callers behave as before.
- Gateway replies are capped at 64 KiB. Gateway responses are small JSON
objects, so an oversized reply with the expected status is itself a
defect and is reported. An oversized refusal is handled as that refusal
(a 503 stays retryable, a 403 discards the pending enrollment).

---------

Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
This commit is contained in:
Tom Brow
2026-11-23 16:25:19 -08:00
committed by GitHub
parent 5825a7a81f
commit d4c0729a86
9 changed files with 293 additions and 30 deletions

View File

@@ -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<http.Response> 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<void>();
@@ -55,7 +57,7 @@ Future<http.Response> boundedHttpResponse(
}
try {
return await read().timeout(const Duration(seconds: 30));
return await read().timeout(timeout);
} on TimeoutException {
noteHttpDeadline(request);
rethrow;

View File

@@ -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.',
);
}

View File

@@ -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<Map<String, Object?>> post(
String route,
Map<String, Object?> 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.',
);
}

View File

@@ -461,6 +461,15 @@ Future<BuzzPushEndpointGrant?> 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);

View File

@@ -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 = <String>[];
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<void>();
gateway.holdResponseFor['/v1/delegations'] = delegated.future;
final session = _Connected();
final descriptorGate = Completer<void>();
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 {

View File

@@ -89,10 +89,16 @@ class FakePushGateway {
/// Routes that answer with this status instead of acting.
final failWith = <String, int>{};
/// 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 = <String>{};
/// Routes whose next response waits for the future after the gateway acted.
final holdResponseFor = <String, Future<void>>{};
/// 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<String, Object?>;
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');
}

View File

@@ -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<AndroidPushGatewayRejection>().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<AndroidPushGatewayRejection>().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<AndroidPushGatewayRejection>()));
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,

View File

@@ -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<void> 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('<html>', 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<void>();
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<TimeoutException>()),
);
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<void> 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<void> aborted;
@override
Future<http.StreamedResponse> 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<http.StreamedResponse>().future;
}
}

View File

@@ -180,6 +180,25 @@ void main() {
},
);
test('a community that opted out enrolls nothing', () async {
debugDefaultTargetPlatformOverride = TargetPlatform.iOS;
final methods = <String>[];
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;