mirror of
https://github.com/block/buzz.git
synced 2026-11-25 02:31:36 +00:00
feat(mobile): enroll Android devices for push (#9811)
## Summary Ticket 7 of the [Android push plan](https://github.com/block/buzz/blob/main/PLANS/ANDROID_PUSH.md). Android phones can now enroll with the push gateway and publish a relay lease, through the same shared push layer iOS uses. The wake handling side is ticket 6, [#9804 Android push wake handling](https://github.com/block/buzz/pull/9804). - The phone gets an FCM token, then generates a sign-only P-256 Keystore key whose attestation challenge is the SHA-256 of the enrollment transcript. The chain goes to the gateway at enrollment. Every later installation call (delegate, rotate endpoint, revoke delegation, revoke installation) is signed with that key over the transcript bytes the gateway builds. - A rotated FCM token rotates the endpoint. Signing out revokes the delegation and the installation. The first enrollment waits a short random time. - Android 13+ asks for the notification permission at the same point iOS does. Declining keeps the app working. - A phone that cannot attest (no hardware attestation, unlocked bootloader, unlisted boot key) keeps working, and Settings says push is unavailable on this phone. - The relay lease keeps the fixed `transport` value iOS sends. - Firebase config is the same build-time setting [#9804 Android push wake handling](https://github.com/block/buzz/pull/9804) adds: four `BUZZ_FIREBASE_*` environment variables become the string resources Firebase reads. Nothing is committed, and builds without them still work (push reports unavailable). The Gradle hunks (permission, config block, `firebase-messaging` dependency) are copied from that PR verbatim so the two merge cleanly, including its `lifecycle-process` line, which this PR does not use. - The token and permission calls use their own `buzz/push_registration` channel, because Android's notification-open handler from that PR already owns `buzz/push` and a channel has one native handler. - The gateway gets an `enroll_android` transcript vector so Dart and Rust agree on the exact bytes. Enrollment state is journaled before each network attempt, so a lost response resumes with byte-identical requests instead of leaving an orphaned installation. ### Related issue None found. Builds on [#9560 enroll Android installations](https://github.com/block/buzz/pull/9560) and [#9562 verify Key Attestation](https://github.com/block/buzz/pull/9562). ### Validation Journey tests cover first enrollment, a second relay, reuse and renewal, lost responses, token rotation, an installation the gateway dropped, a lost Keystore key, a phone that cannot attest, and sign-out revocation, against a fake gateway that keeps the real gateway's semantics. Transcripts replay the shared vectors byte for byte. A settings journey checks the Notifications row and the unavailable row on Android, and a resume table checks the FCM token refresh: it runs while the relay reconnects, but not when push is off or the relay doesn't offer push. On a physical Pixel 9a (debug build, a local test gateway on a local Postgres, reached over `adb reverse`), the real Keystore key and hardware attestation chain enrolled and delegated, and the gateway accepted the attestation. The same session then ran: a signed delivery authorized against the delegation, endpoint rotation and re-delegation at the next epoch, rotating back, delegation revocation, installation revocation, and re-enrolling the same FCM token afterwards. The notification prompt appears when registration starts, before the token is fetched: <img src="https://github.com/user-attachments/assets/2aed92fe-20c1-4658-b990-51c3f3c96120" width="270" alt="Android notification permission prompt"> Not validated on the device: the FCM wake itself (the local gateway has no credentials to call FCM, so the delivery was authorized and then failed at the FCM hop), lease publication to a relay, and the in-app unavailable row, which only the widget tests exercise. A relay-backed run needs a signed-in test community on the phone. ### Settings while turning off Turning notifications off sends a relay tombstone. Until the relay accepts it, the row now says so, on both platforms. An Android build without a gateway also keeps a saved opt-in visible so it can still be turned off; once off, the row goes away. These are rendered from the Settings journey test. | | Before | After | |---|---|---| | Android build without a gateway, saved opt-in | <img src="https://raw.githubusercontent.com/block/buzz/47220acf78ad21639d2a3a8b79be3f0272e74db2/pr-9811--01-before-config-less.png" width="270" alt="Before: no Notifications row"> | <img src="https://raw.githubusercontent.com/block/buzz/47220acf78ad21639d2a3a8b79be3f0272e74db2/pr-9811--02-after-config-less.png" width="270" alt="After: Notifications row with the switch on"> | | After turning off, relay has not accepted yet | <img src="https://raw.githubusercontent.com/block/buzz/47220acf78ad21639d2a3a8b79be3f0272e74db2/pr-9811--03-before-turning-off.png" width="270" alt="Before: plain off switch"> | <img src="https://raw.githubusercontent.com/block/buzz/47220acf78ad21639d2a3a8b79be3f0272e74db2/pr-9811--04-after-turning-off.png" width="270" alt="After: Turning off. Notifications may continue until this finishes."> | ### Regressions - iOS enrollment is unchanged: the shared bridge only branches to the Dart authority on Android. iOS gains the pending opt-out subtitle, and its opt-out now also tombstones after a gateway change using the saved lease id. - The Android app gains the `firebase-messaging` dependency and a `POST_NOTIFICATIONS` permission. Backups exclude the push preferences file. ### Known limits - An FCM token rotation while the app is running is picked up on the next resume or launch, because the wake service owns the single messaging service. It could call into the registration plugin once both Android push PRs merge. - After an endpoint rotation, only the active community's lease is republished. Other enabled communities' grants are void until each is opened, the same way their leases lapse at grant expiry today. --------- Signed-off-by: Tom Brow <tomb@block.xyz> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@localhost>
This commit is contained in:
@@ -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 {
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
<uses-permission android:name="android.permission.RECORD_AUDIO" />
|
||||
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
|
||||
<uses-permission android:name="android.permission.CAMERA" />
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
<uses-permission
|
||||
android:name="android.permission.READ_EXTERNAL_STORAGE"
|
||||
android:maxSdkVersion="32"
|
||||
@@ -75,6 +76,11 @@
|
||||
<meta-data
|
||||
android:name="io.sentry.breadcrumbs.network-events"
|
||||
android:value="false" />
|
||||
<!-- FCM would fetch a token at startup for every install. The app asks
|
||||
for one only once the user turns notifications on. -->
|
||||
<meta-data
|
||||
android:name="firebase_messaging_auto_init_enabled"
|
||||
android:value="false" />
|
||||
<!-- Don't delete the meta-data below.
|
||||
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
|
||||
<meta-data
|
||||
|
||||
@@ -130,6 +130,8 @@ class MainActivity : FlutterFragmentActivity() {
|
||||
private var mediaUploadChannel: MethodChannel? = null
|
||||
private var ageSignalChannel: MethodChannel? = null
|
||||
private val ageSignalRequest = AgeSignalRequest()
|
||||
private var pushRegistrationPlugin: PushRegistrationPlugin? = null
|
||||
private var pushKeystorePlugin: PushKeystorePlugin? = null
|
||||
private var deviceTranscriptionPlugin: DeviceTranscriptionPlugin? = null
|
||||
private var huddleMediaPlugin: HuddleMediaPlugin? = null
|
||||
private var hapticsPlugin: HapticsPlugin? = null
|
||||
@@ -140,6 +142,8 @@ class MainActivity : FlutterFragmentActivity() {
|
||||
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
|
||||
super.configureFlutterEngine(flutterEngine)
|
||||
deviceTranscriptionPlugin = DeviceTranscriptionPlugin(flutterEngine.dartExecutor.binaryMessenger)
|
||||
pushRegistrationPlugin = PushRegistrationPlugin(this, flutterEngine.dartExecutor.binaryMessenger)
|
||||
pushKeystorePlugin = PushKeystorePlugin(flutterEngine.dartExecutor.binaryMessenger)
|
||||
flutterEngine.platformViewsController.registry.registerViewFactory(
|
||||
"buzz/transparent-avatar",
|
||||
TransparentAvatarViewFactory(flutterEngine.dartExecutor.binaryMessenger),
|
||||
@@ -248,6 +252,10 @@ class MainActivity : FlutterFragmentActivity() {
|
||||
hostedHpkePlugin = null
|
||||
hapticsPlugin?.dispose()
|
||||
hapticsPlugin = null
|
||||
pushRegistrationPlugin?.dispose()
|
||||
pushRegistrationPlugin = null
|
||||
pushKeystorePlugin?.dispose()
|
||||
pushKeystorePlugin = null
|
||||
ageSignalRequest.retire()
|
||||
huddleMediaPlugin?.dispose()
|
||||
huddleMediaPlugin = null
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
package xyz.block.buzz.mobile
|
||||
|
||||
import android.security.keystore.KeyGenParameterSpec
|
||||
import android.security.keystore.KeyProperties
|
||||
import io.flutter.plugin.common.BinaryMessenger
|
||||
import io.flutter.plugin.common.MethodCall
|
||||
import io.flutter.plugin.common.MethodChannel
|
||||
import java.security.InvalidAlgorithmParameterException
|
||||
import java.security.KeyPairGenerator
|
||||
import java.security.KeyStore
|
||||
import java.security.PrivateKey
|
||||
import java.security.ProviderException
|
||||
import java.security.Signature
|
||||
import java.security.interfaces.ECPublicKey
|
||||
import java.security.spec.ECGenParameterSpec
|
||||
|
||||
/**
|
||||
* The push installation's Keystore key: a P-256 key that can only sign, with a
|
||||
* key attestation chain whose challenge Dart supplies. The private key never
|
||||
* leaves the Keystore. Dart owns every decision; this only generates, signs
|
||||
* and reports.
|
||||
*/
|
||||
internal class PushKeystorePlugin(messenger: BinaryMessenger) : MethodChannel.MethodCallHandler {
|
||||
private val channel = MethodChannel(
|
||||
messenger, "buzz/push_keystore", io.flutter.plugin.common.StandardMethodCodec.INSTANCE,
|
||||
messenger.makeBackgroundTaskQueue(),
|
||||
).apply { setMethodCallHandler(this@PushKeystorePlugin) }
|
||||
|
||||
override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
|
||||
try {
|
||||
when (call.method) {
|
||||
"current" -> 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<String, Any>? {
|
||||
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"
|
||||
}
|
||||
}
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
@@ -7,4 +7,5 @@
|
||||
<exclude domain="sharedpref" path="FlutterSecureKeyStorage.xml"/>
|
||||
<exclude domain="sharedpref" path="FlutterSecureStorageConfiguration.xml"/>
|
||||
<exclude domain="file" path="diagnostics_install_id"/>
|
||||
<exclude domain="sharedpref" path="buzz_push.xml"/>
|
||||
</full-backup-content>
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
<exclude domain="sharedpref" path="FlutterSecureKeyStorage.xml"/>
|
||||
<exclude domain="sharedpref" path="FlutterSecureStorageConfiguration.xml"/>
|
||||
<exclude domain="file" path="diagnostics_install_id"/>
|
||||
<exclude domain="sharedpref" path="buzz_push.xml"/>
|
||||
</cloud-backup>
|
||||
<device-transfer>
|
||||
<exclude domain="file" path="bestie-transcripts/"/>
|
||||
@@ -20,5 +21,6 @@
|
||||
<exclude domain="sharedpref" path="FlutterSecureKeyStorage.xml"/>
|
||||
<exclude domain="sharedpref" path="FlutterSecureStorageConfiguration.xml"/>
|
||||
<exclude domain="file" path="diagnostics_install_id"/>
|
||||
<exclude domain="sharedpref" path="buzz_push.xml"/>
|
||||
</device-transfer>
|
||||
</data-extraction-rules>
|
||||
|
||||
@@ -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"
|
||||
)
|
||||
|
||||
@@ -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';
|
||||
|
||||
@@ -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<String?>(
|
||||
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),
|
||||
|
||||
@@ -156,11 +156,13 @@ Future<void> _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',
|
||||
|
||||
1028
mobile/lib/shared/push/android_push_authority.dart
Normal file
1028
mobile/lib/shared/push/android_push_authority.dart
Normal file
File diff suppressed because it is too large
Load Diff
84
mobile/lib/shared/push/android_push_gateway.dart
Normal file
84
mobile/lib/shared/push/android_push_gateway.dart
Normal file
@@ -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<Map<String, Object?>> post(
|
||||
String route,
|
||||
Map<String, Object?> body, {
|
||||
int expectedStatus = 200,
|
||||
}) async {
|
||||
final response = await _client
|
||||
.post(
|
||||
baseUrl.resolve(route),
|
||||
headers: const {'content-type': 'application/json'},
|
||||
body: jsonEncode(body),
|
||||
)
|
||||
.timeout(timeout);
|
||||
final 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<String, Object?>? _object(List<int> bytes) {
|
||||
try {
|
||||
final value = jsonDecode(utf8.decode(bytes));
|
||||
return value is Map<String, Object?> ? value : null;
|
||||
} on FormatException {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
void close() => _client.close();
|
||||
}
|
||||
105
mobile/lib/shared/push/android_push_keystore.dart
Normal file
105
mobile/lib/shared/push/android_push_keystore.dart
Normal file
@@ -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<Uint8List> chain;
|
||||
|
||||
/// What the gateway calls this key: SHA-256 of [publicKey], base64.
|
||||
String get keyId => base64.encode(crypto.sha256.convert(publicKey).bytes);
|
||||
|
||||
List<String> 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<AndroidPushKey?> current();
|
||||
|
||||
/// Replaces any key with a new one whose attestation challenge is
|
||||
/// [attestationChallenge]. Throws [AndroidPushAttestationUnavailable] when
|
||||
/// the phone cannot attest.
|
||||
Future<AndroidPushKey> generate(Uint8List attestationChallenge);
|
||||
|
||||
/// A base64 DER ECDSA signature over [data] (SHA-256 digest).
|
||||
Future<String> sign(Uint8List data);
|
||||
|
||||
Future<void> delete();
|
||||
}
|
||||
|
||||
class MethodChannelAndroidPushKeystore implements AndroidPushKeystore {
|
||||
const MethodChannelAndroidPushKeystore();
|
||||
|
||||
@override
|
||||
Future<AndroidPushKey?> current() async =>
|
||||
_key(await _keystoreChannel.invokeMapMethod<String, Object?>('current'));
|
||||
|
||||
@override
|
||||
Future<AndroidPushKey> generate(Uint8List attestationChallenge) async {
|
||||
try {
|
||||
final key = _key(
|
||||
await _keystoreChannel.invokeMapMethod<String, Object?>('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<String> sign(Uint8List data) async {
|
||||
final signature = await _keystoreChannel.invokeMethod<Uint8List>('sign', {
|
||||
'data': data,
|
||||
});
|
||||
if (signature == null) {
|
||||
throw StateError('The Keystore returned no signature.');
|
||||
}
|
||||
return base64.encode(signature);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> delete() => _keystoreChannel.invokeMethod<void>('delete');
|
||||
|
||||
AndroidPushKey? _key(Map<String, Object?>? raw) {
|
||||
if (raw == null) return null;
|
||||
return AndroidPushKey(
|
||||
publicKey: raw['publicKey']! as Uint8List,
|
||||
chain: [
|
||||
for (final cert in raw['chain']! as List<Object?>) cert! as Uint8List,
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
145
mobile/lib/shared/push/android_push_transcript.dart
Normal file
145
mobile/lib/shared/push/android_push_transcript.dart
Normal file
@@ -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
|
||||
/// `<domain> + "\n" + <compact JSON object>` 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();
|
||||
}
|
||||
@@ -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<Community> communities,
|
||||
bool communitiesLoaded,
|
||||
RelayConfig config,
|
||||
Community? community,
|
||||
String? memberPubkey,
|
||||
@@ -228,6 +231,7 @@ final _pushInputsProvider = Provider.autoDispose<AsyncValue<_PushInputs>>((
|
||||
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<String?>(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<BuzzPushEndpointGrant> _publish(
|
||||
/// Returns null when the community stopped wanting push before the lease was
|
||||
/// published.
|
||||
static Future<BuzzPushEndpointGrant?> _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<String> _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<String> _pushRelayOrigins(List<Community> communities) {
|
||||
final origins = <String>{};
|
||||
for (final community in communities) {
|
||||
if (!community.pushNotificationsEnabled) continue;
|
||||
try {
|
||||
origins.add(canonicalBuzzPushRelayOrigin(community.relayUrl));
|
||||
} on FormatException {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
return origins;
|
||||
}
|
||||
|
||||
void _runRevocationOutbox(Future<void> Function() operation) {
|
||||
unawaited(
|
||||
operation().catchError((Object error, StackTrace stackTrace) {
|
||||
|
||||
@@ -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<String?>(null);
|
||||
final apnsRegistrationError = ValueNotifier<String?>(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<String?>(null);
|
||||
final fcmRegistrationError = ValueNotifier<String?>(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<String?>(null);
|
||||
|
||||
final pushEndpointGrants = ValueNotifier<List<BuzzPushEndpointGrant>>([]);
|
||||
final pushEndpointGrantError = ValueNotifier<String?>(null);
|
||||
|
||||
@@ -255,16 +273,77 @@ Future<void> syncPendingBuzzPushNotificationResponse() async {
|
||||
/// APNs registration and enrollment remain valid while display is denied.
|
||||
Future<void> startBuzzPushRegistration() async {
|
||||
if (!Env.pushGatewayConfigured ||
|
||||
defaultTargetPlatform != TargetPlatform.iOS) {
|
||||
(defaultTargetPlatform != TargetPlatform.iOS &&
|
||||
defaultTargetPlatform != TargetPlatform.android)) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await _channel.invokeMethod<void>('startRegistration');
|
||||
await (defaultTargetPlatform == TargetPlatform.android
|
||||
? _registrationChannel
|
||||
: _channel)
|
||||
.invokeMethod<void>('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<void> refreshBuzzPushToken() async {
|
||||
if (!Env.pushGatewayConfigured ||
|
||||
defaultTargetPlatform != TargetPlatform.android) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await _registrationChannel.invokeMethod<void>('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<void> reconcileBuzzPushAuthority({
|
||||
required Set<String> 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<List<BuzzPushEndpointGrant>> readBuzzPushEndpointGrants() async {
|
||||
if (!Env.pushGatewayConfigured ||
|
||||
defaultTargetPlatform != TargetPlatform.iOS) {
|
||||
(defaultTargetPlatform != TargetPlatform.iOS &&
|
||||
defaultTargetPlatform != TargetPlatform.android)) {
|
||||
return const [];
|
||||
}
|
||||
try {
|
||||
final raw = await _channel.invokeListMethod<dynamic>('endpointGrants', {
|
||||
'gatewayUrl': Env.pushGatewayUrl,
|
||||
});
|
||||
final grants = [
|
||||
for (final value in raw ?? const [])
|
||||
BuzzPushEndpointGrant.fromMap(value as Map<dynamic, dynamic>),
|
||||
];
|
||||
final List<BuzzPushEndpointGrant> grants;
|
||||
if (defaultTargetPlatform == TargetPlatform.android) {
|
||||
grants = [
|
||||
for (final grant in await _androidPushAuthority.grants())
|
||||
_grantOf(grant),
|
||||
];
|
||||
} else {
|
||||
final raw = await _channel.invokeListMethod<dynamic>('endpointGrants', {
|
||||
'gatewayUrl': Env.pushGatewayUrl,
|
||||
});
|
||||
grants = [
|
||||
for (final value in raw ?? const [])
|
||||
BuzzPushEndpointGrant.fromMap(value as Map<dynamic, dynamic>),
|
||||
];
|
||||
}
|
||||
pushEndpointGrants.value = grants;
|
||||
pushEndpointGrantError.value = null;
|
||||
return grants;
|
||||
@@ -323,39 +411,83 @@ Future<List<BuzzPushEndpointGrant>> 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<BuzzPushEndpointGrant> 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<BuzzPushEndpointGrant?> enrollBuzzPush(
|
||||
String relayUrl,
|
||||
String gatewayUrl, {
|
||||
List<Community>? communitiesForSnapshotRefresh,
|
||||
String? relayOrigin,
|
||||
String? relayPubkey,
|
||||
Set<String> Function()? desiredRelays,
|
||||
bool Function() stillWanted = _wanted,
|
||||
DiagnosticReporter diagnostics = const NoopDiagnosticReporter(),
|
||||
}) async {
|
||||
final Map<dynamic, dynamic>? raw;
|
||||
try {
|
||||
raw = await _channel.invokeMapMethod<dynamic, dynamic>('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<dynamic, dynamic>? raw;
|
||||
try {
|
||||
raw = await _channel.invokeMapMethod<dynamic, dynamic>('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<void> 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':
|
||||
|
||||
475
mobile/test/features/settings/android_notifications_test.dart
Normal file
475
mobile/test/features/settings/android_notifications_test.dart
Normal file
@@ -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<Switch>(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<List<String>> pumpBootstrap(
|
||||
WidgetTester tester, {
|
||||
required TargetPlatform platform,
|
||||
required String relayUrl,
|
||||
required bool enabled,
|
||||
_Connected? session,
|
||||
bool advertisesPush = true,
|
||||
FakePushGateway? gateway,
|
||||
Future<void>? descriptorGate,
|
||||
List<BuzzPushSubscription>? 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 = <String>[];
|
||||
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<void> 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<void>();
|
||||
await pumpBootstrap(
|
||||
tester,
|
||||
platform: TargetPlatform.android,
|
||||
relayUrl: 'https://relay.example',
|
||||
enabled: true,
|
||||
session: session,
|
||||
gateway: gateway,
|
||||
descriptorGate: descriptorGate.future,
|
||||
subscriptions: [
|
||||
BuzzPushSubscription(
|
||||
filter: BuzzPushFilter(kinds: const [9], pTags: ['a' * 64]),
|
||||
notificationClass: 'default',
|
||||
),
|
||||
],
|
||||
);
|
||||
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<String?> read() async => value;
|
||||
|
||||
@override
|
||||
Future<void> write(String? next) async => value = next;
|
||||
}
|
||||
|
||||
class _Lifecycle extends AppLifecycleNotifier {
|
||||
@override
|
||||
AppLifecycleState build() => AppLifecycleState.resumed;
|
||||
}
|
||||
|
||||
class _Auth extends AuthNotifier {
|
||||
@override
|
||||
Future<AuthState> build() async =>
|
||||
const AuthState(status: AuthStatus.unauthenticated);
|
||||
}
|
||||
|
||||
class _Connected extends RelaySessionNotifier {
|
||||
final leases = <Map<String, dynamic>>[];
|
||||
String executorSecret = '2' * 64;
|
||||
|
||||
@override
|
||||
Future<NostrEvent> publish(
|
||||
NostrEvent event, {
|
||||
Duration timeout = const Duration(seconds: 8),
|
||||
Future<bool> Function()? mayPublish,
|
||||
}) async {
|
||||
expect(event.kind, buzzPushLeaseKind);
|
||||
final plaintext = nip44Decrypt(
|
||||
getConversationKey(executorSecret, event.pubkey),
|
||||
event.content,
|
||||
);
|
||||
leases.add(jsonDecode(plaintext) as Map<String, dynamic>);
|
||||
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,
|
||||
);
|
||||
291
mobile/test/helpers/android_push_fakes.dart
Normal file
291
mobile/test/helpers/android_push_fakes.dart
Normal file
@@ -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<AndroidPushKey?> current() async => key;
|
||||
|
||||
@override
|
||||
Future<AndroidPushKey> generate(Uint8List attestationChallenge) async {
|
||||
if (!attests) {
|
||||
throw const AndroidPushAttestationUnavailable('no attestation chain');
|
||||
}
|
||||
generated++;
|
||||
final public = Uint8List.fromList([
|
||||
4,
|
||||
...crypto.sha256.convert(utf8.encode('key-$generated')).bytes,
|
||||
...crypto.sha256.convert(utf8.encode('key-y-$generated')).bytes,
|
||||
]);
|
||||
return key = AndroidPushKey(
|
||||
publicKey: public,
|
||||
chain: [public, attestationChallenge],
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<String> sign(Uint8List data) async {
|
||||
final current = key;
|
||||
if (current == null) throw StateError('no key');
|
||||
return signatureFor(current.publicKey, data);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> delete() async {
|
||||
deleted++;
|
||||
key = null;
|
||||
}
|
||||
}
|
||||
|
||||
String signatureFor(Uint8List publicKey, List<int> transcript) =>
|
||||
base64.encode(crypto.sha256.convert([...publicKey, ...transcript]).bytes);
|
||||
|
||||
class _Installation {
|
||||
_Installation(this.handle, this.publicKey, this.token, this.expiresAt);
|
||||
|
||||
final String handle;
|
||||
final Uint8List publicKey;
|
||||
String token;
|
||||
int expiresAt;
|
||||
int epoch = 1;
|
||||
bool revoked = false;
|
||||
final delegations = <String, int>{};
|
||||
final revokedDelegations = <String>{};
|
||||
}
|
||||
|
||||
/// The gateway's installation semantics, behind an HTTP client: one active
|
||||
/// installation per token and per key, enrollment replay, single-use
|
||||
/// challenges, strictly increasing delegation generations at the installation's
|
||||
/// epoch, rotation by exactly one epoch, idempotent revocation, and a
|
||||
/// not_authorized 404 for every refused signed call.
|
||||
class FakePushGateway {
|
||||
FakePushGateway({required this.nowSeconds});
|
||||
|
||||
final int Function() nowSeconds;
|
||||
final installations = <String, _Installation>{};
|
||||
final requests = <({String route, Map<String, Object?> body})>[];
|
||||
final _challenges = <String, String>{};
|
||||
var _next = 0;
|
||||
|
||||
/// Routes whose next response is lost after the gateway acted on it.
|
||||
final loseResponseFor = <String>{};
|
||||
|
||||
/// Routes that answer with this status instead of acting.
|
||||
final failWith = <String, int>{};
|
||||
|
||||
/// Routes whose next call is refused like an expired challenge: answered
|
||||
/// `not_authorized` without acting.
|
||||
final refuseOnce = <String>{};
|
||||
|
||||
/// Refuse attestations like a gateway that does not trust this phone.
|
||||
bool refuseAttestation = false;
|
||||
|
||||
List<Map<String, Object?>> bodiesFor(String route) => [
|
||||
for (final request in requests)
|
||||
if (request.route == route) request.body,
|
||||
];
|
||||
|
||||
late final http.Client client = MockClient((request) async {
|
||||
final route = request.url.path;
|
||||
final body = jsonDecode(request.body) as Map<String, Object?>;
|
||||
requests.add((route: route, body: body));
|
||||
final status = failWith[route];
|
||||
if (status != null) return _json(status, {'error': 'unavailable'});
|
||||
if (refuseOnce.remove(route)) return _notAuthorized();
|
||||
final response = _handle(route, body);
|
||||
if (loseResponseFor.remove(route)) {
|
||||
throw http.ClientException('connection lost');
|
||||
}
|
||||
return response;
|
||||
});
|
||||
|
||||
http.Response _json(int status, Map<String, Object?> body) =>
|
||||
http.Response(jsonEncode(body), status);
|
||||
|
||||
http.Response _notAuthorized() => _json(404, {'error': 'not_authorized'});
|
||||
|
||||
http.Response _handle(String route, Map<String, Object?> body) {
|
||||
if (route == '/v1/installations/challenges') {
|
||||
final id = 'challenge-${_next++}';
|
||||
final text = 'text-$id';
|
||||
_challenges[id] = text;
|
||||
return _json(200, {
|
||||
'challenge_id': id,
|
||||
'challenge': text,
|
||||
'expires_at': nowSeconds() + 300,
|
||||
});
|
||||
}
|
||||
if (route == '/v1/installations') return _enroll(body);
|
||||
final installation = installations[body['installation_handle']];
|
||||
final live =
|
||||
installation != null &&
|
||||
installation.expiresAt >= nowSeconds() &&
|
||||
(!installation.revoked || route == '/v1/installations/revoke');
|
||||
if (!live || !_signatureOk(route, body, installation)) {
|
||||
return _notAuthorized();
|
||||
}
|
||||
switch (route) {
|
||||
case '/v1/delegations':
|
||||
final relay = body['relay_pubkey']! as String;
|
||||
final generation = body['generation']! as int;
|
||||
if (body['endpoint_epoch'] != installation.epoch ||
|
||||
generation <= (installation.delegations[relay] ?? 0)) {
|
||||
return _notAuthorized();
|
||||
}
|
||||
installation.delegations[relay] = generation;
|
||||
installation.revokedDelegations.remove('$relay/$generation');
|
||||
installation.expiresAt = max(
|
||||
installation.expiresAt,
|
||||
body['expires_at']! as int,
|
||||
);
|
||||
return _json(201, {
|
||||
'endpoint_grant':
|
||||
'grant:${installation.handle}:$relay:$generation:${installation.epoch}',
|
||||
});
|
||||
case '/v1/installations/endpoint':
|
||||
if (body['endpoint_epoch'] != installation.epoch ||
|
||||
body['new_endpoint_epoch'] != installation.epoch + 1) {
|
||||
return _notAuthorized();
|
||||
}
|
||||
installation.token = body['endpoint']! as String;
|
||||
installation.epoch++;
|
||||
return _json(200, {'status': 'rotated'});
|
||||
case '/v1/delegations/revoke':
|
||||
final relay = body['relay_pubkey']! as String;
|
||||
final generation = body['generation']! as int;
|
||||
if (installation.delegations[relay] != generation) {
|
||||
return _notAuthorized();
|
||||
}
|
||||
installation.revokedDelegations.add('$relay/$generation');
|
||||
return _json(200, {'status': 'revoked'});
|
||||
default:
|
||||
if (body['endpoint_epoch'] == installation.epoch &&
|
||||
body['new_endpoint_epoch'] == installation.epoch + 1) {
|
||||
installation.revoked = true;
|
||||
installation.epoch++;
|
||||
} else if (!(installation.revoked &&
|
||||
body['new_endpoint_epoch'] == installation.epoch)) {
|
||||
return _notAuthorized();
|
||||
}
|
||||
return _json(200, {'status': 'revoked'});
|
||||
}
|
||||
}
|
||||
|
||||
http.Response _enroll(Map<String, Object?> body) {
|
||||
final chain = (body['android_attestation']! as List).cast<String>();
|
||||
final transcript = androidEnrollTranscript(
|
||||
challengeId: body['challenge_id']! as String,
|
||||
challenge: body['challenge']! as String,
|
||||
endpoint: body['endpoint']! as String,
|
||||
endpointEpoch: body['endpoint_epoch']! as int,
|
||||
expiresAt: body['expires_at']! as int,
|
||||
);
|
||||
final attested = base64.decode(chain[1]);
|
||||
if (refuseAttestation ||
|
||||
!_same(attested, crypto.sha256.convert(transcript).bytes)) {
|
||||
return _json(401, {'error': 'invalid_attestation'});
|
||||
}
|
||||
final publicKey = Uint8List.fromList(base64.decode(chain[0]));
|
||||
final token = body['endpoint']! as String;
|
||||
for (final other in installations.values) {
|
||||
if (other.revoked || other.expiresAt < nowSeconds()) continue;
|
||||
if (_same(other.publicKey, publicKey) && other.token == token) {
|
||||
return _json(201, {
|
||||
'installation_handle': other.handle,
|
||||
'endpoint_epoch': other.epoch,
|
||||
'expires_at': other.expiresAt,
|
||||
});
|
||||
}
|
||||
if (_same(other.publicKey, publicKey) || other.token == token) {
|
||||
return _json(409, {'error': 'conflict'});
|
||||
}
|
||||
}
|
||||
final handle = 'installation-${installations.length + 1}';
|
||||
installations[handle] = _Installation(
|
||||
handle,
|
||||
publicKey,
|
||||
token,
|
||||
body['expires_at']! as int,
|
||||
);
|
||||
return _json(201, {
|
||||
'installation_handle': handle,
|
||||
'endpoint_epoch': 1,
|
||||
'expires_at': body['expires_at'],
|
||||
});
|
||||
}
|
||||
|
||||
bool _signatureOk(
|
||||
String route,
|
||||
Map<String, Object?> b,
|
||||
_Installation installation,
|
||||
) {
|
||||
final common = (b['challenge_id']! as String, b['challenge']! as String);
|
||||
final handle = installation.handle;
|
||||
final transcript = switch (route) {
|
||||
'/v1/delegations' => androidDelegateTranscript(
|
||||
challengeId: common.$1,
|
||||
challenge: common.$2,
|
||||
installationHandle: handle,
|
||||
endpointEpoch: b['endpoint_epoch']! as int,
|
||||
generation: b['generation']! as int,
|
||||
relayPubkey: b['relay_pubkey']! as String,
|
||||
notBefore: b['not_before']! as int,
|
||||
expiresAt: b['expires_at']! as int,
|
||||
),
|
||||
'/v1/installations/endpoint' => androidRotateEndpointTranscript(
|
||||
challengeId: common.$1,
|
||||
challenge: common.$2,
|
||||
installationHandle: handle,
|
||||
endpointEpoch: b['endpoint_epoch']! as int,
|
||||
newEndpointEpoch: b['new_endpoint_epoch']! as int,
|
||||
endpoint: b['endpoint']! as String,
|
||||
),
|
||||
'/v1/delegations/revoke' => androidRevokeDelegationTranscript(
|
||||
challengeId: common.$1,
|
||||
challenge: common.$2,
|
||||
installationHandle: handle,
|
||||
relayPubkey: b['relay_pubkey']! as String,
|
||||
generation: b['generation']! as int,
|
||||
),
|
||||
_ => androidRevokeInstallationTranscript(
|
||||
challengeId: common.$1,
|
||||
challenge: common.$2,
|
||||
installationHandle: handle,
|
||||
endpointEpoch: b['endpoint_epoch']! as int,
|
||||
newEndpointEpoch: b['new_endpoint_epoch']! as int,
|
||||
),
|
||||
};
|
||||
// Challenges are single use, whether or not the call is accepted.
|
||||
final issued = _challenges.remove(common.$1);
|
||||
return issued == common.$2 &&
|
||||
b['assertion'] == signatureFor(installation.publicKey, transcript);
|
||||
}
|
||||
|
||||
bool _same(List<int> a, List<int> b) =>
|
||||
a.length == b.length &&
|
||||
Iterable.generate(a.length).every((i) => a[i] == b[i]);
|
||||
}
|
||||
|
||||
AndroidPushGatewayClient fakeGatewayClient(
|
||||
FakePushGateway gateway, {
|
||||
String baseUrl = 'https://push.example',
|
||||
}) => AndroidPushGatewayClient(
|
||||
baseUrl: Uri.parse(baseUrl),
|
||||
client: gateway.client,
|
||||
);
|
||||
@@ -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 = <Map<String, dynamic>>[];
|
||||
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<dynamic>;
|
||||
final event = frame[1] as Map<String, dynamic>;
|
||||
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<String?> read() async => value;
|
||||
|
||||
@override
|
||||
Future<void> write(String? next) async => value = next;
|
||||
}
|
||||
|
||||
Map<String, dynamic> _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);
|
||||
|
||||
|
||||
565
mobile/test/shared/push/android_push_authority_test.dart
Normal file
565
mobile/test/shared/push/android_push_authority_test.dart
Normal file
@@ -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<String?> read() async => value;
|
||||
|
||||
@override
|
||||
Future<void> 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<Duration> 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<AndroidPushGrant> 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<Exception>()));
|
||||
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<void>();
|
||||
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<Exception>()));
|
||||
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<AndroidPushGatewayRejection>().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<AndroidPushAttestationUnavailable>()),
|
||||
);
|
||||
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<AndroidPushAttestationUnavailable>()),
|
||||
);
|
||||
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<Exception>()));
|
||||
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<Exception>()));
|
||||
|
||||
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<AndroidPushGatewayRejection>().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<Exception>()));
|
||||
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<Exception>()),
|
||||
);
|
||||
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<Exception>()));
|
||||
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<Exception>()));
|
||||
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<Exception>()));
|
||||
|
||||
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<void> reconcile(Set<String> 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<void> reconcile(Set<String> 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<Exception>()),
|
||||
);
|
||||
|
||||
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<void>();
|
||||
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));
|
||||
});
|
||||
}
|
||||
89
mobile/test/shared/push/android_push_transcript_test.dart
Normal file
89
mobile/test/shared/push/android_push_transcript_test.dart
Normal file
@@ -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<String, Object?>;
|
||||
final inputs = fixture['inputs']! as Map<String, Object?>;
|
||||
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 = <String, List<int> 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<Map<String, Object?>>()
|
||||
.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,
|
||||
);
|
||||
});
|
||||
}
|
||||
216
mobile/test/shared/push/push_bridge_android_test.dart
Normal file
216
mobile/test/shared/push/push_bridge_android_test.dart
Normal file
@@ -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<void> native(String method, Map<String, Object?> 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 = <String>[];
|
||||
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<AndroidPushAttestationUnavailable>()),
|
||||
);
|
||||
|
||||
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<String?> read() async => value;
|
||||
|
||||
@override
|
||||
Future<void> write(String? next) async => value = next;
|
||||
}
|
||||
@@ -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/',
|
||||
|
||||
@@ -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<Switch>(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<Switch>(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<AuthState> build() async =>
|
||||
const AuthState(status: AuthStatus.unauthenticated);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user