Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/android_unit_tests.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
13 changes: 13 additions & 0 deletions packages/firebase_core/firebase_core/android/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ android {

sourceSets {
main.java.srcDirs += "src/main/kotlin"
test.java.srcDirs += "src/test/kotlin"
}

buildFeatures {
Expand All @@ -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
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,26 +13,30 @@ 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
}

override fun onDetachedFromEngine(binding: FlutterPluginBinding) {
applicationContext = null
FirebaseCoreHostApi.setUp(binding.binaryMessenger, null)
FirebaseAppHostApi.setUp(binding.binaryMessenger, null)
FirebaseTokenHostApi.setUp(binding.binaryMessenger, null)
}

private fun firebaseOptionsToPigeon(options: FirebaseOptions): CoreFirebaseOptions {
Expand Down Expand Up @@ -252,4 +256,56 @@ class FlutterFirebaseCorePlugin : FlutterPlugin, FirebaseCoreHostApi, FirebaseAp

listenToResponse(taskCompletionSource, callback)
}

override fun getAuthIdToken(appName: String, callback: (Result<String?>) -> Unit) {
respondWithToken("auth-token-failed", callback) {
InteropTokenProvider.forApp(appName, cachedThreadPool).getAuthIdToken()
}
}

override fun getAppCheckToken(
appName: String,
limitedUse: Boolean,
callback: (Result<CoreAppCheckInteropToken?>) -> Unit
) {
respondWithToken("app-check-token-failed", callback) {
InteropTokenProvider.forApp(appName, cachedThreadPool).getAppCheckToken(limitedUse)
}
}

override fun getMessagingToken(appName: String, callback: (Result<String?>) -> 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 <T> respondWithToken(
failureCode: String,
callback: (Result<T>) -> Unit,
fetch: () -> Task<T>
) {
val taskCompletionSource = TaskCompletionSource<T>()

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)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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<Any?>): CoreAppCheckInteropToken {
val token = pigeonVar_list[0] as String
val error = pigeonVar_list[1] as String?
return CoreAppCheckInteropToken(token, error)
}
}

fun toList(): List<Any?> {
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) {
Expand All @@ -373,6 +415,9 @@ private open class GeneratedAndroidFirebaseCorePigeonCodec : StandardMessageCode
130.toByte() -> {
return (readValue(buffer) as? List<Any?>)?.let { CoreInitializeResponse.fromList(it) }
}
131.toByte() -> {
return (readValue(buffer) as? List<Any?>)?.let { CoreAppCheckInteropToken.fromList(it) }
}
else -> super.readValueOfType(type, buffer)
}
}
Expand All @@ -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)
}
}
Expand Down Expand Up @@ -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<String?>) -> Unit)

fun getAppCheckToken(
appName: String,
limitedUse: Boolean,
callback: (Result<CoreAppCheckInteropToken?>) -> Unit
)

fun getMessagingToken(appName: String, callback: (Result<String?>) -> Unit)

companion object {
/** The codec used by FirebaseTokenHostApi. */
val codec: MessageCodec<Any?> 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<Any?>(
binaryMessenger,
"dev.flutter.pigeon.firebase_core_platform_interface.FirebaseTokenHostApi.getAuthIdToken$separatedMessageChannelSuffix",
codec)
if (api != null) {
channel.setMessageHandler { message, reply ->
val args = message as List<Any?>
val appNameArg = args[0] as String
api.getAuthIdToken(appNameArg) { result: Result<String?> ->
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<Any?>(
binaryMessenger,
"dev.flutter.pigeon.firebase_core_platform_interface.FirebaseTokenHostApi.getAppCheckToken$separatedMessageChannelSuffix",
codec)
if (api != null) {
channel.setMessageHandler { message, reply ->
val args = message as List<Any?>
val appNameArg = args[0] as String
val limitedUseArg = args[1] as Boolean
api.getAppCheckToken(appNameArg, limitedUseArg) {
result: Result<CoreAppCheckInteropToken?> ->
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<Any?>(
binaryMessenger,
"dev.flutter.pigeon.firebase_core_platform_interface.FirebaseTokenHostApi.getMessagingToken$separatedMessageChannelSuffix",
codec)
if (api != null) {
channel.setMessageHandler { message, reply ->
val args = message as List<Any?>
val appNameArg = args[0] as String
api.getMessagingToken(appNameArg) { result: Result<String?> ->
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)
}
}
}
}
}
Original file line number Diff line number Diff line change
@@ -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 <reified T> 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<String?> {
val auth = get<InternalAuthProvider>() ?: 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<CoreAppCheckInteropToken?> {
val appCheck = get<InteropAppCheckTokenProvider>() ?: 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<String?> {
val instanceId = get<FirebaseInstanceIdInternal>() ?: return Tasks.forResult(null)
val taskCompletionSource = TaskCompletionSource<String?>()
executor.execute {
try {
taskCompletionSource.setResult(instanceId.token)
} catch (e: Exception) {
taskCompletionSource.setException(e)
}
}
return taskCompletionSource.task
}
Comment on lines +74 to +85

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Instead of manually executing a blocking call on the executor and using a TaskCompletionSource, you can leverage the asynchronous tokenTask property already provided by FirebaseInstanceIdInternal. This avoids blocking a thread in the executor pool and simplifies the implementation.

  fun getMessagingToken(): Task<String?> {
    val instanceId = get<FirebaseInstanceIdInternal>() ?: return Tasks.forResult(null)
    return instanceId.tokenTask.continueWith(executor) { task ->
      if (task.isSuccessful) {
        task.result
      } else {
        throw task.exception ?: IllegalStateException("getMessagingToken failed")
      }
    }
  }

}
Loading
Loading