diff --git a/crates/buzz-push-gateway/src/http.rs b/crates/buzz-push-gateway/src/http.rs
index aba87d8b7c..18869d3fee 100644
--- a/crates/buzz-push-gateway/src/http.rs
+++ b/crates/buzz-push-gateway/src/http.rs
@@ -1297,6 +1297,23 @@ mod transcript_vector_tests {
assert_vector("enroll", &transcript("buzz.push.enroll.v1", &t).unwrap());
}
+ #[test]
+ fn android_enroll_transcript_vector() {
+ let t = AndroidEnrollTranscript {
+ v: 1,
+ audience: "https://push.buzz.xyz/v1/installations",
+ challenge_id: CHALLENGE_ID,
+ challenge: CHALLENGE,
+ endpoint: ENDPOINT,
+ endpoint_epoch: 1,
+ expires_at: 1_752_624_000,
+ };
+ assert_vector(
+ "enroll_android",
+ &transcript(ANDROID_ENROLL_DOMAIN, &t).unwrap(),
+ );
+ }
+
#[test]
fn delegate_transcript_vector() {
let t = DelegateTranscript {
diff --git a/crates/buzz-push-gateway/tests/vectors/app_attest_transcripts.json b/crates/buzz-push-gateway/tests/vectors/app_attest_transcripts.json
index e53a8e7741..dee23989e2 100644
--- a/crates/buzz-push-gateway/tests/vectors/app_attest_transcripts.json
+++ b/crates/buzz-push-gateway/tests/vectors/app_attest_transcripts.json
@@ -19,6 +19,12 @@
"transcript": "buzz.push.enroll.v1\n{\"v\":1,\"audience\":\"https://push.buzz.xyz/v1/installations\",\"challenge_id\":\"11111111-1111-4111-8111-111111111111\",\"challenge\":\"AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8\",\"key_id\":\"qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqo=\",\"endpoint\":\"0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20\",\"endpoint_epoch\":1,\"expires_at\":1752624000}",
"sha256": "792966649266bfcebdb79de54e8ed3880746f58efd77427a0f43e88c650d79d0"
},
+ {
+ "name": "enroll_android",
+ "domain": "buzz.push.enroll.android.v1",
+ "transcript": "buzz.push.enroll.android.v1\n{\"v\":1,\"audience\":\"https://push.buzz.xyz/v1/installations\",\"challenge_id\":\"11111111-1111-4111-8111-111111111111\",\"challenge\":\"AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8\",\"endpoint\":\"0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20\",\"endpoint_epoch\":1,\"expires_at\":1752624000}",
+ "sha256": "1a6ec24cb436e3ef9c8eb9e2b87b83ffa536d25f6a562197ce56fe1f978eb430"
+ },
{
"name": "delegate",
"domain": "buzz.push.delegate.v1",
diff --git a/mobile/android/app/build.gradle.kts b/mobile/android/app/build.gradle.kts
index ba4de8049d..5ed2f691f6 100644
--- a/mobile/android/app/build.gradle.kts
+++ b/mobile/android/app/build.gradle.kts
@@ -43,6 +43,26 @@ fun isValidPushGatewayOrigin(value: String, requireHttps: Boolean): Boolean {
(if (requireHttps) uri.port == -1 else uri.port == -1 || uri.port in 1..65535)
}
+// Firebase Cloud Messaging is configured per distributor at build time and
+// nothing is committed. Supply all four values from the distributor's Firebase
+// project (its Android app's settings), or none: a build without them has no
+// push wake and everything else works.
+val firebaseValues =
+ mapOf(
+ "google_app_id" to providers.environmentVariable("BUZZ_FIREBASE_APP_ID").orNull,
+ "google_api_key" to providers.environmentVariable("BUZZ_FIREBASE_API_KEY").orNull,
+ "project_id" to providers.environmentVariable("BUZZ_FIREBASE_PROJECT_ID").orNull,
+ "gcm_defaultSenderId" to providers.environmentVariable("BUZZ_FIREBASE_SENDER_ID").orNull,
+ )
+val suppliedFirebaseValues = firebaseValues.filterValues { !it.isNullOrBlank() }
+if (suppliedFirebaseValues.isNotEmpty() && suppliedFirebaseValues.size != firebaseValues.size) {
+ throw GradleException(
+ "Firebase configuration needs BUZZ_FIREBASE_APP_ID, BUZZ_FIREBASE_API_KEY, " +
+ "BUZZ_FIREBASE_PROJECT_ID and BUZZ_FIREBASE_SENDER_ID together; supplied only: " +
+ suppliedFirebaseValues.keys.sorted().joinToString(", "),
+ )
+}
+
tasks.matching { it.name.startsWith("compileFlutterBuild") }.configureEach {
doFirst {
val requireHttps = !name.endsWith("Debug", ignoreCase = true)
@@ -160,6 +180,11 @@ android {
versionName = flutter.versionName
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
resValue("string", "app_name", "Buzz")
+ // Firebase reads its options from these resources when no
+ // google-services file is processed.
+ suppliedFirebaseValues.forEach { (name, value) ->
+ resValue("string", name, requireNotNull(value))
+ }
}
signingConfigs {
@@ -197,6 +222,9 @@ android {
}
dependencies {
+ implementation(platform("com.google.firebase:firebase-bom:35.2.0"))
+ implementation("com.google.firebase:firebase-messaging")
+ implementation("androidx.lifecycle:lifecycle-process:2.10.0")
implementation("com.google.android.play:age-signals:0.0.4")
implementation("androidx.appcompat:appcompat:1.6.1")
implementation("androidx.browser:browser:1.9.0")
diff --git a/mobile/android/app/src/main/AndroidManifest.xml b/mobile/android/app/src/main/AndroidManifest.xml
index a999429a8b..e0447a2c26 100644
--- a/mobile/android/app/src/main/AndroidManifest.xml
+++ b/mobile/android/app/src/main/AndroidManifest.xml
@@ -5,6 +5,7 @@
+
+
+
result.success(describe())
+ "generate" -> {
+ val challenge = (call.arguments as? Map<*, *>)?.get("challenge") as? ByteArray
+ if (challenge == null) {
+ result.error("invalid_arguments", "Expected an attestation challenge.", null)
+ } else {
+ generate(challenge, result)
+ }
+ }
+ "sign" -> {
+ val data = (call.arguments as? Map<*, *>)?.get("data") as? ByteArray
+ if (data == null) {
+ result.error("invalid_arguments", "Expected bytes to sign.", null)
+ } else {
+ result.success(sign(data))
+ }
+ }
+ "delete" -> {
+ keyStore().deleteEntry(ALIAS)
+ result.success(null)
+ }
+ else -> result.notImplemented()
+ }
+ } catch (error: Exception) {
+ result.error("keystore_failed", error.message, error.javaClass.simpleName)
+ }
+ }
+
+ private fun keyStore(): KeyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) }
+
+ private fun generate(challenge: ByteArray, result: MethodChannel.Result) {
+ val store = keyStore()
+ store.deleteEntry(ALIAS)
+ try {
+ KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_EC, "AndroidKeyStore").apply {
+ initialize(
+ KeyGenParameterSpec.Builder(ALIAS, KeyProperties.PURPOSE_SIGN)
+ .setAlgorithmParameterSpec(ECGenParameterSpec("secp256r1"))
+ .setDigests(KeyProperties.DIGEST_SHA256)
+ .setAttestationChallenge(challenge)
+ .build(),
+ )
+ }.generateKeyPair()
+ } catch (error: ProviderException) {
+ result.error("attestation_unavailable", error.message ?: "key generation failed", null)
+ return
+ } catch (error: InvalidAlgorithmParameterException) {
+ result.error("attestation_unavailable", error.message ?: "key generation failed", null)
+ return
+ }
+ // A phone without hardware attestation hands back a lone self-signed
+ // certificate. That chain proves nothing, so it never leaves here.
+ if ((store.getCertificateChain(ALIAS)?.size ?: 0) < 2) {
+ store.deleteEntry(ALIAS)
+ result.error("attestation_unavailable", "no attestation chain", null)
+ return
+ }
+ result.success(describe())
+ }
+
+ private fun describe(): Map? {
+ val store = keyStore()
+ if (!store.containsAlias(ALIAS)) return null
+ val chain = store.getCertificateChain(ALIAS) ?: return null
+ val point = (chain[0].publicKey as ECPublicKey).w
+ return mapOf(
+ "publicKey" to byteArrayOf(0x04) + fixed32(point.affineX.toByteArray()) + fixed32(point.affineY.toByteArray()),
+ "chain" to chain.map { it.encoded },
+ )
+ }
+
+ private fun sign(data: ByteArray): ByteArray {
+ val key = keyStore().getKey(ALIAS, null) as? PrivateKey
+ ?: throw IllegalStateException("The push installation key is missing.")
+ return Signature.getInstance("SHA256withECDSA").run {
+ initSign(key)
+ update(data)
+ sign()
+ }
+ }
+
+ /** A big-endian integer as exactly 32 bytes: BigInteger adds or drops a sign byte. */
+ private fun fixed32(bytes: ByteArray): ByteArray {
+ val trimmed = if (bytes.size > 32) bytes.copyOfRange(bytes.size - 32, bytes.size) else bytes
+ return ByteArray(32 - trimmed.size) + trimmed
+ }
+
+ fun dispose() { channel.setMethodCallHandler(null) }
+
+ private companion object {
+ const val ALIAS = "xyz.block.buzz.push.installation.v1"
+ }
+}
diff --git a/mobile/android/app/src/main/kotlin/xyz/block/buzz/mobile/PushRegistrationPlugin.kt b/mobile/android/app/src/main/kotlin/xyz/block/buzz/mobile/PushRegistrationPlugin.kt
new file mode 100644
index 0000000000..03b984dc4a
--- /dev/null
+++ b/mobile/android/app/src/main/kotlin/xyz/block/buzz/mobile/PushRegistrationPlugin.kt
@@ -0,0 +1,95 @@
+package xyz.block.buzz.mobile
+
+import android.Manifest
+import android.app.Activity
+import android.content.pm.PackageManager
+import android.os.Build
+import androidx.core.app.ActivityCompat
+import androidx.core.content.ContextCompat
+import com.google.firebase.FirebaseApp
+import com.google.firebase.messaging.FirebaseMessaging
+import io.flutter.plugin.common.BinaryMessenger
+import io.flutter.plugin.common.MethodCall
+import io.flutter.plugin.common.MethodChannel
+
+/**
+ * Notification permission and the FCM registration token, on a channel of
+ * its own: `buzz/push` has one native handler, which opens tapped
+ * notifications. The token and a failure to get one reach Dart as calls, like
+ * the iOS APNs callbacks.
+ *
+ * The permission prompt never gates the token: the installation is enrolled
+ * whether or not notifications may be displayed, as on iOS.
+ */
+internal class PushRegistrationPlugin(
+ private val activity: Activity,
+ messenger: BinaryMessenger,
+) : MethodChannel.MethodCallHandler {
+ private val channel = MethodChannel(messenger, "buzz/push_registration").apply {
+ setMethodCallHandler(this@PushRegistrationPlugin)
+ }
+
+ override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
+ when (call.method) {
+ "startRegistration" -> {
+ // A build without Firebase has no token to wait for, and must
+ // not ask the user for a permission that only push needs.
+ if (firebaseConfigured()) {
+ requestNotificationPermission()
+ fetchToken()
+ }
+ result.success(null)
+ }
+ "refreshToken" -> {
+ if (firebaseConfigured()) fetchToken()
+ result.success(null)
+ }
+ else -> result.notImplemented()
+ }
+ }
+
+ private fun requestNotificationPermission() {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) return
+ val permission = Manifest.permission.POST_NOTIFICATIONS
+ if (ContextCompat.checkSelfPermission(activity, permission) == PackageManager.PERMISSION_GRANTED) return
+ // Ask once, as iOS does. A decline stands until the user changes it in
+ // system settings; asking again on every launch would nag.
+ val asked = activity.getSharedPreferences(PREFERENCES, android.content.Context.MODE_PRIVATE)
+ if (asked.getBoolean(ASKED_KEY, false)) return
+ asked.edit().putBoolean(ASKED_KEY, true).apply()
+ ActivityCompat.requestPermissions(activity, arrayOf(permission), REQUEST_CODE)
+ }
+
+ /** Whether Firebase is set up; when not, tells Dart registration failed. */
+ private fun firebaseConfigured(): Boolean {
+ if (FirebaseApp.getApps(activity).isNotEmpty()) return true
+ channel.invokeMethod(
+ "fcmRegistrationFailed",
+ mapOf("message" to "Firebase is not configured in this build."),
+ )
+ return false
+ }
+
+ private fun fetchToken() {
+ FirebaseMessaging.getInstance().token.addOnCompleteListener { task ->
+ // `result` throws for a failed task, so read it only after success.
+ val token = if (task.isSuccessful) task.result else null
+ if (!token.isNullOrEmpty()) {
+ channel.invokeMethod("fcmTokenChanged", mapOf("token" to token))
+ } else {
+ channel.invokeMethod(
+ "fcmRegistrationFailed",
+ mapOf("message" to (task.exception?.message ?: "FCM returned no token.")),
+ )
+ }
+ }
+ }
+
+ fun dispose() { channel.setMethodCallHandler(null) }
+
+ companion object {
+ const val REQUEST_CODE = 0x6275
+ private const val PREFERENCES = "buzz_push"
+ private const val ASKED_KEY = "notification_permission_asked"
+ }
+}
diff --git a/mobile/android/app/src/main/res/xml/backup_rules.xml b/mobile/android/app/src/main/res/xml/backup_rules.xml
index 3529e95201..da69a8ec52 100644
--- a/mobile/android/app/src/main/res/xml/backup_rules.xml
+++ b/mobile/android/app/src/main/res/xml/backup_rules.xml
@@ -7,4 +7,5 @@
+
diff --git a/mobile/android/app/src/main/res/xml/data_extraction_rules.xml b/mobile/android/app/src/main/res/xml/data_extraction_rules.xml
index 8491106a80..cfd12ae4f8 100644
--- a/mobile/android/app/src/main/res/xml/data_extraction_rules.xml
+++ b/mobile/android/app/src/main/res/xml/data_extraction_rules.xml
@@ -12,6 +12,7 @@
+
@@ -20,5 +21,6 @@
+
diff --git a/mobile/ios/BuzzPushKit/Tests/BuzzPushKitTests/BuzzPushTranscriptTests.swift b/mobile/ios/BuzzPushKit/Tests/BuzzPushKitTests/BuzzPushTranscriptTests.swift
index 65e4d01f20..ebc25c9555 100644
--- a/mobile/ios/BuzzPushKit/Tests/BuzzPushKitTests/BuzzPushTranscriptTests.swift
+++ b/mobile/ios/BuzzPushKit/Tests/BuzzPushKitTests/BuzzPushTranscriptTests.swift
@@ -129,8 +129,9 @@ final class BuzzPushTranscriptTests: XCTestCase {
}
func testAllFixtureVectorsCovered() throws {
+ // enroll_android is Android-only; the Dart transcript test covers it.
XCTAssertEqual(
- Set(try Self.fixture().vectors.map(\.name)),
+ Set(try Self.fixture().vectors.map(\.name)).subtracting(["enroll_android"]),
["enroll", "delegate", "rotate_endpoint", "revoke_delegation", "revoke_installation"],
"fixture gained or lost a vector; add/remove the matching known-answer test"
)
diff --git a/mobile/lib/features/settings/settings_page.dart b/mobile/lib/features/settings/settings_page.dart
index 44428df9f0..a53e88dba1 100644
--- a/mobile/lib/features/settings/settings_page.dart
+++ b/mobile/lib/features/settings/settings_page.dart
@@ -22,6 +22,7 @@ import '../../shared/diagnostics/diagnostic_reporter.dart';
import '../../shared/widgets/confirmation_dialog.dart';
import '../../shared/hosted/hosted_environment.dart';
import '../../shared/hosted/sign_out.dart';
+import '../../shared/push/push_bridge.dart';
import '../../shared/push/push_relay_capability_provider.dart';
import '../../shared/push/push_bootstrap.dart';
import '../../shared/relay/relay.dart';
diff --git a/mobile/lib/features/settings/settings_page/notifications_section.dart b/mobile/lib/features/settings/settings_page/notifications_section.dart
index 5d30246e1d..c794a53861 100644
--- a/mobile/lib/features/settings/settings_page/notifications_section.dart
+++ b/mobile/lib/features/settings/settings_page/notifications_section.dart
@@ -1,9 +1,21 @@
part of '../settings_page.dart';
bool _notificationsVisible(WidgetRef ref) {
- if (defaultTargetPlatform != TargetPlatform.iOS) return false;
+ if (defaultTargetPlatform != TargetPlatform.iOS &&
+ defaultTargetPlatform != TargetPlatform.android) {
+ return false;
+ }
final community = ref.watch(activeCommunityProvider).value;
if (community == null) return false;
+ // Without a gateway an Android build never enrolls, so there is nothing to
+ // switch on. A saved opt-in (or an unfinished opt-out) still shows the row:
+ // turning it off is the only move left, and the row goes inert once off.
+ // (iOS keeps a saved opt-in visible the same way.)
+ if (defaultTargetPlatform == TargetPlatform.android &&
+ !Env.pushGatewayConfigured) {
+ return community.pushNotificationsEnabled ||
+ community.pushSubscriptionState.pendingTombstoneGeneration != null;
+ }
final setup = ref.watch(buzzPushSetupStatusProvider);
final capability = ref.watch(currentRelayPushDescriptorProvider);
return (!capability.isLoading &&
@@ -48,6 +60,18 @@ class _NotificationsSection extends ConsumerWidget {
subtitle: 'You can keep using Buzz. Tap to retry notifications.',
onTap: () => retryBuzzPushSetup(ref),
),
+ ValueListenableBuilder(
+ valueListenable: pushUnavailableReason,
+ builder: (context, reason, _) => reason == null
+ ? const SizedBox.shrink()
+ : const AppListRow(
+ key: ValueKey('push-unavailable'),
+ title: 'Push is unavailable on this phone',
+ subtitle:
+ 'You can keep using Buzz. New messages appear when you '
+ 'open the app.',
+ ),
+ ),
MergeSemantics(
key: const ValueKey('push-notifications-setting'),
child: Stack(
@@ -56,6 +80,15 @@ class _NotificationsSection extends ConsumerWidget {
AppListRow(
key: const ValueKey('push-notifications-enabled'),
title: 'Notifications',
+ subtitle:
+ !community.pushNotificationsEnabled &&
+ community
+ .pushSubscriptionState
+ .pendingTombstoneGeneration !=
+ null
+ ? 'Turning off. Notifications may continue until this '
+ 'finishes.'
+ : null,
// Reserve horizontal room without letting the switch's 48dp
// layout height expand this single-line row.
trailing: const SizedBox(width: 60),
diff --git a/mobile/lib/shared/community/community_provider.dart b/mobile/lib/shared/community/community_provider.dart
index 2a4b5aa6ff..62efa434db 100644
--- a/mobile/lib/shared/community/community_provider.dart
+++ b/mobile/lib/shared/community/community_provider.dart
@@ -156,11 +156,13 @@ Future _deactivateCommunityPushLease(
final matchingGrant = (await readBuzzPushEndpointGrants())
.where((grant) => grant.relayOrigin == descriptor.origin)
.firstOrNull;
- if (matchingGrant == null) {
+ // A gateway change leaves no grant for the relay, but the lease the relay
+ // holds is still addressed by the id the community saved.
+ if (matchingGrant == null && community.pushLeaseInstallationId == null) {
throw StateError('No endpoint grant exists for push lease tombstone.');
}
final installationId =
- community.pushLeaseInstallationId ?? matchingGrant.installationId;
+ community.pushLeaseInstallationId ?? matchingGrant!.installationId;
final uri = Uri.parse(community.relayUrl);
final httpScheme = switch (uri.scheme) {
'wss' => 'https',
diff --git a/mobile/lib/shared/push/android_push_authority.dart b/mobile/lib/shared/push/android_push_authority.dart
new file mode 100644
index 0000000000..11d7e86966
--- /dev/null
+++ b/mobile/lib/shared/push/android_push_authority.dart
@@ -0,0 +1,1028 @@
+import 'dart:async';
+import 'dart:convert';
+import 'dart:math';
+import 'dart:typed_data';
+
+import 'package:crypto/crypto.dart' as crypto;
+import 'package:flutter_secure_storage/flutter_secure_storage.dart';
+
+import '../storage/secure_storage.dart';
+import 'android_push_gateway.dart';
+import 'android_push_keystore.dart';
+import 'android_push_transcript.dart';
+
+/// Lifetime of an installation and of each delegation, as on iOS.
+const _lifetimeSeconds = 2592000;
+
+/// Backdates `not_before` and `expires_at` so a phone clock slightly ahead of
+/// the gateway's is not refused.
+const _clockSkewAllowanceSeconds = 120;
+
+/// A grant in its final minutes is replaced by a new delegation.
+const _renewWindowSeconds = 300;
+
+/// The most a first enrollment waits, so phones that update or sign in
+/// together do not all enroll in the same second.
+const androidPushFirstEnrollmentJitterMax = Duration(seconds: 20);
+
+/// The phone's push authority for one relay: the opaque grant the relay
+/// stores in its lease, and the lease's installation id.
+class AndroidPushGrant {
+ const AndroidPushGrant({
+ required this.relayOrigin,
+ required this.relayPubkey,
+ required this.installationId,
+ required this.endpointGrant,
+ required this.endpointHash,
+ required this.endpointEpoch,
+ required this.generation,
+ required this.expiresAt,
+ });
+
+ final String relayOrigin;
+ final String relayPubkey;
+ final String installationId;
+ final String endpointGrant;
+ final String endpointHash;
+ final int endpointEpoch;
+ final int generation;
+ final int expiresAt;
+}
+
+/// Durable authority state, as one secure-storage string.
+abstract interface class AndroidPushStateStore {
+ Future read();
+ Future write(String? value);
+}
+
+class SecureAndroidPushStateStore implements AndroidPushStateStore {
+ SecureAndroidPushStateStore({FlutterSecureStorage? secure})
+ : _secure = secure ?? communitySecureStorage;
+
+ static const _key = 'buzz_android_push_authority_v2';
+
+ /// The state keyed by origin, from before delegations were keyed by executor
+ /// key. Android push had not shipped, so it is dropped rather than migrated.
+ static const _legacyKey = 'buzz_android_push_authority_v1';
+
+ final FlutterSecureStorage _secure;
+ Future? _legacyDropped;
+
+ @override
+ Future read() async {
+ await (_legacyDropped ??= _secure.delete(key: _legacyKey));
+ return _secure.read(key: _key);
+ }
+
+ @override
+ Future write(String? value) => value == null
+ ? _secure.delete(key: _key)
+ : _secure.write(key: _key, value: value);
+}
+
+/// The Android installation and its delegations.
+///
+/// The Keystore key is the installation's only authority: it signs the
+/// enrollment attestation challenge and every later call. Each call is
+/// journaled before its first network attempt (the exact enrollment request;
+/// the next delegation generation; an unfinished endpoint rotation), so a
+/// lost response or a killed process is resumed rather than repeated with
+/// different bytes. Calls that change state run one at a time.
+///
+/// The gateway keys a delegation by the relay's executor key, so that is what
+/// is delegated, generated and revoked here. Relay origins only point at the
+/// key they use, which lets communities that share a relay share one
+/// delegation, and a key that no origin points at any more be revoked.
+class AndroidPushAuthority {
+ AndroidPushAuthority({
+ required this.keystore,
+ required this.gateway,
+ required this.store,
+ DateTime Function()? now,
+ Random? random,
+ Future Function(Duration delay)? sleep,
+ this.firstEnrollmentJitterMax = androidPushFirstEnrollmentJitterMax,
+ }) : _now = now ?? DateTime.now,
+ _random = random ?? Random.secure(),
+ _sleep = sleep ?? Future.delayed;
+
+ final AndroidPushKeystore keystore;
+ final AndroidPushGatewayClient gateway;
+ final AndroidPushStateStore store;
+ final Duration firstEnrollmentJitterMax;
+ final DateTime Function() _now;
+ final Random _random;
+ final Future Function(Duration delay) _sleep;
+
+ Future _tail = Future.value();
+
+ int get _nowSeconds => _now().millisecondsSinceEpoch ~/ 1000;
+
+ /// The gateway the stored state belongs to. A key and an installation mean
+ /// nothing to any other gateway.
+ String get _gatewayOrigin => gateway.baseUrl.origin;
+
+ Future _serialized(Future Function() operation) {
+ final result = _tail.then((_) => operation());
+ _tail = result.then((_) {}, onError: (Object _, StackTrace _) {});
+ return result;
+ }
+
+ /// Every relay origin's current grant. A plain read of the stored state,
+ /// outside the call queue: it must not wait behind gateway calls or the
+ /// enrollment jitter, and the state is only ever replaced whole.
+ Future> grants() async {
+ final state = await _load();
+ return [
+ for (final origin in state.origins.values)
+ ?_grantOf(origin, state.delegations[origin.pubkey]),
+ ];
+ }
+
+ /// Makes [endpoint] (the FCM token) the installation's endpoint and returns
+ /// a grant from the installation to [relayPubkey] for [relayOrigin],
+ /// enrolling, rotating and delegating only as far as the stored state needs.
+ ///
+ /// [stillWanted] is read inside the call queue, before each gateway call
+ /// that creates authority, so an opt-out that lands while this waited its
+ /// turn or the enrollment jitter leaves nothing behind. Returns null when it
+ /// said no.
+ ///
+ /// Once the origin points at [relayPubkey], delegations that no relay in
+ /// [desiredRelays] points at are revoked, so a relay that rotated its
+ /// executor key does not leave the old key delegated. A failure propagates:
+ /// the caller retries, which reuses the new grant and sweeps again.
+ Future enroll({
+ required String relayOrigin,
+ required String relayPubkey,
+ required String endpoint,
+ required bool Function() stillWanted,
+ required Set Function() desiredRelays,
+ }) => _serialized(() async {
+ await _dropForeignGateway();
+ var retriedDelegation = false;
+ var attemptedReset = false;
+ try {
+ while (true) {
+ _fence(stillWanted);
+ await _ensureInstallation(endpoint, stillWanted);
+ final state = await _load();
+ final delegation = state.delegations[relayPubkey];
+ if (delegation == null || !_reusable(state, delegation)) {
+ _fence(stillWanted);
+ try {
+ await _delegate(relayPubkey);
+ } on AndroidPushGatewayRejection catch (rejection) {
+ // The gateway answers every refused installation call with the
+ // same 404. A challenge that expired while the app stalled is the
+ // mild case, so try once more with a fresh one. After that, and
+ // after the one case we can explain (an endpoint rotation whose
+ // response was lost, which _rotate has already accounted for), a
+ // refused delegation means the installation is gone: revoked,
+ // expired, or enrolled under a key this phone no longer has.
+ if (!rejection.isNotAuthorized) rethrow;
+ if (!retriedDelegation) {
+ retriedDelegation = true;
+ continue;
+ }
+ if (attemptedReset) rethrow;
+ attemptedReset = true;
+ await _reset();
+ continue;
+ }
+ }
+ final grant = await _pointOrigin(relayOrigin, relayPubkey);
+ await _revokeUnreferencedDelegations(desiredRelays());
+ return grant;
+ }
+ } on _EnrollmentNoLongerWanted {
+ return null;
+ }
+ });
+
+ /// Revokes the delegation of every executor key no origin in
+ /// [desiredRelays] uses, and, when [revokeInstallation], the installation
+ /// itself, which frees the FCM token and deletes the key. [desiredRelays] is
+ /// read when the work runs, so a relay enabled while this waited is kept.
+ Future reconcile({
+ required Set Function() desiredRelays,
+ required bool Function() revokeInstallation,
+ }) => _serialized(() async {
+ await _dropForeignGateway();
+ var state = await _load();
+ final pending = state.pendingEnrollment;
+ if (state.installation == null && pending != null && revokeInstallation()) {
+ // An enrollment whose response was lost may have created an
+ // installation that holds the FCM token. Learn its handle by replaying
+ // the journaled request, so it can be revoked below.
+ await _settlePendingEnrollment(pending);
+ state = await _load();
+ }
+ if (state.installation == null) return;
+ await _revokeUnreferencedDelegations(desiredRelays());
+ if (revokeInstallation()) await _revokeInstallation();
+ });
+
+ /// Revokes every delegated executor key that no origin in [desired] points
+ /// at. Needs an installation.
+ Future _revokeUnreferencedDelegations(Set desired) async {
+ final state = await _load();
+ final referenced = {
+ for (final origin in state.origins.values)
+ if (desired.contains(origin.origin)) origin.pubkey,
+ };
+ for (final delegation in state.delegations.values.toList()) {
+ if (delegation.delegated && !referenced.contains(delegation.pubkey)) {
+ await _revokeDelegation(delegation);
+ }
+ }
+ }
+
+ void _fence(bool Function() stillWanted) {
+ if (!stillWanted()) throw const _EnrollmentNoLongerWanted();
+ }
+
+ // ---- installation ----
+
+ Future _ensureInstallation(
+ String endpoint,
+ bool Function() stillWanted,
+ ) async {
+ var state = await _load();
+ if (state.pendingEnrollment != null) {
+ await _finishEnrollment(state.pendingEnrollment!, stillWanted);
+ state = await _load();
+ }
+ final installation = state.installation;
+ if (installation != null) {
+ final key = await keystore.current();
+ if (key == null ||
+ key.keyId != installation.keyId ||
+ installation.expiresAt <= _nowSeconds) {
+ // Nothing can sign for this installation any more, or the gateway no
+ // longer holds it.
+ await _reset();
+ }
+ }
+ state = await _load();
+ if (state.installation == null) {
+ await _enrollFresh(endpoint, stillWanted);
+ return;
+ }
+ var current = state.installation!;
+ // A journaled rotation target comes first: it may have reached the
+ // gateway, and the epoch it consumed must be accounted for before the
+ // current token's rotation.
+ while (current.endpoint != endpoint || current.rotatingTo != null) {
+ current = await _rotate(current, current.rotatingTo ?? endpoint);
+ }
+ }
+
+ Future _enrollFresh(
+ String endpoint,
+ bool Function() stillWanted,
+ ) async {
+ if ((await _load()).origins.isEmpty &&
+ firstEnrollmentJitterMax > Duration.zero) {
+ await _sleep(
+ Duration(
+ milliseconds: _random.nextInt(
+ firstEnrollmentJitterMax.inMilliseconds,
+ ),
+ ),
+ );
+ }
+ _fence(stillWanted);
+ final challenge = await _challenge();
+ final expiresAt =
+ _nowSeconds - _clockSkewAllowanceSeconds + _lifetimeSeconds;
+ final transcript = androidEnrollTranscript(
+ challengeId: challenge.id,
+ challenge: challenge.text,
+ endpoint: endpoint,
+ endpointEpoch: 1,
+ expiresAt: expiresAt,
+ );
+ // The attestation challenge is the digest of exactly what the gateway
+ // will rebuild from the request.
+ final key = await keystore.generate(
+ Uint8List.fromList(crypto.sha256.convert(transcript).bytes),
+ );
+ final pending = _PendingEnrollment(
+ keyId: key.keyId,
+ expiresAt: expiresAt,
+ body: {
+ 'v': 1,
+ 'challenge_id': challenge.id,
+ 'challenge': challenge.text,
+ 'android_attestation': key.chainBase64,
+ 'endpoint': endpoint,
+ 'endpoint_epoch': 1,
+ 'expires_at': expiresAt,
+ },
+ );
+ // Durable before the first network attempt: a lost response is resumed
+ // with these exact bytes, which the gateway accepts again.
+ await _save((await _load()).copyWith(pendingEnrollment: pending));
+ await _finishEnrollment(pending);
+ }
+
+ Future _finishEnrollment(
+ _PendingEnrollment pending, [
+ bool Function() stillWanted = _always,
+ ]) async {
+ if (pending.expiresAt <= _nowSeconds) {
+ await _discardPendingEnrollment();
+ return _enrollFresh(pending.body['endpoint']! as String, stillWanted);
+ }
+ final Map response;
+ try {
+ response = await gateway.post(
+ '/v1/installations',
+ pending.body,
+ expectedStatus: 201,
+ );
+ } on AndroidPushGatewayRejection catch (rejection) {
+ if (rejection.isTransient) rethrow;
+ await _discardPendingEnrollment();
+ if (rejection.isInvalidAttestation) {
+ throw const AndroidPushAttestationUnavailable(
+ 'the gateway did not accept this phone\'s key attestation',
+ );
+ }
+ rethrow;
+ }
+ final handle = response['installation_handle'];
+ final expiresAt = response['expires_at'];
+ if (handle is! String || expiresAt is! int) {
+ throw const FormatException(
+ 'Push gateway returned a malformed installation.',
+ );
+ }
+ await _save(
+ (await _load()).copyWith(
+ clearPendingEnrollment: true,
+ installation: _Installation(
+ handle: handle,
+ keyId: pending.keyId,
+ endpoint: pending.body['endpoint']! as String,
+ endpointEpoch: 1,
+ expiresAt: expiresAt,
+ ),
+ ),
+ );
+ }
+
+ /// Sign-out's view of a journaled enrollment: replay it so a created
+ /// installation can be revoked. Nothing is enrolled afresh, and a request
+ /// the gateway refuses or that expired created nothing.
+ Future _settlePendingEnrollment(_PendingEnrollment pending) async {
+ if (pending.expiresAt <= _nowSeconds) {
+ await _discardPendingEnrollment();
+ return;
+ }
+ try {
+ await _finishEnrollment(pending);
+ } on AndroidPushAttestationUnavailable {
+ // The gateway refused the attestation, so there is nothing to revoke.
+ } on AndroidPushGatewayRejection catch (rejection) {
+ if (rejection.isTransient) rethrow;
+ }
+ }
+
+ Future _discardPendingEnrollment() async {
+ await keystore.delete();
+ await _save((await _load()).copyWith(clearPendingEnrollment: true));
+ }
+
+ /// Local state for an installation the gateway no longer honors. Its
+ /// delegations died with it, but their records stay readable: a lease
+ /// tombstone still needs the relay's installation id.
+ Future _reset() async {
+ await keystore.delete();
+ final state = await _load();
+ await _save(
+ state.copyWith(
+ clearInstallation: true,
+ delegations: {
+ for (final delegation in state.delegations.values)
+ delegation.pubkey: delegation.copyWith(
+ generation: 0,
+ delegated: false,
+ ),
+ },
+ ),
+ );
+ }
+
+ Future<_Installation> _rotate(
+ _Installation installation,
+ String endpoint,
+ ) async {
+ // Journal the target first: if the response is lost the gateway may be at
+ // the next epoch already.
+ await _save(
+ (await _load()).copyWith(
+ installation: installation.copyWith(rotatingTo: endpoint),
+ ),
+ );
+ try {
+ await _signed(
+ '/v1/installations/endpoint',
+ {
+ 'installation_handle': installation.handle,
+ 'endpoint_epoch': installation.endpointEpoch,
+ 'new_endpoint_epoch': installation.endpointEpoch + 1,
+ 'endpoint': endpoint,
+ },
+ (challenge) => androidRotateEndpointTranscript(
+ challengeId: challenge.id,
+ challenge: challenge.text,
+ installationHandle: installation.handle,
+ endpointEpoch: installation.endpointEpoch,
+ newEndpointEpoch: installation.endpointEpoch + 1,
+ endpoint: endpoint,
+ ),
+ );
+ } on AndroidPushGatewayRejection catch (rejection) {
+ // A retry of a rotation that already landed is refused like any other
+ // bad call. Carry on as if it landed: the delegation that follows is at
+ // the new epoch, so it succeeds exactly when that guess was right and
+ // otherwise sends enroll() to a fresh installation.
+ if (!rejection.isNotAuthorized) rethrow;
+ }
+ // Grants at the old epoch are void at the gateway. They stay stored, and
+ // stop being reused because their epoch no longer matches.
+ final rotated = installation.copyWith(
+ endpoint: endpoint,
+ endpointEpoch: installation.endpointEpoch + 1,
+ clearRotatingTo: true,
+ );
+ await _save((await _load()).copyWith(installation: rotated));
+ return rotated;
+ }
+
+ // ---- delegations ----
+
+ /// Whether [delegation]'s grant can still be used as is.
+ bool _reusable(_State state, _Delegation delegation) {
+ final installation = state.installation!;
+ final grant = delegation.grant;
+ return grant != null &&
+ delegation.delegated &&
+ grant.installationHandle == installation.handle &&
+ grant.endpointEpoch == installation.endpointEpoch &&
+ // A higher journaled generation is a delegation that has not
+ // finished, after a revocation or a change this grant predates.
+ grant.generation == delegation.generation &&
+ grant.expiresAt > _nowSeconds + _renewWindowSeconds;
+ }
+
+ AndroidPushGrant? _grantOf(_Origin origin, _Delegation? delegation) {
+ final grant = delegation?.grant;
+ if (grant == null) return null;
+ return AndroidPushGrant(
+ relayOrigin: origin.origin,
+ relayPubkey: origin.pubkey,
+ installationId: origin.installationId,
+ endpointGrant: grant.endpointGrant,
+ endpointHash: grant.endpointHash,
+ endpointEpoch: grant.endpointEpoch,
+ generation: grant.generation,
+ expiresAt: grant.expiresAt,
+ );
+ }
+
+ /// Points [relayOrigin] at [relayPubkey], whose delegation is current, and
+ /// returns the origin's grant.
+ Future _pointOrigin(
+ String relayOrigin,
+ String relayPubkey,
+ ) async {
+ final state = await _load();
+ final existing = state.origins[relayOrigin];
+ final origin = _Origin(
+ origin: relayOrigin,
+ installationId: existing?.installationId ?? _newInstallationId(),
+ pubkey: relayPubkey,
+ );
+ if (existing?.pubkey != relayPubkey) {
+ await _save(
+ state.copyWith(origins: {...state.origins, relayOrigin: origin}),
+ );
+ }
+ return _grantOf(origin, state.delegations[relayPubkey])!;
+ }
+
+ Future _delegate(String relayPubkey) async {
+ var state = await _load();
+ final installation = state.installation!;
+ final existing = state.delegations[relayPubkey];
+ // The generation is spent before the call: a response that never arrived
+ // may have been accepted, and the gateway needs each one to be higher.
+ final generation = (existing?.generation ?? 0) + 1;
+ final delegation = (existing ?? _Delegation(pubkey: relayPubkey)).copyWith(
+ generation: generation,
+ delegated: true,
+ );
+ final notBefore = _nowSeconds - _clockSkewAllowanceSeconds;
+ final expiresAt = notBefore + _lifetimeSeconds;
+ await _save(
+ state.copyWith(
+ delegations: {...state.delegations, relayPubkey: delegation},
+ // An accepted delegation extends the installation to the grant's
+ // expiry, and its response may be lost, so the extension is recorded
+ // first. If the gateway never accepted it, the installation's next
+ // refused call resets it instead.
+ installation: installation.copyWith(
+ expiresAt: max(installation.expiresAt, expiresAt),
+ ),
+ ),
+ );
+ final response = await _signed(
+ '/v1/delegations',
+ {
+ 'installation_handle': installation.handle,
+ 'endpoint_epoch': installation.endpointEpoch,
+ 'generation': generation,
+ 'relay_pubkey': relayPubkey,
+ 'not_before': notBefore,
+ 'expires_at': expiresAt,
+ },
+ (challenge) => androidDelegateTranscript(
+ challengeId: challenge.id,
+ challenge: challenge.text,
+ installationHandle: installation.handle,
+ endpointEpoch: installation.endpointEpoch,
+ generation: generation,
+ relayPubkey: relayPubkey,
+ notBefore: notBefore,
+ expiresAt: expiresAt,
+ ),
+ expectedStatus: 201,
+ );
+ final endpointGrant = response['endpoint_grant'];
+ if (endpointGrant is! String || endpointGrant.isEmpty) {
+ throw const FormatException('Push gateway returned a malformed grant.');
+ }
+ state = await _load();
+ final granted = delegation.copyWith(
+ grant: _DelegationGrant(
+ installationHandle: installation.handle,
+ endpointGrant: endpointGrant,
+ endpointHash: crypto.sha256
+ .convert(utf8.encode(installation.endpoint))
+ .toString(),
+ endpointEpoch: installation.endpointEpoch,
+ generation: generation,
+ expiresAt: expiresAt,
+ ),
+ );
+ await _save(
+ state.copyWith(delegations: {...state.delegations, relayPubkey: granted}),
+ );
+ }
+
+ Future _revokeDelegation(_Delegation delegation) async {
+ final installation = (await _load()).installation!;
+ final pubkey = delegation.pubkey;
+ // The highest generation spent may never have been accepted, and the
+ // gateway revokes by the generation it holds: try that one, then the last
+ // one accepted.
+ for (final generation in {
+ delegation.generation,
+ ?delegation.grant?.generation,
+ }) {
+ try {
+ await _signed(
+ '/v1/delegations/revoke',
+ {
+ 'installation_handle': installation.handle,
+ 'relay_pubkey': pubkey,
+ 'generation': generation,
+ },
+ (challenge) => androidRevokeDelegationTranscript(
+ challengeId: challenge.id,
+ challenge: challenge.text,
+ installationHandle: installation.handle,
+ relayPubkey: pubkey,
+ generation: generation,
+ ),
+ );
+ break;
+ } on AndroidPushGatewayRejection catch (rejection) {
+ // Not found at this generation. If no generation matches, the
+ // delegation is already gone or its installation is, and there is
+ // nothing left to revoke.
+ if (!rejection.isNotAuthorized) rethrow;
+ }
+ }
+ final state = await _load();
+ await _save(
+ state.copyWith(
+ delegations: {
+ ...state.delegations,
+ pubkey: delegation.copyWith(delegated: false),
+ },
+ ),
+ );
+ }
+
+ Future _revokeInstallation() async {
+ final installation = (await _load()).installation!;
+ // A journaled rotation may have reached the gateway, which then sits one
+ // epoch ahead of what is stored. Try the stored epoch, then the next. The
+ // key stays until a revocation lands or both are refused.
+ final epochs = [
+ installation.endpointEpoch,
+ if (installation.rotatingTo != null) installation.endpointEpoch + 1,
+ ];
+ for (final epoch in epochs) {
+ try {
+ await _signed(
+ '/v1/installations/revoke',
+ {
+ 'installation_handle': installation.handle,
+ 'endpoint_epoch': epoch,
+ 'new_endpoint_epoch': epoch + 1,
+ },
+ (challenge) => androidRevokeInstallationTranscript(
+ challengeId: challenge.id,
+ challenge: challenge.text,
+ installationHandle: installation.handle,
+ endpointEpoch: epoch,
+ newEndpointEpoch: epoch + 1,
+ ),
+ );
+ break;
+ } on AndroidPushGatewayRejection catch (rejection) {
+ // Revoking twice succeeds, so a refusal at the last epoch means the
+ // installation is already gone, which is what this call is for.
+ if (!rejection.isNotAuthorized) rethrow;
+ }
+ }
+ await keystore.delete();
+ final state = await _load();
+ await _save(
+ state.copyWith(
+ clearInstallation: true,
+ delegations: {
+ for (final delegation in state.delegations.values)
+ delegation.pubkey: delegation.copyWith(
+ generation: 0,
+ delegated: false,
+ ),
+ },
+ ),
+ );
+ }
+
+ // ---- gateway ----
+
+ Future<_Challenge> _challenge() async {
+ final response = await gateway.post('/v1/installations/challenges', {
+ 'v': 1,
+ });
+ final id = response['challenge_id'];
+ final text = response['challenge'];
+ if (id is! String || text is! String) {
+ throw const FormatException(
+ 'Push gateway returned a malformed challenge.',
+ );
+ }
+ return _Challenge(id, text);
+ }
+
+ Future