Files
buzz/mobile/test/helpers/android_push_fakes.dart
Tom Brow 2e3bebe9b6 feat(mobile): enroll Android devices for push (#9811)
## Summary

Ticket 7 of the [Android push
plan](https://github.com/block/buzz/blob/main/PLANS/ANDROID_PUSH.md).
Android phones can now enroll with the push gateway and publish a relay
lease, through the same shared push layer iOS uses. The wake handling
side is ticket 6, [#9804 Android push wake
handling](https://github.com/block/buzz/pull/9804).

- The phone gets an FCM token, then generates a sign-only P-256 Keystore
key whose attestation challenge is the SHA-256 of the enrollment
transcript. The chain goes to the gateway at enrollment. Every later
installation call (delegate, rotate endpoint, revoke delegation, revoke
installation) is signed with that key over the transcript bytes the
gateway builds.
- A rotated FCM token rotates the endpoint. Signing out revokes the
delegation and the installation. The first enrollment waits a short
random time.
- Android 13+ asks for the notification permission at the same point iOS
does. Declining keeps the app working.
- A phone that cannot attest (no hardware attestation, unlocked
bootloader, unlisted boot key) keeps working, and Settings says push is
unavailable on this phone.
- The relay lease keeps the fixed `transport` value iOS sends.
- Firebase config is the same build-time setting [#9804 Android push
wake handling](https://github.com/block/buzz/pull/9804) adds: four
`BUZZ_FIREBASE_*` environment variables become the string resources
Firebase reads. Nothing is committed, and builds without them still work
(push reports unavailable). The Gradle hunks (permission, config block,
`firebase-messaging` dependency) are copied from that PR verbatim so the
two merge cleanly, including its `lifecycle-process` line, which this PR
does not use.
- The token and permission calls use their own `buzz/push_registration`
channel, because Android's notification-open handler from that PR
already owns `buzz/push` and a channel has one native handler.
- The gateway gets an `enroll_android` transcript vector so Dart and
Rust agree on the exact bytes.

Enrollment state is journaled before each network attempt, so a lost
response resumes with byte-identical requests instead of leaving an
orphaned installation.

### Related issue

None found. Builds on [#9560 enroll Android
installations](https://github.com/block/buzz/pull/9560) and [#9562
verify Key Attestation](https://github.com/block/buzz/pull/9562).

### Validation

Journey tests cover first enrollment, a second relay, reuse and renewal,
lost responses, token rotation, an installation the gateway dropped, a
lost Keystore key, a phone that cannot attest, and sign-out revocation,
against a fake gateway that keeps the real gateway's semantics.
Transcripts replay the shared vectors byte for byte. A settings journey
checks the Notifications row and the unavailable row on Android, and a
resume table checks the FCM token refresh: it runs while the relay
reconnects, but not when push is off or the relay doesn't offer push.

On a physical Pixel 9a (debug build, a local test gateway on a local
Postgres, reached over `adb reverse`), the real Keystore key and
hardware attestation chain enrolled and delegated, and the gateway
accepted the attestation. The same session then ran: a signed delivery
authorized against the delegation, endpoint rotation and re-delegation
at the next epoch, rotating back, delegation revocation, installation
revocation, and re-enrolling the same FCM token afterwards.

The notification prompt appears when registration starts, before the
token is fetched:

<img
src="https://github.com/user-attachments/assets/2aed92fe-20c1-4658-b990-51c3f3c96120"
width="270" alt="Android notification permission prompt">

Not validated on the device: the FCM wake itself (the local gateway has
no credentials to call FCM, so the delivery was authorized and then
failed at the FCM hop), lease publication to a relay, and the in-app
unavailable row, which only the widget tests exercise. A relay-backed
run needs a signed-in test community on the phone.

### Settings while turning off

Turning notifications off sends a relay tombstone. Until the relay
accepts it, the row now says so, on both platforms. An Android build
without a gateway also keeps a saved opt-in visible so it can still be
turned off; once off, the row goes away. These are rendered from the
Settings journey test.

| | Before | After |
|---|---|---|
| Android build without a gateway, saved opt-in | <img
src="https://raw.githubusercontent.com/block/buzz/47220acf78ad21639d2a3a8b79be3f0272e74db2/pr-9811--01-before-config-less.png"
width="270" alt="Before: no Notifications row"> | <img
src="https://raw.githubusercontent.com/block/buzz/47220acf78ad21639d2a3a8b79be3f0272e74db2/pr-9811--02-after-config-less.png"
width="270" alt="After: Notifications row with the switch on"> |
| After turning off, relay has not accepted yet | <img
src="https://raw.githubusercontent.com/block/buzz/47220acf78ad21639d2a3a8b79be3f0272e74db2/pr-9811--03-before-turning-off.png"
width="270" alt="Before: plain off switch"> | <img
src="https://raw.githubusercontent.com/block/buzz/47220acf78ad21639d2a3a8b79be3f0272e74db2/pr-9811--04-after-turning-off.png"
width="270" alt="After: Turning off. Notifications may continue until
this finishes."> |

### Regressions

- iOS enrollment is unchanged: the shared bridge only branches to the
Dart authority on Android. iOS gains the pending opt-out subtitle, and
its opt-out now also tombstones after a gateway change using the saved
lease id.
- The Android app gains the `firebase-messaging` dependency and a
`POST_NOTIFICATIONS` permission. Backups exclude the push preferences
file.



### Known limits

- An FCM token rotation while the app is running is picked up on the
next resume or launch, because the wake service owns the single
messaging service. It could call into the registration plugin once both
Android push PRs merge.
- After an endpoint rotation, only the active community's lease is
republished. Other enabled communities' grants are void until each is
opened, the same way their leases lapse at grant expiry today.

---------

Signed-off-by: Tom Brow <tomb@block.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz>
Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
2026-11-23 09:35:56 -07:00

292 lines
10 KiB
Dart

import 'dart:convert';
import 'dart:math';
import 'dart:typed_data';
import 'package:buzz/shared/push/android_push_gateway.dart';
import 'package:buzz/shared/push/android_push_keystore.dart';
import 'package:buzz/shared/push/android_push_transcript.dart';
import 'package:crypto/crypto.dart' as crypto;
import 'package:http/http.dart' as http;
import 'package:http/testing.dart';
/// A Keystore stand-in. Its "signature" is the digest of the public key and
/// the bytes signed, which [FakePushGateway] recomputes from the transcript it
/// rebuilds, so a call signed over the wrong bytes is refused. Its chain is the
/// public key and the attestation challenge, like the gateway test verifier's.
class FakeAndroidKeystore implements AndroidPushKeystore {
AndroidPushKey? key;
int generated = 0;
int deleted = 0;
bool attests = true;
@override
Future<AndroidPushKey?> current() async => key;
@override
Future<AndroidPushKey> generate(Uint8List attestationChallenge) async {
if (!attests) {
throw const AndroidPushAttestationUnavailable('no attestation chain');
}
generated++;
final public = Uint8List.fromList([
4,
...crypto.sha256.convert(utf8.encode('key-$generated')).bytes,
...crypto.sha256.convert(utf8.encode('key-y-$generated')).bytes,
]);
return key = AndroidPushKey(
publicKey: public,
chain: [public, attestationChallenge],
);
}
@override
Future<String> sign(Uint8List data) async {
final current = key;
if (current == null) throw StateError('no key');
return signatureFor(current.publicKey, data);
}
@override
Future<void> delete() async {
deleted++;
key = null;
}
}
String signatureFor(Uint8List publicKey, List<int> transcript) =>
base64.encode(crypto.sha256.convert([...publicKey, ...transcript]).bytes);
class _Installation {
_Installation(this.handle, this.publicKey, this.token, this.expiresAt);
final String handle;
final Uint8List publicKey;
String token;
int expiresAt;
int epoch = 1;
bool revoked = false;
final delegations = <String, int>{};
final revokedDelegations = <String>{};
}
/// The gateway's installation semantics, behind an HTTP client: one active
/// installation per token and per key, enrollment replay, single-use
/// challenges, strictly increasing delegation generations at the installation's
/// epoch, rotation by exactly one epoch, idempotent revocation, and a
/// not_authorized 404 for every refused signed call.
class FakePushGateway {
FakePushGateway({required this.nowSeconds});
final int Function() nowSeconds;
final installations = <String, _Installation>{};
final requests = <({String route, Map<String, Object?> body})>[];
final _challenges = <String, String>{};
var _next = 0;
/// Routes whose next response is lost after the gateway acted on it.
final loseResponseFor = <String>{};
/// Routes that answer with this status instead of acting.
final failWith = <String, int>{};
/// Routes whose next call is refused like an expired challenge: answered
/// `not_authorized` without acting.
final refuseOnce = <String>{};
/// Refuse attestations like a gateway that does not trust this phone.
bool refuseAttestation = false;
List<Map<String, Object?>> bodiesFor(String route) => [
for (final request in requests)
if (request.route == route) request.body,
];
late final http.Client client = MockClient((request) async {
final route = request.url.path;
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 (refuseOnce.remove(route)) return _notAuthorized();
final response = _handle(route, body);
if (loseResponseFor.remove(route)) {
throw http.ClientException('connection lost');
}
return response;
});
http.Response _json(int status, Map<String, Object?> body) =>
http.Response(jsonEncode(body), status);
http.Response _notAuthorized() => _json(404, {'error': 'not_authorized'});
http.Response _handle(String route, Map<String, Object?> body) {
if (route == '/v1/installations/challenges') {
final id = 'challenge-${_next++}';
final text = 'text-$id';
_challenges[id] = text;
return _json(200, {
'challenge_id': id,
'challenge': text,
'expires_at': nowSeconds() + 300,
});
}
if (route == '/v1/installations') return _enroll(body);
final installation = installations[body['installation_handle']];
final live =
installation != null &&
installation.expiresAt >= nowSeconds() &&
(!installation.revoked || route == '/v1/installations/revoke');
if (!live || !_signatureOk(route, body, installation)) {
return _notAuthorized();
}
switch (route) {
case '/v1/delegations':
final relay = body['relay_pubkey']! as String;
final generation = body['generation']! as int;
if (body['endpoint_epoch'] != installation.epoch ||
generation <= (installation.delegations[relay] ?? 0)) {
return _notAuthorized();
}
installation.delegations[relay] = generation;
installation.revokedDelegations.remove('$relay/$generation');
installation.expiresAt = max(
installation.expiresAt,
body['expires_at']! as int,
);
return _json(201, {
'endpoint_grant':
'grant:${installation.handle}:$relay:$generation:${installation.epoch}',
});
case '/v1/installations/endpoint':
if (body['endpoint_epoch'] != installation.epoch ||
body['new_endpoint_epoch'] != installation.epoch + 1) {
return _notAuthorized();
}
installation.token = body['endpoint']! as String;
installation.epoch++;
return _json(200, {'status': 'rotated'});
case '/v1/delegations/revoke':
final relay = body['relay_pubkey']! as String;
final generation = body['generation']! as int;
if (installation.delegations[relay] != generation) {
return _notAuthorized();
}
installation.revokedDelegations.add('$relay/$generation');
return _json(200, {'status': 'revoked'});
default:
if (body['endpoint_epoch'] == installation.epoch &&
body['new_endpoint_epoch'] == installation.epoch + 1) {
installation.revoked = true;
installation.epoch++;
} else if (!(installation.revoked &&
body['new_endpoint_epoch'] == installation.epoch)) {
return _notAuthorized();
}
return _json(200, {'status': 'revoked'});
}
}
http.Response _enroll(Map<String, Object?> body) {
final chain = (body['android_attestation']! as List).cast<String>();
final transcript = androidEnrollTranscript(
challengeId: body['challenge_id']! as String,
challenge: body['challenge']! as String,
endpoint: body['endpoint']! as String,
endpointEpoch: body['endpoint_epoch']! as int,
expiresAt: body['expires_at']! as int,
);
final attested = base64.decode(chain[1]);
if (refuseAttestation ||
!_same(attested, crypto.sha256.convert(transcript).bytes)) {
return _json(401, {'error': 'invalid_attestation'});
}
final publicKey = Uint8List.fromList(base64.decode(chain[0]));
final token = body['endpoint']! as String;
for (final other in installations.values) {
if (other.revoked || other.expiresAt < nowSeconds()) continue;
if (_same(other.publicKey, publicKey) && other.token == token) {
return _json(201, {
'installation_handle': other.handle,
'endpoint_epoch': other.epoch,
'expires_at': other.expiresAt,
});
}
if (_same(other.publicKey, publicKey) || other.token == token) {
return _json(409, {'error': 'conflict'});
}
}
final handle = 'installation-${installations.length + 1}';
installations[handle] = _Installation(
handle,
publicKey,
token,
body['expires_at']! as int,
);
return _json(201, {
'installation_handle': handle,
'endpoint_epoch': 1,
'expires_at': body['expires_at'],
});
}
bool _signatureOk(
String route,
Map<String, Object?> b,
_Installation installation,
) {
final common = (b['challenge_id']! as String, b['challenge']! as String);
final handle = installation.handle;
final transcript = switch (route) {
'/v1/delegations' => androidDelegateTranscript(
challengeId: common.$1,
challenge: common.$2,
installationHandle: handle,
endpointEpoch: b['endpoint_epoch']! as int,
generation: b['generation']! as int,
relayPubkey: b['relay_pubkey']! as String,
notBefore: b['not_before']! as int,
expiresAt: b['expires_at']! as int,
),
'/v1/installations/endpoint' => androidRotateEndpointTranscript(
challengeId: common.$1,
challenge: common.$2,
installationHandle: handle,
endpointEpoch: b['endpoint_epoch']! as int,
newEndpointEpoch: b['new_endpoint_epoch']! as int,
endpoint: b['endpoint']! as String,
),
'/v1/delegations/revoke' => androidRevokeDelegationTranscript(
challengeId: common.$1,
challenge: common.$2,
installationHandle: handle,
relayPubkey: b['relay_pubkey']! as String,
generation: b['generation']! as int,
),
_ => androidRevokeInstallationTranscript(
challengeId: common.$1,
challenge: common.$2,
installationHandle: handle,
endpointEpoch: b['endpoint_epoch']! as int,
newEndpointEpoch: b['new_endpoint_epoch']! as int,
),
};
// Challenges are single use, whether or not the call is accepted.
final issued = _challenges.remove(common.$1);
return issued == common.$2 &&
b['assertion'] == signatureFor(installation.publicKey, transcript);
}
bool _same(List<int> a, List<int> b) =>
a.length == b.length &&
Iterable.generate(a.length).every((i) => a[i] == b[i]);
}
AndroidPushGatewayClient fakeGatewayClient(
FakePushGateway gateway, {
String baseUrl = 'https://push.example',
}) => AndroidPushGatewayClient(
baseUrl: Uri.parse(baseUrl),
client: gateway.client,
);