From 11b2ba30f1e1a2cdc63080fa4d5e886208727ffe Mon Sep 17 00:00:00 2001 From: jonathanedey Date: Wed, 11 Nov 2026 14:19:37 -0500 Subject: [PATCH 01/12] feat(core): add the interop token API to the platform interface Firebase packages that send their own requests (the Dart transport for `cloud_functions`) need the Auth, App Check and FCM tokens the native Functions SDK used to fetch for them, without depending on the Auth, App Check or Messaging plugins. This adds the API; the native and web implementations follow. - `FirebaseAppPlatform` gains three per-app calls: `getAuthIdToken()`, `getAppCheckToken({limitedUse})` and `getMessagingToken()`. Each returns null when the SDK isn't linked or has nothing to give; null never means failure. An Auth failure throws a core `FirebaseException` with the SDK's message. An App Check failure comes back as `AppCheckInteropToken(token, error)`: the SDK's placeholder plus the reason, as the native SDKs report it. - `MethodChannelFirebaseApp` implements them through a new Pigeon host API, `FirebaseTokenHostApi`, rather than `FirebaseAppHostApi`: other packages' tests implement `TestFirebaseAppHostApi` and would break. Native failures surface as `FirebaseException(plugin: 'core')` with the code and message native chose. - Generated code is regenerated with Pigeon 26.3.4 (Dart, Kotlin, Swift, C++). No native plugin registers the new API yet, so nothing changes at runtime. Tested with `flutter test` in `firebase_core_platform_interface`: the defaults and the value type, and a `TestFirebaseTokenHostApi` fake that drives token, null, failure and `limitedUse` cases for each call. --- .../core/GeneratedAndroidFirebaseCore.g.kt | 159 +++++++++++ .../FirebaseCoreMessages.g.swift | 131 +++++++++ .../firebase_core/windows/messages.g.cpp | 257 ++++++++++++++++++ .../firebase_core/windows/messages.g.h | 83 ++++++ .../lib/firebase_core_platform_interface.dart | 1 + .../lib/src/app_check_interop_token.dart | 38 +++ .../method_channel_firebase_app.dart | 40 +++ .../lib/src/pigeon/messages.pigeon.dart | 137 ++++++++++ .../lib/src/pigeon/test_api.dart | 132 +++++++++ .../platform_interface_firebase_app.dart | 42 +++ .../pigeons/messages.dart | 26 ++ .../method_channel_firebase_app_test.dart | 167 ++++++++++++ .../interop_tokens_test.dart | 55 ++++ 13 files changed, 1268 insertions(+) create mode 100644 packages/firebase_core/firebase_core_platform_interface/lib/src/app_check_interop_token.dart create mode 100644 packages/firebase_core/firebase_core_platform_interface/test/method_channel_tests/method_channel_firebase_app_test.dart create mode 100644 packages/firebase_core/firebase_core_platform_interface/test/platform_interface_tests/interop_tokens_test.dart 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/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/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..6c178ca70d02 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,42 @@ 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 failure reported by the native plugin as a [FirebaseException] + /// for plugin `core`, keeping the code and message native chose. + Future _guardTokenCall(Future Function() call) async { + 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..50c62bb3892f 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,48 @@ 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, as the native SDKs report it. + /// With [limitedUse], the SDK issues a limited-use token instead of a cached + /// one. + /// + /// 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 and, on Apple and web, never generates a token. + /// Messaging only serves the default app, so other apps get `null`. + /// On Android, where fetching may hit the network, a failure throws a + /// [FirebaseException] for plugin `core` with code `messaging-token-failed`. + /// + /// 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..7a9ede5a4947 --- /dev/null +++ b/packages/firebase_core/firebase_core_platform_interface/test/method_channel_tests/method_channel_firebase_app_test.dart @@ -0,0 +1,167 @@ +// 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/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); + }); + }); + }); +} + +/// 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')); + }); + }); +} From 2e40493bc0255f35b5b9db75f8717861deab3f13 Mon Sep 17 00:00:00 2001 From: jonathanedey Date: Tue, 10 Nov 2026 14:54:59 -0500 Subject: [PATCH 02/12] feat(core): look up Auth, App Check and FCM tokens on Android Implements FirebaseTokenHostApi in the Android plugin the way the Functions SDK's FirebaseContextProvider gets its tokens: through the interop components the Auth, App Check and Instance ID SDKs register in the app's component container. - InteropTokenProvider looks each component up per call with FirebaseApp.get(), which returns null when no linked SDK registered it, so no registrar changes or deferred providers are needed. Auth: getAccessToken(false), signed out is null, other failures propagate. App Check: getToken(false) or getLimitedUseToken(), returning the SDK's token and error together, placeholder included. Messaging: FirebaseInstanceIdInternal.getToken() on the thread pool. - The plugin reports an SDK failure as a FlutterError with the SDK's message under auth-token-failed, app-check-token-failed or messaging-token-failed, which Dart surfaces as a core FirebaseException. - build.gradle adds firebase-auth-interop, firebase-appcheck-interop and firebase-iid-interop, interface-only artifacts the BoM does not manage, at the versions the BoM's own SDKs depend on. Only the deprecated firebase-iid library provides FirebaseInstanceIdInternal; firebase-messaging merely consumes it. The native Functions SDK depends on firebase-iid directly, which is why it sends an Instance ID token on every Android call. InteropTokenProvider matches that whenever firebase-iid is linked and returns null otherwise. Tested with JUnit fakes for the three interop interfaces (16 cases: not linked, signed out, token, failure, placeholder plus error, limited-use, no token yet) via tests/android, which the Android unit test workflow now runs for firebase_core, and by building the tests app APK with every plugin linked. --- .github/workflows/android_unit_tests.yaml | 2 +- .../firebase_core/android/build.gradle | 15 + .../core/FlutterFirebaseCorePlugin.kt | 55 +++- .../firebase/core/InteropTokenProvider.kt | 92 +++++++ .../firebase/core/InteropTokenProviderTest.kt | 256 ++++++++++++++++++ 5 files changed, 418 insertions(+), 2 deletions(-) create mode 100644 packages/firebase_core/firebase_core/android/src/main/kotlin/io/flutter/plugins/firebase/core/InteropTokenProvider.kt create mode 100644 packages/firebase_core/firebase_core/android/src/test/kotlin/io/flutter/plugins/firebase/core/InteropTokenProviderTest.kt 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 7711ae9943ca..830e128cf4e5 100644 --- a/packages/firebase_core/firebase_core/android/build.gradle +++ b/packages/firebase_core/firebase_core/android/build.gradle @@ -55,6 +55,7 @@ android { sourceSets { main.java.srcDirs += "src/main/kotlin" + test.java.srcDirs += "src/test/kotlin" } buildFeatures { @@ -69,7 +70,21 @@ android { implementation platform("com.google.firebase:firebase-bom:${getRootProjectExtOrDefaultProperty("FirebaseSDKVersion")}") implementation "com.google.firebase:firebase-common" + // Interfaces through which the Auth, App Check and Messaging SDKs hand + // tokens to other SDKs (see InteropTokenProvider). + // Interface-only; the BoM does not manage them, so the versions are the + // ones 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..ee2fc018b3d5 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,53 @@ 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 to Dart under [failureCode] + * with the SDK's message, so the Dart side can surface it as a core FirebaseException. + */ + 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: Exception) { + taskCompletionSource.setException(e) + } + } + + listenToResponse(taskCompletionSource, callback) + } } 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..14748249dccd --- /dev/null +++ b/packages/firebase_core/firebase_core/android/src/main/kotlin/io/flutter/plugins/firebase/core/InteropTokenProvider.kt @@ -0,0 +1,92 @@ +// 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 from whichever SDKs the app links, the way the + * Firebase Functions SDK's `FirebaseContextProvider` does. + * + * Each SDK registers an interop component in its app's component container when it is linked. + * [getComponent] looks a component up by interface and returns null when no linked SDK registered + * it, so a null token means "not linked" or "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 the Auth SDK isn't linked or nobody is signed in. + * Fails with the Auth SDK's exception when it can't produce a token. + */ + 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") + } + } + } + } + + /** + * The App Check SDK's answer, or null when App Check isn't linked. When the SDK can't produce a + * token, for example before it is activated, the answer carries its placeholder token and the + * reason, as the SDK reports it. + */ + 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 -> + Tasks.forResult( + CoreAppCheckInteropToken( + token = result.token, + error = result.error?.let { it.message ?: it.toString() }, + )) + } + } + + /** + * The FCM registration token, or null when nothing provides `FirebaseInstanceIdInternal`. + * + * Only the Instance ID library provides it, so this answers whenever that library is linked. + * `getToken()` blocks on the network when no token is cached yet, 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 + } +} From e4e4182179a3f5b27c7574f41896c56123a093b4 Mon Sep 17 00:00:00 2001 From: jonathanedey Date: Wed, 11 Nov 2026 10:38:40 -0500 Subject: [PATCH 03/12] feat(core): look up Auth, App Check and FCM tokens on Apple Implements FirebaseTokenHostApi in the iOS and macOS plugin the way the Functions SDK's FunctionsContextProvider gets its tokens: through the interop components the Auth, App Check and Messaging SDKs register in the app's component container. - FirebaseCoreExtension and the SDKs' interop modules are targets, not products, of the Firebase Swift package, so the plugin can't import them. InteropTokenProvider reaches the same Objective-C API by name: FIRApp's container property and __instanceForProtocol:, the call behind ComponentType.instance(for:in:), with each protocol looked up by its runtime name. When no linked binary declares the protocol, the SDK isn't linked and the answer is null. - The interop methods are declared in @objc protocols with the SDK headers' selectors and sent through Swift's AnyObject lookup, which skips the call when an object doesn't respond. Auth: getToken(forcingRefresh: false), signed out is null. App Check: getToken(forcingRefresh: false) or the optional getLimitedUseToken(completion:), with the token and error together. Messaging: the cached fcmToken, never a new one. - SDK failures reach Dart under the same codes as on Android, with the SDK's message. Replies go back on the main thread. Tested end to end by the tests app's core suite (next commit) on an iPhone simulator and on macOS, built with Swift Package Manager, and checked with swift-format lint. --- .../firebase_core/FLTFirebaseCorePlugin.swift | 68 ++++++++- .../firebase_core/InteropTokenProvider.swift | 143 ++++++++++++++++++ .../firebase_core/InteropTokenProvider.swift | 1 + 3 files changed, 211 insertions(+), 1 deletion(-) create mode 100644 packages/firebase_core/firebase_core/ios/firebase_core/Sources/firebase_core/InteropTokenProvider.swift create mode 120000 packages/firebase_core/firebase_core/macos/firebase_core/Sources/firebase_core/InteropTokenProvider.swift 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 33d5b130fc58..813a31c0e58d 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 @@ -24,7 +24,7 @@ private let kFLTFirebaseCoreChannelName = @objc(FLTFirebaseCorePlugin) public class FLTFirebaseCorePlugin: NSObject, FlutterPlugin, FLTFirebasePluginProtocol, - FirebaseCoreHostApi, FirebaseAppHostApi + FirebaseCoreHostApi, FirebaseAppHostApi, FirebaseTokenHostApi { private var coreInitialized = false @@ -64,6 +64,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) { @@ -259,4 +260,69 @@ 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())) + } + } + + /// Runs a token lookup for the app named `appName` and reports an SDK failure to Dart under + /// `failureCode` with the SDK's message, so the Dart side can surface it as a core + /// FirebaseException. 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/InteropTokenProvider.swift b/packages/firebase_core/firebase_core/ios/firebase_core/Sources/firebase_core/InteropTokenProvider.swift new file mode 100644 index 000000000000..d65ba7ffb8dc --- /dev/null +++ b/packages/firebase_core/firebase_core/ios/firebase_core/Sources/firebase_core/InteropTokenProvider.swift @@ -0,0 +1,143 @@ +// 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 from whichever SDKs the app links, the way the +/// Firebase Functions SDK's `FunctionsContextProvider` does. +/// +/// Each SDK registers an interop component in its app's component container when it is linked. +/// `getComponent` looks a component up by the name of its Objective-C protocol and returns nil +/// when no linked SDK registered it, so a nil token means "not linked" or "nothing to give", never +/// failure. +final class InteropTokenProvider { + private let getComponent: (String) -> AnyObject? + + init(getComponent: @escaping (String) -> AnyObject?) { + self.getComponent = getComponent + } + + /// Looks tokens up in the component container of `app`. + /// + /// The container and the interop protocols are declared in `FirebaseCoreExtension` and the SDKs' + /// interop modules, which are not products of the Firebase Swift package, so this plugin can't + /// import them. It reaches the same Objective-C API by name instead: `FIRApp`'s `container` + /// property and `-[FIRComponentContainer __instanceForProtocol:]`, which is what + /// `ComponentType.instance(for:in:)` calls. + 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 the Auth SDK isn't linked or nobody is signed in. + /// Fails with the Auth SDK's error when it can't produce a token. + 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)) + } + } + + /// The App Check SDK's answer, or nil when App Check isn't linked. When the SDK can't produce a + /// token, for example before it is activated, the answer carries its placeholder token and the + /// reason, as the SDK reports it. + func getAppCheckToken( + limitedUse: Bool, + completion: @escaping (Result) -> Void + ) { + let appCheck = getComponent(appCheckInteropProtocolName) + let handleResult: (AnyObject) -> Void = { result in + guard let token = result.interopToken else { + completion(.success(nil)) + return + } + let error: NSError? = result.interopError ?? nil + completion( + .success( + CoreAppCheckInteropToken( + token: token, + error: error?.localizedDescription + ))) + } + // `getLimitedUseToken(completion:)` is optional in the protocol; an SDK without it has no + // limited-use token to give, as in the Functions SDK. + let started: Void? = + limitedUse + ? appCheck?.interopGetLimitedUseToken?(completion: handleResult) + : appCheck?.interopGetToken?(forcingRefresh: false, completion: handleResult) + if started == nil { + completion(.success(nil)) + } + } + + /// The FCM registration token the Messaging SDK has cached, or nil when Messaging isn't linked + /// or has no token yet. Like the Functions SDK, this never asks for a new token. + func getMessagingToken() -> String? { + let token: String?? = getComponent(messagingInteropProtocolName)?.interopFCMToken + return token ?? nil + } +} + +// The Objective-C runtime names of the interop protocols (Swift sees them as `AuthInterop`, +// `AppCheckInterop` and `MessagingInterop`). +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, declared here because their headers can't be imported (see +// `InteropTokenProvider.forApp`). The selectors match the SDK headers named below. The SDKs' +// objects don't conform to these protocols: Swift's `AnyObject` lookup sends the selectors to them +// directly and skips the call when an object doesn't respond. + +/// `FIRAuthInterop`, in FirebaseAuth/Interop/Public/FirebaseAuthInterop/FIRAuthInterop.h. +@objc private protocol AuthInteropMethods { + @objc(getTokenForcingRefresh:withCallback:) + func interopGetToken(forcingRefresh: Bool, callback: @escaping (String?, Error?) -> Void) +} + +/// `FIRAppCheckInterop`, in FirebaseAppCheck/Interop/Public/FirebaseAppCheckInterop/ +/// 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`, in the same directory. +@objc private protocol AppCheckTokenResultProperties { + @objc(token) var interopToken: String { get } + @objc(error) var interopError: NSError? { get } +} + +/// `FIRMessagingInterop`, in FirebaseMessaging/Interop/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 From 8c3e7e56407c6a4cc3131a27606696c3a77bd16a Mon Sep 17 00:00:00 2001 From: jonathanedey Date: Wed, 11 Nov 2026 10:38:59 -0500 Subject: [PATCH 04/12] test(core): cover the interop tokens in the tests app core suite The tests app links every plugin, so its core suite can check the token lookups against the real Auth, App Check and Messaging SDKs. CI already runs it inside the Firebase emulators on every platform. - getAuthIdToken is null when signed out and equals the signed-in user's getIdToken() against the Auth emulator. Skipped on macOS, whose unsigned test app can't write the user to the keychain. - getAppCheckToken returns the SDK's placeholder and an error, as App Check is linked but never activated. - getMessagingToken is null for a secondary app, as Messaging serves only the default app. Skipped on Android, where the Instance ID library answers for any app over the network. - The group is skipped on web, whose implementation comes next, and on Windows, which has none. Passed locally on an iPhone simulator, on macOS and on an Android emulator. --- .../firebase_core/firebase_core_e2e_test.dart | 75 +++++++++++++++++++ 1 file changed, 75 insertions(+) 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..1b134a4c6970 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,79 @@ void main() { expect(app.name, demoProjectId); expect(app.options.projectId, demoProjectId); }); + + // The tests app links the Auth, App Check and Messaging plugins, so the + // native SDKs' interop components are in the container. Auth runs against + // the emulator that CI starts around this suite. + 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 persists the user to the keychain, which the unsigned + // macOS test app cannot write to (errSecMissingEntitlement), as in + // the firebase_auth suite. + skip: defaultTargetPlatform == TargetPlatform.macOS, + ); + + test( + 'getAppCheckToken answers with a placeholder before activation', + () async { + // App Check is linked but never activated in this app, so the SDK + // answers with its placeholder token and the reason. + final answer = await defaultApp.getAppCheckToken(); + + expect(answer, isNotNull); + expect(answer!.token, isNotEmpty); + expect(answer.error, isNotNull); + }, + ); + + 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, + ); + }, + // On Android the token comes from the Instance ID library, which + // answers for any app and fetches over the network. + skip: defaultTargetPlatform == TargetPlatform.android, + ); + }, + // No implementation on Windows yet; web lands separately. + skip: kIsWeb || defaultTargetPlatform == TargetPlatform.windows, + ); }); } From 30ae2baf5f77cb9ce29d1bff67004cf993fe9274 Mon Sep 17 00:00:00 2001 From: jonathanedey Date: Wed, 11 Nov 2026 14:28:19 -0500 Subject: [PATCH 05/12] feat(core): look up Auth, App Check and FCM tokens on web Implements the three token calls in firebase_core_web the way the JS Functions SDK's ContextProvider gets its tokens: through the internal components the Auth, App Check and Messaging modules register in the app's component container. - core_interop binds _getProvider, which firebase-app.js exports for the SDK's own modules. getImmediate({optional: true}) is null when a module isn't loaded or hasn't been initialized, so the answer is null in both cases. - InteropTokenProvider asks auth-internal for the signed-in user's token (null when signed out), app-check-internal for a token or a limited-use one (the placeholder and the error together, as the SDK reports them), and messaging-internal for the FCM token. - App Check's internal component only exists once App Check is activated, so before activation the answer is null, not the placeholder the native SDKs return. The JS Functions SDK sends no App Check token in that case either. - Messaging is asked only when notification permission is already granted, since its getToken() prompts while the permission is undecided; Messaging may then create a token, as it does for the JS Functions SDK. A Messaging failure gives null, as there. - An Auth failure, or an App Check call that rejects instead of answering (a limited-use request can), throws a core FirebaseException with the SDK's message under auth-token-failed or app-check-token-failed. A missing or deleted app fails with no-app. Tested with flutter test --platform chrome, with and without --wasm (17 new cases). Stand-in components cover each call's null, token and failure paths; the real JS SDK files cover modules not loaded, Auth signed out, App Check before and after activation (limited-use included), Messaging without permission, and a deleted app. --- .../lib/firebase_core_web.dart | 1 + .../lib/src/firebase_app_web.dart | 19 ++ .../lib/src/interop/core_interop.dart | 19 ++ .../lib/src/interop_token_provider.dart | 177 ++++++++++ .../test/interop_token_provider_test.dart | 309 ++++++++++++++++++ 5 files changed, 525 insertions(+) create mode 100644 packages/firebase_core/firebase_core_web/lib/src/interop_token_provider.dart create mode 100644 packages/firebase_core/firebase_core_web/test/interop_token_provider_test.dart 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..3c13f4418da7 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,25 @@ external void registerVersion( JSString? variant, ]); +/// The provider for the component named [name] in [app]'s component container. +/// +/// Internal to the Firebase JS SDK: its modules reach each other's components +/// through it, as the Functions SDK does for Auth, App Check and Messaging. +@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..12a7def61679 --- /dev/null +++ b/packages/firebase_core/firebase_core_web/lib/src/interop_token_provider.dart @@ -0,0 +1,177 @@ +// 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 from whichever Firebase JS SDK +/// modules the app loaded, the way the JS Functions SDK's `ContextProvider` +/// does. +/// +/// Each module registers an internal component in its app's component +/// container once it's loaded and initialized. `getComponent` looks one up by +/// name and returns null otherwise, so a null token means "not loaded" or +/// "nothing to give", never failure. +class InteropTokenProvider { + /// Creates a provider over `getComponent` that asks Messaging only when + /// `notificationsGranted` says the user has already allowed notifications. + InteropTokenProvider({ + required JSObject? Function(String name) getComponent, + required bool Function() notificationsGranted, + }) : _getComponent = getComponent, + _notificationsGranted = notificationsGranted; + + /// Looks tokens up in the component container of the app named [appName]. + /// + /// Throws [noAppExists] when there is no such app. + 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 a core [FirebaseException] with code `auth-token-failed` and Auth's + /// message when Auth fails to produce one. + 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 when App Check isn't loaded or hasn't been + /// activated. + /// + /// When App Check can't produce a token, the answer carries its placeholder + /// token and the reason, as the JS SDK reports them. + 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 { + // Checked before anything else: Messaging's getToken() would ask the user + // for permission while it's still 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) { + // isA on Object requires Dart 3.12; this package supports 3.10. + // 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`, the component Auth registers for other modules. +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`, the component App Check registers for other modules. +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`, the component Messaging registers for other modules. +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..e870a54da330 --- /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_js 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); From e12caa0b4fbb9295285b057ec5f931bf16612f42 Mon Sep 17 00:00:00 2001 From: jonathanedey Date: Wed, 11 Nov 2026 13:43:04 -0500 Subject: [PATCH 06/12] test(core): cover the interop tokens on web in the core suite The tests app's core suite now runs the interop token group on web too, where CI drives Chrome against the Firebase emulators as on the other platforms. - getAppCheckToken is null on web before activation: the JS SDK creates App Check's internal component only on activation, which this suite never does. The placeholder case stays native-only. - getMessagingToken is null on web for the default app: the test browser never grants notification permission, so the call returns without asking Messaging. The secondary-app case is skipped on web, where Messaging serves any app. - The macOS and Windows skips now check kIsWeb first, as the firebase_auth suite does: on web, defaultTargetPlatform is the browser's OS, so those skips would also skip web in such browsers. Not run locally, as there is no chromedriver here; the e2e-smoke web and web-wasm jobs run it. --- .../firebase_core/firebase_core_e2e_test.dart | 34 +++++++++++++++---- 1 file changed, 27 insertions(+), 7 deletions(-) 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 1b134a4c6970..6c817899e71e 100644 --- a/tests/integration_test/firebase_core/firebase_core_e2e_test.dart +++ b/tests/integration_test/firebase_core/firebase_core_e2e_test.dart @@ -87,8 +87,9 @@ void main() { }); // The tests app links the Auth, App Check and Messaging plugins, so the - // native SDKs' interop components are in the container. Auth runs against - // the emulator that CI starts around this suite. + // native SDKs' interop components are in the container and, on web, the + // JS SDK modules are loaded. Auth runs against the emulator that CI starts + // around this suite. group( 'interop tokens', () { @@ -118,7 +119,7 @@ void main() { // Signing in persists the user to the keychain, which the unsigned // macOS test app cannot write to (errSecMissingEntitlement), as in // the firebase_auth suite. - skip: defaultTargetPlatform == TargetPlatform.macOS, + skip: !kIsWeb && defaultTargetPlatform == TargetPlatform.macOS, ); test( @@ -132,8 +133,16 @@ void main() { expect(answer!.token, isNotEmpty); expect(answer.error, isNotNull); }, + skip: kIsWeb, ); + test('getAppCheckToken is null on web before activation', () async { + // The JS SDK creates App Check's token service only on activation, + // so until then there is nothing to ask; the JS Functions SDK sends + // no App Check token then either. + expect(await defaultApp.getAppCheckToken(), isNull); + }, skip: !kIsWeb); + test( 'getMessagingToken is null for an app other than the default', () async { @@ -152,12 +161,23 @@ void main() { ); }, // On Android the token comes from the Instance ID library, which - // answers for any app and fetches over the network. - skip: defaultTargetPlatform == TargetPlatform.android, + // answers for any app and fetches over the network. On web, + // Messaging also serves any app; the next test covers web. + skip: kIsWeb || defaultTargetPlatform == TargetPlatform.android, + ); + + test( + 'getMessagingToken is null on web without notification permission', + () async { + // The test browser never grants notification permission, so the + // call returns null without asking Messaging, which would prompt. + expect(await defaultApp.getMessagingToken(), isNull); + }, + skip: !kIsWeb, ); }, - // No implementation on Windows yet; web lands separately. - skip: kIsWeb || defaultTargetPlatform == TargetPlatform.windows, + // No implementation on Windows yet. + skip: !kIsWeb && defaultTargetPlatform == TargetPlatform.windows, ); }); } From 791675e4e878620d7c94630d69d71d6af6179521 Mon Sep 17 00:00:00 2001 From: jonathanedey Date: Wed, 11 Nov 2026 13:58:48 -0500 Subject: [PATCH 07/12] fix(core): answer null for the interop tokens on Windows The Windows plugin has no token lookup yet, so FirebaseTokenHostApi is generated there but never registered. Calling an unregistered Pigeon API fails with channel-error, which the token calls surfaced as a core FirebaseException. The contract says a missing SDK answers null and never fails. - _guardTokenCall answers null on Windows before touching the channel, the way method_channel_firebase.dart already branches on defaultTargetPlatform. One check covers all three calls. - The e2e group stays skipped on Windows: Auth works there through the C++ SDK, so the signed-in check can't hold against null. Tested with a unit test that fakes Windows through debugDefaultTargetPlatformOverride and checks that every call is null and the host API is never asked. --- .../method_channel_firebase_app.dart | 9 +++++++- .../method_channel_firebase_app_test.dart | 23 +++++++++++++++++++ .../firebase_core/firebase_core_e2e_test.dart | 3 ++- 3 files changed, 33 insertions(+), 2 deletions(-) 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 6c178ca70d02..c5c143202af8 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 @@ -97,7 +97,14 @@ class MethodChannelFirebaseApp extends FirebaseAppPlatform { /// Surfaces a failure reported by the native plugin as a [FirebaseException] /// for plugin `core`, keeping the code and message native chose. - Future _guardTokenCall(Future Function() call) async { + /// + /// Answers `null` on Windows, whose plugin has no token lookup yet: from + /// core's point of view nothing is linked there, and the contract's answer + /// for that is `null`, not the channel error an unregistered API would give. + Future _guardTokenCall(Future Function() call) async { + if (defaultTargetPlatform == TargetPlatform.windows) { + return null; + } try { return await call(); } on PlatformException catch (exception, stackTrace) { 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 index 7a9ede5a4947..ac50ee2d857d 100644 --- 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 @@ -4,6 +4,7 @@ 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'; @@ -120,6 +121,28 @@ void main() { 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); + }); + }); }); } 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 6c817899e71e..e12512aba8fc 100644 --- a/tests/integration_test/firebase_core/firebase_core_e2e_test.dart +++ b/tests/integration_test/firebase_core/firebase_core_e2e_test.dart @@ -176,7 +176,8 @@ void main() { skip: !kIsWeb, ); }, - // No implementation on Windows yet. + // Windows has no token lookup yet: every call answers null there, so the + // signed-in check can't hold. skip: !kIsWeb && defaultTargetPlatform == TargetPlatform.windows, ); }); From 337207b855159db335d546542e2c750ac51fe32f Mon Sep 17 00:00:00 2001 From: jonathanedey Date: Wed, 11 Nov 2026 16:03:54 -0500 Subject: [PATCH 08/12] chore(core): trim the interop token comments to the reasons --- .../firebase_core/android/build.gradle | 6 +-- .../core/FlutterFirebaseCorePlugin.kt | 4 +- .../firebase/core/InteropTokenProvider.kt | 26 ++++------ .../firebase_core/FLTFirebaseCorePlugin.swift | 5 +- .../firebase_core/InteropTokenProvider.swift | 52 +++++++------------ .../method_channel_firebase_app.dart | 9 ++-- .../lib/src/interop/core_interop.dart | 6 +-- .../lib/src/interop_token_provider.dart | 40 +++++--------- .../test/interop_token_provider_test.dart | 2 +- .../firebase_core/firebase_core_e2e_test.dart | 30 ++++------- 10 files changed, 63 insertions(+), 117 deletions(-) diff --git a/packages/firebase_core/firebase_core/android/build.gradle b/packages/firebase_core/firebase_core/android/build.gradle index 830e128cf4e5..6b4a8580dfaa 100644 --- a/packages/firebase_core/firebase_core/android/build.gradle +++ b/packages/firebase_core/firebase_core/android/build.gradle @@ -70,10 +70,8 @@ android { implementation platform("com.google.firebase:firebase-bom:${getRootProjectExtOrDefaultProperty("FirebaseSDKVersion")}") implementation "com.google.firebase:firebase-common" - // Interfaces through which the Auth, App Check and Messaging SDKs hand - // tokens to other SDKs (see InteropTokenProvider). - // Interface-only; the BoM does not manage them, so the versions are the - // ones the BoM's own SDKs depend on. + // 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" 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 ee2fc018b3d5..2fd350cfb7b8 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 @@ -280,8 +280,8 @@ class FlutterFirebaseCorePlugin : } /** - * Runs a token lookup off the main thread and reports an SDK failure to Dart under [failureCode] - * with the SDK's message, so the Dart side can surface it as a core FirebaseException. + * Runs a token lookup off the main thread and reports an SDK failure as a FlutterError under + * [failureCode]. */ private fun respondWithToken( failureCode: String, 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 index 14748249dccd..243c4b460473 100644 --- 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 @@ -14,12 +14,9 @@ import com.google.firebase.internal.api.FirebaseNoSignedInUserException import java.util.concurrent.Executor /** - * Fetches the Auth, App Check and FCM tokens from whichever SDKs the app links, the way the - * Firebase Functions SDK's `FirebaseContextProvider` does. - * - * Each SDK registers an interop component in its app's component container when it is linked. - * [getComponent] looks a component up by interface and returns null when no linked SDK registered - * it, so a null token means "not linked" or "nothing to give", never failure. + * 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?, @@ -35,10 +32,7 @@ class InteropTokenProvider( private inline fun get(): T? = getComponent(T::class.java) as? T - /** - * The signed-in user's ID token, or null when the Auth SDK isn't linked or nobody is signed in. - * Fails with the Auth SDK's exception when it can't produce a token. - */ + /** 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 -> @@ -55,9 +49,8 @@ class InteropTokenProvider( } /** - * The App Check SDK's answer, or null when App Check isn't linked. When the SDK can't produce a - * token, for example before it is activated, the answer carries its placeholder token and the - * reason, as the SDK reports it. + * 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) @@ -72,10 +65,9 @@ class InteropTokenProvider( } /** - * The FCM registration token, or null when nothing provides `FirebaseInstanceIdInternal`. - * - * Only the Instance ID library provides it, so this answers whenever that library is linked. - * `getToken()` blocks on the network when no token is cached yet, hence the executor. + * 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) 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 813a31c0e58d..6e1d591c1be3 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 @@ -294,9 +294,8 @@ public class FLTFirebaseCorePlugin: NSObject, FlutterPlugin, FLTFirebasePluginPr } } - /// Runs a token lookup for the app named `appName` and reports an SDK failure to Dart under - /// `failureCode` with the SDK's message, so the Dart side can surface it as a core - /// FirebaseException. Replies on the main thread, since the SDKs call back on their own queues. + /// 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, 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 index d65ba7ffb8dc..baf0dd3d1aa0 100644 --- 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 @@ -5,13 +5,9 @@ import FirebaseCore import Foundation -/// Fetches the Auth, App Check and FCM tokens from whichever SDKs the app links, the way the -/// Firebase Functions SDK's `FunctionsContextProvider` does. -/// -/// Each SDK registers an interop component in its app's component container when it is linked. -/// `getComponent` looks a component up by the name of its Objective-C protocol and returns nil -/// when no linked SDK registered it, so a nil token means "not linked" or "nothing to give", never -/// failure. +/// 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? @@ -19,13 +15,9 @@ final class InteropTokenProvider { self.getComponent = getComponent } - /// Looks tokens up in the component container of `app`. - /// - /// The container and the interop protocols are declared in `FirebaseCoreExtension` and the SDKs' - /// interop modules, which are not products of the Firebase Swift package, so this plugin can't - /// import them. It reaches the same Objective-C API by name instead: `FIRApp`'s `container` - /// property and `-[FIRComponentContainer __instanceForProtocol:]`, which is what - /// `ComponentType.instance(for:in:)` calls. + /// `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. @@ -41,8 +33,7 @@ final class InteropTokenProvider { } } - /// The signed-in user's ID token, or nil when the Auth SDK isn't linked or nobody is signed in. - /// Fails with the Auth SDK's error when it can't produce a token. + /// 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?( @@ -61,9 +52,8 @@ final class InteropTokenProvider { } } - /// The App Check SDK's answer, or nil when App Check isn't linked. When the SDK can't produce a - /// token, for example before it is activated, the answer carries its placeholder token and the - /// reason, as the SDK reports it. + /// 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 @@ -82,8 +72,7 @@ final class InteropTokenProvider { error: error?.localizedDescription ))) } - // `getLimitedUseToken(completion:)` is optional in the protocol; an SDK without it has no - // limited-use token to give, as in the Functions SDK. + // `getLimitedUseToken(completion:)` is optional in the protocol. let started: Void? = limitedUse ? appCheck?.interopGetLimitedUseToken?(completion: handleResult) @@ -93,16 +82,14 @@ final class InteropTokenProvider { } } - /// The FCM registration token the Messaging SDK has cached, or nil when Messaging isn't linked - /// or has no token yet. Like the Functions SDK, this never asks for a new token. + /// 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 } } -// The Objective-C runtime names of the interop protocols (Swift sees them as `AuthInterop`, -// `AppCheckInterop` and `MessagingInterop`). +// Objective-C runtime names of the interop protocols. private let authInteropProtocolName = "FIRAuthInterop" private let appCheckInteropProtocolName = "FIRAppCheckInterop" private let messagingInteropProtocolName = "FIRMessagingInterop" @@ -110,19 +97,16 @@ private let messagingInteropProtocolName = "FIRMessagingInterop" private let containerSelector = NSSelectorFromString("container") private let instanceForProtocolSelector = NSSelectorFromString("__instanceForProtocol:") -// The SDK methods this file calls, declared here because their headers can't be imported (see -// `InteropTokenProvider.forApp`). The selectors match the SDK headers named below. The SDKs' -// objects don't conform to these protocols: Swift's `AnyObject` lookup sends the selectors to them -// directly and skips the call when an object doesn't respond. +// 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`, in FirebaseAuth/Interop/Public/FirebaseAuthInterop/FIRAuthInterop.h. +/// FIRAuthInterop.h @objc private protocol AuthInteropMethods { @objc(getTokenForcingRefresh:withCallback:) func interopGetToken(forcingRefresh: Bool, callback: @escaping (String?, Error?) -> Void) } -/// `FIRAppCheckInterop`, in FirebaseAppCheck/Interop/Public/FirebaseAppCheckInterop/ -/// FIRAppCheckInterop.h. +/// FIRAppCheckInterop.h @objc private protocol AppCheckInteropMethods { @objc(getTokenForcingRefresh:completion:) func interopGetToken(forcingRefresh: Bool, completion: @escaping (AnyObject) -> Void) @@ -131,13 +115,13 @@ private let instanceForProtocolSelector = NSSelectorFromString("__instanceForPro func interopGetLimitedUseToken(completion: @escaping (AnyObject) -> Void) } -/// `FIRAppCheckTokenResultInterop`, in the same directory. +/// FIRAppCheckTokenResultInterop.h @objc private protocol AppCheckTokenResultProperties { @objc(token) var interopToken: String { get } @objc(error) var interopError: NSError? { get } } -/// `FIRMessagingInterop`, in FirebaseMessaging/Interop/FIRMessagingInterop.h. +/// FIRMessagingInterop.h @objc private protocol MessagingInteropProperties { @objc(FCMToken) var interopFCMToken: String? { get } } 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 c5c143202af8..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 @@ -95,12 +95,9 @@ class MethodChannelFirebaseApp extends FirebaseAppPlatform { return _guardTokenCall(() => _tokenApi.getMessagingToken(name)); } - /// Surfaces a failure reported by the native plugin as a [FirebaseException] - /// for plugin `core`, keeping the code and message native chose. - /// - /// Answers `null` on Windows, whose plugin has no token lookup yet: from - /// core's point of view nothing is linked there, and the contract's answer - /// for that is `null`, not the channel error an unregistered API would give. + /// 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; 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 3c13f4418da7..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,10 +37,8 @@ external void registerVersion( JSString? variant, ]); -/// The provider for the component named [name] in [app]'s component container. -/// -/// Internal to the Firebase JS SDK: its modules reach each other's components -/// through it, as the Functions SDK does for Auth, App Check and Messaging. +/// 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); 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 index 12a7def61679..9fc4b2790874 100644 --- 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 @@ -11,26 +11,19 @@ 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 from whichever Firebase JS SDK -/// modules the app loaded, the way the JS Functions SDK's `ContextProvider` -/// does. -/// -/// Each module registers an internal component in its app's component -/// container once it's loaded and initialized. `getComponent` looks one up by -/// name and returns null otherwise, so a null token means "not loaded" or -/// "nothing to give", never failure. +/// 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` that asks Messaging only when - /// `notificationsGranted` says the user has already allowed notifications. + /// Creates a provider over [getComponent]; [notificationsGranted] gates the + /// Messaging lookup. InteropTokenProvider({ required JSObject? Function(String name) getComponent, required bool Function() notificationsGranted, }) : _getComponent = getComponent, _notificationsGranted = notificationsGranted; - /// Looks tokens up in the component container of the app named [appName]. - /// - /// Throws [noAppExists] when there is no such app. + /// Throws [noAppExists] when there is no app named [appName]. factory InteropTokenProvider.forApp(String appName) { final firebase.AppJsImpl app; try { @@ -50,10 +43,7 @@ class InteropTokenProvider { final bool Function() _notificationsGranted; /// The signed-in user's ID token, or null when Auth isn't loaded or nobody is - /// signed in. - /// - /// Throws a core [FirebaseException] with code `auth-token-failed` and Auth's - /// message when Auth fails to produce one. + /// signed in. Throws `auth-token-failed` when Auth fails. Future getAuthIdToken() async { final auth = _getComponent('auth-internal') as _AuthInternal?; if (auth == null) { @@ -71,11 +61,8 @@ class InteropTokenProvider { } } - /// App Check's answer, or null when App Check isn't loaded or hasn't been - /// activated. - /// - /// When App Check can't produce a token, the answer carries its placeholder - /// token and the reason, as the JS SDK reports them. + /// 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 { @@ -106,8 +93,7 @@ class InteropTokenProvider { /// 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 { - // Checked before anything else: Messaging's getToken() would ask the user - // for permission while it's still undecided. + // Messaging's getToken() prompts while permission is undecided. if (!_notificationsGranted()) { return null; } @@ -143,7 +129,7 @@ String _messageOf(Object error) { return '$error'; } -/// `auth-internal`, the component Auth registers for other modules. +/// `auth-internal`, Auth's internal component. extension type _AuthInternal._(JSObject _) implements JSObject { /// Resolves to null when nobody is signed in. external JSPromise<_AuthToken?> getToken(); @@ -153,7 +139,7 @@ extension type _AuthToken._(JSObject _) implements JSObject { external JSString get accessToken; } -/// `app-check-internal`, the component App Check registers for other modules. +/// `app-check-internal`, App Check's internal component. extension type _AppCheckInternal._(JSObject _) implements JSObject { external JSPromise<_AppCheckTokenResult> getToken(); @@ -171,7 +157,7 @@ extension type _ErrorLike._(JSObject _) implements JSObject { external JSString? get message; } -/// `messaging-internal`, the component Messaging registers for other modules. +/// `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 index e870a54da330..48279b49af38 100644 --- 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 @@ -175,7 +175,7 @@ void main() { }); }); - // Loads the real Firebase JS SDK files, as firebase_core_js does, so these + // 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; 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 e12512aba8fc..7aac024fb532 100644 --- a/tests/integration_test/firebase_core/firebase_core_e2e_test.dart +++ b/tests/integration_test/firebase_core/firebase_core_e2e_test.dart @@ -86,10 +86,8 @@ void main() { expect(app.options.projectId, demoProjectId); }); - // The tests app links the Auth, App Check and Messaging plugins, so the - // native SDKs' interop components are in the container and, on web, the - // JS SDK modules are loaded. Auth runs against the emulator that CI starts - // around this suite. + // 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. group( 'interop tokens', () { @@ -116,17 +114,16 @@ void main() { expect(await defaultApp.getAuthIdToken(), idToken); }, - // Signing in persists the user to the keychain, which the unsigned - // macOS test app cannot write to (errSecMissingEntitlement), as in - // the firebase_auth suite. + // Signing in needs the keychain, which the unsigned macOS test app + // can't use, as in the firebase_auth suite. skip: !kIsWeb && defaultTargetPlatform == TargetPlatform.macOS, ); test( 'getAppCheckToken answers with a placeholder before activation', () async { - // App Check is linked but never activated in this app, so the SDK - // answers with its placeholder token and the reason. + // App Check is never activated here, so the SDK answers with its + // placeholder. final answer = await defaultApp.getAppCheckToken(); expect(answer, isNotNull); @@ -137,9 +134,7 @@ void main() { ); test('getAppCheckToken is null on web before activation', () async { - // The JS SDK creates App Check's token service only on activation, - // so until then there is nothing to ask; the JS Functions SDK sends - // no App Check token then either. + // The JS SDK creates App Check's token service only on activation. expect(await defaultApp.getAppCheckToken(), isNull); }, skip: !kIsWeb); @@ -160,24 +155,21 @@ void main() { isNull, ); }, - // On Android the token comes from the Instance ID library, which - // answers for any app and fetches over the network. On web, - // Messaging also serves any app; the next test covers web. + // 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 { - // The test browser never grants notification permission, so the - // call returns null without asking Messaging, which would prompt. + // CI's browser never grants notification permission. expect(await defaultApp.getMessagingToken(), isNull); }, skip: !kIsWeb, ); }, - // Windows has no token lookup yet: every call answers null there, so the - // signed-in check can't hold. + // Windows has no token lookup yet; every call is null there. skip: !kIsWeb && defaultTargetPlatform == TargetPlatform.windows, ); }); From 41e3ccc91bca7e73ce7456bf3325fac791e17d90 Mon Sep 17 00:00:00 2001 From: jonathanedey Date: Wed, 11 Nov 2026 16:32:36 -0500 Subject: [PATCH 09/12] fix(core): report a missing app and a tokenless App Check answer - Android: FirebaseApp.getInstance throws IllegalStateException for an unknown or deleted app, which Pigeon reported under the exception class name. It now surfaces as no-app, as on Apple and in Dart. - Apple: an App Check result without a token answered nil, which reads as "App Check isn't linked". It now fails under app-check-token-failed, so an SDK shape change can't silently drop App Check. --- .../plugins/firebase/core/FlutterFirebaseCorePlugin.kt | 3 +++ .../Sources/firebase_core/InteropTokenProvider.swift | 7 ++++++- 2 files changed, 9 insertions(+), 1 deletion(-) 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 2fd350cfb7b8..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 @@ -298,6 +298,9 @@ class FlutterFirebaseCorePlugin : 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) } 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 index baf0dd3d1aa0..71ab5cafc855 100644 --- 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 @@ -60,8 +60,13 @@ final class InteropTokenProvider { ) { 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(.success(nil)) + completion( + .failure( + NSError( + domain: "FlutterFirebaseCore", code: 0, + userInfo: [NSLocalizedDescriptionKey: "App Check result has no token"]))) return } let error: NSError? = result.interopError ?? nil From a73cc70be26bd848f35b37682ee5a818615b49d1 Mon Sep 17 00:00:00 2001 From: jonathanedey Date: Wed, 11 Nov 2026 16:32:50 -0500 Subject: [PATCH 10/12] docs(core): describe the interop token behavior on web The web implementation differs from native in three ways the API docs did not state: App Check answers null before activation, Messaging is asked only once notification permission is granted and may then create a token, and Messaging serves any app on Android and web. --- .../platform_interface_firebase_app.dart | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) 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 50c62bb3892f..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 @@ -73,9 +73,13 @@ class FirebaseAppPlatform extends PlatformInterface { /// 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, as the native SDKs report it. + /// 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. + /// 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. @@ -88,10 +92,14 @@ class FirebaseAppPlatform extends PlatformInterface { /// The FCM registration token, or `null` when Messaging isn't linked into /// the app or has no token. /// - /// Never prompts the user and, on Apple and web, never generates a token. - /// Messaging only serves the default app, so other apps get `null`. + /// 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. From 3c61d360f2287126ae5e10c61be9e461f4878243 Mon Sep 17 00:00:00 2001 From: jonathanedey Date: Tue, 17 Nov 2026 13:57:43 -0500 Subject: [PATCH 11/12] fix(core): build the interop token code on the merged toolchain main raised firebase_core_web's SDK floor to 3.12 and migrated Android to built-in Kotlin, which changed two things for this branch: - Kotlin now sees the Tasks API's results as nullable. getAuthIdToken reads the token through a safe call, and getAppCheckToken treats a missing result as a failure, as the Apple side already does. - The web provider's constructor uses private initializing formals, which the 3.12 floor allows and the analyzer now asks for. The note on the JSError check no longer cites the old floor. --- .../plugins/firebase/core/InteropTokenProvider.kt | 8 +++++--- .../lib/src/interop_token_provider.dart | 10 +++++----- 2 files changed, 10 insertions(+), 8 deletions(-) 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 index 243c4b460473..1d84ab559b00 100644 --- 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 @@ -37,7 +37,7 @@ class InteropTokenProvider( val auth = get() ?: return Tasks.forResult(null) return auth.getAccessToken(false).continueWith(executor) { task -> if (task.isSuccessful) { - task.result.token + task.result?.token } else { when (val exception = task.exception) { // Signed out is an answer, not a failure. @@ -56,10 +56,12 @@ class InteropTokenProvider( 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 = result.token, - error = result.error?.let { it.message ?: it.toString() }, + token = answer.token, + error = answer.error?.let { it.message ?: it.toString() }, )) } } 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 index 9fc4b2790874..3db0950a3a6e 100644 --- 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 @@ -18,10 +18,9 @@ class InteropTokenProvider { /// Creates a provider over [getComponent]; [notificationsGranted] gates the /// Messaging lookup. InteropTokenProvider({ - required JSObject? Function(String name) getComponent, - required bool Function() notificationsGranted, - }) : _getComponent = getComponent, - _notificationsGranted = notificationsGranted; + required this._getComponent, + required this._notificationsGranted, + }); /// Throws [noAppExists] when there is no app named [appName]. factory InteropTokenProvider.forApp(String appName) { @@ -118,7 +117,8 @@ bool _browserNotificationsGranted() => /// The message of a JS error thrown by an SDK, or the error itself otherwise. String _messageOf(Object error) { - // isA on Object requires Dart 3.12; this package supports 3.10. + // 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; From ef4aceba4197e8378f5f7ec88ebf9b54ff07f469 Mon Sep 17 00:00:00 2001 From: jonathanedey Date: Tue, 17 Nov 2026 15:18:01 -0500 Subject: [PATCH 12/12] test(core): skip the token checks per test on Windows A test's own skip argument replaces its group's, even when it is false, so the group-level Windows skip reached only the one test without a skip of its own. The other tests ran on Windows and the two that expect a token failed. The Windows condition now sits on those two tests. The null checks run on Windows, where every call answers null. --- .../firebase_core/firebase_core_e2e_test.dart | 170 +++++++++--------- 1 file changed, 86 insertions(+), 84 deletions(-) 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 7aac024fb532..587169ad82da 100644 --- a/tests/integration_test/firebase_core/firebase_core_e2e_test.dart +++ b/tests/integration_test/firebase_core/firebase_core_e2e_test.dart @@ -88,89 +88,91 @@ void main() { // 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. - 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. - skip: !kIsWeb && defaultTargetPlatform == TargetPlatform.macOS, - ); - - 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); - }, - skip: kIsWeb, - ); - - 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, - ); - }, - // Windows has no token lookup yet; every call is null there. - skip: !kIsWeb && defaultTargetPlatform == TargetPlatform.windows, - ); + // 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, + ); + }); }); }