diff --git a/.github/workflows/android_unit_tests.yaml b/.github/workflows/android_unit_tests.yaml index c2975d226af2..4d96c57a66ae 100644 --- a/.github/workflows/android_unit_tests.yaml +++ b/.github/workflows/android_unit_tests.yaml @@ -50,7 +50,7 @@ jobs: # Tasks are listed per package rather than using the root testDebugUnitTest # task, which would also build the Dart sources of the aggregate test app. # Add a task here when a package gains an android/src/test directory. - run: cd tests/android && ./gradlew :firebase_crashlytics:testDebugUnitTest :cloud_functions:testDebugUnitTest :firebase_messaging:testDebugUnitTest + run: cd tests/android && ./gradlew :firebase_core:testDebugUnitTest :firebase_crashlytics:testDebugUnitTest :cloud_functions:testDebugUnitTest :firebase_messaging:testDebugUnitTest - name: 'Upload test reports' if: failure() uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 diff --git a/packages/firebase_core/firebase_core/android/build.gradle b/packages/firebase_core/firebase_core/android/build.gradle index 126c5dd1a6dd..b5472b78db8d 100644 --- a/packages/firebase_core/firebase_core/android/build.gradle +++ b/packages/firebase_core/firebase_core/android/build.gradle @@ -45,6 +45,7 @@ android { sourceSets { main.java.srcDirs += "src/main/kotlin" + test.java.srcDirs += "src/test/kotlin" } buildFeatures { @@ -59,7 +60,19 @@ android { implementation platform("com.google.firebase:firebase-bom:${getRootProjectExtOrDefaultProperty("FirebaseSDKVersion")}") implementation "com.google.firebase:firebase-common" + // Interop interfaces of the Auth, App Check and Instance ID SDKs. Not in the + // BoM; pinned to the versions the BoM's own SDKs depend on. + implementation "com.google.firebase:firebase-auth-interop:20.0.0" + implementation "com.google.firebase:firebase-appcheck-interop:18.0.0" + implementation "com.google.firebase:firebase-iid-interop:17.1.0" + implementation 'androidx.annotation:annotation:1.7.0' + + testImplementation 'junit:junit:4.13.2' + } + + testOptions { + unitTests.returnDefaultValues = true } } diff --git a/packages/firebase_core/firebase_core/android/src/main/kotlin/io/flutter/plugins/firebase/core/FlutterFirebaseCorePlugin.kt b/packages/firebase_core/firebase_core/android/src/main/kotlin/io/flutter/plugins/firebase/core/FlutterFirebaseCorePlugin.kt index 10a44449e739..49909be3dedd 100644 --- a/packages/firebase_core/firebase_core/android/src/main/kotlin/io/flutter/plugins/firebase/core/FlutterFirebaseCorePlugin.kt +++ b/packages/firebase_core/firebase_core/android/src/main/kotlin/io/flutter/plugins/firebase/core/FlutterFirebaseCorePlugin.kt @@ -13,19 +13,22 @@ import com.google.firebase.FirebaseOptions import io.flutter.embedding.engine.plugins.FlutterPlugin import io.flutter.embedding.engine.plugins.FlutterPlugin.FlutterPluginBinding import io.flutter.plugins.firebase.core.FlutterFirebasePlugin.cachedThreadPool +import java.util.concurrent.ExecutionException /** * Flutter plugin implementation controlling the entrypoint for the Firebase SDK. * * Instantiate this in an add to app scenario to gracefully handle activity and context changes. */ -class FlutterFirebaseCorePlugin : FlutterPlugin, FirebaseCoreHostApi, FirebaseAppHostApi { +class FlutterFirebaseCorePlugin : + FlutterPlugin, FirebaseCoreHostApi, FirebaseAppHostApi, FirebaseTokenHostApi { private var applicationContext: Context? = null private var coreInitialized = false override fun onAttachedToEngine(binding: FlutterPluginBinding) { FirebaseCoreHostApi.setUp(binding.binaryMessenger, this) FirebaseAppHostApi.setUp(binding.binaryMessenger, this) + FirebaseTokenHostApi.setUp(binding.binaryMessenger, this) applicationContext = binding.applicationContext } @@ -33,6 +36,7 @@ class FlutterFirebaseCorePlugin : FlutterPlugin, FirebaseCoreHostApi, FirebaseAp applicationContext = null FirebaseCoreHostApi.setUp(binding.binaryMessenger, null) FirebaseAppHostApi.setUp(binding.binaryMessenger, null) + FirebaseTokenHostApi.setUp(binding.binaryMessenger, null) } private fun firebaseOptionsToPigeon(options: FirebaseOptions): CoreFirebaseOptions { @@ -252,4 +256,56 @@ class FlutterFirebaseCorePlugin : FlutterPlugin, FirebaseCoreHostApi, FirebaseAp listenToResponse(taskCompletionSource, callback) } + + override fun getAuthIdToken(appName: String, callback: (Result) -> Unit) { + respondWithToken("auth-token-failed", callback) { + InteropTokenProvider.forApp(appName, cachedThreadPool).getAuthIdToken() + } + } + + override fun getAppCheckToken( + appName: String, + limitedUse: Boolean, + callback: (Result) -> Unit + ) { + respondWithToken("app-check-token-failed", callback) { + InteropTokenProvider.forApp(appName, cachedThreadPool).getAppCheckToken(limitedUse) + } + } + + override fun getMessagingToken(appName: String, callback: (Result) -> Unit) { + respondWithToken("messaging-token-failed", callback) { + InteropTokenProvider.forApp(appName, cachedThreadPool).getMessagingToken() + } + } + + /** + * Runs a token lookup off the main thread and reports an SDK failure as a FlutterError under + * [failureCode]. + */ + private fun respondWithToken( + failureCode: String, + callback: (Result) -> Unit, + fetch: () -> Task + ) { + val taskCompletionSource = TaskCompletionSource() + + cachedThreadPool.execute { + try { + taskCompletionSource.setResult(Tasks.await(fetch())) + } catch (e: ExecutionException) { + // Tasks.await wraps the token task's own failure. + val cause = e.cause ?: e + taskCompletionSource.setException( + FlutterError(failureCode, cause.message ?: cause.toString(), null)) + } catch (e: IllegalStateException) { + // FirebaseApp.getInstance / FirebaseApp.get: no app with that name, or a deleted one. + taskCompletionSource.setException(FlutterError("no-app", e.message, null)) + } catch (e: Exception) { + taskCompletionSource.setException(e) + } + } + + listenToResponse(taskCompletionSource, callback) + } } diff --git a/packages/firebase_core/firebase_core/android/src/main/kotlin/io/flutter/plugins/firebase/core/GeneratedAndroidFirebaseCore.g.kt b/packages/firebase_core/firebase_core/android/src/main/kotlin/io/flutter/plugins/firebase/core/GeneratedAndroidFirebaseCore.g.kt index 5eef321656cd..178734131edb 100644 --- a/packages/firebase_core/firebase_core/android/src/main/kotlin/io/flutter/plugins/firebase/core/GeneratedAndroidFirebaseCore.g.kt +++ b/packages/firebase_core/firebase_core/android/src/main/kotlin/io/flutter/plugins/firebase/core/GeneratedAndroidFirebaseCore.g.kt @@ -364,6 +364,48 @@ data class CoreInitializeResponse( } } +/** + * The App Check SDK's answer to a token request, as the native SDKs report it: when the SDK can't + * produce a token, [token] is its placeholder and [error] the reason. + * + * Generated class from Pigeon that represents data sent in messages. + */ +data class CoreAppCheckInteropToken(val token: String, val error: String? = null) { + companion object { + fun fromList(pigeonVar_list: List): CoreAppCheckInteropToken { + val token = pigeonVar_list[0] as String + val error = pigeonVar_list[1] as String? + return CoreAppCheckInteropToken(token, error) + } + } + + fun toList(): List { + return listOf( + token, + error, + ) + } + + override fun equals(other: Any?): Boolean { + if (other == null || other.javaClass != javaClass) { + return false + } + if (this === other) { + return true + } + val other = other as CoreAppCheckInteropToken + return GeneratedAndroidFirebaseCorePigeonUtils.deepEquals(this.token, other.token) && + GeneratedAndroidFirebaseCorePigeonUtils.deepEquals(this.error, other.error) + } + + override fun hashCode(): Int { + var result = javaClass.hashCode() + result = 31 * result + GeneratedAndroidFirebaseCorePigeonUtils.deepHash(this.token) + result = 31 * result + GeneratedAndroidFirebaseCorePigeonUtils.deepHash(this.error) + return result + } +} + private open class GeneratedAndroidFirebaseCorePigeonCodec : StandardMessageCodec() { override fun readValueOfType(type: Byte, buffer: ByteBuffer): Any? { return when (type) { @@ -373,6 +415,9 @@ private open class GeneratedAndroidFirebaseCorePigeonCodec : StandardMessageCode 130.toByte() -> { return (readValue(buffer) as? List)?.let { CoreInitializeResponse.fromList(it) } } + 131.toByte() -> { + return (readValue(buffer) as? List)?.let { CoreAppCheckInteropToken.fromList(it) } + } else -> super.readValueOfType(type, buffer) } } @@ -387,6 +432,10 @@ private open class GeneratedAndroidFirebaseCorePigeonCodec : StandardMessageCode stream.write(130) writeValue(stream, value.toList()) } + is CoreAppCheckInteropToken -> { + stream.write(131) + writeValue(stream, value.toList()) + } else -> super.writeValue(stream, value) } } @@ -597,3 +646,113 @@ interface FirebaseAppHostApi { } } } +/** + * Tokens from whichever Auth, App Check and Messaging SDKs the app links, looked up through the + * Firebase component container the way the Functions SDKs do. A null result means the SDK isn't + * linked or has nothing to give; it never means failure. + * + * Generated interface from Pigeon that represents a handler of messages from Flutter. + */ +interface FirebaseTokenHostApi { + fun getAuthIdToken(appName: String, callback: (Result) -> Unit) + + fun getAppCheckToken( + appName: String, + limitedUse: Boolean, + callback: (Result) -> Unit + ) + + fun getMessagingToken(appName: String, callback: (Result) -> Unit) + + companion object { + /** The codec used by FirebaseTokenHostApi. */ + val codec: MessageCodec by lazy { GeneratedAndroidFirebaseCorePigeonCodec() } + /** + * Sets up an instance of `FirebaseTokenHostApi` to handle messages through the + * `binaryMessenger`. + */ + @JvmOverloads + fun setUp( + binaryMessenger: BinaryMessenger, + api: FirebaseTokenHostApi?, + messageChannelSuffix: String = "" + ) { + val separatedMessageChannelSuffix = + if (messageChannelSuffix.isNotEmpty()) ".$messageChannelSuffix" else "" + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.firebase_core_platform_interface.FirebaseTokenHostApi.getAuthIdToken$separatedMessageChannelSuffix", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val appNameArg = args[0] as String + api.getAuthIdToken(appNameArg) { result: Result -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(GeneratedAndroidFirebaseCorePigeonUtils.wrapError(error)) + } else { + val data = result.getOrNull() + reply.reply(GeneratedAndroidFirebaseCorePigeonUtils.wrapResult(data)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.firebase_core_platform_interface.FirebaseTokenHostApi.getAppCheckToken$separatedMessageChannelSuffix", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val appNameArg = args[0] as String + val limitedUseArg = args[1] as Boolean + api.getAppCheckToken(appNameArg, limitedUseArg) { + result: Result -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(GeneratedAndroidFirebaseCorePigeonUtils.wrapError(error)) + } else { + val data = result.getOrNull() + reply.reply(GeneratedAndroidFirebaseCorePigeonUtils.wrapResult(data)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } + run { + val channel = + BasicMessageChannel( + binaryMessenger, + "dev.flutter.pigeon.firebase_core_platform_interface.FirebaseTokenHostApi.getMessagingToken$separatedMessageChannelSuffix", + codec) + if (api != null) { + channel.setMessageHandler { message, reply -> + val args = message as List + val appNameArg = args[0] as String + api.getMessagingToken(appNameArg) { result: Result -> + val error = result.exceptionOrNull() + if (error != null) { + reply.reply(GeneratedAndroidFirebaseCorePigeonUtils.wrapError(error)) + } else { + val data = result.getOrNull() + reply.reply(GeneratedAndroidFirebaseCorePigeonUtils.wrapResult(data)) + } + } + } + } else { + channel.setMessageHandler(null) + } + } + } + } +} diff --git a/packages/firebase_core/firebase_core/android/src/main/kotlin/io/flutter/plugins/firebase/core/InteropTokenProvider.kt b/packages/firebase_core/firebase_core/android/src/main/kotlin/io/flutter/plugins/firebase/core/InteropTokenProvider.kt new file mode 100644 index 000000000000..1d84ab559b00 --- /dev/null +++ b/packages/firebase_core/firebase_core/android/src/main/kotlin/io/flutter/plugins/firebase/core/InteropTokenProvider.kt @@ -0,0 +1,86 @@ +// Copyright 2026 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. +package io.flutter.plugins.firebase.core + +import com.google.android.gms.tasks.Task +import com.google.android.gms.tasks.TaskCompletionSource +import com.google.android.gms.tasks.Tasks +import com.google.firebase.FirebaseApp +import com.google.firebase.appcheck.interop.InteropAppCheckTokenProvider +import com.google.firebase.auth.internal.InternalAuthProvider +import com.google.firebase.iid.internal.FirebaseInstanceIdInternal +import com.google.firebase.internal.api.FirebaseNoSignedInUserException +import java.util.concurrent.Executor + +/** + * Fetches the Auth, App Check and FCM tokens through the interop components the SDKs register in + * the app's component container, as the Functions SDK does. A null token means the SDK isn't linked + * or has nothing to give, never failure. + */ +class InteropTokenProvider( + private val getComponent: (Class<*>) -> Any?, + private val executor: Executor, +) { + companion object { + /** Looks tokens up in the component container of the app named [appName]. */ + fun forApp(appName: String, executor: Executor): InteropTokenProvider { + val app = FirebaseApp.getInstance(appName) + return InteropTokenProvider({ app.get(it) }, executor) + } + } + + private inline fun get(): T? = getComponent(T::class.java) as? T + + /** The signed-in user's ID token, or null when Auth isn't linked or nobody is signed in. */ + fun getAuthIdToken(): Task { + val auth = get() ?: return Tasks.forResult(null) + return auth.getAccessToken(false).continueWith(executor) { task -> + if (task.isSuccessful) { + task.result?.token + } else { + when (val exception = task.exception) { + // Signed out is an answer, not a failure. + is FirebaseNoSignedInUserException -> null + else -> throw exception ?: IllegalStateException("getAccessToken failed") + } + } + } + } + + /** + * App Check's answer, or null when it isn't linked. Before activation the SDK answers with its + * placeholder token and an error. + */ + fun getAppCheckToken(limitedUse: Boolean): Task { + val appCheck = get() ?: return Tasks.forResult(null) + val tokenTask = if (limitedUse) appCheck.limitedUseToken else appCheck.getToken(false) + return tokenTask.onSuccessTask(executor) { result -> + // A result without a token means the SDK changed shape; that's a failure, not "not linked". + val answer = result ?: throw IllegalStateException("App Check returned no token result") + Tasks.forResult( + CoreAppCheckInteropToken( + token = answer.token, + error = answer.error?.let { it.message ?: it.toString() }, + )) + } + } + + /** + * The FCM token, or null when the Instance ID library, the only provider of + * `FirebaseInstanceIdInternal`, isn't linked. `getToken()` may block on the network, hence the + * executor. + */ + fun getMessagingToken(): Task { + val instanceId = get() ?: return Tasks.forResult(null) + val taskCompletionSource = TaskCompletionSource() + executor.execute { + try { + taskCompletionSource.setResult(instanceId.token) + } catch (e: Exception) { + taskCompletionSource.setException(e) + } + } + return taskCompletionSource.task + } +} diff --git a/packages/firebase_core/firebase_core/android/src/test/kotlin/io/flutter/plugins/firebase/core/InteropTokenProviderTest.kt b/packages/firebase_core/firebase_core/android/src/test/kotlin/io/flutter/plugins/firebase/core/InteropTokenProviderTest.kt new file mode 100644 index 000000000000..d148adfa9f5f --- /dev/null +++ b/packages/firebase_core/firebase_core/android/src/test/kotlin/io/flutter/plugins/firebase/core/InteropTokenProviderTest.kt @@ -0,0 +1,256 @@ +// Copyright 2026 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. +package io.flutter.plugins.firebase.core + +import com.google.android.gms.tasks.Task +import com.google.android.gms.tasks.Tasks +import com.google.firebase.FirebaseException +import com.google.firebase.appcheck.AppCheckTokenResult +import com.google.firebase.appcheck.interop.AppCheckTokenListener +import com.google.firebase.appcheck.interop.InteropAppCheckTokenProvider +import com.google.firebase.auth.GetTokenResult +import com.google.firebase.auth.internal.IdTokenListener +import com.google.firebase.auth.internal.InternalAuthProvider +import com.google.firebase.iid.internal.FirebaseInstanceIdInternal +import com.google.firebase.internal.api.FirebaseNoSignedInUserException +import java.io.IOException +import java.util.concurrent.Executor +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertSame +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith +import org.junit.runners.JUnit4 + +@RunWith(JUnit4::class) +class InteropTokenProviderTest { + /** Stands in for an app's component container: whatever the test "links". */ + private val linked = mutableMapOf, Any>() + + /** Runs continuations inline so tasks complete synchronously under test. */ + private val directExecutor = Executor { it.run() } + + private val provider = InteropTokenProvider({ linked[it] }, directExecutor) + + // Auth + + @Test + fun authIdToken_isNullWhenAuthIsNotLinked() { + assertNull(provider.getAuthIdToken().completedResult()) + } + + @Test + fun authIdToken_isNullWhenNobodyIsSignedIn() { + linked[InternalAuthProvider::class.java] = + FakeAuth(Tasks.forException(FirebaseNoSignedInUserException("no user"))) + + assertNull(provider.getAuthIdToken().completedResult()) + } + + @Test + fun authIdToken_isTheSdkTokenWhenSignedIn() { + linked[InternalAuthProvider::class.java] = + FakeAuth(Tasks.forResult(GetTokenResult("id-token", emptyMap()))) + + assertEquals("id-token", provider.getAuthIdToken().completedResult()) + } + + @Test + fun authIdToken_failsWithTheSdkExceptionOtherwise() { + val failure = FirebaseException("A network error has occurred.") + linked[InternalAuthProvider::class.java] = FakeAuth(Tasks.forException(failure)) + + assertSame(failure, provider.getAuthIdToken().completedException()) + } + + @Test + fun authIdToken_neverForcesARefresh() { + val auth = FakeAuth(Tasks.forResult(GetTokenResult("id-token", emptyMap()))) + linked[InternalAuthProvider::class.java] = auth + + provider.getAuthIdToken().completedResult() + + assertEquals(listOf(false), auth.forceRefreshRequests) + } + + // App Check + + @Test + fun appCheckToken_isNullWhenAppCheckIsNotLinked() { + assertNull(provider.getAppCheckToken(limitedUse = false).completedResult()) + } + + @Test + fun appCheckToken_carriesTheRealTokenWithoutAnError() { + linked[InteropAppCheckTokenProvider::class.java] = + FakeAppCheck(regular = appCheckResult("app-check-token", error = null)) + + val result = provider.getAppCheckToken(limitedUse = false).completedResult() + + assertEquals(CoreAppCheckInteropToken(token = "app-check-token", error = null), result) + } + + @Test + fun appCheckToken_carriesThePlaceholderAndTheErrorBeforeActivation() { + linked[InteropAppCheckTokenProvider::class.java] = + FakeAppCheck( + regular = + appCheckResult("placeholder", FirebaseException("No AppCheckProvider installed."))) + + val result = provider.getAppCheckToken(limitedUse = false).completedResult() + + assertEquals( + CoreAppCheckInteropToken(token = "placeholder", error = "No AppCheckProvider installed."), + result) + } + + @Test + fun appCheckToken_describesAnErrorWithoutAMessage() { + linked[InteropAppCheckTokenProvider::class.java] = + FakeAppCheck(regular = appCheckResult("placeholder", IllegalStateException())) + + val result = provider.getAppCheckToken(limitedUse = false).completedResult() + + assertEquals("java.lang.IllegalStateException", result?.error) + } + + @Test + fun appCheckToken_asksForALimitedUseTokenOnRequest() { + val appCheck = + FakeAppCheck( + regular = appCheckResult("regular", error = null), + limitedUse = appCheckResult("limited-use", error = null)) + linked[InteropAppCheckTokenProvider::class.java] = appCheck + + val result = provider.getAppCheckToken(limitedUse = true).completedResult() + + assertEquals("limited-use", result?.token) + assertEquals(listOf("limitedUse"), appCheck.requests) + } + + @Test + fun appCheckToken_asksForACachedTokenByDefault() { + val appCheck = FakeAppCheck(regular = appCheckResult("regular", error = null)) + linked[InteropAppCheckTokenProvider::class.java] = appCheck + + provider.getAppCheckToken(limitedUse = false).completedResult() + + assertEquals(listOf("getToken(forceRefresh=false)"), appCheck.requests) + } + + // Messaging + + @Test + fun messagingToken_isNullWhenNothingProvidesInstanceId() { + assertNull(provider.getMessagingToken().completedResult()) + } + + @Test + fun messagingToken_isNullWhenThereIsNoTokenYet() { + linked[FirebaseInstanceIdInternal::class.java] = FakeInstanceId(token = null) + + assertNull(provider.getMessagingToken().completedResult()) + } + + @Test + fun messagingToken_isTheRegistrationToken() { + linked[FirebaseInstanceIdInternal::class.java] = FakeInstanceId(token = "fcm-token") + + assertEquals("fcm-token", provider.getMessagingToken().completedResult()) + } + + @Test + fun messagingToken_failsWithTheSdkExceptionOtherwise() { + val failure = IOException("SERVICE_NOT_AVAILABLE") + linked[FirebaseInstanceIdInternal::class.java] = FakeInstanceId(failure = failure) + + assertSame(failure, provider.getMessagingToken().completedException()) + } + + @Test + fun lookupsIgnoreAComponentOfTheWrongType() { + linked[InternalAuthProvider::class.java] = "not an auth provider" + + assertNull(provider.getAuthIdToken().completedResult()) + } + + // Helpers + + private fun Task.completedResult(): T? { + assertTrue("task should complete synchronously under test", isComplete) + assertTrue("task failed: $exception", isSuccessful) + return result + } + + private fun Task.completedException(): Exception? { + assertTrue("task should complete synchronously under test", isComplete) + // Don't read `result` here: on a failed task it rethrows the failure. + assertFalse("task unexpectedly succeeded", isSuccessful) + return exception + } + + private fun appCheckResult(token: String, error: Exception?): Task = + Tasks.forResult( + object : AppCheckTokenResult() { + override fun getToken() = token + + override fun getError() = error + }) + + private class FakeAuth(private val accessToken: Task) : InternalAuthProvider { + val forceRefreshRequests = mutableListOf() + + override fun getAccessToken(forceRefresh: Boolean): Task { + forceRefreshRequests.add(forceRefresh) + return accessToken + } + + override fun getUid(): String? = null + + override fun addIdTokenListener(listener: IdTokenListener) = Unit + + override fun removeIdTokenListener(listener: IdTokenListener) = Unit + } + + private class FakeAppCheck( + private val regular: Task, + private val limitedUse: Task = regular, + ) : InteropAppCheckTokenProvider { + val requests = mutableListOf() + + override fun getToken(forceRefresh: Boolean): Task { + requests.add("getToken(forceRefresh=$forceRefresh)") + return regular + } + + override fun getLimitedUseToken(): Task { + requests.add("limitedUse") + return limitedUse + } + + override fun addAppCheckTokenListener(listener: AppCheckTokenListener) = Unit + + override fun removeAppCheckTokenListener(listener: AppCheckTokenListener) = Unit + } + + private class FakeInstanceId( + private val token: String? = null, + private val failure: Exception? = null, + ) : FirebaseInstanceIdInternal { + override fun getId(): String = "instance-id" + + override fun getToken(): String? { + failure?.let { throw it } + return token + } + + override fun getTokenTask(): Task = Tasks.forResult(token) + + override fun deleteToken(senderId: String, scope: String) = Unit + + override fun addNewTokenListener(listener: FirebaseInstanceIdInternal.NewTokenListener) = Unit + } +} diff --git a/packages/firebase_core/firebase_core/ios/firebase_core/Sources/firebase_core/FLTFirebaseCorePlugin.swift b/packages/firebase_core/firebase_core/ios/firebase_core/Sources/firebase_core/FLTFirebaseCorePlugin.swift index 744c413a3eb5..bb6775b78433 100644 --- a/packages/firebase_core/firebase_core/ios/firebase_core/Sources/firebase_core/FLTFirebaseCorePlugin.swift +++ b/packages/firebase_core/firebase_core/ios/firebase_core/Sources/firebase_core/FLTFirebaseCorePlugin.swift @@ -40,7 +40,7 @@ private func installAppCheckProviderFactoryIfLinked() { @objc(FLTFirebaseCorePlugin) public class FLTFirebaseCorePlugin: NSObject, FlutterPlugin, FLTFirebasePluginProtocol, - FirebaseCoreHostApi, FirebaseAppHostApi + FirebaseCoreHostApi, FirebaseAppHostApi, FirebaseTokenHostApi { private var coreInitialized = false @@ -81,6 +81,7 @@ public class FLTFirebaseCorePlugin: NSObject, FlutterPlugin, FLTFirebasePluginPr #endif FirebaseCoreHostApiSetup.setUp(binaryMessenger: binaryMessenger, api: instance) FirebaseAppHostApiSetup.setUp(binaryMessenger: binaryMessenger, api: instance) + FirebaseTokenHostApiSetup.setUp(binaryMessenger: binaryMessenger, api: instance) } public func didReinitializeFirebaseCore(_ completion: @escaping () -> Void) { @@ -276,4 +277,68 @@ public class FLTFirebaseCorePlugin: NSObject, FlutterPlugin, FLTFirebasePluginPr // Unsupported on iOS/macOS. completion(.success(())) } + + func getAuthIdToken( + appName: String, + completion: @escaping (Result) -> Void + ) { + respondWithToken(appName: appName, failureCode: "auth-token-failed", completion: completion) { + provider, done in + provider.getAuthIdToken(completion: done) + } + } + + func getAppCheckToken( + appName: String, + limitedUse: Bool, + completion: @escaping (Result) -> Void + ) { + respondWithToken( + appName: appName, failureCode: "app-check-token-failed", completion: completion + ) { provider, done in + provider.getAppCheckToken(limitedUse: limitedUse, completion: done) + } + } + + func getMessagingToken( + appName: String, + completion: @escaping (Result) -> Void + ) { + respondWithToken( + appName: appName, failureCode: "messaging-token-failed", completion: completion + ) { provider, done in + done(.success(provider.getMessagingToken())) + } + } + + /// Reports an SDK failure as a FlutterError under `failureCode` and replies on the main thread, + /// since the SDKs call back on their own queues. + private func respondWithToken( + appName: String, + failureCode: String, + completion: @escaping (Result) -> Void, + fetch: (InteropTokenProvider, @escaping (Result) -> Void) -> Void + ) { + guard let firebaseApp = FLTFirebasePlugin.firebaseAppNamed(appName) else { + completion( + .failure( + FlutterError( + code: "no-app", + message: + "No Firebase App '\(appName)' has been created - call Firebase.initializeApp()", + details: nil + ) + ) + ) + return + } + fetch(InteropTokenProvider.forApp(firebaseApp)) { result in + let reply = result.mapError { error -> Error in + FlutterError(code: failureCode, message: error.localizedDescription, details: nil) + } + DispatchQueue.main.async { + completion(reply) + } + } + } } diff --git a/packages/firebase_core/firebase_core/ios/firebase_core/Sources/firebase_core/FirebaseCoreMessages.g.swift b/packages/firebase_core/firebase_core/ios/firebase_core/Sources/firebase_core/FirebaseCoreMessages.g.swift index 50cbf2d210cb..841071842444 100644 --- a/packages/firebase_core/firebase_core/ios/firebase_core/Sources/firebase_core/FirebaseCoreMessages.g.swift +++ b/packages/firebase_core/firebase_core/ios/firebase_core/Sources/firebase_core/FirebaseCoreMessages.g.swift @@ -333,6 +333,46 @@ struct CoreInitializeResponse: Hashable { } } +/// The App Check SDK's answer to a token request, as the native SDKs report +/// it: when the SDK can't produce a token, [token] is its placeholder and +/// [error] the reason. +/// +/// Generated class from Pigeon that represents data sent in messages. +struct CoreAppCheckInteropToken: Hashable { + var token: String + var error: String? = nil + + // swift-format-ignore: AlwaysUseLowerCamelCase + static func fromList(_ pigeonVar_list: [Any?]) -> CoreAppCheckInteropToken? { + let token = pigeonVar_list[0] as! String + let error: String? = nilOrValue(pigeonVar_list[1]) + + return CoreAppCheckInteropToken( + token: token, + error: error + ) + } + func toList() -> [Any?] { + return [ + token, + error, + ] + } + static func == (lhs: CoreAppCheckInteropToken, rhs: CoreAppCheckInteropToken) -> Bool { + if Swift.type(of: lhs) != Swift.type(of: rhs) { + return false + } + return deepEqualsFirebaseCoreMessages(lhs.token, rhs.token) + && deepEqualsFirebaseCoreMessages(lhs.error, rhs.error) + } + + func hash(into hasher: inout Hasher) { + hasher.combine("CoreAppCheckInteropToken") + deepHashFirebaseCoreMessages(value: token, hasher: &hasher) + deepHashFirebaseCoreMessages(value: error, hasher: &hasher) + } +} + private class FirebaseCoreMessagesPigeonCodecReader: FlutterStandardReader { override func readValue(ofType type: UInt8) -> Any? { switch type { @@ -340,6 +380,8 @@ private class FirebaseCoreMessagesPigeonCodecReader: FlutterStandardReader { return CoreFirebaseOptions.fromList(self.readValue() as! [Any?]) case 130: return CoreInitializeResponse.fromList(self.readValue() as! [Any?]) + case 131: + return CoreAppCheckInteropToken.fromList(self.readValue() as! [Any?]) default: return super.readValue(ofType: type) } @@ -354,6 +396,9 @@ private class FirebaseCoreMessagesPigeonCodecWriter: FlutterStandardWriter { } else if let value = value as? CoreInitializeResponse { super.writeByte(130) super.writeValue(value.toList()) + } else if let value = value as? CoreAppCheckInteropToken { + super.writeByte(131) + super.writeValue(value.toList()) } else { super.writeValue(value) } @@ -536,3 +581,89 @@ class FirebaseAppHostApiSetup { } } } +/// Tokens from whichever Auth, App Check and Messaging SDKs the app links, +/// looked up through the Firebase component container the way the Functions +/// SDKs do. A null result means the SDK isn't linked or has nothing to give; +/// it never means failure. +/// +/// Generated protocol from Pigeon that represents a handler of messages from Flutter. +protocol FirebaseTokenHostApi { + func getAuthIdToken(appName: String, completion: @escaping (Result) -> Void) + func getAppCheckToken( + appName: String, limitedUse: Bool, + completion: @escaping (Result) -> Void) + func getMessagingToken(appName: String, completion: @escaping (Result) -> Void) +} + +/// Generated setup class from Pigeon to handle messages through the `binaryMessenger`. +class FirebaseTokenHostApiSetup { + static var codec: FlutterStandardMessageCodec { FirebaseCoreMessagesPigeonCodec.shared } + /// Sets up an instance of `FirebaseTokenHostApi` to handle messages through the `binaryMessenger`. + static func setUp( + binaryMessenger: FlutterBinaryMessenger, api: FirebaseTokenHostApi?, + messageChannelSuffix: String = "" + ) { + let channelSuffix = messageChannelSuffix.count > 0 ? ".\(messageChannelSuffix)" : "" + let getAuthIdTokenChannel = FlutterBasicMessageChannel( + name: + "dev.flutter.pigeon.firebase_core_platform_interface.FirebaseTokenHostApi.getAuthIdToken\(channelSuffix)", + binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + getAuthIdTokenChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let appNameArg = args[0] as! String + api.getAuthIdToken(appName: appNameArg) { result in + switch result { + case .success(let res): + reply(wrapResult(res)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + getAuthIdTokenChannel.setMessageHandler(nil) + } + let getAppCheckTokenChannel = FlutterBasicMessageChannel( + name: + "dev.flutter.pigeon.firebase_core_platform_interface.FirebaseTokenHostApi.getAppCheckToken\(channelSuffix)", + binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + getAppCheckTokenChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let appNameArg = args[0] as! String + let limitedUseArg = args[1] as! Bool + api.getAppCheckToken(appName: appNameArg, limitedUse: limitedUseArg) { result in + switch result { + case .success(let res): + reply(wrapResult(res)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + getAppCheckTokenChannel.setMessageHandler(nil) + } + let getMessagingTokenChannel = FlutterBasicMessageChannel( + name: + "dev.flutter.pigeon.firebase_core_platform_interface.FirebaseTokenHostApi.getMessagingToken\(channelSuffix)", + binaryMessenger: binaryMessenger, codec: codec) + if let api = api { + getMessagingTokenChannel.setMessageHandler { message, reply in + let args = message as! [Any?] + let appNameArg = args[0] as! String + api.getMessagingToken(appName: appNameArg) { result in + switch result { + case .success(let res): + reply(wrapResult(res)) + case .failure(let error): + reply(wrapError(error)) + } + } + } + } else { + getMessagingTokenChannel.setMessageHandler(nil) + } + } +} diff --git a/packages/firebase_core/firebase_core/ios/firebase_core/Sources/firebase_core/InteropTokenProvider.swift b/packages/firebase_core/firebase_core/ios/firebase_core/Sources/firebase_core/InteropTokenProvider.swift new file mode 100644 index 000000000000..71ab5cafc855 --- /dev/null +++ b/packages/firebase_core/firebase_core/ios/firebase_core/Sources/firebase_core/InteropTokenProvider.swift @@ -0,0 +1,132 @@ +// Copyright 2026 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import FirebaseCore +import Foundation + +/// Fetches the Auth, App Check and FCM tokens through the interop components the SDKs register +/// in the app's component container, as the Functions SDK does. A nil token means the SDK isn't +/// linked or has nothing to give, never failure. +final class InteropTokenProvider { + private let getComponent: (String) -> AnyObject? + + init(getComponent: @escaping (String) -> AnyObject?) { + self.getComponent = getComponent + } + + /// `FirebaseCoreExtension` and the SDKs' interop modules aren't products of the Firebase Swift + /// package, so this plugin can't import them. It reaches the same Objective-C API by name: + /// `FIRApp`'s `container` and `-[FIRComponentContainer __instanceForProtocol:]`. + static func forApp(_ app: FirebaseApp) -> InteropTokenProvider { + InteropTokenProvider { protocolName in + // NSProtocolFromString is nil when no linked binary declares the protocol. + guard let interopProtocol = NSProtocolFromString(protocolName), + app.responds(to: containerSelector), + let container = app.perform(containerSelector)?.takeUnretainedValue() as? NSObject, + container.responds(to: instanceForProtocolSelector) + else { + return nil + } + return container.perform(instanceForProtocolSelector, with: interopProtocol)? + .takeUnretainedValue() + } + } + + /// The signed-in user's ID token, or nil when Auth isn't linked or nobody is signed in. + func getAuthIdToken(completion: @escaping (Result) -> Void) { + let auth = getComponent(authInteropProtocolName) + let started: Void? = auth?.interopGetToken?( + forcingRefresh: false, + callback: { token, error in + if let error { + completion(.failure(error)) + } else { + // The Auth SDK answers (nil, nil) when nobody is signed in. + completion(.success(token)) + } + } + ) + if started == nil { + completion(.success(nil)) + } + } + + /// App Check's answer, or nil when it isn't linked. Before activation the SDK answers with its + /// placeholder token and an error. + func getAppCheckToken( + limitedUse: Bool, + completion: @escaping (Result) -> Void + ) { + let appCheck = getComponent(appCheckInteropProtocolName) + let handleResult: (AnyObject) -> Void = { result in + // A result without `token` means the SDK changed shape; that's a failure, not "not linked". + guard let token = result.interopToken else { + completion( + .failure( + NSError( + domain: "FlutterFirebaseCore", code: 0, + userInfo: [NSLocalizedDescriptionKey: "App Check result has no token"]))) + return + } + let error: NSError? = result.interopError ?? nil + completion( + .success( + CoreAppCheckInteropToken( + token: token, + error: error?.localizedDescription + ))) + } + // `getLimitedUseToken(completion:)` is optional in the protocol. + let started: Void? = + limitedUse + ? appCheck?.interopGetLimitedUseToken?(completion: handleResult) + : appCheck?.interopGetToken?(forcingRefresh: false, completion: handleResult) + if started == nil { + completion(.success(nil)) + } + } + + /// The cached FCM token, or nil when Messaging isn't linked or has none. Never requests one. + func getMessagingToken() -> String? { + let token: String?? = getComponent(messagingInteropProtocolName)?.interopFCMToken + return token ?? nil + } +} + +// Objective-C runtime names of the interop protocols. +private let authInteropProtocolName = "FIRAuthInterop" +private let appCheckInteropProtocolName = "FIRAppCheckInterop" +private let messagingInteropProtocolName = "FIRMessagingInterop" + +private let containerSelector = NSSelectorFromString("container") +private let instanceForProtocolSelector = NSSelectorFromString("__instanceForProtocol:") + +// The SDK methods this file calls, redeclared with the selectors from the SDK headers because +// those can't be imported. `AnyObject` lookup skips a call when the object doesn't respond. + +/// FIRAuthInterop.h +@objc private protocol AuthInteropMethods { + @objc(getTokenForcingRefresh:withCallback:) + func interopGetToken(forcingRefresh: Bool, callback: @escaping (String?, Error?) -> Void) +} + +/// FIRAppCheckInterop.h +@objc private protocol AppCheckInteropMethods { + @objc(getTokenForcingRefresh:completion:) + func interopGetToken(forcingRefresh: Bool, completion: @escaping (AnyObject) -> Void) + + @objc(getLimitedUseTokenWithCompletion:) + func interopGetLimitedUseToken(completion: @escaping (AnyObject) -> Void) +} + +/// FIRAppCheckTokenResultInterop.h +@objc private protocol AppCheckTokenResultProperties { + @objc(token) var interopToken: String { get } + @objc(error) var interopError: NSError? { get } +} + +/// FIRMessagingInterop.h +@objc private protocol MessagingInteropProperties { + @objc(FCMToken) var interopFCMToken: String? { get } +} diff --git a/packages/firebase_core/firebase_core/macos/firebase_core/Sources/firebase_core/InteropTokenProvider.swift b/packages/firebase_core/firebase_core/macos/firebase_core/Sources/firebase_core/InteropTokenProvider.swift new file mode 120000 index 000000000000..fa47b4aa0d36 --- /dev/null +++ b/packages/firebase_core/firebase_core/macos/firebase_core/Sources/firebase_core/InteropTokenProvider.swift @@ -0,0 +1 @@ +../../../../ios/firebase_core/Sources/firebase_core/InteropTokenProvider.swift \ No newline at end of file diff --git a/packages/firebase_core/firebase_core/windows/messages.g.cpp b/packages/firebase_core/firebase_core/windows/messages.g.cpp index 42e8046a21e1..04f78ce3f2ed 100644 --- a/packages/firebase_core/firebase_core/windows/messages.g.cpp +++ b/packages/firebase_core/firebase_core/windows/messages.g.cpp @@ -717,6 +717,74 @@ size_t PigeonInternalDeepHash(const CoreInitializeResponse& v) { return v.Hash(); } +// CoreAppCheckInteropToken + +CoreAppCheckInteropToken::CoreAppCheckInteropToken(const std::string& token) + : token_(token) {} + +CoreAppCheckInteropToken::CoreAppCheckInteropToken(const std::string& token, + const std::string* error) + : token_(token), + error_(error ? std::optional(*error) : std::nullopt) {} + +const std::string& CoreAppCheckInteropToken::token() const { return token_; } + +void CoreAppCheckInteropToken::set_token(std::string_view value_arg) { + token_ = value_arg; +} + +const std::string* CoreAppCheckInteropToken::error() const { + return error_ ? &(*error_) : nullptr; +} + +void CoreAppCheckInteropToken::set_error(const std::string_view* value_arg) { + error_ = value_arg ? std::optional(*value_arg) : std::nullopt; +} + +void CoreAppCheckInteropToken::set_error(std::string_view value_arg) { + error_ = value_arg; +} + +EncodableList CoreAppCheckInteropToken::ToEncodableList() const { + EncodableList list; + list.reserve(2); + list.push_back(EncodableValue(token_)); + list.push_back(error_ ? EncodableValue(*error_) : EncodableValue()); + return list; +} + +CoreAppCheckInteropToken CoreAppCheckInteropToken::FromEncodableList( + const EncodableList& list) { + CoreAppCheckInteropToken decoded(std::get(list[0])); + auto& encodable_error = list[1]; + if (!encodable_error.IsNull()) { + decoded.set_error(std::get(encodable_error)); + } + return decoded; +} + +bool CoreAppCheckInteropToken::operator==( + const CoreAppCheckInteropToken& other) const { + return PigeonInternalDeepEquals(token_, other.token_) && + PigeonInternalDeepEquals(error_, other.error_); +} + +bool CoreAppCheckInteropToken::operator!=( + const CoreAppCheckInteropToken& other) const { + return !(*this == other); +} + +size_t CoreAppCheckInteropToken::Hash() const { + size_t result = 1; + result = result * 31 + PigeonInternalDeepHash(token_); + result = result * 31 + PigeonInternalDeepHash(error_); + return result; +} + +size_t PigeonInternalDeepHash(const CoreAppCheckInteropToken& v) { + return v.Hash(); +} + PigeonInternalCodecSerializer::PigeonInternalCodecSerializer() {} EncodableValue PigeonInternalCodecSerializer::ReadValueOfType( @@ -730,6 +798,10 @@ EncodableValue PigeonInternalCodecSerializer::ReadValueOfType( return CustomEncodableValue(CoreInitializeResponse::FromEncodableList( std::get(ReadValue(stream)))); } + case 131: { + return CustomEncodableValue(CoreAppCheckInteropToken::FromEncodableList( + std::get(ReadValue(stream)))); + } default: return ::flutter::StandardCodecSerializer::ReadValueOfType(type, stream); } @@ -755,6 +827,14 @@ void PigeonInternalCodecSerializer::WriteValue( stream); return; } + if (custom_value->type() == typeid(CoreAppCheckInteropToken)) { + stream->WriteByte(131); + WriteValue( + EncodableValue(std::any_cast(*custom_value) + .ToEncodableList()), + stream); + return; + } } ::flutter::StandardCodecSerializer::WriteValue(value, stream); } @@ -1065,4 +1145,181 @@ EncodableValue FirebaseAppHostApi::WrapError(const FlutterError& error) { error.details()}); } +/// The codec used by FirebaseTokenHostApi. +const ::flutter::StandardMessageCodec& FirebaseTokenHostApi::GetCodec() { + return ::flutter::StandardMessageCodec::GetInstance( + &PigeonInternalCodecSerializer::GetInstance()); +} + +// Sets up an instance of `FirebaseTokenHostApi` to handle messages through the +// `binary_messenger`. +void FirebaseTokenHostApi::SetUp(::flutter::BinaryMessenger* binary_messenger, + FirebaseTokenHostApi* api) { + FirebaseTokenHostApi::SetUp(binary_messenger, api, ""); +} + +void FirebaseTokenHostApi::SetUp(::flutter::BinaryMessenger* binary_messenger, + FirebaseTokenHostApi* api, + const std::string& message_channel_suffix) { + const std::string prepended_suffix = + message_channel_suffix.length() > 0 + ? std::string(".") + message_channel_suffix + : ""; + { + BasicMessageChannel<> channel( + binary_messenger, + "dev.flutter.pigeon.firebase_core_platform_interface." + "FirebaseTokenHostApi.getAuthIdToken" + + prepended_suffix, + &GetCodec()); + if (api != nullptr) { + channel.SetMessageHandler( + [api](const EncodableValue& message, + const ::flutter::MessageReply& reply) { + try { + const auto& args = std::get(message); + const auto& encodable_app_name_arg = args.at(0); + if (encodable_app_name_arg.IsNull()) { + reply(WrapError("app_name_arg unexpectedly null.")); + return; + } + const auto& app_name_arg = + std::get(encodable_app_name_arg); + api->GetAuthIdToken( + app_name_arg, + [reply](ErrorOr>&& output) { + if (output.has_error()) { + reply(WrapError(output.error())); + return; + } + EncodableList wrapped; + auto output_optional = std::move(output).TakeValue(); + if (output_optional) { + wrapped.push_back( + EncodableValue(std::move(output_optional).value())); + } else { + wrapped.push_back(EncodableValue()); + } + reply(EncodableValue(std::move(wrapped))); + }); + } catch (const std::exception& exception) { + reply(WrapError(exception.what())); + } + }); + } else { + channel.SetMessageHandler(nullptr); + } + } + { + BasicMessageChannel<> channel( + binary_messenger, + "dev.flutter.pigeon.firebase_core_platform_interface." + "FirebaseTokenHostApi.getAppCheckToken" + + prepended_suffix, + &GetCodec()); + if (api != nullptr) { + channel.SetMessageHandler( + [api](const EncodableValue& message, + const ::flutter::MessageReply& reply) { + try { + const auto& args = std::get(message); + const auto& encodable_app_name_arg = args.at(0); + if (encodable_app_name_arg.IsNull()) { + reply(WrapError("app_name_arg unexpectedly null.")); + return; + } + const auto& app_name_arg = + std::get(encodable_app_name_arg); + const auto& encodable_limited_use_arg = args.at(1); + if (encodable_limited_use_arg.IsNull()) { + reply(WrapError("limited_use_arg unexpectedly null.")); + return; + } + const auto& limited_use_arg = + std::get(encodable_limited_use_arg); + api->GetAppCheckToken( + app_name_arg, limited_use_arg, + [reply](ErrorOr>&& + output) { + if (output.has_error()) { + reply(WrapError(output.error())); + return; + } + EncodableList wrapped; + auto output_optional = std::move(output).TakeValue(); + if (output_optional) { + wrapped.push_back(CustomEncodableValue( + std::move(output_optional).value())); + } else { + wrapped.push_back(EncodableValue()); + } + reply(EncodableValue(std::move(wrapped))); + }); + } catch (const std::exception& exception) { + reply(WrapError(exception.what())); + } + }); + } else { + channel.SetMessageHandler(nullptr); + } + } + { + BasicMessageChannel<> channel( + binary_messenger, + "dev.flutter.pigeon.firebase_core_platform_interface." + "FirebaseTokenHostApi.getMessagingToken" + + prepended_suffix, + &GetCodec()); + if (api != nullptr) { + channel.SetMessageHandler( + [api](const EncodableValue& message, + const ::flutter::MessageReply& reply) { + try { + const auto& args = std::get(message); + const auto& encodable_app_name_arg = args.at(0); + if (encodable_app_name_arg.IsNull()) { + reply(WrapError("app_name_arg unexpectedly null.")); + return; + } + const auto& app_name_arg = + std::get(encodable_app_name_arg); + api->GetMessagingToken( + app_name_arg, + [reply](ErrorOr>&& output) { + if (output.has_error()) { + reply(WrapError(output.error())); + return; + } + EncodableList wrapped; + auto output_optional = std::move(output).TakeValue(); + if (output_optional) { + wrapped.push_back( + EncodableValue(std::move(output_optional).value())); + } else { + wrapped.push_back(EncodableValue()); + } + reply(EncodableValue(std::move(wrapped))); + }); + } catch (const std::exception& exception) { + reply(WrapError(exception.what())); + } + }); + } else { + channel.SetMessageHandler(nullptr); + } + } +} + +EncodableValue FirebaseTokenHostApi::WrapError(std::string_view error_message) { + return EncodableValue( + EncodableList{EncodableValue(std::string(error_message)), + EncodableValue("Error"), EncodableValue()}); +} + +EncodableValue FirebaseTokenHostApi::WrapError(const FlutterError& error) { + return EncodableValue(EncodableList{EncodableValue(error.code()), + EncodableValue(error.message()), + error.details()}); +} + } // namespace firebase_core_windows diff --git a/packages/firebase_core/firebase_core/windows/messages.g.h b/packages/firebase_core/firebase_core/windows/messages.g.h index c456febacce9..0fa415275054 100644 --- a/packages/firebase_core/firebase_core/windows/messages.g.h +++ b/packages/firebase_core/firebase_core/windows/messages.g.h @@ -53,6 +53,7 @@ class ErrorOr { private: friend class FirebaseCoreHostApi; friend class FirebaseAppHostApi; + friend class FirebaseTokenHostApi; ErrorOr() = default; T TakeValue() && { return std::get(std::move(v_)); } @@ -143,6 +144,7 @@ class CoreFirebaseOptions { friend class CoreInitializeResponse; friend class FirebaseCoreHostApi; friend class FirebaseAppHostApi; + friend class FirebaseTokenHostApi; friend class PigeonInternalCodecSerializer; std::string api_key_; std::string app_id_; @@ -205,6 +207,7 @@ class CoreInitializeResponse { ::flutter::EncodableList ToEncodableList() const; friend class FirebaseCoreHostApi; friend class FirebaseAppHostApi; + friend class FirebaseTokenHostApi; friend class PigeonInternalCodecSerializer; std::string name_; std::unique_ptr options_; @@ -212,6 +215,45 @@ class CoreInitializeResponse { ::flutter::EncodableMap plugin_constants_; }; +// The App Check SDK's answer to a token request, as the native SDKs report +// it: when the SDK can't produce a token, [token] is its placeholder and +// [error] the reason. +// +// Generated class from Pigeon that represents data sent in messages. +class CoreAppCheckInteropToken { + public: + // Constructs an object setting all non-nullable fields. + explicit CoreAppCheckInteropToken(const std::string& token); + + // Constructs an object setting all fields. + explicit CoreAppCheckInteropToken(const std::string& token, + const std::string* error); + + const std::string& token() const; + void set_token(std::string_view value_arg); + + const std::string* error() const; + void set_error(const std::string_view* value_arg); + void set_error(std::string_view value_arg); + + bool operator==(const CoreAppCheckInteropToken& other) const; + bool operator!=(const CoreAppCheckInteropToken& other) const; + /// Returns a hash code value for the object. This method is supported for the + /// benefit of hash tables. + size_t Hash() const; + + private: + static CoreAppCheckInteropToken FromEncodableList( + const ::flutter::EncodableList& list); + ::flutter::EncodableList ToEncodableList() const; + friend class FirebaseCoreHostApi; + friend class FirebaseAppHostApi; + friend class FirebaseTokenHostApi; + friend class PigeonInternalCodecSerializer; + std::string token_; + std::optional error_; +}; + class PigeonInternalCodecSerializer : public ::flutter::StandardCodecSerializer { public: @@ -292,5 +334,46 @@ class FirebaseAppHostApi { protected: FirebaseAppHostApi() = default; }; +// Tokens from whichever Auth, App Check and Messaging SDKs the app links, +// looked up through the Firebase component container the way the Functions +// SDKs do. A null result means the SDK isn't linked or has nothing to give; +// it never means failure. +// +// Generated interface from Pigeon that represents a handler of messages from +// Flutter. +class FirebaseTokenHostApi { + public: + FirebaseTokenHostApi(const FirebaseTokenHostApi&) = delete; + FirebaseTokenHostApi& operator=(const FirebaseTokenHostApi&) = delete; + virtual ~FirebaseTokenHostApi() {} + virtual void GetAuthIdToken( + const std::string& app_name, + std::function> reply)> + result) = 0; + virtual void GetAppCheckToken( + const std::string& app_name, bool limited_use, + std::function< + void(ErrorOr> reply)> + result) = 0; + virtual void GetMessagingToken( + const std::string& app_name, + std::function> reply)> + result) = 0; + + // The codec used by FirebaseTokenHostApi. + static const ::flutter::StandardMessageCodec& GetCodec(); + // Sets up an instance of `FirebaseTokenHostApi` to handle messages through + // the `binary_messenger`. + static void SetUp(::flutter::BinaryMessenger* binary_messenger, + FirebaseTokenHostApi* api); + static void SetUp(::flutter::BinaryMessenger* binary_messenger, + FirebaseTokenHostApi* api, + const std::string& message_channel_suffix); + static ::flutter::EncodableValue WrapError(std::string_view error_message); + static ::flutter::EncodableValue WrapError(const FlutterError& error); + + protected: + FirebaseTokenHostApi() = default; +}; } // namespace firebase_core_windows #endif // PIGEON_MESSAGES_G_H_ diff --git a/packages/firebase_core/firebase_core_platform_interface/lib/firebase_core_platform_interface.dart b/packages/firebase_core/firebase_core_platform_interface/lib/firebase_core_platform_interface.dart index 5e5fe29248f1..d5c232ef7df5 100644 --- a/packages/firebase_core/firebase_core_platform_interface/lib/firebase_core_platform_interface.dart +++ b/packages/firebase_core/firebase_core_platform_interface/lib/firebase_core_platform_interface.dart @@ -14,6 +14,7 @@ import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; import 'package:plugin_platform_interface/plugin_platform_interface.dart'; +part 'src/app_check_interop_token.dart'; part 'src/firebase_core_exceptions.dart'; part 'src/firebase_exception.dart'; part 'src/firebase_options.dart'; diff --git a/packages/firebase_core/firebase_core_platform_interface/lib/src/app_check_interop_token.dart b/packages/firebase_core/firebase_core_platform_interface/lib/src/app_check_interop_token.dart new file mode 100644 index 000000000000..9aa6f273d481 --- /dev/null +++ b/packages/firebase_core/firebase_core_platform_interface/lib/src/app_check_interop_token.dart @@ -0,0 +1,38 @@ +// Copyright 2026 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +part of '../firebase_core_platform_interface.dart'; + +/// The App Check SDK's answer to a token request, as the native SDKs report +/// it. +/// +/// When the SDK can't produce a token (for example before App Check is +/// activated), [token] holds the SDK's placeholder and [error] the reason. +/// Consumers decide whether to attach the placeholder; the Functions SDKs do. +@immutable +class AppCheckInteropToken { + /// Creates the SDK's answer: a [token] and, on failure, the [error]. + const AppCheckInteropToken({required this.token, this.error}); + + /// The App Check token, or the SDK's placeholder when [error] is set. + final String token; + + /// Why the SDK couldn't produce a token, or `null` when [token] is real. + final String? error; + + @override + bool operator ==(Object other) => + identical(this, other) || + other is AppCheckInteropToken && + other.token == token && + other.error == error; + + @override + int get hashCode => Object.hash(token, error); + + /// Describes the answer without printing the token itself. + @override + String toString() => + '$AppCheckInteropToken(token: <${token.length} chars>, error: $error)'; +} diff --git a/packages/firebase_core/firebase_core_platform_interface/lib/src/method_channel/method_channel_firebase_app.dart b/packages/firebase_core/firebase_core_platform_interface/lib/src/method_channel/method_channel_firebase_app.dart index 50c4c0216b23..ef43e3f06d6e 100644 --- a/packages/firebase_core/firebase_core_platform_interface/lib/src/method_channel/method_channel_firebase_app.dart +++ b/packages/firebase_core/firebase_core_platform_interface/lib/src/method_channel/method_channel_firebase_app.dart @@ -30,6 +30,8 @@ class MethodChannelFirebaseApp extends FirebaseAppPlatform { final _api = FirebaseAppHostApi(); + final _tokenApi = FirebaseTokenHostApi(); + /// Returns whether automatic data collection enabled or disabled. @override bool get isAutomaticDataCollectionEnabled { @@ -69,4 +71,46 @@ class MethodChannelFirebaseApp extends FirebaseAppPlatform { Future setAutomaticResourceManagementEnabled(bool enabled) async { await _api.setAutomaticResourceManagementEnabled(name, enabled); } + + @override + Future getAuthIdToken() { + return _guardTokenCall(() => _tokenApi.getAuthIdToken(name)); + } + + @override + Future getAppCheckToken({ + bool limitedUse = false, + }) async { + final result = await _guardTokenCall( + () => _tokenApi.getAppCheckToken(name, limitedUse), + ); + if (result == null) { + return null; + } + return AppCheckInteropToken(token: result.token, error: result.error); + } + + @override + Future getMessagingToken() { + return _guardTokenCall(() => _tokenApi.getMessagingToken(name)); + } + + /// Surfaces a native failure as a core [FirebaseException] with native's + /// code and message. Answers `null` on Windows, whose plugin has no token + /// lookup yet: nothing is linked there, which the contract maps to `null`. + Future _guardTokenCall(Future Function() call) async { + if (defaultTargetPlatform == TargetPlatform.windows) { + return null; + } + try { + return await call(); + } on PlatformException catch (exception, stackTrace) { + throw FirebaseException( + plugin: 'core', + code: exception.code, + message: exception.message, + stackTrace: stackTrace, + ); + } + } } diff --git a/packages/firebase_core/firebase_core_platform_interface/lib/src/pigeon/messages.pigeon.dart b/packages/firebase_core/firebase_core_platform_interface/lib/src/pigeon/messages.pigeon.dart index a668f49d7b08..aeeca821c640 100644 --- a/packages/firebase_core/firebase_core_platform_interface/lib/src/pigeon/messages.pigeon.dart +++ b/packages/firebase_core/firebase_core_platform_interface/lib/src/pigeon/messages.pigeon.dart @@ -296,6 +296,50 @@ class CoreInitializeResponse { int get hashCode => _deepHash([runtimeType, ..._toList()]); } +/// The App Check SDK's answer to a token request, as the native SDKs report +/// it: when the SDK can't produce a token, [token] is its placeholder and +/// [error] the reason. +class CoreAppCheckInteropToken { + CoreAppCheckInteropToken({required this.token, this.error}); + + String token; + + String? error; + + List _toList() { + return [token, error]; + } + + Object encode() { + return _toList(); + } + + static CoreAppCheckInteropToken decode(Object result) { + result as List; + return CoreAppCheckInteropToken( + token: result[0]! as String, + error: result[1] as String?, + ); + } + + @override + // ignore: avoid_equals_and_hash_code_on_mutable_classes + bool operator ==(Object other) { + if (other is! CoreAppCheckInteropToken || + other.runtimeType != runtimeType) { + return false; + } + if (identical(this, other)) { + return true; + } + return _deepEquals(token, other.token) && _deepEquals(error, other.error); + } + + @override + // ignore: avoid_equals_and_hash_code_on_mutable_classes + int get hashCode => _deepHash([runtimeType, ..._toList()]); +} + class _PigeonCodec extends StandardMessageCodec { const _PigeonCodec(); @override @@ -309,6 +353,9 @@ class _PigeonCodec extends StandardMessageCodec { } else if (value is CoreInitializeResponse) { buffer.putUint8(130); writeValue(buffer, value.encode()); + } else if (value is CoreAppCheckInteropToken) { + buffer.putUint8(131); + writeValue(buffer, value.encode()); } else { super.writeValue(buffer, value); } @@ -321,6 +368,8 @@ class _PigeonCodec extends StandardMessageCodec { return CoreFirebaseOptions.decode(readValue(buffer)!); case 130: return CoreInitializeResponse.decode(readValue(buffer)!); + case 131: + return CoreAppCheckInteropToken.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); } @@ -491,3 +540,91 @@ class FirebaseAppHostApi { ); } } + +/// Tokens from whichever Auth, App Check and Messaging SDKs the app links, +/// looked up through the Firebase component container the way the Functions +/// SDKs do. A null result means the SDK isn't linked or has nothing to give; +/// it never means failure. +class FirebaseTokenHostApi { + /// Constructor for [FirebaseTokenHostApi]. The [binaryMessenger] named argument is + /// available for dependency injection. If it is left null, the default + /// BinaryMessenger will be used which routes to the host platform. + FirebaseTokenHostApi({ + BinaryMessenger? binaryMessenger, + String messageChannelSuffix = '', + }) : pigeonVar_binaryMessenger = binaryMessenger, + pigeonVar_messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; + final BinaryMessenger? pigeonVar_binaryMessenger; + + static const MessageCodec pigeonChannelCodec = _PigeonCodec(); + + final String pigeonVar_messageChannelSuffix; + + Future getAuthIdToken(String appName) async { + final pigeonVar_channelName = + 'dev.flutter.pigeon.firebase_core_platform_interface.FirebaseTokenHostApi.getAuthIdToken$pigeonVar_messageChannelSuffix'; + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [appName], + ); + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue as String?; + } + + Future getAppCheckToken( + String appName, + bool limitedUse, + ) async { + final pigeonVar_channelName = + 'dev.flutter.pigeon.firebase_core_platform_interface.FirebaseTokenHostApi.getAppCheckToken$pigeonVar_messageChannelSuffix'; + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [appName, limitedUse], + ); + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue as CoreAppCheckInteropToken?; + } + + Future getMessagingToken(String appName) async { + final pigeonVar_channelName = + 'dev.flutter.pigeon.firebase_core_platform_interface.FirebaseTokenHostApi.getMessagingToken$pigeonVar_messageChannelSuffix'; + final pigeonVar_channel = BasicMessageChannel( + pigeonVar_channelName, + pigeonChannelCodec, + binaryMessenger: pigeonVar_binaryMessenger, + ); + final Future pigeonVar_sendFuture = pigeonVar_channel.send( + [appName], + ); + final pigeonVar_replyList = await pigeonVar_sendFuture as List?; + + final Object? pigeonVar_replyValue = _extractReplyValueOrThrow( + pigeonVar_replyList, + pigeonVar_channelName, + isNullValid: true, + ); + return pigeonVar_replyValue as String?; + } +} diff --git a/packages/firebase_core/firebase_core_platform_interface/lib/src/pigeon/test_api.dart b/packages/firebase_core/firebase_core_platform_interface/lib/src/pigeon/test_api.dart index fc50255eb331..caf04c9fce41 100644 --- a/packages/firebase_core/firebase_core_platform_interface/lib/src/pigeon/test_api.dart +++ b/packages/firebase_core/firebase_core_platform_interface/lib/src/pigeon/test_api.dart @@ -26,6 +26,9 @@ class _PigeonCodec extends StandardMessageCodec { } else if (value is CoreInitializeResponse) { buffer.putUint8(130); writeValue(buffer, value.encode()); + } else if (value is CoreAppCheckInteropToken) { + buffer.putUint8(131); + writeValue(buffer, value.encode()); } else { super.writeValue(buffer, value); } @@ -38,6 +41,8 @@ class _PigeonCodec extends StandardMessageCodec { return CoreFirebaseOptions.decode(readValue(buffer)!); case 130: return CoreInitializeResponse.decode(readValue(buffer)!); + case 131: + return CoreAppCheckInteropToken.decode(readValue(buffer)!); default: return super.readValueOfType(type, buffer); } @@ -296,3 +301,130 @@ abstract class TestFirebaseAppHostApi { } } } + +/// Tokens from whichever Auth, App Check and Messaging SDKs the app links, +/// looked up through the Firebase component container the way the Functions +/// SDKs do. A null result means the SDK isn't linked or has nothing to give; +/// it never means failure. +abstract class TestFirebaseTokenHostApi { + static TestDefaultBinaryMessengerBinding? get _testBinaryMessengerBinding => + TestDefaultBinaryMessengerBinding.instance; + static const MessageCodec pigeonChannelCodec = _PigeonCodec(); + + Future getAuthIdToken(String appName); + + Future getAppCheckToken( + String appName, + bool limitedUse, + ); + + Future getMessagingToken(String appName); + + static void setUp( + TestFirebaseTokenHostApi? api, { + BinaryMessenger? binaryMessenger, + String messageChannelSuffix = '', + }) { + messageChannelSuffix = messageChannelSuffix.isNotEmpty + ? '.$messageChannelSuffix' + : ''; + { + final pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.firebase_core_platform_interface.FirebaseTokenHostApi.getAuthIdToken$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); + if (api == null) { + _testBinaryMessengerBinding!.defaultBinaryMessenger + .setMockDecodedMessageHandler(pigeonVar_channel, null); + } else { + _testBinaryMessengerBinding!.defaultBinaryMessenger + .setMockDecodedMessageHandler(pigeonVar_channel, ( + Object? message, + ) async { + final List args = message! as List; + final String arg_appName = args[0]! as String; + try { + final String? output = await api.getAuthIdToken(arg_appName); + return [output]; + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException( + code: 'error', + message: e.toString(), + ), + ); + } + }); + } + } + { + final pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.firebase_core_platform_interface.FirebaseTokenHostApi.getAppCheckToken$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); + if (api == null) { + _testBinaryMessengerBinding!.defaultBinaryMessenger + .setMockDecodedMessageHandler(pigeonVar_channel, null); + } else { + _testBinaryMessengerBinding!.defaultBinaryMessenger + .setMockDecodedMessageHandler(pigeonVar_channel, ( + Object? message, + ) async { + final List args = message! as List; + final String arg_appName = args[0]! as String; + final bool arg_limitedUse = args[1]! as bool; + try { + final CoreAppCheckInteropToken? output = await api + .getAppCheckToken(arg_appName, arg_limitedUse); + return [output]; + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException( + code: 'error', + message: e.toString(), + ), + ); + } + }); + } + } + { + final pigeonVar_channel = BasicMessageChannel( + 'dev.flutter.pigeon.firebase_core_platform_interface.FirebaseTokenHostApi.getMessagingToken$messageChannelSuffix', + pigeonChannelCodec, + binaryMessenger: binaryMessenger, + ); + if (api == null) { + _testBinaryMessengerBinding!.defaultBinaryMessenger + .setMockDecodedMessageHandler(pigeonVar_channel, null); + } else { + _testBinaryMessengerBinding!.defaultBinaryMessenger + .setMockDecodedMessageHandler(pigeonVar_channel, ( + Object? message, + ) async { + final List args = message! as List; + final String arg_appName = args[0]! as String; + try { + final String? output = await api.getMessagingToken(arg_appName); + return [output]; + } on PlatformException catch (e) { + return wrapResponse(error: e); + } catch (e) { + return wrapResponse( + error: PlatformException( + code: 'error', + message: e.toString(), + ), + ); + } + }); + } + } + } +} diff --git a/packages/firebase_core/firebase_core_platform_interface/lib/src/platform_interface/platform_interface_firebase_app.dart b/packages/firebase_core/firebase_core_platform_interface/lib/src/platform_interface/platform_interface_firebase_app.dart index 37be7d7f30e8..98167239dc90 100644 --- a/packages/firebase_core/firebase_core_platform_interface/lib/src/platform_interface/platform_interface_firebase_app.dart +++ b/packages/firebase_core/firebase_core_platform_interface/lib/src/platform_interface/platform_interface_firebase_app.dart @@ -57,6 +57,56 @@ class FirebaseAppPlatform extends PlatformInterface { ); } + /// The signed-in user's ID token, or `null` when the Auth SDK isn't linked + /// into the app or nobody is signed in. + /// + /// Throws a [FirebaseException] for plugin `core` when the Auth SDK fails to + /// produce a token; its message is the SDK's and its code is + /// `auth-token-failed`. + /// + /// For Firebase packages that attach the token to their own requests, as the + /// native Functions SDK does; not for app code. + Future getAuthIdToken() async { + throw UnimplementedError('getAuthIdToken() has not been implemented.'); + } + + /// The App Check SDK's answer, or `null` when it isn't linked into the app. + /// + /// Asking before App Check is activated returns the SDK's placeholder token + /// with [AppCheckInteropToken.error] set on Android and Apple. On web, App + /// Check has no token service until it's activated, so the answer is `null` + /// until then. + /// With [limitedUse], the SDK issues a limited-use token instead of a cached + /// one. If the SDK's call fails instead of answering, as a web limited-use + /// request can, throws a [FirebaseException] for plugin `core` with code + /// `app-check-token-failed`. + /// + /// For Firebase packages that attach the token to their own requests, as the + /// native Functions SDK does; not for app code. + Future getAppCheckToken({ + bool limitedUse = false, + }) async { + throw UnimplementedError('getAppCheckToken() has not been implemented.'); + } + + /// The FCM registration token, or `null` when Messaging isn't linked into + /// the app or has no token. + /// + /// Never prompts the user. On Apple, returns only a token Messaging already + /// holds, and only for the default app. On web, asks Messaging only if the + /// user already allowed notifications; Messaging may then create a token, + /// as it does for the JS Functions SDK. On Android and web, other apps can + /// get a token too. + /// On Android, where fetching may hit the network, a failure throws a + /// [FirebaseException] for plugin `core` with code `messaging-token-failed`. + /// On web, a failure returns `null`, as the JS Functions SDK ignores it. + /// + /// For Firebase packages that attach the token to their own requests, as the + /// native Functions SDK does; not for app code. + Future getMessagingToken() async { + throw UnimplementedError('getMessagingToken() has not been implemented.'); + } + @override // ignore: avoid_equals_and_hash_code_on_mutable_classes bool operator ==(Object other) { diff --git a/packages/firebase_core/firebase_core_platform_interface/pigeons/messages.dart b/packages/firebase_core/firebase_core_platform_interface/pigeons/messages.dart index f91556633385..42207cdf4f0f 100644 --- a/packages/firebase_core/firebase_core_platform_interface/pigeons/messages.dart +++ b/packages/firebase_core/firebase_core_platform_interface/pigeons/messages.dart @@ -111,3 +111,29 @@ abstract class FirebaseAppHostApi { @async void delete(String appName); } + +/// The App Check SDK's answer to a token request, as the native SDKs report +/// it: when the SDK can't produce a token, [token] is its placeholder and +/// [error] the reason. +class CoreAppCheckInteropToken { + CoreAppCheckInteropToken({required this.token, required this.error}); + + String token; + String? error; +} + +/// Tokens from whichever Auth, App Check and Messaging SDKs the app links, +/// looked up through the Firebase component container the way the Functions +/// SDKs do. A null result means the SDK isn't linked or has nothing to give; +/// it never means failure. +@HostApi(dartHostTestHandler: 'TestFirebaseTokenHostApi') +abstract class FirebaseTokenHostApi { + @async + String? getAuthIdToken(String appName); + + @async + CoreAppCheckInteropToken? getAppCheckToken(String appName, bool limitedUse); + + @async + String? getMessagingToken(String appName); +} diff --git a/packages/firebase_core/firebase_core_platform_interface/test/method_channel_tests/method_channel_firebase_app_test.dart b/packages/firebase_core/firebase_core_platform_interface/test/method_channel_tests/method_channel_firebase_app_test.dart new file mode 100644 index 000000000000..ac50ee2d857d --- /dev/null +++ b/packages/firebase_core/firebase_core_platform_interface/test/method_channel_tests/method_channel_firebase_app_test.dart @@ -0,0 +1,190 @@ +// Copyright 2026 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'package:firebase_core_platform_interface/firebase_core_platform_interface.dart'; +import 'package:firebase_core_platform_interface/test.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + const options = FirebaseOptions( + apiKey: 'apiKey', + appId: 'appId', + messagingSenderId: 'messagingSenderId', + projectId: 'projectId', + ); + + group('$MethodChannelFirebaseApp interop tokens', () { + late FakeFirebaseTokenHostApi native; + late MethodChannelFirebaseApp app; + + setUp(() { + native = FakeFirebaseTokenHostApi(); + TestFirebaseTokenHostApi.setUp(native); + app = MethodChannelFirebaseApp('testApp', options); + }); + + tearDown(() { + TestFirebaseTokenHostApi.setUp(null); + }); + + group('getAuthIdToken', () { + test('asks native for this app and returns its token', () async { + native.authIdToken = 'id-token'; + + expect(await app.getAuthIdToken(), 'id-token'); + expect(native.calls, ['getAuthIdToken(testApp)']); + }); + + test('returns null when native has nothing to give', () async { + expect(await app.getAuthIdToken(), isNull); + }); + + test('surfaces a native failure as a core FirebaseException', () async { + native.failure = PlatformException( + code: 'auth-token-failed', + message: 'A network error has occurred.', + ); + + await expectLater( + app.getAuthIdToken(), + throwsA( + isA() + .having((e) => e.plugin, 'plugin', 'core') + .having((e) => e.code, 'code', 'auth-token-failed') + .having( + (e) => e.message, + 'message', + 'A network error has occurred.', + ), + ), + ); + }); + }); + + group('getAppCheckToken', () { + test('maps the native answer and defaults to a regular token', () async { + native.appCheckToken = CoreAppCheckInteropToken( + token: 'app-check-token', + ); + + expect( + await app.getAppCheckToken(), + const AppCheckInteropToken(token: 'app-check-token'), + ); + expect(native.calls, ['getAppCheckToken(testApp, limitedUse: false)']); + }); + + test('passes limitedUse through', () async { + native.appCheckToken = CoreAppCheckInteropToken( + token: 'limited-use-token', + ); + + await app.getAppCheckToken(limitedUse: true); + + expect(native.calls, ['getAppCheckToken(testApp, limitedUse: true)']); + }); + + test('keeps the placeholder and the error together', () async { + native.appCheckToken = CoreAppCheckInteropToken( + token: 'placeholder', + error: 'App Check is not activated.', + ); + + expect( + await app.getAppCheckToken(), + const AppCheckInteropToken( + token: 'placeholder', + error: 'App Check is not activated.', + ), + ); + }); + + test('returns null when App Check is not linked', () async { + expect(await app.getAppCheckToken(), isNull); + }); + }); + + group('getMessagingToken', () { + test('asks native for this app and returns its token', () async { + native.messagingToken = 'fcm-token'; + + expect(await app.getMessagingToken(), 'fcm-token'); + expect(native.calls, ['getMessagingToken(testApp)']); + }); + + test('returns null when Messaging has nothing to give', () async { + expect(await app.getMessagingToken(), isNull); + }); + }); + + group('on Windows', () { + setUp(() { + debugDefaultTargetPlatformOverride = TargetPlatform.windows; + }); + + tearDown(() { + debugDefaultTargetPlatformOverride = null; + }); + + test('every call is null and native is never asked', () async { + native + ..authIdToken = 'id-token' + ..appCheckToken = CoreAppCheckInteropToken(token: 'app-check-token') + ..messagingToken = 'fcm-token'; + + expect(await app.getAuthIdToken(), isNull); + expect(await app.getAppCheckToken(), isNull); + expect(await app.getMessagingToken(), isNull); + expect(native.calls, isEmpty); + }); + }); + }); +} + +/// Stands in for the native side of [FirebaseTokenHostApi]. +class FakeFirebaseTokenHostApi implements TestFirebaseTokenHostApi { + String? authIdToken; + CoreAppCheckInteropToken? appCheckToken; + String? messagingToken; + + /// Thrown by every call when set, the way native reports a failure. + PlatformException? failure; + + final List calls = []; + + @override + Future getAuthIdToken(String appName) async { + calls.add('getAuthIdToken($appName)'); + _failIfRequested(); + return authIdToken; + } + + @override + Future getAppCheckToken( + String appName, + bool limitedUse, + ) async { + calls.add('getAppCheckToken($appName, limitedUse: $limitedUse)'); + _failIfRequested(); + return appCheckToken; + } + + @override + Future getMessagingToken(String appName) async { + calls.add('getMessagingToken($appName)'); + _failIfRequested(); + return messagingToken; + } + + void _failIfRequested() { + final failure = this.failure; + if (failure != null) { + throw failure; + } + } +} diff --git a/packages/firebase_core/firebase_core_platform_interface/test/platform_interface_tests/interop_tokens_test.dart b/packages/firebase_core/firebase_core_platform_interface/test/platform_interface_tests/interop_tokens_test.dart new file mode 100644 index 000000000000..d5d2d55ef909 --- /dev/null +++ b/packages/firebase_core/firebase_core_platform_interface/test/platform_interface_tests/interop_tokens_test.dart @@ -0,0 +1,55 @@ +// Copyright 2026 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'package:firebase_core_platform_interface/firebase_core_platform_interface.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + const options = FirebaseOptions( + apiKey: 'apiKey', + appId: 'appId', + messagingSenderId: 'messagingSenderId', + projectId: 'projectId', + ); + + group('$FirebaseAppPlatform interop token defaults', () { + final app = FirebaseAppPlatform('testApp', options); + + test('getAuthIdToken is unimplemented', () { + expect(app.getAuthIdToken, throwsUnimplementedError); + }); + + test('getAppCheckToken is unimplemented', () { + expect(app.getAppCheckToken, throwsUnimplementedError); + }); + + test('getMessagingToken is unimplemented', () { + expect(app.getMessagingToken, throwsUnimplementedError); + }); + }); + + group('$AppCheckInteropToken', () { + test('compares by value', () { + expect( + const AppCheckInteropToken(token: 'a', error: 'e'), + const AppCheckInteropToken(token: 'a', error: 'e'), + ); + expect( + const AppCheckInteropToken(token: 'a'), + isNot(const AppCheckInteropToken(token: 'a', error: 'e')), + ); + expect( + const AppCheckInteropToken(token: 'a').hashCode, + const AppCheckInteropToken(token: 'a').hashCode, + ); + }); + + test('toString does not print the token', () { + const token = AppCheckInteropToken(token: 'secret', error: 'reason'); + + expect(token.toString(), isNot(contains('secret'))); + expect(token.toString(), contains('reason')); + }); + }); +} diff --git a/packages/firebase_core/firebase_core_web/lib/firebase_core_web.dart b/packages/firebase_core/firebase_core_web/lib/firebase_core_web.dart index ad0a67e97a2f..df603a35c3eb 100644 --- a/packages/firebase_core/firebase_core_web/lib/firebase_core_web.dart +++ b/packages/firebase_core/firebase_core_web/lib/firebase_core_web.dart @@ -15,6 +15,7 @@ import 'package:meta/meta.dart'; import 'package:web/web.dart' as web; import 'src/interop/core.dart' as firebase; +import 'src/interop_token_provider.dart'; part 'src/firebase_app_web.dart'; part 'src/firebase_core_web.dart'; diff --git a/packages/firebase_core/firebase_core_web/lib/src/firebase_app_web.dart b/packages/firebase_core/firebase_core_web/lib/src/firebase_app_web.dart index 5b3b539dcfd6..51a2ab1fd871 100644 --- a/packages/firebase_core/firebase_core_web/lib/src/firebase_app_web.dart +++ b/packages/firebase_core/firebase_core_web/lib/src/firebase_app_web.dart @@ -49,4 +49,23 @@ class FirebaseAppWeb extends FirebaseAppPlatform { Future setAutomaticResourceManagementEnabled(bool enabled) { return Future.value(); } + + @override + Future getAuthIdToken() async { + return InteropTokenProvider.forApp(name).getAuthIdToken(); + } + + @override + Future getAppCheckToken({ + bool limitedUse = false, + }) async { + return InteropTokenProvider.forApp( + name, + ).getAppCheckToken(limitedUse: limitedUse); + } + + @override + Future getMessagingToken() async { + return InteropTokenProvider.forApp(name).getMessagingToken(); + } } diff --git a/packages/firebase_core/firebase_core_web/lib/src/interop/core_interop.dart b/packages/firebase_core/firebase_core_web/lib/src/interop/core_interop.dart index c4f3be7aa58e..ba772197b8e4 100644 --- a/packages/firebase_core/firebase_core_web/lib/src/interop/core_interop.dart +++ b/packages/firebase_core/firebase_core_web/lib/src/interop/core_interop.dart @@ -37,6 +37,23 @@ external void registerVersion( JSString? variant, ]); +/// The provider for the component named [name] in [app]'s container. Internal +/// to the JS SDK; how its modules reach each other's components. +@JS('_getProvider') +external ProviderJsImpl getProvider(AppJsImpl app, JSString name); + +/// A component provider of the Firebase JS SDK. +extension type ProviderJsImpl._(JSObject _) implements JSObject { + /// The component's instance. With `optional: true`, null when the module that + /// registers the component isn't loaded or hasn't been initialized. + external JSObject? getImmediate(ProviderGetImmediateOptions options); +} + +/// Options for [ProviderJsImpl.getImmediate]. +extension type ProviderGetImmediateOptions._(JSObject _) implements JSObject { + external factory ProviderGetImmediateOptions({bool optional}); +} + /// FirebaseError is a subclass of the standard Error object. /// In addition to a message string, it contains a string-valued code. /// diff --git a/packages/firebase_core/firebase_core_web/lib/src/interop_token_provider.dart b/packages/firebase_core/firebase_core_web/lib/src/interop_token_provider.dart new file mode 100644 index 000000000000..3db0950a3a6e --- /dev/null +++ b/packages/firebase_core/firebase_core_web/lib/src/interop_token_provider.dart @@ -0,0 +1,163 @@ +// Copyright 2026 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'dart:js_interop'; +import 'dart:js_interop_unsafe'; + +import 'package:firebase_core_platform_interface/firebase_core_platform_interface.dart'; +import 'package:web/web.dart' as web; + +import 'interop/core.dart' as firebase; +import 'interop/utils/es6_interop.dart'; + +/// Fetches the Auth, App Check and FCM tokens through the internal components +/// the Firebase JS SDK modules register, as the JS Functions SDK does. A null +/// token means the module isn't loaded or has nothing to give, never failure. +class InteropTokenProvider { + /// Creates a provider over [getComponent]; [notificationsGranted] gates the + /// Messaging lookup. + InteropTokenProvider({ + required this._getComponent, + required this._notificationsGranted, + }); + + /// Throws [noAppExists] when there is no app named [appName]. + factory InteropTokenProvider.forApp(String appName) { + final firebase.AppJsImpl app; + try { + app = firebase.app(appName).jsObject; + } catch (_) { + throw noAppExists(appName); + } + return InteropTokenProvider( + getComponent: (name) => firebase + .getProvider(app, name.toJS) + .getImmediate(firebase.ProviderGetImmediateOptions(optional: true)), + notificationsGranted: _browserNotificationsGranted, + ); + } + + final JSObject? Function(String name) _getComponent; + final bool Function() _notificationsGranted; + + /// The signed-in user's ID token, or null when Auth isn't loaded or nobody is + /// signed in. Throws `auth-token-failed` when Auth fails. + Future getAuthIdToken() async { + final auth = _getComponent('auth-internal') as _AuthInternal?; + if (auth == null) { + return null; + } + try { + final token = await auth.getToken().toDart; + return token?.accessToken.toDart; + } catch (error) { + throw FirebaseException( + plugin: 'core', + code: 'auth-token-failed', + message: _messageOf(error), + ); + } + } + + /// App Check's answer, or null until App Check is activated. On failure, the + /// SDK's placeholder token and the reason. + Future getAppCheckToken({ + required bool limitedUse, + }) async { + final appCheck = _getComponent('app-check-internal') as _AppCheckInternal?; + if (appCheck == null) { + return null; + } + try { + final result = + await (limitedUse + ? appCheck.getLimitedUseToken() + : appCheck.getToken()) + .toDart; + final error = result.error; + return AppCheckInteropToken( + token: result.token.toDart, + error: error == null ? null : (error.message?.toDart ?? '$error'), + ); + } catch (error) { + throw FirebaseException( + plugin: 'core', + code: 'app-check-token-failed', + message: _messageOf(error), + ); + } + } + + /// The FCM registration token, or null when Messaging isn't loaded, the user + /// hasn't allowed notifications, or Messaging can't produce one. + Future getMessagingToken() async { + // Messaging's getToken() prompts while permission is undecided. + if (!_notificationsGranted()) { + return null; + } + final messaging = + _getComponent('messaging-internal') as _MessagingInternal?; + if (messaging == null) { + return null; + } + try { + return (await messaging.getToken().toDart).toDart; + } catch (_) { + // The JS Functions SDK sends no token when Messaging fails. + return null; + } + } +} + +/// Whether the page may show notifications, without asking the user. +bool _browserNotificationsGranted() => + globalContext.has('Notification') && + web.Notification.permission == 'granted'; + +/// The message of a JS error thrown by an SDK, or the error itself otherwise. +String _messageOf(Object error) { + // JSError is a @staticInterop class, so `is` matches any JS object. That is + // the intent here; the lint can't tell. + // ignore: invalid_runtime_check_with_js_interop_types + if (error is JSError) { + final message = error.message?.toDart; + if (message != null) { + return message; + } + } + return '$error'; +} + +/// `auth-internal`, Auth's internal component. +extension type _AuthInternal._(JSObject _) implements JSObject { + /// Resolves to null when nobody is signed in. + external JSPromise<_AuthToken?> getToken(); +} + +extension type _AuthToken._(JSObject _) implements JSObject { + external JSString get accessToken; +} + +/// `app-check-internal`, App Check's internal component. +extension type _AppCheckInternal._(JSObject _) implements JSObject { + external JSPromise<_AppCheckTokenResult> getToken(); + + external JSPromise<_AppCheckTokenResult> getLimitedUseToken(); +} + +extension type _AppCheckTokenResult._(JSObject _) implements JSObject { + /// The token, or App Check's placeholder when [error] is set. + external JSString get token; + + external _ErrorLike? get error; +} + +extension type _ErrorLike._(JSObject _) implements JSObject { + external JSString? get message; +} + +/// `messaging-internal`, Messaging's internal component. +extension type _MessagingInternal._(JSObject _) implements JSObject { + external JSPromise getToken(); +} diff --git a/packages/firebase_core/firebase_core_web/test/interop_token_provider_test.dart b/packages/firebase_core/firebase_core_web/test/interop_token_provider_test.dart new file mode 100644 index 000000000000..48279b49af38 --- /dev/null +++ b/packages/firebase_core/firebase_core_web/test/interop_token_provider_test.dart @@ -0,0 +1,309 @@ +// Copyright 2026 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +@TestOn('browser') +library; + +import 'dart:js_interop'; +import 'dart:js_interop_unsafe'; + +import 'package:firebase_core_platform_interface/firebase_core_platform_interface.dart'; +import 'package:firebase_core_web/firebase_core_web.dart'; +import 'package:firebase_core_web/src/interop/core.dart' as firebase; +import 'package:firebase_core_web/src/interop_token_provider.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('with stand-in components', () { + late Map loaded; + late List calls; + late bool notificationsGranted; + late InteropTokenProvider provider; + + setUp(() { + loaded = {}; + calls = []; + notificationsGranted = false; + provider = InteropTokenProvider( + getComponent: (name) => loaded[name], + notificationsGranted: () => notificationsGranted, + ); + }); + + JSObject component(Map Function()> methods) { + final object = JSObject(); + methods.forEach((name, method) { + object[name] = (() { + calls.add(name); + return method(); + }).toJS; + }); + return object; + } + + group('getAuthIdToken', () { + test('is null when Auth is not loaded', () async { + expect(await provider.getAuthIdToken(), isNull); + }); + + test('is null when nobody is signed in', () async { + loaded['auth-internal'] = component({'getToken': () => _resolve(null)}); + + expect(await provider.getAuthIdToken(), isNull); + }); + + test("is the signed-in user's access token", () async { + loaded['auth-internal'] = component({ + 'getToken': () => + _resolve(JSObject()..['accessToken'] = 'id-token'.toJS), + }); + + expect(await provider.getAuthIdToken(), 'id-token'); + }); + + test("throws a core FirebaseException with Auth's message", () async { + loaded['auth-internal'] = component({ + 'getToken': () => _reject('A network error has occurred.'), + }); + + await expectLater( + provider.getAuthIdToken(), + throwsA( + isA() + .having((e) => e.plugin, 'plugin', 'core') + .having((e) => e.code, 'code', 'auth-token-failed') + .having( + (e) => e.message, + 'message', + 'A network error has occurred.', + ), + ), + ); + }); + }); + + group('getAppCheckToken', () { + test('is null when App Check is not loaded or activated', () async { + expect(await provider.getAppCheckToken(limitedUse: false), isNull); + }); + + test('carries the token', () async { + loaded['app-check-internal'] = component({ + 'getToken': () => + _resolve(JSObject()..['token'] = 'app-check-token'.toJS), + }); + + expect( + await provider.getAppCheckToken(limitedUse: false), + const AppCheckInteropToken(token: 'app-check-token'), + ); + expect(calls, ['getToken']); + }); + + test('carries the placeholder and the error together', () async { + loaded['app-check-internal'] = component({ + 'getToken': () => _resolve( + JSObject() + ..['token'] = 'placeholder'.toJS + ..['error'] = _jsError('AppCheck: Fetch server returned 403.'), + ), + }); + + expect( + await provider.getAppCheckToken(limitedUse: false), + const AppCheckInteropToken( + token: 'placeholder', + error: 'AppCheck: Fetch server returned 403.', + ), + ); + }); + + test('asks for a limited-use token on request', () async { + loaded['app-check-internal'] = component({ + 'getToken': () => _resolve(JSObject()..['token'] = 'regular'.toJS), + 'getLimitedUseToken': () => + _resolve(JSObject()..['token'] = 'limited-use'.toJS), + }); + + final answer = await provider.getAppCheckToken(limitedUse: true); + + expect(answer?.token, 'limited-use'); + expect(calls, ['getLimitedUseToken']); + }); + }); + + group('getMessagingToken', () { + test( + 'is null, without asking Messaging, until notifications are allowed', + () async { + loaded['messaging-internal'] = component({ + 'getToken': () => _resolve('fcm-token'.toJS), + }); + + expect(await provider.getMessagingToken(), isNull); + expect(calls, isEmpty); + }, + ); + + test('is null when Messaging is not loaded', () async { + notificationsGranted = true; + + expect(await provider.getMessagingToken(), isNull); + }); + + test('is the token once notifications are allowed', () async { + notificationsGranted = true; + loaded['messaging-internal'] = component({ + 'getToken': () => _resolve('fcm-token'.toJS), + }); + + expect(await provider.getMessagingToken(), 'fcm-token'); + }); + + test( + 'is null when Messaging fails, as in the JS Functions SDK', + () async { + notificationsGranted = true; + loaded['messaging-internal'] = component({ + 'getToken': () => _reject('Messaging: permission-blocked'), + }); + + expect(await provider.getMessagingToken(), isNull); + }, + ); + }); + }); + + // Loads the real Firebase JS SDK files, as firebase_core_web does, so these + // tests check the lookups against the components the SDK registers. + group('with the Firebase JS SDK', () { + late FirebaseCoreWeb coreWeb; + late FirebaseAppPlatform app; + + JSObject module(String windowVariable) => + globalContext[windowVariable]! as JSObject; + + JSObject jsApp() => + module('firebase_core').callMethod('getApp'.toJS); + + Future load(String product) => coreWeb.injectSrcScript( + 'https://www.gstatic.com/firebasejs/' + '${coreWeb.firebaseSDKVersion}/firebase-$product.js', + 'firebase_${product.replaceAll('-', '_')}', + ); + + setUpAll(() async { + FirebasePlatform.instance = coreWeb = FirebaseCoreWeb(); + await load('app'); + await FirebasePlatform.instance.initializeApp( + options: const FirebaseOptions( + apiKey: 'fake-api-key', + appId: '1:1234567890:web:fake', + messagingSenderId: '1234567890', + projectId: 'fake-project', + ), + ); + app = FirebasePlatform.instance.app(); + }); + + test('every token is null when only firebase-app.js is loaded', () async { + expect(await app.getAuthIdToken(), isNull); + expect(await app.getAppCheckToken(), isNull); + expect(await app.getMessagingToken(), isNull); + }); + + test( + "a signed-out user's token is null once Auth is initialized", + () async { + await load('auth'); + module('firebase_auth').callMethod('getAuth'.toJS, jsApp()); + + final authInternal = firebase + .getProvider(firebase.app().jsObject, 'auth-internal'.toJS) + .getImmediate(firebase.ProviderGetImmediateOptions(optional: true)); + expect( + authInternal, + isNotNull, + reason: 'Auth registered its component', + ); + expect(await app.getAuthIdToken(), isNull); + }, + ); + + test("the token is App Check's once App Check is activated", () async { + await load('app-check'); + expect( + await app.getAppCheckToken(), + isNull, + reason: 'App Check is loaded but not activated yet', + ); + + final appCheck = module('firebase_app_check'); + final customProvider = (appCheck['CustomProvider']! as JSFunction) + .callAsConstructor( + JSObject() + ..['getToken'] = (() => _resolve( + JSObject() + ..['token'] = 'custom-app-check-token'.toJS + ..['expireTimeMillis'] = DateTime.now() + .add(const Duration(hours: 1)) + .millisecondsSinceEpoch + .toJS, + )).toJS, + ); + appCheck.callMethod( + 'initializeAppCheck'.toJS, + jsApp(), + JSObject() + ..['provider'] = customProvider + ..['isTokenAutoRefreshEnabled'] = false.toJS, + ); + + expect( + await app.getAppCheckToken(), + const AppCheckInteropToken(token: 'custom-app-check-token'), + ); + expect( + (await app.getAppCheckToken(limitedUse: true))?.token, + 'custom-app-check-token', + ); + }); + + test( + 'the Messaging token is null while notifications are not allowed', + () async { + await load('messaging'); + + expect(await app.getMessagingToken(), isNull); + }, + ); + + test('a deleted app fails with no-app', () async { + await FirebasePlatform.instance.initializeApp( + name: 'deleted', + options: app.options, + ); + final deleted = FirebasePlatform.instance.app('deleted'); + await deleted.delete(); + + await expectLater( + deleted.getAuthIdToken(), + throwsA( + isA().having((e) => e.code, 'code', 'no-app'), + ), + ); + }); + }); +} + +JSPromise _resolve(JSAny? value) => Future.value(value).toJS; + +JSPromise _reject(String message) => + (globalContext['Promise']! as JSObject).callMethod>( + 'reject'.toJS, + _jsError(message), + ); + +JSObject _jsError(String message) => (globalContext['Error']! as JSFunction) + .callAsConstructor(message.toJS); diff --git a/tests/integration_test/firebase_core/firebase_core_e2e_test.dart b/tests/integration_test/firebase_core/firebase_core_e2e_test.dart index 075095927417..587169ad82da 100644 --- a/tests/integration_test/firebase_core/firebase_core_e2e_test.dart +++ b/tests/integration_test/firebase_core/firebase_core_e2e_test.dart @@ -2,6 +2,7 @@ // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. +import 'package:firebase_auth/firebase_auth.dart'; import 'package:firebase_core/firebase_core.dart'; import 'package:firebase_core_platform_interface/firebase_core_platform_interface.dart'; import 'package:flutter/foundation.dart'; @@ -84,5 +85,94 @@ void main() { expect(app.name, demoProjectId); expect(app.options.projectId, demoProjectId); }); + + // The tests app links the Auth, App Check and Messaging plugins, so every + // lookup has an SDK to ask. Auth uses the emulator CI starts for this suite. + // Windows has no token lookup yet and answers null, so only the null checks + // run there. Each test carries its own skip: a test's `skip:` argument + // replaces the group's, so a group-level skip wouldn't reach them. + group('interop tokens', () { + late FirebaseAppPlatform defaultApp; + + setUpAll(() async { + defaultApp = FirebasePlatform.instance.app(); + await FirebaseAuth.instance.useAuthEmulator('localhost', 9099); + }); + + tearDown(() => FirebaseAuth.instance.signOut()); + + test('getAuthIdToken is null when nobody is signed in', () async { + await FirebaseAuth.instance.signOut(); + + expect(await defaultApp.getAuthIdToken(), isNull); + }); + + test( + "getAuthIdToken is the signed-in user's ID token", + () async { + final credential = await FirebaseAuth.instance.signInAnonymously(); + final idToken = await credential.user!.getIdToken(); + + expect(await defaultApp.getAuthIdToken(), idToken); + }, + // Signing in needs the keychain, which the unsigned macOS test app + // can't use, as in the firebase_auth suite. Windows has no lookup. + skip: + !kIsWeb && + (defaultTargetPlatform == TargetPlatform.macOS || + defaultTargetPlatform == TargetPlatform.windows), + ); + + test( + 'getAppCheckToken answers with a placeholder before activation', + () async { + // App Check is never activated here, so the SDK answers with its + // placeholder. + final answer = await defaultApp.getAppCheckToken(); + + expect(answer, isNotNull); + expect(answer!.token, isNotEmpty); + expect(answer.error, isNotNull); + }, + // Web is covered by the next test; Windows has no lookup. + skip: kIsWeb || defaultTargetPlatform == TargetPlatform.windows, + ); + + test('getAppCheckToken is null on web before activation', () async { + // The JS SDK creates App Check's token service only on activation. + expect(await defaultApp.getAppCheckToken(), isNull); + }, skip: !kIsWeb); + + test( + 'getMessagingToken is null for an app other than the default', + () async { + // Messaging only serves the default app. + final secondary = await Firebase.initializeApp( + name: 'InteropTokensApp', + options: DefaultFirebaseOptions.currentPlatform, + ); + addTearDown(secondary.delete); + + expect( + await FirebasePlatform.instance + .app('InteropTokensApp') + .getMessagingToken(), + isNull, + ); + }, + // Android's Instance ID library answers for any app, over the + // network; web is covered by the next test. + skip: kIsWeb || defaultTargetPlatform == TargetPlatform.android, + ); + + test( + 'getMessagingToken is null on web without notification permission', + () async { + // CI's browser never grants notification permission. + expect(await defaultApp.getMessagingToken(), isNull); + }, + skip: !kIsWeb, + ); + }); }); }