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> _signed( + String route, + Map fields, + Uint8List Function(_Challenge challenge) transcript, { + int expectedStatus = 200, + }) async { + final challenge = await _challenge(); + final assertion = await keystore.sign(transcript(challenge)); + return gateway.post(route, { + 'v': 1, + 'challenge_id': challenge.id, + 'challenge': challenge.text, + ...fields, + 'assertion': assertion, + }, expectedStatus: expectedStatus); + } + + String _newInstallationId() => [ + for (var i = 0; i < 16; i++) + _random.nextInt(256).toRadixString(16).padLeft(2, '0'), + ].join(); + + // ---- storage ---- + + Future<_State> _load() async { + final json = _decode(await store.read()); + if (json == null || json['gatewayOrigin'] != _gatewayOrigin) { + return _State.empty; + } + return _State.fromJson(json); + } + + Map? _decode(String? raw) { + if (raw == null) return null; + final decoded = jsonDecode(raw); + if (decoded is! Map) { + throw const FormatException('Android push authority state is malformed.'); + } + return decoded; + } + + /// State stored for another gateway is dropped: its installation and key + /// mean nothing to this one, which enrolls afresh. The old installation + /// expires under its own gateway's policy. + Future _dropForeignGateway() async { + final json = _decode(await store.read()); + if (json == null || json['gatewayOrigin'] == _gatewayOrigin) return; + await keystore.delete(); + await store.write(null); + } + + Future _save(_State state) => store.write( + state.isEmpty + ? null + : jsonEncode({...state.toJson(), 'gatewayOrigin': _gatewayOrigin}), + ); +} + +bool _always() => true; + +/// Control flow for [AndroidPushAuthority.enroll]: the caller's `stillWanted` +/// said no, so nothing more is created. +class _EnrollmentNoLongerWanted implements Exception { + const _EnrollmentNoLongerWanted(); +} + +class _Challenge { + const _Challenge(this.id, this.text); + + final String id; + final String text; +} + +class _PendingEnrollment { + const _PendingEnrollment({ + required this.keyId, + required this.expiresAt, + required this.body, + }); + + final String keyId; + final int expiresAt; + final Map body; + + Map toJson() => { + 'keyId': keyId, + 'expiresAt': expiresAt, + 'body': body, + }; + + factory _PendingEnrollment.fromJson(Map json) => + _PendingEnrollment( + keyId: json['keyId']! as String, + expiresAt: json['expiresAt']! as int, + body: Map.from(json['body']! as Map), + ); +} + +class _Installation { + const _Installation({ + required this.handle, + required this.keyId, + required this.endpoint, + required this.endpointEpoch, + required this.expiresAt, + this.rotatingTo, + }); + + final String handle; + final String keyId; + final String endpoint; + final int endpointEpoch; + final int expiresAt; + + /// The endpoint of a rotation that may have reached the gateway. + final String? rotatingTo; + + _Installation copyWith({ + String? endpoint, + int? endpointEpoch, + int? expiresAt, + String? rotatingTo, + bool clearRotatingTo = false, + }) => _Installation( + handle: handle, + keyId: keyId, + endpoint: endpoint ?? this.endpoint, + endpointEpoch: endpointEpoch ?? this.endpointEpoch, + expiresAt: expiresAt ?? this.expiresAt, + rotatingTo: clearRotatingTo ? null : rotatingTo ?? this.rotatingTo, + ); + + Map toJson() => { + 'handle': handle, + 'keyId': keyId, + 'endpoint': endpoint, + 'endpointEpoch': endpointEpoch, + 'expiresAt': expiresAt, + 'rotatingTo': rotatingTo, + }; + + factory _Installation.fromJson(Map json) => _Installation( + handle: json['handle']! as String, + keyId: json['keyId']! as String, + endpoint: json['endpoint']! as String, + endpointEpoch: json['endpointEpoch']! as int, + expiresAt: json['expiresAt']! as int, + rotatingTo: json['rotatingTo'] as String?, + ); +} + +class _DelegationGrant { + const _DelegationGrant({ + required this.installationHandle, + required this.endpointGrant, + required this.endpointHash, + required this.endpointEpoch, + required this.generation, + required this.expiresAt, + }); + + final String installationHandle; + final String endpointGrant; + final String endpointHash; + final int endpointEpoch; + final int generation; + final int expiresAt; + + Map toJson() => { + 'installationHandle': installationHandle, + 'endpointGrant': endpointGrant, + 'endpointHash': endpointHash, + 'endpointEpoch': endpointEpoch, + 'generation': generation, + 'expiresAt': expiresAt, + }; + + factory _DelegationGrant.fromJson(Map json) => + _DelegationGrant( + installationHandle: json['installationHandle']! as String, + endpointGrant: json['endpointGrant']! as String, + endpointHash: json['endpointHash']! as String, + endpointEpoch: json['endpointEpoch']! as int, + generation: json['generation']! as int, + expiresAt: json['expiresAt']! as int, + ); +} + +/// What the phone holds for one executor key, which is what the gateway keys +/// a delegation by. +class _Delegation { + const _Delegation({ + required this.pubkey, + this.generation = 0, + this.delegated = false, + this.grant, + }); + + final String pubkey; + + /// The highest delegation generation spent, accepted or not. + final int generation; + + /// Whether a delegation from this installation to the key may exist at the + /// gateway: set before the first attempt, cleared by revocation. + final bool delegated; + + /// The last delegation the gateway accepted. It stays after revocation or + /// a reset, because a lease tombstone still reads it. + final _DelegationGrant? grant; + + _Delegation copyWith({ + int? generation, + bool? delegated, + _DelegationGrant? grant, + }) => _Delegation( + pubkey: pubkey, + generation: generation ?? this.generation, + delegated: delegated ?? this.delegated, + grant: grant ?? this.grant, + ); + + Map toJson() => { + 'pubkey': pubkey, + 'generation': generation, + 'delegated': delegated, + 'grant': grant?.toJson(), + }; + + factory _Delegation.fromJson(Map json) => _Delegation( + pubkey: json['pubkey']! as String, + generation: json['generation']! as int, + delegated: json['delegated']! as bool, + grant: json['grant'] == null + ? null + : _DelegationGrant.fromJson(json['grant']! as Map), + ); +} + +/// What the phone holds for one relay origin: its lease identity, and the +/// executor key it currently uses. +class _Origin { + const _Origin({ + required this.origin, + required this.installationId, + required this.pubkey, + }); + + final String origin; + + /// The lease's identity, kept across installations and keys. + final String installationId; + final String pubkey; + + Map toJson() => { + 'origin': origin, + 'installationId': installationId, + 'pubkey': pubkey, + }; + + factory _Origin.fromJson(Map json) => _Origin( + origin: json['origin']! as String, + installationId: json['installationId']! as String, + pubkey: json['pubkey']! as String, + ); +} + +class _State { + const _State({ + this.installation, + this.pendingEnrollment, + this.delegations = const {}, + this.origins = const {}, + }); + + static const empty = _State(); + + final _Installation? installation; + final _PendingEnrollment? pendingEnrollment; + final Map delegations; + final Map origins; + + bool get isEmpty => + installation == null && + pendingEnrollment == null && + delegations.isEmpty && + origins.isEmpty; + + _State copyWith({ + _Installation? installation, + bool clearInstallation = false, + _PendingEnrollment? pendingEnrollment, + bool clearPendingEnrollment = false, + Map? delegations, + Map? origins, + }) => _State( + installation: clearInstallation ? null : installation ?? this.installation, + pendingEnrollment: clearPendingEnrollment + ? null + : pendingEnrollment ?? this.pendingEnrollment, + delegations: delegations ?? this.delegations, + origins: origins ?? this.origins, + ); + + Map toJson() => { + 'installation': installation?.toJson(), + 'pendingEnrollment': pendingEnrollment?.toJson(), + 'delegations': [for (final value in delegations.values) value.toJson()], + 'origins': [for (final value in origins.values) value.toJson()], + }; + + factory _State.fromJson(Map json) => _State( + installation: json['installation'] == null + ? null + : _Installation.fromJson(json['installation']! as Map), + pendingEnrollment: json['pendingEnrollment'] == null + ? null + : _PendingEnrollment.fromJson( + json['pendingEnrollment']! as Map, + ), + delegations: { + for (final value in json['delegations']! as List) + (value! as Map)['pubkey']! as String: + _Delegation.fromJson(value as Map), + }, + origins: { + for (final value in json['origins']! as List) + (value! as Map)['origin']! as String: _Origin.fromJson( + value as Map, + ), + }, + ); +} diff --git a/mobile/lib/shared/push/android_push_gateway.dart b/mobile/lib/shared/push/android_push_gateway.dart new file mode 100644 index 0000000000..4d7d39e17d --- /dev/null +++ b/mobile/lib/shared/push/android_push_gateway.dart @@ -0,0 +1,84 @@ +import 'dart:convert'; + +import 'package:http/http.dart' as http; + +import '../http/app_http_client.dart'; + +/// The gateway answered with a refusal. Signed installation calls answer every +/// refusal with `404 not_authorized`, so [status] and [code] say what the +/// gateway said and nothing more. +class AndroidPushGatewayRejection implements Exception { + const AndroidPushGatewayRejection(this.route, this.status, this.code); + + final String route; + final int status; + final String? code; + + bool get isNotAuthorized => status == 404 && code == 'not_authorized'; + + /// A refusal of the attestation itself, which only a different phone or boot + /// state changes. + bool get isInvalidAttestation => + status == 401 && code == 'invalid_attestation'; + + /// Refusals worth retrying later with the same request: throttling and + /// gateway-side trouble. Every other refusal is final for that request. + bool get isTransient => status == 429 || status >= 500; + + @override + String toString() => 'Push gateway refused $route: $status ${code ?? ''}'; +} + +/// One round trip to the gateway's JSON API. +class AndroidPushGatewayClient { + AndroidPushGatewayClient({ + required this.baseUrl, + http.Client? client, + this.timeout = const Duration(seconds: 15), + }) : _client = client ?? newAppHttpClient(); + + final Uri baseUrl; + final Duration timeout; + final http.Client _client; + + /// Posts [body] to [route] and returns the JSON object answered with + /// [expectedStatus]. Transport failures propagate unchanged. + 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 decoded = _object(response.bodyBytes); + if (response.statusCode != expectedStatus) { + throw AndroidPushGatewayRejection( + route, + response.statusCode, + decoded?['error'] as String?, + ); + } + if (decoded == null) { + throw FormatException( + 'Push gateway answered $route without a JSON object.', + ); + } + return decoded; + } + + Map? _object(List bytes) { + try { + final value = jsonDecode(utf8.decode(bytes)); + return value is Map ? value : null; + } on FormatException { + return null; + } + } + + void close() => _client.close(); +} diff --git a/mobile/lib/shared/push/android_push_keystore.dart b/mobile/lib/shared/push/android_push_keystore.dart new file mode 100644 index 0000000000..3fce987296 --- /dev/null +++ b/mobile/lib/shared/push/android_push_keystore.dart @@ -0,0 +1,105 @@ +import 'dart:convert'; + +import 'package:crypto/crypto.dart' as crypto; +import 'package:flutter/services.dart'; + +const _keystoreChannel = MethodChannel('buzz/push_keystore'); + +/// The installation's Android Keystore key: P-256, sign-only, never +/// exportable, with the key attestation chain the gateway verifies. +class AndroidPushKey { + const AndroidPushKey({required this.publicKey, required this.chain}); + + /// The uncompressed SEC1 point, 65 bytes. + final Uint8List publicKey; + + /// Leaf-first DER certificates. + final List chain; + + /// What the gateway calls this key: SHA-256 of [publicKey], base64. + String get keyId => base64.encode(crypto.sha256.convert(publicKey).bytes); + + List get chainBase64 => [ + for (final cert in chain) base64.encode(cert), + ]; +} + +/// This phone cannot produce hardware key attestation, so it cannot enroll. +class AndroidPushAttestationUnavailable implements Exception { + const AndroidPushAttestationUnavailable(this.reason); + + final String reason; + + @override + String toString() => 'Key attestation is unavailable: $reason'; +} + +/// The Keystore boundary. One installation key exists at a time. +abstract interface class AndroidPushKeystore { + /// The existing key, or null when none was generated. + Future current(); + + /// Replaces any key with a new one whose attestation challenge is + /// [attestationChallenge]. Throws [AndroidPushAttestationUnavailable] when + /// the phone cannot attest. + Future generate(Uint8List attestationChallenge); + + /// A base64 DER ECDSA signature over [data] (SHA-256 digest). + Future sign(Uint8List data); + + Future delete(); +} + +class MethodChannelAndroidPushKeystore implements AndroidPushKeystore { + const MethodChannelAndroidPushKeystore(); + + @override + Future current() async => + _key(await _keystoreChannel.invokeMapMethod('current')); + + @override + Future generate(Uint8List attestationChallenge) async { + try { + final key = _key( + await _keystoreChannel.invokeMapMethod('generate', { + 'challenge': attestationChallenge, + }), + ); + if (key == null) { + throw StateError('The Keystore returned no key.'); + } + return key; + } on PlatformException catch (error) { + if (error.code == 'attestation_unavailable') { + throw AndroidPushAttestationUnavailable( + error.message ?? 'no attestation', + ); + } + rethrow; + } + } + + @override + Future sign(Uint8List data) async { + final signature = await _keystoreChannel.invokeMethod('sign', { + 'data': data, + }); + if (signature == null) { + throw StateError('The Keystore returned no signature.'); + } + return base64.encode(signature); + } + + @override + Future delete() => _keystoreChannel.invokeMethod('delete'); + + AndroidPushKey? _key(Map? raw) { + if (raw == null) return null; + return AndroidPushKey( + publicKey: raw['publicKey']! as Uint8List, + chain: [ + for (final cert in raw['chain']! as List) cert! as Uint8List, + ], + ); + } +} diff --git a/mobile/lib/shared/push/android_push_transcript.dart b/mobile/lib/shared/push/android_push_transcript.dart new file mode 100644 index 0000000000..82a4dc2535 --- /dev/null +++ b/mobile/lib/shared/push/android_push_transcript.dart @@ -0,0 +1,145 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +/// Canonical transcripts for Android push installations. +/// +/// The gateway builds the same bytes with serde_json and verifies a signature +/// (or an attestation challenge) over them, so one differing byte is a silent +/// `401 invalid_attestation` or `404 not_authorized`. The encoding is +/// ` + "\n" + ` with members in a fixed order per +/// route. Ground truth is `app_attest_transcripts.json` in the gateway crate, +/// which the tests replay byte for byte. +/// +/// `audience` is the origin and route registered by NIP-PL v1. A configured +/// gateway origin changes where requests go, never these bytes. +const _audienceOrigin = 'https://push.buzz.xyz'; +const _wireVersion = 1; + +const androidEnrollDomain = 'buzz.push.enroll.android.v1'; +const androidDelegateDomain = 'buzz.push.delegate.v1'; +const androidRotateEndpointDomain = 'buzz.push.rotate-endpoint.v1'; +const androidRevokeDelegationDomain = 'buzz.push.revoke-delegation.v1'; +const androidRevokeInstallationDomain = 'buzz.push.revoke-installation.v1'; + +/// The Android enrollment transcript. It has no key id: the Keystore key is +/// generated from this transcript's digest, and the gateway derives the id +/// from the attested key. +Uint8List androidEnrollTranscript({ + required String challengeId, + required String challenge, + required String endpoint, + required int endpointEpoch, + required int expiresAt, +}) => _transcript(androidEnrollDomain, [ + ('v', _wireVersion), + ('audience', '$_audienceOrigin/v1/installations'), + ('challenge_id', challengeId), + ('challenge', challenge), + ('endpoint', endpoint), + ('endpoint_epoch', endpointEpoch), + ('expires_at', expiresAt), +]); + +Uint8List androidDelegateTranscript({ + required String challengeId, + required String challenge, + required String installationHandle, + required int endpointEpoch, + required int generation, + required String relayPubkey, + required int notBefore, + required int expiresAt, +}) => _transcript(androidDelegateDomain, [ + ('v', _wireVersion), + ('audience', '$_audienceOrigin/v1/delegations'), + ('challenge_id', challengeId), + ('challenge', challenge), + ('installation_handle', installationHandle), + ('endpoint_epoch', endpointEpoch), + ('generation', generation), + ('relay_pubkey', relayPubkey), + ('not_before', notBefore), + ('expires_at', expiresAt), +]); + +Uint8List androidRotateEndpointTranscript({ + required String challengeId, + required String challenge, + required String installationHandle, + required int endpointEpoch, + required int newEndpointEpoch, + required String endpoint, +}) => _transcript(androidRotateEndpointDomain, [ + ('v', _wireVersion), + ('audience', '$_audienceOrigin/v1/installations/endpoint'), + ('challenge_id', challengeId), + ('challenge', challenge), + ('installation_handle', installationHandle), + ('endpoint_epoch', endpointEpoch), + ('new_endpoint_epoch', newEndpointEpoch), + ('endpoint', endpoint), +]); + +Uint8List androidRevokeDelegationTranscript({ + required String challengeId, + required String challenge, + required String installationHandle, + required String relayPubkey, + required int generation, +}) => _transcript(androidRevokeDelegationDomain, [ + ('v', _wireVersion), + ('audience', '$_audienceOrigin/v1/delegations/revoke'), + ('challenge_id', challengeId), + ('challenge', challenge), + ('installation_handle', installationHandle), + ('relay_pubkey', relayPubkey), + ('generation', generation), +]); + +Uint8List androidRevokeInstallationTranscript({ + required String challengeId, + required String challenge, + required String installationHandle, + required int endpointEpoch, + required int newEndpointEpoch, +}) => _transcript(androidRevokeInstallationDomain, [ + ('v', _wireVersion), + ('audience', '$_audienceOrigin/v1/installations/revoke'), + ('challenge_id', challengeId), + ('challenge', challenge), + ('installation_handle', installationHandle), + ('endpoint_epoch', endpointEpoch), + ('new_endpoint_epoch', newEndpointEpoch), +]); + +Uint8List _transcript(String domain, List<(String, Object)> members) { + final body = StringBuffer('{'); + for (var index = 0; index < members.length; index++) { + final (name, value) = members[index]; + if (index > 0) body.write(','); + body + ..write('"$name":') + ..write(switch (value) { + final int number => '$number', + final String text => _jsonString(name, text), + _ => throw ArgumentError.value(value, name, 'Unsupported type'), + }); + } + body.write('}'); + return Uint8List.fromList(utf8.encode('$domain\n$body')); +} + +/// Authority-bearing strings are printable ASCII. Anything else is a bug in +/// the caller, so it fails here rather than guessing at an escaping the +/// gateway might not reproduce. +String _jsonString(String field, String value) { + final out = StringBuffer('"'); + for (final unit in value.codeUnits) { + if (unit < 0x20 || unit > 0x7e) { + throw FormatException('Transcript field $field is not printable ASCII.'); + } + if (unit == 0x22 || unit == 0x5c) out.writeCharCode(0x5c); + out.writeCharCode(unit); + } + return (out..write('"')).toString(); +} diff --git a/mobile/lib/shared/push/push_bootstrap.dart b/mobile/lib/shared/push/push_bootstrap.dart index b6e87f5cfe..80616e4551 100644 --- a/mobile/lib/shared/push/push_bootstrap.dart +++ b/mobile/lib/shared/push/push_bootstrap.dart @@ -1,6 +1,7 @@ import 'dart:async'; import 'dart:math'; +import 'package:flutter/foundation.dart' show defaultTargetPlatform; import 'package:flutter/material.dart'; import 'package:flutter_hooks/flutter_hooks.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; @@ -11,6 +12,7 @@ import '../diagnostics/diagnostic_reporter.dart'; import '../relay/relay_provider.dart'; import '../relay/relay_session.dart'; import '../relay/signed_event_relay.dart'; +import 'android_push_keystore.dart'; import 'dev_push_lease.dart'; import 'push_bridge.dart'; import 'push_lease_revocation_outbox.dart'; @@ -212,6 +214,7 @@ typedef _PushInputs = ({ BuzzPushLeaseRevocationOutbox revocationOutbox, SessionState session, List communities, + bool communitiesLoaded, RelayConfig config, Community? community, String? memberPubkey, @@ -228,6 +231,7 @@ final _pushInputsProvider = Provider.autoDispose>(( revocationOutbox: ref.watch(buzzPushLeaseRevocationOutboxProvider), session: ref.watch(relaySessionProvider), communities: ref.watch(communityListProvider).value ?? const [], + communitiesLoaded: ref.watch(communityListProvider).hasValue, config: ref.watch(relayConfigProvider), community: ref.watch(activeCommunityProvider).value, memberPubkey: ref.watch(myPubkeyProvider), @@ -324,19 +328,40 @@ class _BuzzPushLifecycle extends HookConsumerWidget { @override Widget build(BuildContext context, WidgetRef ref) { useListenable(apnsDeviceToken); + useListenable(fcmDeviceToken); final publicationAttempt = useMemoized(BuzzPushAttemptGate.new); final tombstoneAttempt = useMemoized(BuzzPushAttemptGate.new); + final reconcileAttempt = useMemoized(BuzzPushAttemptGate.new); final publicationRetry = useState(0); final tombstoneRetry = useState(0); + final reconcileRetry = useState(0); final ( :revocationOutbox, :session, :communities, + :communitiesLoaded, :config, :community, :memberPubkey, :descriptor, ) = inputs; + final optedIn = + Env.pushGatewayConfigured && + community?.pushNotificationsEnabled == true && + _signedIn(config, community, memberPubkey); + final shouldRegister = + session.status == SessionStatus.connected && + optedIn && + descriptor != null; + // Read by the resume listener, which outlives a build. A resume often + // lands while the relay reconnects, when its descriptor is gone, and the + // registration attempt after reconnecting reuses its key, so it would not + // refresh the token either. Remember instead whether this community's + // relay advertised push, so a relay without it never fetches a token. + final pushRelay = useRef(null); + if (descriptor != null) pushRelay.value = community?.id; + final registering = useRef(false); + registering.value = optedIn && pushRelay.value == community?.id; final enablementEpoch = useRef(0); useEffect(() { // Each opt-in needs a fresh active lease even when endpoint, executor, @@ -350,7 +375,20 @@ class _BuzzPushLifecycle extends HookConsumerWidget { useEffect(() { final listener = AppLifecycleListener( - onResume: () => _runRevocationOutbox(revocationOutbox.trigger), + onResume: () { + _runRevocationOutbox(revocationOutbox.trigger); + // FCM rotates its token without telling a stopped app. Only a phone + // that registers for push has one to refresh. + if (!registering.value) return; + unawaited( + refreshBuzzPushToken().catchError(( + Object error, + StackTrace stackTrace, + ) { + debugPrint('FCM token refresh failed: $error'); + }), + ); + }, ); _runRevocationOutbox(revocationOutbox.start); return listener.dispose; @@ -367,6 +405,7 @@ class _BuzzPushLifecycle extends HookConsumerWidget { () => () { publicationAttempt.dispose(); tombstoneAttempt.dispose(); + reconcileAttempt.dispose(); }, const [], ); @@ -430,19 +469,62 @@ class _BuzzPushLifecycle extends HookConsumerWidget { ], ); - final token = apnsDeviceToken.value; + // Removing the last community with push already off leaves the relay set + // unchanged (empty), but it is what makes the installation revocable. + final noCommunities = communities.isEmpty; + final pushRelayUrls = [ + for (final candidate in communities) + if (candidate.pushNotificationsEnabled) candidate.relayUrl, + ]; useEffect( () { - if (!_ready(session, config, community, memberPubkey) || - !buzzPushLifecycleEnabled( - community: community, - descriptor: descriptor, - ) || - token == null) { + // Authority the phone holds for relays no community uses is revoked: + // a community whose push is off, or removed, and at last the whole + // installation. A list still loading looks empty, so wait for it. + if (!communitiesLoaded || + !Env.pushGatewayConfigured || + defaultTargetPlatform != TargetPlatform.android) { + return null; + } + final attempt = + '${_pushRelayOrigins(communities).join('|')}|$noCommunities'; + if (!reconcileAttempt.tryBegin(attempt)) return null; + unawaited(() async { + try { + await reconcileBuzzPushAuthority( + desiredRelays: () => _desiredPushRelays(ref), + noCommunities: () => + (ref.read(communityListProvider).value ?? const []).isEmpty, + ); + reconcileAttempt.complete(attempt); + } catch (error, stack) { + reconcileAttempt.failed( + attempt, + retry: () { + if (context.mounted) reconcileRetry.value += 1; + }, + ); + reportPushLeaseCleanupError(error, stack); + } + }()); + return null; + }, + [ + communitiesLoaded, + pushRelayUrls.join('|'), + noCommunities, + reconcileRetry.value, + ], + ); + + final token = apnsDeviceToken.value ?? fcmDeviceToken.value; + useEffect( + () { + if (!shouldRegister || token == null) { return null; } final activeCommunity = community!; - final activeDescriptor = descriptor!; + final activeDescriptor = descriptor; final state = activeCommunity.pushSubscriptionState; if (state.desired.isEmpty) return null; final publicationKey = buzzPushPublicationAttemptKey( @@ -467,6 +549,12 @@ class _BuzzPushLifecycle extends HookConsumerWidget { memberPubkey!, relay, ); + if (grant == null) { + // Push was turned off, or the community removed, while this + // waited. Nothing was published, and the opt-out already ran. + publicationAttempt.complete(attempt); + return; + } final renewInMilliseconds = grant.expiresAt * 1000 - DateTime.now().millisecondsSinceEpoch - @@ -487,7 +575,15 @@ class _BuzzPushLifecycle extends HookConsumerWidget { if (context.mounted) publicationRetry.value += 1; } - if (error is BuzzPushChannelGrammarException) { + if (error is AndroidPushAttestationUnavailable) { + // Only a different boot state or gateway configuration changes + // this, so look again rarely rather than backing off briefly. + publicationAttempt.retryAfter( + attempt, + delay: const Duration(hours: 1), + retry: retry, + ); + } else if (error is BuzzPushChannelGrammarException) { // Re-fetch capabilities after a relay upgrade without repeatedly // enrolling or publishing a lease the old relay cannot accept. publicationAttempt.retryAfter( @@ -518,31 +614,26 @@ class _BuzzPushLifecycle extends HookConsumerWidget { ); return BuzzPushRegistrationBootstrap( - shouldRegister: - _ready(session, config, community, memberPubkey) && - buzzPushLifecycleEnabled( - community: community, - descriptor: descriptor, - ), + shouldRegister: shouldRegister, attemptKey: '${community?.id}|${config.baseUrl}', child: const SizedBox.shrink(), ); } - static bool _ready( - SessionState session, + static bool _signedIn( RelayConfig config, Community? community, String? memberPubkey, ) => - session.status == SessionStatus.connected && community != null && config.nsec != null && config.nsec!.isNotEmpty && memberPubkey != null && memberPubkey.isNotEmpty; - static Future _publish( + /// Returns null when the community stopped wanting push before the lease was + /// published. + static Future _publish( WidgetRef ref, RelayConfig config, Community community, @@ -555,11 +646,20 @@ class _BuzzPushLifecycle extends HookConsumerWidget { config.baseUrl, ); validateBuzzPushChannelGrammar(descriptor, desired); + // The opt-out's revocation may already have run while the descriptor was + // fetched or enrollment waited its turn, so enrolling or publishing now + // would create authority nothing revokes. Asked again before each step. + bool stillWanted() => (ref.read(communityListProvider).value ?? const []) + .any((c) => c.id == community.id && c.pushNotificationsEnabled); final grant = await enrollBuzzPush( config.wsUrl, Env.pushGatewayUrl, communitiesForSnapshotRefresh: ref.read(communityListProvider).value ?? [community], + relayOrigin: descriptor.origin, + relayPubkey: descriptor.executorPubkey, + desiredRelays: () => _desiredPushRelays(ref), + stillWanted: stillWanted, // Enrollment can finish after a community switch, when reports already // name the next member. diagnostics: SignerDiagnosticReporter( @@ -567,6 +667,7 @@ class _BuzzPushLifecycle extends HookConsumerWidget { signer: memberPubkey, ), ); + if (grant == null || !stillWanted()) return null; // Relay lease replacement and gateway delegation are independent state // machines. Subscription changes advance only the kind-30350 generation; // the opaque grant remains reusable until its own authority changes. @@ -594,6 +695,24 @@ class _BuzzPushLifecycle extends HookConsumerWidget { } } +Set _desiredPushRelays(WidgetRef ref) => + _pushRelayOrigins(ref.read(communityListProvider).value ?? const []); + +/// The relays of the communities whose push is on, as grants name them. A +/// relay URL with no origin (a path, say) never had a grant, so it names none. +Set _pushRelayOrigins(List communities) { + final origins = {}; + for (final community in communities) { + if (!community.pushNotificationsEnabled) continue; + try { + origins.add(canonicalBuzzPushRelayOrigin(community.relayUrl)); + } on FormatException { + continue; + } + } + return origins; +} + void _runRevocationOutbox(Future Function() operation) { unawaited( operation().catchError((Object error, StackTrace stackTrace) { diff --git a/mobile/lib/shared/push/push_bridge.dart b/mobile/lib/shared/push/push_bridge.dart index 27bfcd338e..ea1f700918 100644 --- a/mobile/lib/shared/push/push_bridge.dart +++ b/mobile/lib/shared/push/push_bridge.dart @@ -8,10 +8,18 @@ import '../community/community.dart'; import '../deeplink/deep_link.dart'; import '../diagnostics/diagnostic_reporter.dart'; import '../relay/relay_provider.dart'; +import 'android_push_authority.dart'; +import 'android_push_gateway.dart'; +import 'android_push_keystore.dart'; import 'push_snapshot.dart'; const _channel = MethodChannel('buzz/push'); +/// Android's FCM token registration. It has its own channel because Android's +/// notification-open handler already owns `buzz/push`, and a channel has one +/// native handler. +const _registrationChannel = MethodChannel('buzz/push_registration'); + /// The code native enrollment fails with when the push gateway's reply does /// not match its protocol. const _gatewayResponseInvalid = 'gateway_response_invalid'; @@ -21,6 +29,16 @@ const _gatewayResponseInvalid = 'gateway_response_invalid'; final apnsDeviceToken = ValueNotifier(null); final apnsRegistrationError = ValueNotifier(null); +/// Latest FCM registration token and failure on Android. They play the role +/// of the two APNs notifiers above; a phone only ever sets one pair. +final fcmDeviceToken = ValueNotifier(null); +final fcmRegistrationError = ValueNotifier(null); + +/// Why push cannot work on this phone (no hardware key attestation, no +/// Firebase, no FCM token), or null. The app works without push; settings +/// shows the reason. +final pushUnavailableReason = ValueNotifier(null); + final pushEndpointGrants = ValueNotifier>([]); final pushEndpointGrantError = ValueNotifier(null); @@ -255,16 +273,77 @@ Future syncPendingBuzzPushNotificationResponse() async { /// APNs registration and enrollment remain valid while display is denied. Future startBuzzPushRegistration() async { if (!Env.pushGatewayConfigured || - defaultTargetPlatform != TargetPlatform.iOS) { + (defaultTargetPlatform != TargetPlatform.iOS && + defaultTargetPlatform != TargetPlatform.android)) { return; } try { - await _channel.invokeMethod('startRegistration'); + await (defaultTargetPlatform == TargetPlatform.android + ? _registrationChannel + : _channel) + .invokeMethod('startRegistration'); } on MissingPluginException { // Flutter tests and non-Runner embeddings do not install the native bridge. } } +/// Asks Android for the current FCM token. FCM rotates it on its own, and the +/// app learns of that when it next runs. A changed token arrives through +/// [fcmDeviceToken] like the first one. +Future refreshBuzzPushToken() async { + if (!Env.pushGatewayConfigured || + defaultTargetPlatform != TargetPlatform.android) { + return; + } + try { + await _registrationChannel.invokeMethod('refreshToken'); + } on MissingPluginException { + // Flutter tests and non-Runner embeddings do not install the native bridge. + } +} + +AndroidPushAuthority? _androidAuthority; + +AndroidPushAuthority get _androidPushAuthority => + _androidAuthority ??= AndroidPushAuthority( + keystore: const MethodChannelAndroidPushKeystore(), + gateway: AndroidPushGatewayClient(baseUrl: Uri.parse(Env.pushGatewayUrl)), + store: SecureAndroidPushStateStore(), + ); + +@visibleForTesting +set debugAndroidPushAuthority(AndroidPushAuthority? authority) => + _androidAuthority = authority; + +BuzzPushEndpointGrant _grantOf(AndroidPushGrant grant) => BuzzPushEndpointGrant( + relayOrigin: grant.relayOrigin, + relayPubkey: grant.relayPubkey, + installationId: grant.installationId, + endpointGrant: grant.endpointGrant, + endpointHash: grant.endpointHash, + endpointEpoch: grant.endpointEpoch, + generation: grant.generation, + expiresAt: grant.expiresAt, +); + +/// Revokes what the phone's push installation holds for relays no community +/// uses any more, and the installation itself once no community remains. +/// Android only; iOS revokes only relay leases. [desiredRelays] and +/// [noCommunities] are read when the work runs. +Future reconcileBuzzPushAuthority({ + required Set Function() desiredRelays, + required bool Function() noCommunities, +}) async { + if (!Env.pushGatewayConfigured || + defaultTargetPlatform != TargetPlatform.android) { + return; + } + await _androidPushAuthority.reconcile( + desiredRelays: desiredRelays, + revokeInstallation: noCommunities, + ); +} + class BuzzPushEndpointGrant { final String relayOrigin; final String relayPubkey; @@ -303,17 +382,26 @@ class BuzzPushEndpointGrant { Future> readBuzzPushEndpointGrants() async { if (!Env.pushGatewayConfigured || - defaultTargetPlatform != TargetPlatform.iOS) { + (defaultTargetPlatform != TargetPlatform.iOS && + defaultTargetPlatform != TargetPlatform.android)) { return const []; } try { - final raw = await _channel.invokeListMethod('endpointGrants', { - 'gatewayUrl': Env.pushGatewayUrl, - }); - final grants = [ - for (final value in raw ?? const []) - BuzzPushEndpointGrant.fromMap(value as Map), - ]; + final List grants; + if (defaultTargetPlatform == TargetPlatform.android) { + grants = [ + for (final grant in await _androidPushAuthority.grants()) + _grantOf(grant), + ]; + } else { + final raw = await _channel.invokeListMethod('endpointGrants', { + 'gatewayUrl': Env.pushGatewayUrl, + }); + grants = [ + for (final value in raw ?? const []) + BuzzPushEndpointGrant.fromMap(value as Map), + ]; + } pushEndpointGrants.value = grants; pushEndpointGrantError.value = null; return grants; @@ -323,39 +411,83 @@ Future> readBuzzPushEndpointGrants() async { } } +bool _wanted() => true; + /// Enrolls the endpoint and optionally rewrites the NSE snapshot afterward. /// /// The rewrite propagates NIP-11 `self` rotations even when the opaque grant /// and accepted relay lease remain reusable and their generations do not move. -Future enrollBuzzPush( +/// +/// On Android the grant comes from the Dart-side [AndroidPushAuthority], which +/// needs the relay's [relayOrigin] and push key [relayPubkey] from its +/// descriptor, where iOS native code fetches them itself. +/// +/// [desiredRelays] (Android) are the relay origins whose push is on, which +/// enrollment uses to revoke delegations no relay points at any more. +/// +/// [stillWanted] says whether the community still wants push. It is read before +/// each call that creates authority, and the result is null once it said no. +Future enrollBuzzPush( String relayUrl, String gatewayUrl, { List? communitiesForSnapshotRefresh, + String? relayOrigin, + String? relayPubkey, + Set Function()? desiredRelays, + bool Function() stillWanted = _wanted, DiagnosticReporter diagnostics = const NoopDiagnosticReporter(), }) async { - final Map? raw; - try { - raw = await _channel.invokeMapMethod('enrollPush', { - 'relayUrl': relayUrl, - 'gatewayUrl': gatewayUrl, - }); - } on PlatformException catch (error, stackTrace) { - // The gateway is called from native code. It has its own code for a reply - // the app cannot read; every other failure (offline, refused, expired, - // server errors) is routine and not reported. - if (error.code == _gatewayResponseInvalid) { - diagnostics.reportError( - error, - stackTrace, - operation: DiagnosticOperation.pushGatewayResponse, - ); + final BuzzPushEndpointGrant grant; + if (defaultTargetPlatform == TargetPlatform.android) { + final token = fcmDeviceToken.value; + if (token == null || + relayOrigin == null || + relayPubkey == null || + desiredRelays == null) { + throw StateError('Android push enrollment needs a token and a relay.'); } - rethrow; + final AndroidPushGrant? enrolled; + try { + enrolled = await _androidPushAuthority.enroll( + relayOrigin: relayOrigin, + relayPubkey: relayPubkey, + endpoint: token, + stillWanted: stillWanted, + desiredRelays: desiredRelays, + ); + } on AndroidPushAttestationUnavailable catch (error) { + pushUnavailableReason.value = error.reason; + rethrow; + } + if (enrolled == null) return null; + grant = _grantOf(enrolled); + pushUnavailableReason.value = null; + } else { + if (!stillWanted()) return null; + final Map? raw; + try { + raw = await _channel.invokeMapMethod('enrollPush', { + 'relayUrl': relayUrl, + 'gatewayUrl': gatewayUrl, + }); + } on PlatformException catch (error, stackTrace) { + // The gateway is called from native code. It has its own code for a + // reply the app cannot read; every other failure (offline, refused, + // expired, server errors) is routine and not reported. + if (error.code == _gatewayResponseInvalid) { + diagnostics.reportError( + error, + stackTrace, + operation: DiagnosticOperation.pushGatewayResponse, + ); + } + rethrow; + } + if (raw == null) { + throw StateError('Native push enrollment returned no grant.'); + } + grant = BuzzPushEndpointGrant.fromMap(raw); } - if (raw == null) { - throw StateError('Native push enrollment returned no grant.'); - } - final grant = BuzzPushEndpointGrant.fromMap(raw); await readBuzzPushEndpointGrants(); if (communitiesForSnapshotRefresh != null) { try { @@ -489,6 +621,44 @@ Future shareHostedSessionWithNotifications({ } void installBuzzPushMethodHandler() { + _registrationChannel.setMethodCallHandler((call) async { + switch (call.method) { + case 'fcmTokenChanged': + final args = call.arguments; + if (args is Map) { + final token = args['token']; + if (token is String && token.isNotEmpty) { + fcmDeviceToken.value = token; + // A token ends an earlier failure to get one, but not an + // attestation failure, which enrollment owns. + if (pushUnavailableReason.value == fcmRegistrationError.value) { + pushUnavailableReason.value = null; + } + fcmRegistrationError.value = null; + } + } + return null; + case 'fcmRegistrationFailed': + final args = call.arguments; + final message = args is Map ? args['message'] : null; + final reason = message is String && message.isNotEmpty + ? message + : 'FCM registration failed'; + final previous = fcmRegistrationError.value; + fcmRegistrationError.value = reason; + // A held token still delivers, so a failed refresh is transient. Never + // overwrite another reason, such as attestation, which enrollment owns. + final shown = pushUnavailableReason.value; + if (fcmDeviceToken.value == null && + (shown == null || shown == previous)) { + pushUnavailableReason.value = reason; + } + debugPrint('FCM registration failed: $reason'); + return null; + default: + throw MissingPluginException('Unexpected ${call.method}'); + } + }); _channel.setMethodCallHandler((call) async { switch (call.method) { case 'apnsTokenChanged': diff --git a/mobile/test/features/settings/android_notifications_test.dart b/mobile/test/features/settings/android_notifications_test.dart new file mode 100644 index 0000000000..9442513514 --- /dev/null +++ b/mobile/test/features/settings/android_notifications_test.dart @@ -0,0 +1,475 @@ +import 'dart:async'; +import 'dart:convert'; + +import 'package:buzz/features/settings/settings_page.dart'; +import 'package:buzz/shared/auth/auth_provider.dart'; +import 'package:buzz/shared/community/community.dart'; +import 'package:buzz/shared/community/community_provider.dart'; +import 'package:buzz/shared/community/community_storage.dart'; +import 'package:buzz/shared/push/dev_push_lease.dart'; +import 'package:buzz/shared/push/push_bootstrap.dart'; +import 'package:buzz/shared/push/push_lease_revocation_outbox.dart'; +import 'package:buzz/shared/crypto/nip44.dart'; +import 'package:buzz/shared/relay/nostr_models.dart'; +import 'package:buzz/shared/push/android_push_authority.dart'; +import 'package:buzz/shared/push/push_bridge.dart'; +import 'package:buzz/shared/push/push_relay_capability_provider.dart'; +import 'package:buzz/shared/push/push_subscription.dart'; +import 'package:buzz/shared/relay/app_lifecycle_provider.dart'; +import 'package:buzz/shared/relay/relay_provider.dart'; +import 'package:buzz/shared/relay/relay_session.dart'; +import 'package:buzz/shared/theme/theme.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:hooks_riverpod/hooks_riverpod.dart'; +import 'package:package_info_plus/package_info_plus.dart'; +import 'package:nostr/nostr.dart' as nostr; +import 'package:shared_preferences/shared_preferences.dart'; + +import '../../helpers/android_push_fakes.dart'; +import '../../shared/community/community_storage_test.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + setUpAll(() async { + final fonts = FontLoader('Inter') + ..addFont(rootBundle.load('assets/fonts/InterVariable.ttf')); + await fonts.load(); + }); + + for (final attests in [true, false]) { + testWidgets( + attests + ? 'an attesting Android phone enrolls and publishes its lease' + : 'an Android phone that cannot attest keeps working and says so', + (tester) async { + tester.view.physicalSize = const Size(375, 1800); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + debugDefaultTargetPlatformOverride = TargetPlatform.android; + addTearDown(() => debugDefaultTargetPlatformOverride = null); + PackageInfo.setMockInitialValues( + appName: 'Buzz', + packageName: 'buzz', + version: '1.0.0', + buildNumber: '1', + buildSignature: '', + ); + SharedPreferences.setMockInitialValues({}); + final prefs = await SharedPreferences.getInstance(); + final storage = CommunityStorage(secure: FakeSecureStorage()); + final subscriptions = [ + BuzzPushSubscription( + filter: BuzzPushFilter(kinds: const [9], pTags: ['a' * 64]), + notificationClass: 'default', + ), + ]; + final session = _Connected(); + var advertised = _descriptor; + final now = DateTime.now().millisecondsSinceEpoch ~/ 1000; + final gateway = FakePushGateway(nowSeconds: () => now); + debugAndroidPushAuthority = AndroidPushAuthority( + keystore: FakeAndroidKeystore()..attests = attests, + gateway: fakeGatewayClient(gateway), + store: _MemoryStore(), + sleep: (_) async {}, + ); + addTearDown(() { + debugAndroidPushAuthority = null; + fcmDeviceToken.value = null; + pushUnavailableReason.value = null; + pushEndpointGrants.value = const []; + }); + fcmDeviceToken.value = 'test-fcm-token'; + const nativePush = MethodChannel('buzz/push_registration'); + final messenger = + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; + messenger.setMockMethodCallHandler( + nativePush, + (call) async => switch (call.method) { + 'startRegistration' || 'refreshToken' || 'syncPushSnapshot' => null, + _ => throw StateError('Unexpected native call ${call.method}'), + }, + ); + addTearDown(() => messenger.setMockMethodCallHandler(nativePush, null)); + final community = + Community.create( + name: 'Team', + relayUrl: 'https://relay.example', + ).copyWith( + nsec: nostr.Nip19.encode( + prefix: nostr.Nip19Prefix.nsec, + data: '1' * 64, + ), + pushNotificationsEnabled: true, + pushLeaseInstallationId: 'd' * 32, + pushSubscriptionState: BuzzPushLeaseSubscriptionState.desired( + desired: subscriptions, + ).withAccepted(subscriptions: subscriptions, generation: 7), + ); + await storage.save(community); + await storage.saveActiveId(community.id); + + await tester.pumpWidget( + ProviderScope( + overrides: [ + savedPrefsProvider.overrideWithValue(prefs), + authProvider.overrideWith(_Auth.new), + communityStorageProvider.overrideWithValue(storage), + communitySnapshotWriterProvider.overrideWithValue( + (communities) async {}, + ), + buzzPushLeaseRevocationStorageProvider.overrideWithValue( + BuzzPushLeaseRevocationStorage(secure: FakeSecureStorage()), + ), + relaySessionProvider.overrideWith(() => session), + myPubkeyProvider.overrideWithValue(nostr.Keys('1' * 64).public), + buzzPushDescriptorFetcherProvider.overrideWithValue( + (_) async => advertised, + ), + appLifecycleProvider.overrideWith(_Lifecycle.new), + ], + child: BuzzPushBootstrap( + child: MaterialApp( + theme: AppTheme.light(), + home: SettingsPage( + profileHeader: const SizedBox.shrink(), + identityRecoveryPageBuilder: (_) => const SizedBox.shrink(), + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + + // Notification settings exist on Android, and the app stays usable + // either way. + expect( + find.byKey(const ValueKey('push-notifications-setting')), + findsOneWidget, + ); + expect(tester.widget(find.byType(Switch)).value, isTrue); + expect(tester.takeException(), isNull); + if (attests) { + expect(find.byKey(const ValueKey('push-unavailable')), findsNothing); + expect(gateway.installations, hasLength(1)); + expect(session.leases.last['active'], isTrue); + expect(session.leases.last['endpoint'], isNotEmpty); + + // The relay reconnects advertising a new executor key: the old key's + // delegation is revoked while push stays on, and the lease carries a + // grant for the new key. + final oldExecutor = _descriptor.executorPubkey; + final newExecutor = nostr.Keys('3' * 64).public; + advertised = _descriptorFor(newExecutor); + session.executorSecret = '3' * 64; + final installationBefore = gateway.installations.values.single; + session.setStatus(SessionStatus.reconnecting); + await tester.pumpAndSettle(); + session.setStatus(SessionStatus.connected); + await tester.pumpAndSettle(); + expect(installationBefore.revokedDelegations, {'$oldExecutor/1'}); + expect(installationBefore.delegations, contains(newExecutor)); + expect(session.leases.last['endpoint'], contains(newExecutor)); + + // Turning push off keeps the installation: the community remains. + // Removing that community afterwards is what revokes it. + final installation = gateway.installations.values.single; + await tester.tap(find.byType(Switch)); + await tester.pumpAndSettle(); + expect(installation.revokedDelegations, isNotEmpty); + expect(installation.revoked, isFalse); + final container = ProviderScope.containerOf( + tester.element(find.byType(SettingsPage)), + ); + await container + .read(communityListProvider.notifier) + .removeCommunity(community.id); + await tester.pumpAndSettle(); + expect(installation.revoked, isTrue); + } else { + expect( + find.byKey(const ValueKey('push-unavailable')), + findsOneWidget, + ); + expect(find.text('Push is unavailable on this phone'), findsOne); + expect(gateway.installations, isEmpty); + expect(session.leases.where((l) => l['active'] == true), isEmpty); + } + await tester.pumpWidget(const SizedBox.shrink()); + await tester.pumpAndSettle(); + // Foundation checks its debug variables before teardowns run. + debugDefaultTargetPlatformOverride = null; + }, + ); + } + + // Mounts only the push bootstrap over a community with the given relay URL + // and opt-in, recording the native registration calls. + Future> pumpBootstrap( + WidgetTester tester, { + required TargetPlatform platform, + required String relayUrl, + required bool enabled, + _Connected? session, + bool advertisesPush = true, + FakePushGateway? gateway, + Future? descriptorGate, + List? subscriptions, + }) async { + debugDefaultTargetPlatformOverride = platform; + addTearDown(() => debugDefaultTargetPlatformOverride = null); + SharedPreferences.setMockInitialValues({}); + final prefs = await SharedPreferences.getInstance(); + final storage = CommunityStorage(secure: FakeSecureStorage()); + final pushGateway = + gateway ?? + FakePushGateway( + nowSeconds: () => DateTime.now().millisecondsSinceEpoch ~/ 1000, + ); + debugAndroidPushAuthority = AndroidPushAuthority( + keystore: FakeAndroidKeystore(), + gateway: fakeGatewayClient(pushGateway), + store: _MemoryStore(), + sleep: (_) async {}, + ); + addTearDown(() => debugAndroidPushAuthority = null); + var descriptorFetches = 0; + final calls = []; + final messenger = + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; + for (final channel in const [ + MethodChannel('buzz/push_registration'), + MethodChannel('buzz/push'), + ]) { + messenger.setMockMethodCallHandler(channel, (call) async { + calls.add(call.method); + return null; + }); + addTearDown(() => messenger.setMockMethodCallHandler(channel, null)); + } + final community = Community.create(name: 'Team', relayUrl: relayUrl) + .copyWith( + nsec: nostr.Nip19.encode( + prefix: nostr.Nip19Prefix.nsec, + data: '1' * 64, + ), + pushNotificationsEnabled: enabled, + pushSubscriptionState: subscriptions == null + ? null + : BuzzPushLeaseSubscriptionState.desired(desired: subscriptions), + ); + await storage.save(community); + await storage.saveActiveId(community.id); + + await tester.pumpWidget( + ProviderScope( + overrides: [ + savedPrefsProvider.overrideWithValue(prefs), + authProvider.overrideWith(_Auth.new), + communityStorageProvider.overrideWithValue(storage), + communitySnapshotWriterProvider.overrideWithValue( + (communities) async {}, + ), + buzzPushLeaseRevocationStorageProvider.overrideWithValue( + BuzzPushLeaseRevocationStorage(secure: FakeSecureStorage()), + ), + relaySessionProvider.overrideWith(() => session ?? _Connected()), + myPubkeyProvider.overrideWithValue(nostr.Keys('1' * 64).public), + buzzPushDescriptorFetcherProvider.overrideWithValue((_) async { + // Discovery reads the descriptor first, which sets push up; the + // fetch that publication makes next is the one held back. + if (++descriptorFetches > 1) await descriptorGate; + if (!advertisesPush) throw const BuzzPushNotAdvertised(); + return _descriptor; + }), + appLifecycleProvider.overrideWith(_Lifecycle.new), + ], + child: const BuzzPushBootstrap(child: SizedBox()), + ), + ); + await tester.pumpAndSettle(); + return calls; + } + + Future unmount(WidgetTester tester) async { + await tester.pumpWidget(const SizedBox.shrink()); + await tester.pumpAndSettle(); + // Foundation checks its debug variables before teardowns run. + debugDefaultTargetPlatformOverride = null; + } + + for (final platform in [TargetPlatform.android, TargetPlatform.iOS]) { + testWidgets('a relay URL with a path does not break push on $platform', ( + tester, + ) async { + await pumpBootstrap( + tester, + platform: platform, + relayUrl: 'https://relay.example/team', + enabled: true, + ); + + expect(tester.takeException(), isNull); + await unmount(tester); + }); + } + + for (final (name, enabled, advertisesPush) in [ + ('refreshes the FCM token', true, true), + ('fetches no token while opted out', false, true), + ('fetches no token for a relay without push', true, false), + ]) { + testWidgets('resuming the app $name', (tester) async { + fcmDeviceToken.value = 'test-fcm-token'; + addTearDown(() => fcmDeviceToken.value = null); + final calls = await pumpBootstrap( + tester, + platform: TargetPlatform.android, + relayUrl: 'https://relay.example', + enabled: enabled, + advertisesPush: advertisesPush, + ); + calls.clear(); + + tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive); + tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed); + await tester.pumpAndSettle(); + + expect(calls.contains('refreshToken'), enabled && advertisesPush); + await unmount(tester); + }); + } + + testWidgets('turning push off while its enrollment waits publishes nothing', ( + tester, + ) async { + fcmDeviceToken.value = 'test-fcm-token'; + addTearDown(() => fcmDeviceToken.value = null); + final gateway = FakePushGateway( + nowSeconds: () => DateTime.now().millisecondsSinceEpoch ~/ 1000, + ); + 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', + ), + ], + ); + final container = ProviderScope.containerOf( + tester.element(find.byType(BuzzPushBootstrap)), + ); + final notifier = container.read(communityListProvider.notifier); + await notifier.setPushNotificationsEnabled( + container.read(communityListProvider).value!.single.id, + false, + ); + + // The descriptor arrives after the opt-out: nothing is enrolled, delegated + // or published for a community that no longer wants push. + descriptorGate.complete(); + await tester.pumpAndSettle(); + + expect(gateway.requests, isEmpty); + expect(session.leases.where((lease) => lease['active'] == true), isEmpty); + await unmount(tester); + }); + + testWidgets('resuming while the relay reconnects refreshes the FCM token', ( + tester, + ) async { + fcmDeviceToken.value = 'test-fcm-token'; + addTearDown(() => fcmDeviceToken.value = null); + final session = _Connected(); + final calls = await pumpBootstrap( + tester, + platform: TargetPlatform.android, + relayUrl: 'https://relay.example', + enabled: true, + session: session, + ); + session.setStatus(SessionStatus.reconnecting); + await tester.pumpAndSettle(); + calls.clear(); + + tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive); + tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed); + await tester.pumpAndSettle(); + + expect(calls, contains('refreshToken')); + await unmount(tester); + }); +} + +class _MemoryStore implements AndroidPushStateStore { + String? value; + + @override + Future read() async => value; + + @override + Future write(String? next) async => value = next; +} + +class _Lifecycle extends AppLifecycleNotifier { + @override + AppLifecycleState build() => AppLifecycleState.resumed; +} + +class _Auth extends AuthNotifier { + @override + Future build() async => + const AuthState(status: AuthStatus.unauthenticated); +} + +class _Connected extends RelaySessionNotifier { + final leases = >[]; + String executorSecret = '2' * 64; + + @override + Future publish( + NostrEvent event, { + Duration timeout = const Duration(seconds: 8), + Future Function()? mayPublish, + }) async { + expect(event.kind, buzzPushLeaseKind); + final plaintext = nip44Decrypt( + getConversationKey(executorSecret, event.pubkey), + event.content, + ); + leases.add(jsonDecode(plaintext) as Map); + return event; + } + + void setStatus(SessionStatus status) => state = SessionState(status: status); + + @override + SessionState build() => const SessionState(status: SessionStatus.connected); +} + +final _descriptor = _descriptorFor(nostr.Keys('2' * 64).public); + +BuzzPushLeaseDescriptor _descriptorFor(String executorPubkey) => + BuzzPushLeaseDescriptor( + origin: 'wss://relay.example', + executorKeyId: 'relay-v1', + executorPubkey: executorPubkey, + transport: 'apns', + maxLeaseTtlSeconds: 3600, + maxContentLength: 4096, + maxPlaintextLength: 4096, + maxEndpointLength: 2048, + maxStringLength: 512, + ); diff --git a/mobile/test/helpers/android_push_fakes.dart b/mobile/test/helpers/android_push_fakes.dart new file mode 100644 index 0000000000..3b15914eff --- /dev/null +++ b/mobile/test/helpers/android_push_fakes.dart @@ -0,0 +1,291 @@ +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 current() async => key; + + @override + Future 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 sign(Uint8List data) async { + final current = key; + if (current == null) throw StateError('no key'); + return signatureFor(current.publicKey, data); + } + + @override + Future delete() async { + deleted++; + key = null; + } +} + +String signatureFor(Uint8List publicKey, List 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 = {}; + final revokedDelegations = {}; +} + +/// 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 = {}; + final requests = <({String route, Map body})>[]; + final _challenges = {}; + var _next = 0; + + /// Routes whose next response is lost after the gateway acted on it. + final loseResponseFor = {}; + + /// Routes that answer with this status instead of acting. + final failWith = {}; + + /// Routes whose next call is refused like an expired challenge: answered + /// `not_authorized` without acting. + final refuseOnce = {}; + + /// Refuse attestations like a gateway that does not trust this phone. + bool refuseAttestation = false; + + List> 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; + 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 body) => + http.Response(jsonEncode(body), status); + + http.Response _notAuthorized() => _json(404, {'error': 'not_authorized'}); + + http.Response _handle(String route, Map 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 body) { + final chain = (body['android_attestation']! as List).cast(); + 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 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 a, List 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, +); diff --git a/mobile/test/shared/community/community_provider_test.dart b/mobile/test/shared/community/community_provider_test.dart index f1f8c9ce57..8e35805a3f 100644 --- a/mobile/test/shared/community/community_provider_test.dart +++ b/mobile/test/shared/community/community_provider_test.dart @@ -21,9 +21,14 @@ import 'package:buzz/shared/community/community.dart'; import 'package:buzz/shared/community/community_provider.dart'; import 'package:buzz/shared/community/community_storage.dart'; import 'package:buzz/shared/diagnostics/diagnostic_reporter.dart'; +import 'package:buzz/shared/push/android_push_authority.dart'; +import 'package:buzz/shared/push/push_bridge.dart'; import 'package:buzz/shared/push/push_subscription.dart'; +import 'package:flutter/foundation.dart' + show TargetPlatform, debugDefaultTargetPlatformOverride; import 'package:nostr/nostr.dart' as nostr; +import '../../helpers/android_push_fakes.dart'; import 'community_storage_test.dart'; void main() { @@ -430,6 +435,120 @@ void main() { }, ); + test( + 'opt-out after a gateway change still tombstones with the saved lease id', + () async { + // The test binding answers every HttpClient request with a 400, but + // this test runs a real local relay. + final overrides = HttpOverrides.current; + HttpOverrides.global = null; + addTearDown(() => HttpOverrides.global = overrides); + debugDefaultTargetPlatformOverride = TargetPlatform.android; + addTearDown(() => debugDefaultTargetPlatformOverride = null); + final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0); + addTearDown(() => server.close(force: true)); + final origin = 'ws://127.0.0.1:${server.port}'; + final tombstones = >[]; + server.listen((request) async { + if (WebSocketTransformer.isUpgradeRequest(request)) { + final socket = await WebSocketTransformer.upgrade(request); + socket.add(jsonEncode(['AUTH', 'challenge'])); + socket.listen((message) { + final frame = jsonDecode(message as String) as List; + final event = frame[1] as Map; + if (frame.first == 'EVENT') tombstones.add(event); + socket.add(jsonEncode(['OK', event['id'], true, ''])); + }); + return; + } + request.response + ..headers.contentType = ContentType('application', 'nostr+json') + ..write(jsonEncode(_descriptorJson(origin))) + ..close(); + }); + + // The phone enrolled with one gateway, then the app was built for + // another: that gateway's state reads empty, so no grant names the + // relay, but the community remembers its lease's installation id. + final store = _MemoryStore(); + final keystore = FakeAndroidKeystore(); + final now = DateTime.now().millisecondsSinceEpoch ~/ 1000; + final oldAuthority = AndroidPushAuthority( + keystore: keystore, + gateway: fakeGatewayClient(FakePushGateway(nowSeconds: () => now)), + store: store, + sleep: (_) async {}, + ); + await oldAuthority.enroll( + relayOrigin: origin, + relayPubkey: '2' * 64, + endpoint: 'token-1', + stillWanted: () => true, + desiredRelays: () => {origin}, + ); + debugAndroidPushAuthority = AndroidPushAuthority( + keystore: keystore, + gateway: fakeGatewayClient( + FakePushGateway(nowSeconds: () => now), + baseUrl: 'https://other-push.example', + ), + store: store, + sleep: (_) async {}, + ); + addTearDown(() => debugAndroidPushAuthority = null); + expect(await readBuzzPushEndpointGrants(), isEmpty); + + final keys = nostr.Keys.generate(); + final subscription = BuzzPushSubscription( + filter: BuzzPushFilter(kinds: const [9], pTags: ['a' * 64]), + notificationClass: 'default', + ); + final community = + Community.create( + name: 'Test', + relayUrl: 'http://127.0.0.1:${server.port}', + nsec: keys.nsec, + ).copyWith( + pushNotificationsEnabled: true, + pushLeaseInstallationId: 'd' * 32, + pushSubscriptionState: BuzzPushLeaseSubscriptionState.desired( + desired: [subscription], + ).withAccepted(subscriptions: [subscription], generation: 7), + ); + // The real deactivator, unlike the injected one createContainer uses. + container = ProviderContainer( + overrides: [ + communityStorageProvider.overrideWithValue(communityStorage), + communitySnapshotWriterProvider.overrideWithValue( + (communities) async {}, + ), + communityPushLeaseRevocationEnqueuerProvider.overrideWithValue( + (community) async => true, + ), + communityPushLeaseRevocationTriggerProvider.overrideWithValue( + () async {}, + ), + ], + ); + await container.read(communityListProvider.future); + final notifier = container.read(communityListProvider.notifier); + await notifier.addCommunity(community); + + await notifier.setPushNotificationsEnabled(community.id, false); + await notifier.retryPendingPushLeaseTombstone(community.id); + + final stored = (await communityStorage.loadAll()).single; + expect(stored.pushSubscriptionState.pendingTombstoneGeneration, isNull); + final tombstone = tombstones.single; + expect( + (tombstone['tags'] as List).any( + (tag) => (tag as List).contains('d' * 32), + ), + isTrue, + ); + }, + ); + test('removeCommunity removes from list', () async { container = createContainer(); await container.read(communityListProvider.future); @@ -1239,6 +1358,49 @@ class _FailingLoadStorage extends CommunityStorage { } } +class _MemoryStore implements AndroidPushStateStore { + String? value; + + @override + Future read() async => value; + + @override + Future write(String? next) async => value = next; +} + +Map _descriptorJson(String origin) => { + 'supported_extensions': ['nip-er', 'buzz-push-v1'], + 'push': { + 'origin': origin, + 'keys': [ + { + 'id': 'relay-v1', + 'pubkey': nostr.Keys('2' * 64).public, + 'current': true, + }, + ], + 'push_kinds': [9, 40002, 45001, 45003], + 'h_grammar': 'uuid-lowercase', + 'class_support': { + 'apns': ['default'], + }, + 'limitation': { + 'max_lease_ttl': 2592000, + 'max_leases_per_pubkey': 16, + 'max_subscriptions_per_lease': 16, + 'max_kinds': 16, + 'max_authors': 20, + 'max_h': 50, + 'max_tag_values': 20, + 'max_ignore': 8, + 'max_content_len': 65536, + 'max_plaintext_len': 32768, + 'max_endpoint_len': 4096, + 'max_string_len': 512, + }, + }, +}; + class _ObservedSaveStorage extends CommunityStorage { _ObservedSaveStorage(FlutterSecureStorage secure) : super(secure: secure); diff --git a/mobile/test/shared/push/android_push_authority_test.dart b/mobile/test/shared/push/android_push_authority_test.dart new file mode 100644 index 0000000000..dac1ab5d0f --- /dev/null +++ b/mobile/test/shared/push/android_push_authority_test.dart @@ -0,0 +1,565 @@ +import 'dart:async'; +import 'dart:convert'; + +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:flutter_test/flutter_test.dart'; + +import '../../helpers/android_push_fakes.dart'; +import '../community/community_storage_test.dart' show FakeSecureStorage; + +class _MemoryStore implements AndroidPushStateStore { + String? value; + + @override + Future read() async => value; + + @override + Future write(String? next) async => value = next; +} + +const _relayA = 'wss://relay-a.example'; +const _relayB = 'wss://relay-b.example'; +final _keyA = 'a' * 64; +final _keyB = 'b' * 64; +final _keyC = 'c' * 64; + +void main() { + late int now; + late FakePushGateway gateway; + late FakeAndroidKeystore keystore; + late _MemoryStore store; + late List sleeps; + late AndroidPushAuthority authority; + + setUp(() { + now = 1_750_000_000; + gateway = FakePushGateway(nowSeconds: () => now); + keystore = FakeAndroidKeystore(); + store = _MemoryStore(); + sleeps = []; + authority = AndroidPushAuthority( + keystore: keystore, + gateway: fakeGatewayClient(gateway), + store: store, + now: () => DateTime.fromMillisecondsSinceEpoch(now * 1000), + sleep: (delay) async => sleeps.add(delay), + ); + }); + + Future enroll({ + String relay = _relayA, + String? pubkey, + String token = 'token-1', + }) async => (await authority.enroll( + relayOrigin: relay, + relayPubkey: pubkey ?? (relay == _relayA ? _keyA : _keyB), + endpoint: token, + stillWanted: () => true, + desiredRelays: () => {_relayA, _relayB}, + ))!; + + test('first enrollment, a second relay, reuse and renewal', () async { + final first = await enroll(); + + // The first enrollment waits a bounded random time, then enrolls with an + // attestation over the transcript's digest and delegates once. + expect(sleeps.single, lessThan(androidPushFirstEnrollmentJitterMax)); + expect(gateway.installations.values.single.token, 'token-1'); + expect( + gateway.bodiesFor('/v1/installations').single, + isNot(contains('key_id')), + ); + expect(first.generation, 1); + expect(first.endpointEpoch, 1); + expect(first.relayOrigin, _relayA); + expect(first.installationId, matches(RegExp(r'^[0-9a-f]{32}$'))); + expect(first.expiresAt, greaterThan(now + 86400)); + expect(first.endpointHash, hasLength(64)); + + // The same relay again reuses the grant without calling the gateway; a + // second relay delegates from the same installation. + final calls = gateway.requests.length; + expect((await enroll()).endpointGrant, first.endpointGrant); + expect(gateway.requests.length, calls); + final second = await enroll(relay: _relayB); + expect(gateway.installations, hasLength(1)); + expect(second.generation, 1); + expect(sleeps, hasLength(1)); + expect((await authority.grants()).map((g) => g.relayOrigin), { + _relayA, + _relayB, + }); + + // In the grant's final minutes the next call delegates again at a higher + // generation. + now = first.expiresAt - 200; + final renewed = await enroll(); + expect(renewed.generation, 2); + expect(renewed.endpointGrant, isNot(first.endpointGrant)); + + // A renewal the gateway accepted, with its response lost, extended the + // installation, so the phone keeps signing for it past the last expiry + // it saw confirmed rather than enrolling again over the same token. + now = renewed.expiresAt - 200; + gateway.loseResponseFor.add('/v1/delegations'); + await expectLater(enroll(), throwsA(isA())); + now = renewed.expiresAt + 60; + final resumed = await enroll(); + expect(resumed.generation, 4); + expect(gateway.installations, hasLength(1)); + expect(keystore.generated, 1); + }); + + test('reading grants does not wait behind a queued enrollment', () async { + final release = Completer(); + authority = AndroidPushAuthority( + keystore: keystore, + gateway: fakeGatewayClient(gateway), + store: store, + now: () => DateTime.fromMillisecondsSinceEpoch(now * 1000), + sleep: (_) => release.future, + ); + final enrolling = enroll(); + await pumpEventQueue(); + + expect(await authority.grants(), isEmpty); + + release.complete(); + await enrolling; + expect(await authority.grants(), hasLength(1)); + }); + + test('a lost enrollment response is resumed with the same request', () async { + gateway.loseResponseFor.add('/v1/installations'); + await expectLater(enroll(), throwsA(isA())); + expect(store.value, contains('pendingEnrollment')); + + final grant = await enroll(); + + final bodies = gateway.bodiesFor('/v1/installations'); + expect(bodies, hasLength(2)); + expect(jsonEncode(bodies[1]), jsonEncode(bodies[0])); + expect(keystore.generated, 1); + expect(gateway.installations, hasLength(1)); + expect(grant.generation, 1); + }); + + 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, + ), + ), + ); + expect(store.value, contains('pendingEnrollment')); + expect(keystore.key, isNotNull); + gateway.failWith.remove('/v1/installations'); + + gateway.refuseAttestation = true; + await expectLater( + enroll(), + throwsA(isA()), + ); + expect(keystore.key, isNull); + expect(store.value, isNot(contains('pendingEnrollment'))); + expect(gateway.installations, isEmpty); + + gateway.refuseAttestation = false; + await enroll(); + expect(gateway.installations, hasLength(1)); + }, + ); + + test( + 'a phone that cannot attest never contacts the enrollment route', + () async { + keystore.attests = false; + await expectLater( + enroll(), + throwsA(isA()), + ); + expect(gateway.bodiesFor('/v1/installations'), isEmpty); + expect(await authority.grants(), isEmpty); + }, + ); + + test('a new FCM token rotates the endpoint and re-delegates', () async { + final first = await enroll(); + await enroll(relay: _relayB); + + final rotated = await enroll(token: 'token-2'); + + final installation = gateway.installations.values.single; + expect(installation.token, 'token-2'); + expect(installation.epoch, 2); + expect(rotated.endpointEpoch, 2); + expect(rotated.generation, 2); + expect(rotated.endpointHash, isNot(first.endpointHash)); + // The other relay's grant was void at the old epoch, so it is replaced on + // its next enrollment rather than reused. + final other = await enroll(relay: _relayB, token: 'token-2'); + expect(other.endpointEpoch, 2); + expect(other.generation, 2); + expect(gateway.bodiesFor('/v1/installations'), hasLength(1)); + }); + + test('a lost rotation response is accounted for on the retry', () async { + await enroll(); + gateway.loseResponseFor.add('/v1/installations/endpoint'); + await expectLater(enroll(token: 'token-2'), throwsA(isA())); + expect(gateway.installations.values.single.token, 'token-2'); + + // The retry's rotation is refused (the gateway is already at the next + // epoch), the delegation at that epoch succeeds, and nothing re-enrolls. + final grant = await enroll(token: 'token-2'); + + expect(grant.endpointEpoch, 2); + expect(gateway.bodiesFor('/v1/installations'), hasLength(1)); + expect(gateway.installations.values.single.token, 'token-2'); + }); + + test( + 'a token that changed again before a lost rotation was settled', + () async { + await enroll(); + gateway.loseResponseFor.add('/v1/installations/endpoint'); + await expectLater(enroll(token: 'token-2'), throwsA(isA())); + + final grant = await enroll(token: 'token-3'); + + final installation = gateway.installations.values.single; + expect(installation.token, 'token-3'); + expect(installation.epoch, 3); + expect(grant.endpointEpoch, 3); + }, + ); + + test( + 'an installation the gateway dropped is replaced by a new one', + () async { + final first = await enroll(); + gateway.installations.values.single.revoked = true; + // The phone only finds out when it next needs the gateway. + now = first.expiresAt - 200; + + final grant = await enroll(); + + expect(gateway.installations, hasLength(2)); + expect(keystore.generated, 2); + expect(grant.generation, 1); + expect(grant.endpointGrant, isNot(first.endpointGrant)); + expect(grant.installationId, first.installationId); + }, + ); + + test('a lost Keystore key is replaced, not signed around', () async { + await enroll(); + keystore.key = null; + // The gateway still holds the old installation for this token, so the + // new one is refused loudly instead of the old authority being reused. + await expectLater( + enroll(), + throwsA( + isA().having( + (e) => e.status, + 'status', + 409, + ), + ), + ); + }); + + test( + 'sign-out revokes delegations, then the installation, and frees the token', + () async { + final a = await enroll(); + await enroll(relay: _relayB); + + // One community stays: only the other relay's delegation goes. + await authority.reconcile( + desiredRelays: () => {_relayA}, + revokeInstallation: () => false, + ); + final installation = gateway.installations.values.single; + expect(installation.revokedDelegations, {'$_keyB/1'}); + expect(installation.revoked, isFalse); + + // The community comes back, and its first delegation's response is + // lost: the retry delegates again instead of reusing the revoked grant. + gateway.loseResponseFor.add('/v1/delegations'); + await expectLater(enroll(relay: _relayB), throwsA(isA())); + final b = await enroll(relay: _relayB); + expect(b.generation, 3); + expect(installation.delegations[_keyB], 3); + + // The last community goes: the installation is revoked, the key deleted. + gateway.loseResponseFor.add('/v1/installations/revoke'); + await expectLater( + authority.reconcile( + desiredRelays: () => {}, + revokeInstallation: () => true, + ), + throwsA(isA()), + ); + await authority.reconcile( + desiredRelays: () => {}, + revokeInstallation: () => true, + ); + expect(installation.revoked, isTrue); + expect(keystore.key, isNull); + + // Lease tombstones still read the relay's installation id afterwards, and + // a later sign-in enrolls the same token again. + expect( + (await authority.grants()).map((g) => g.installationId), + contains(a.installationId), + ); + final again = await enroll(); + expect(gateway.installations, hasLength(2)); + expect(again.generation, 1); + }, + ); + + test('sign-out settles a rotation whose response was lost', () async { + await enroll(); + gateway.loseResponseFor.add('/v1/installations/endpoint'); + await expectLater(enroll(token: 'token-2'), throwsA(isA())); + final installation = gateway.installations.values.single; + expect(installation.epoch, 2); + + // The stored epoch is stale. The installation is still revoked, and the + // token it held is free again. + await authority.reconcile( + desiredRelays: () => {}, + revokeInstallation: () => true, + ); + + expect(installation.revoked, isTrue); + expect(keystore.key, isNull); + await enroll(token: 'token-2'); + expect(gateway.installations, hasLength(2)); + }); + + test('sign-out revokes an installation whose enrollment was lost', () async { + gateway.loseResponseFor.add('/v1/installations'); + await expectLater(enroll(), throwsA(isA())); + final installation = gateway.installations.values.single; + + await authority.reconcile( + desiredRelays: () => {}, + revokeInstallation: () => true, + ); + + expect(installation.revoked, isTrue); + expect(keystore.key, isNull); + expect(gateway.bodiesFor('/v1/installations'), hasLength(2)); + await enroll(); + expect(gateway.installations, hasLength(2)); + }); + + test( + 'a revocation whose delegation response was lost still finds it', + () async { + await enroll(); + gateway.loseResponseFor.add('/v1/delegations'); + now += + 400 * 24 * 3600; // far past the grant, so enrolling delegates again + // The installation expired too, so this re-enrolls, then loses the + // delegation response after the gateway accepted generation 1. + await expectLater(enroll(), throwsA(isA())); + + await authority.reconcile( + desiredRelays: () => {}, + revokeInstallation: () => false, + ); + + expect(gateway.installations.values.last.revokedDelegations, { + '$_keyA/1', + }); + }, + ); + + // ---- delegations are keyed by executor key ---- + + test('communities on one relay share the delegation of its key', () async { + await enroll(relay: _relayA, pubkey: _keyA); + await enroll(relay: _relayB, pubkey: _keyA); + + // The gateway keys a delegation by relay key, so one call serves both. + expect(gateway.bodiesFor('/v1/delegations'), hasLength(1)); + expect(gateway.installations, hasLength(1)); + final installation = gateway.installations.values.single; + + Future reconcile(Set desired) => authority.reconcile( + desiredRelays: () => desired, + revokeInstallation: () => false, + ); + await reconcile({_relayB}); + await reconcile({_relayA}); + expect(installation.revokedDelegations, isEmpty); + + await reconcile({}); + expect(installation.revokedDelegations, {'$_keyA/1'}); + // Tombstones still read each origin's grant afterwards. + expect((await authority.grants()).map((g) => g.relayOrigin), { + _relayA, + _relayB, + }); + }); + + test('a rotated relay key is revoked, and so is its successor', () async { + await enroll(relay: _relayA, pubkey: _keyA); + await enroll(relay: _relayB, pubkey: _keyC); + final rotated = await enroll(relay: _relayA, pubkey: _keyB); + expect(rotated.relayPubkey, _keyB); + final installation = gateway.installations.values.single; + + Future reconcile(Set desired) => authority.reconcile( + desiredRelays: () => desired, + revokeInstallation: () => false, + ); + await reconcile({_relayA, _relayB}); + expect(installation.revokedDelegations, {'$_keyA/1'}); + + // The community on the other key stays, so only the first one's goes. + await reconcile({_relayB}); + expect(installation.revokedDelegations, {'$_keyA/1', '$_keyB/1'}); + }); + + test('a lost delegation response for a new key is revoked too', () async { + await enroll(relay: _relayA, pubkey: _keyA); + gateway.loseResponseFor.add('/v1/delegations'); + await expectLater( + enroll(relay: _relayA, pubkey: _keyB), + throwsA(isA()), + ); + + await authority.reconcile( + desiredRelays: () => {}, + revokeInstallation: () => false, + ); + + // The gateway accepted the key's first generation, which was never stored + // as accepted, so it is the spent one that is tried. + expect(gateway.installations.values.single.revokedDelegations, { + '$_keyA/1', + '$_keyB/1', + }); + }); + + test('state from the previous storage key is dropped', () async { + final secure = FakeSecureStorage(); + await secure.write(key: 'buzz_android_push_authority_v1', value: '{}'); + final store = SecureAndroidPushStateStore(secure: secure); + + expect(await store.read(), isNull); + + expect(await secure.read(key: 'buzz_android_push_authority_v1'), isNull); + await store.write('state'); + expect(await store.read(), 'state'); + expect(await secure.read(key: 'buzz_android_push_authority_v2'), 'state'); + }); + + // ---- opt-in fence ---- + + test( + 'an opt-out during the enrollment jitter leaves nothing behind', + () async { + final release = Completer(); + authority = AndroidPushAuthority( + keystore: keystore, + gateway: fakeGatewayClient(gateway), + store: store, + now: () => DateTime.fromMillisecondsSinceEpoch(now * 1000), + sleep: (_) => release.future, + ); + var wanted = true; + final enrolling = authority.enroll( + relayOrigin: _relayA, + relayPubkey: _keyA, + endpoint: 'token-1', + stillWanted: () => wanted, + desiredRelays: () => {_relayA}, + ); + await pumpEventQueue(); + wanted = false; + release.complete(); + + expect(await enrolling, isNull); + expect(gateway.requests, isEmpty); + expect(keystore.generated, 0); + expect(await authority.grants(), isEmpty); + }, + ); + + test('an opt-out after enrollment creates no delegation', () async { + final enrolling = authority.enroll( + relayOrigin: _relayA, + relayPubkey: _keyA, + endpoint: 'token-1', + // Wanted until the installation exists. + stillWanted: () => gateway.installations.isEmpty, + desiredRelays: () => {_relayA}, + ); + + expect(await enrolling, isNull); + expect(gateway.installations, hasLength(1)); + expect(gateway.bodiesFor('/v1/delegations'), isEmpty); + expect(await authority.grants(), isEmpty); + }); + + // ---- gateway binding ---- + + test('state from another gateway is dropped, not reused', () async { + final first = await enroll(); + final other = FakePushGateway(nowSeconds: () => now); + authority = AndroidPushAuthority( + keystore: keystore, + gateway: fakeGatewayClient(other, baseUrl: 'https://push-b.example'), + store: store, + now: () => DateTime.fromMillisecondsSinceEpoch(now * 1000), + sleep: (_) async {}, + ); + + // Nothing of the first gateway's is readable, and nothing is revoked on + // either gateway: its installation just expires there. + expect(await authority.grants(), isEmpty); + final grant = await enroll(); + + expect(keystore.deleted, 1); + expect(keystore.generated, 2); + expect(other.installations, hasLength(1)); + expect(other.bodiesFor('/v1/delegations').single['generation'], 1); + expect(grant.installationId, isNot(first.installationId)); + expect(gateway.installations.values.single.revoked, isFalse); + expect(store.value, contains('https://push-b.example')); + }); + + // ---- a refused delegation ---- + + test('a delegation refused once is retried with a fresh challenge', () async { + final first = await enroll(); + now = first.expiresAt - 200; + gateway.refuseOnce.add('/v1/delegations'); + + final renewed = await enroll(); + + // A challenge that expired while the app stalled is not a lost + // installation: the key stays and the same installation is used. + final bodies = gateway.bodiesFor('/v1/delegations'); + expect(bodies, hasLength(3)); + expect(bodies[2]['challenge_id'], isNot(bodies[1]['challenge_id'])); + expect(renewed.generation, 3); + expect(keystore.deleted, 0); + expect(gateway.installations, hasLength(1)); + }); +} diff --git a/mobile/test/shared/push/android_push_transcript_test.dart b/mobile/test/shared/push/android_push_transcript_test.dart new file mode 100644 index 0000000000..9cf0fc475d --- /dev/null +++ b/mobile/test/shared/push/android_push_transcript_test.dart @@ -0,0 +1,89 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:buzz/shared/push/android_push_transcript.dart'; +import 'package:crypto/crypto.dart' as crypto; +import 'package:flutter_test/flutter_test.dart'; + +/// The gateway's encoder and this one must agree to the byte: the gateway +/// verifies signatures and attestation challenges over its own copy. +void main() { + final file = File( + '../crates/buzz-push-gateway/tests/vectors/app_attest_transcripts.json', + ); + final fixture = jsonDecode(file.readAsStringSync()) as Map; + final inputs = fixture['inputs']! as Map; + final challengeId = inputs['challenge_id']! as String; + final challenge = inputs['challenge']! as String; + final handle = inputs['installation_handle']! as String; + final endpoint = inputs['endpoint']! as String; + final relay = inputs['relay_pubkey']! as String; + final notBefore = inputs['not_before']! as int; + final expiresAt = inputs['expires_at']! as int; + + final encoders = Function()>{ + 'enroll_android': () => androidEnrollTranscript( + challengeId: challengeId, + challenge: challenge, + endpoint: endpoint, + endpointEpoch: 1, + expiresAt: expiresAt, + ), + 'delegate': () => androidDelegateTranscript( + challengeId: challengeId, + challenge: challenge, + installationHandle: handle, + endpointEpoch: 1, + generation: 1, + relayPubkey: relay, + notBefore: notBefore, + expiresAt: expiresAt, + ), + 'rotate_endpoint': () => androidRotateEndpointTranscript( + challengeId: challengeId, + challenge: challenge, + installationHandle: handle, + endpointEpoch: 1, + newEndpointEpoch: 2, + endpoint: endpoint, + ), + 'revoke_delegation': () => androidRevokeDelegationTranscript( + challengeId: challengeId, + challenge: challenge, + installationHandle: handle, + relayPubkey: relay, + generation: 2, + ), + 'revoke_installation': () => androidRevokeInstallationTranscript( + challengeId: challengeId, + challenge: challenge, + installationHandle: handle, + endpointEpoch: 1, + newEndpointEpoch: 2, + ), + }; + + for (final MapEntry(:key, :value) in encoders.entries) { + test('$key transcript matches the gateway vector', () { + final vector = (fixture['vectors']! as List) + .cast>() + .singleWhere((vector) => vector['name'] == key); + final bytes = value(); + expect(utf8.decode(bytes), vector['transcript']); + expect(crypto.sha256.convert(bytes).toString(), vector['sha256']); + }); + } + + test('a field that is not printable ASCII fails instead of escaping', () { + expect( + () => androidEnrollTranscript( + challengeId: challengeId, + challenge: challenge, + endpoint: 'tokené', + endpointEpoch: 1, + expiresAt: expiresAt, + ), + throwsFormatException, + ); + }); +} diff --git a/mobile/test/shared/push/push_bridge_android_test.dart b/mobile/test/shared/push/push_bridge_android_test.dart new file mode 100644 index 0000000000..3f8ea594b4 --- /dev/null +++ b/mobile/test/shared/push/push_bridge_android_test.dart @@ -0,0 +1,216 @@ +import 'package:buzz/shared/push/android_push_authority.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 '../../helpers/android_push_fakes.dart'; + +const _channel = MethodChannel('buzz/push_registration'); + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + setUp(() { + fcmDeviceToken.value = null; + fcmRegistrationError.value = null; + pushUnavailableReason.value = null; + pushEndpointGrants.value = const []; + pushEndpointGrantError.value = null; + installBuzzPushMethodHandler(); + }); + + tearDown(() { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(_channel, null); + debugDefaultTargetPlatformOverride = null; + debugAndroidPushAuthority = null; + }); + + Future native(String method, Map arguments) => + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .handlePlatformMessage( + _channel.name, + _channel.codec.encodeMethodCall(MethodCall(method, arguments)), + (_) {}, + ); + + test('asks the native side to register and to refresh the token', () async { + debugDefaultTargetPlatformOverride = TargetPlatform.android; + final methods = []; + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(_channel, (call) async { + methods.add(call.method); + return null; + }); + + await startBuzzPushRegistration(); + await refreshBuzzPushToken(); + + expect(methods, ['startRegistration', 'refreshToken']); + }); + + // Each row: the state before, native token events, then what Settings sees. + // "Unavailable" is reserved for a phone that cannot get a token at all or + // cannot attest; a token fetch failing while a token is held is transient. + const attest = 'The phone cannot attest its key.'; + for (final row + in < + ({ + String name, + String? token, + String? shown, + List<(String, String)> events, + String? reason, + }) + >[ + ( + name: 'a token clears an earlier registration failure', + token: null, + shown: null, + events: [('fail', 'no network'), ('token', 'fcm-token')], + reason: null, + ), + ( + name: 'a failure with no token shows unavailable', + token: null, + shown: null, + events: [('fail', 'no network')], + reason: 'no network', + ), + ( + name: 'a token does not clear an attestation failure', + token: null, + shown: attest, + events: [('token', 'fcm-token')], + reason: attest, + ), + ( + name: 'a failure while a token is held shows nothing', + token: 'fcm-token', + shown: null, + events: [('fail', 'SERVICE_NOT_AVAILABLE')], + reason: null, + ), + ( + name: 'a failure then a token leave an attestation failure', + token: null, + shown: attest, + events: [('fail', 'no network'), ('token', 'fcm-token')], + reason: attest, + ), + ( + name: 'two different failures then a token clear the row', + token: null, + shown: null, + events: [ + ('fail', 'no network'), + ('fail', 'SERVICE_NOT_AVAILABLE'), + ('token', 'fcm-token'), + ], + reason: null, + ), + ]) { + test(row.name, () async { + fcmDeviceToken.value = row.token; + pushUnavailableReason.value = row.shown; + + for (final (kind, value) in row.events) { + if (kind == 'fail') { + await native('fcmRegistrationFailed', {'message': value}); + expect(fcmRegistrationError.value, value); + } else { + await native('fcmTokenChanged', {'token': value}); + expect(fcmDeviceToken.value, value); + expect(fcmRegistrationError.value, isNull); + } + } + + expect(pushUnavailableReason.value, row.reason); + }); + } + + test('enrolls through the Dart authority and exposes its grants', () async { + debugDefaultTargetPlatformOverride = TargetPlatform.android; + var now = 1_750_000_000; + final gateway = FakePushGateway(nowSeconds: () => now); + debugAndroidPushAuthority = AndroidPushAuthority( + keystore: FakeAndroidKeystore(), + gateway: fakeGatewayClient(gateway), + store: _MemoryStore(), + now: () => DateTime.fromMillisecondsSinceEpoch(now * 1000), + sleep: (_) async {}, + ); + fcmDeviceToken.value = 'fcm-token'; + pushUnavailableReason.value = 'stale'; + + final grant = (await enrollBuzzPush( + 'wss://relay.example/', + 'https://gateway.example/', + relayOrigin: 'wss://relay.example', + relayPubkey: 'a' * 64, + desiredRelays: () => {'wss://relay.example'}, + ))!; + + expect(grant.relayOrigin, 'wss://relay.example'); + expect(grant.relayPubkey, 'a' * 64); + expect(pushUnavailableReason.value, isNull); + expect(pushEndpointGrants.value.single.endpointGrant, grant.endpointGrant); + expect( + (await readBuzzPushEndpointGrants()).single.installationId, + grant.installationId, + ); + }); + + test('a phone that cannot attest reports push as unavailable', () async { + debugDefaultTargetPlatformOverride = TargetPlatform.android; + var now = 1_750_000_000; + debugAndroidPushAuthority = AndroidPushAuthority( + keystore: FakeAndroidKeystore()..attests = false, + gateway: fakeGatewayClient(FakePushGateway(nowSeconds: () => now)), + store: _MemoryStore(), + now: () => DateTime.fromMillisecondsSinceEpoch(now * 1000), + sleep: (_) async {}, + ); + fcmDeviceToken.value = 'fcm-token'; + + await expectLater( + enrollBuzzPush( + 'wss://relay.example/', + 'https://gateway.example/', + relayOrigin: 'wss://relay.example', + relayPubkey: 'a' * 64, + desiredRelays: () => {'wss://relay.example'}, + ), + throwsA(isA()), + ); + + expect(pushUnavailableReason.value, isNotNull); + }); + + test('enrolling without a token fails loudly', () async { + debugDefaultTargetPlatformOverride = TargetPlatform.android; + + await expectLater( + enrollBuzzPush( + 'wss://relay.example/', + 'https://gateway.example/', + relayOrigin: 'wss://relay.example', + relayPubkey: 'a' * 64, + desiredRelays: () => {'wss://relay.example'}, + ), + throwsStateError, + ); + }); +} + +class _MemoryStore implements AndroidPushStateStore { + String? value; + + @override + Future read() async => value; + + @override + Future write(String? next) async => value = next; +} diff --git a/mobile/test/shared/push/push_bridge_test.dart b/mobile/test/shared/push/push_bridge_test.dart index efde78fdeb..550a8b7d19 100644 --- a/mobile/test/shared/push/push_bridge_test.dart +++ b/mobile/test/shared/push/push_bridge_test.dart @@ -142,8 +142,8 @@ void main() { ], ); - expect(firstGrant.endpointGrant, 'new-grant'); - expect(secondGrant.endpointGrant, 'new-grant'); + expect(firstGrant!.endpointGrant, 'new-grant'); + expect(secondGrant!.endpointGrant, 'new-grant'); expect(enrollmentArguments, [ { 'relayUrl': 'wss://relay.example/', diff --git a/mobile/test/shared/push/push_unconfigured_build_test.dart b/mobile/test/shared/push/push_unconfigured_build_test.dart index b2ca728ab8..fdd4c65cda 100644 --- a/mobile/test/shared/push/push_unconfigured_build_test.dart +++ b/mobile/test/shared/push/push_unconfigured_build_test.dart @@ -1,10 +1,14 @@ import 'package:buzz/features/settings/settings_page.dart'; +import 'package:buzz/shared/auth/auth_provider.dart'; import 'package:buzz/shared/community/community.dart'; import 'package:buzz/shared/community/community_provider.dart'; +import 'package:buzz/shared/community/community_storage.dart'; import 'package:buzz/shared/push/dev_push_lease.dart'; import 'package:buzz/shared/push/push_bootstrap.dart'; import 'package:buzz/shared/push/push_bridge.dart'; import 'package:buzz/shared/push/push_relay_capability_provider.dart'; +import 'package:buzz/shared/push/push_subscription.dart'; +import 'package:buzz/shared/relay/app_lifecycle_provider.dart'; import 'package:buzz/shared/relay/relay_provider.dart'; import 'package:buzz/shared/relay/relay_session.dart'; import 'package:buzz/shared/theme/theme.dart'; @@ -13,8 +17,14 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:hooks_riverpod/hooks_riverpod.dart'; +import 'package:package_info_plus/package_info_plus.dart'; import 'package:shared_preferences/shared_preferences.dart'; +import '../community/community_storage_test.dart'; + +const _turningOff = + 'Turning off. Notifications may continue until this finishes.'; + void main() { TestWidgetsFlutterBinding.ensureInitialized(); group('artifact without a gateway define', () { @@ -135,5 +145,119 @@ void main() { }, ); } + + testWidgets( + 'Android without a gateway shows a saved opt-in only until it is off', + (tester) async { + tester.view.physicalSize = const Size(430, 1800); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + debugDefaultTargetPlatformOverride = TargetPlatform.android; + addTearDown(() => debugDefaultTargetPlatformOverride = null); + PackageInfo.setMockInitialValues( + appName: 'Buzz', + packageName: 'buzz', + version: '1.0.0', + buildNumber: '1', + buildSignature: '', + ); + SharedPreferences.setMockInitialValues({}); + final prefs = await SharedPreferences.getInstance(); + final storage = CommunityStorage(secure: FakeSecureStorage()); + final subscriptions = [ + BuzzPushSubscription( + filter: BuzzPushFilter(kinds: const [9], pTags: ['a' * 64]), + notificationClass: 'default', + ), + ]; + final community = + Community.create( + name: 'Team', + relayUrl: 'wss://relay.example', + ).copyWith( + pushNotificationsEnabled: true, + pushSubscriptionState: BuzzPushLeaseSubscriptionState.desired( + desired: subscriptions, + ).withAccepted(subscriptions: subscriptions, generation: 7), + ); + await storage.save(community); + await storage.saveActiveId(community.id); + var relayAccepts = false; + await tester.pumpWidget( + ProviderScope( + overrides: [ + savedPrefsProvider.overrideWithValue(prefs), + authProvider.overrideWith(_Auth.new), + communityStorageProvider.overrideWithValue(storage), + communitySnapshotWriterProvider.overrideWithValue( + (communities) async {}, + ), + communityPushLeaseDeactivatorProvider.overrideWithValue(( + community, { + generation, + }) async { + if (!relayAccepts) throw StateError('relay rejected'); + }), + appLifecycleProvider.overrideWith(_Lifecycle.new), + ], + child: MaterialApp( + theme: AppTheme.light(), + home: SettingsPage( + profileHeader: const SizedBox.shrink(), + identityRecoveryPageBuilder: (_) => const SizedBox.shrink(), + ), + ), + ), + ); + await tester.pumpAndSettle(); + + // The saved opt-in stays visible so it can be turned off. + expect(find.text('Notifications'), findsOneWidget); + expect(tester.widget(find.byType(Switch)).value, isTrue); + + await tester.tap(find.byType(Switch)); + await tester.pumpAndSettle(); + + // The relay rejected the tombstone: the row stays, inert, and says so + // until a retry gets through. + expect(find.text('Notifications'), findsOneWidget); + expect(find.text(_turningOff), findsOneWidget); + final offSwitch = tester.widget(find.byType(Switch)); + expect(offSwitch.value, isFalse); + expect(offSwitch.onChanged, isNull); + + relayAccepts = true; + final container = ProviderScope.containerOf( + tester.element(find.byType(SettingsPage)), + ); + await container + .read(communityListProvider.notifier) + .retryPendingPushLeaseTombstone(community.id); + await tester.pumpAndSettle(); + + expect( + (await storage.loadAll()) + .single + .pushSubscriptionState + .pendingTombstoneGeneration, + isNull, + ); + expect(find.text(_turningOff), findsNothing); + expect(find.text('Notifications'), findsNothing); + expect(tester.takeException(), isNull); + debugDefaultTargetPlatformOverride = null; + }, + ); }); } + +class _Lifecycle extends AppLifecycleNotifier { + @override + AppLifecycleState build() => AppLifecycleState.resumed; +} + +class _Auth extends AuthNotifier { + @override + Future build() async => + const AuthState(status: AuthStatus.unauthenticated); +}