From dc3ada66dfbd5a155ff95aeb29bd3264310613bf Mon Sep 17 00:00:00 2001 From: jonathanedey Date: Mon, 23 Nov 2026 18:13:28 -0500 Subject: [PATCH 1/6] feat(core): add the token provider contracts and service factories Firebase packages that attach Auth, App Check and FCM tokens to their own requests, as the Functions SDKs do, can ask the app for them through AuthTokenProvider, AppCheckTokenProvider and MessagingTokenProvider instead of depending on the packages that implement them. The implementing packages register a provider, and registerFirebaseServiceFactory lets them do so before any app exists, so a provider is reachable before the app has used the package (for example for a user restored from a previous launch). The contracts are re-exported by firebase_core_platform_interface only, like the other plugin contracts: the public API of firebase_core is unchanged. --- .../lib/firebase_core_interface.dart | 2 + .../lib/src/app_check_interop_token.dart | 51 ++++++ .../lib/src/firebase_app.dart | 58 +++++- .../lib/src/token_providers.dart | 78 ++++++++ .../test/firebase_app_services_test.dart | 173 ++++++++++++++++++ .../lib/firebase_core_platform_interface.dart | 10 +- 6 files changed, 368 insertions(+), 4 deletions(-) create mode 100644 packages/firebase_core/firebase_core_interface/lib/src/app_check_interop_token.dart create mode 100644 packages/firebase_core/firebase_core_interface/lib/src/token_providers.dart create mode 100644 packages/firebase_core/firebase_core_interface/test/firebase_app_services_test.dart diff --git a/packages/firebase_core/firebase_core_interface/lib/firebase_core_interface.dart b/packages/firebase_core/firebase_core_interface/lib/firebase_core_interface.dart index 3179d368325e..e9a5f3ab5b43 100644 --- a/packages/firebase_core/firebase_core_interface/lib/firebase_core_interface.dart +++ b/packages/firebase_core/firebase_core_interface/lib/firebase_core_interface.dart @@ -8,6 +8,7 @@ library; export 'package:firebase_common/firebase_common.dart' show FirebaseException; +export 'src/app_check_interop_token.dart'; export 'src/constants.dart'; export 'src/firebase.dart'; export 'src/firebase_core_exceptions.dart'; @@ -15,3 +16,4 @@ export 'src/firebase_options.dart'; export 'src/platform_interface/platform_interface_firebase.dart'; export 'src/platform_interface/platform_interface_firebase_app.dart'; export 'src/platform_interface/platform_interface_firebase_plugin.dart'; +export 'src/token_providers.dart'; diff --git a/packages/firebase_core/firebase_core_interface/lib/src/app_check_interop_token.dart b/packages/firebase_core/firebase_core_interface/lib/src/app_check_interop_token.dart new file mode 100644 index 000000000000..142511309dd9 --- /dev/null +++ b/packages/firebase_core/firebase_core_interface/lib/src/app_check_interop_token.dart @@ -0,0 +1,51 @@ +// 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:meta/meta.dart'; + +/// An App Check implementation's answer to a token request, in the shape the +/// Firebase SDKs hand each other. +/// +/// When App Check can't produce a token (for example before it is activated, +/// or when attestation fails), [token] holds [placeholderToken] and [error] +/// the reason. Consumers decide whether to attach the placeholder: the native +/// Functions SDKs send it, the JS Functions SDK omits the header. +@immutable +class AppCheckInteropToken { + /// Creates the answer: a [token] and, on failure, the [error]. + const AppCheckInteropToken({required this.token, this.error}); + + /// The answer when no token could be produced for the reason in [error]. + const AppCheckInteropToken.failure(String error) + : this(token: placeholderToken, error: error); + + /// The token the App Check SDKs give other Firebase SDKs when they can't + /// produce a real one: base64 for `{"error":"UNKNOWN_ERROR"}`. + /// + /// The same value as `DefaultAppCheckTokenResult.DUMMY_TOKEN` on Android, + /// `kPlaceholderTokenValue` in the Apple SDK's AppCheckCore and the + /// JS SDK's `formatDummyToken` output. + static const String placeholderToken = 'eyJlcnJvciI6IlVOS05PV05fRVJST1IifQ=='; + + /// The App Check token, or [placeholderToken] when [error] is set. + final String token; + + /// Why no token could be produced, 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_interface/lib/src/firebase_app.dart b/packages/firebase_core/firebase_core_interface/lib/src/firebase_app.dart index 07724729b29e..095576a0fca7 100644 --- a/packages/firebase_core/firebase_core_interface/lib/src/firebase_app.dart +++ b/packages/firebase_core/firebase_core_interface/lib/src/firebase_app.dart @@ -97,15 +97,54 @@ class FirebaseApp { ); } - /// Returns a registered service instance for this app. + /// Returns the service registered for this app as [T], or creates it from + /// the factory registered with `registerFirebaseServiceFactory`, or `null` + /// when there is neither. T? getService() { - return _registries[name]?[T]?.service as T?; + final registered = _registries[name]?[T]?.service; + if (registered != null) { + return registered as T; + } + final factory = _serviceFactories[T]; + if (factory == null) { + return null; + } + final service = factory.create(this) as T; + final registry = _registries.putIfAbsent(name, () => {}); + registry[T] = _RegisteredFirebaseService( + service, + factory.disposer(service), + ); + return service; } } /// A marker interface for Firebase services that can be registered in [FirebaseApp]. abstract class FirebaseService {} +final Map _serviceFactories = {}; + +/// Registers how to create a [T] for any [FirebaseApp] that has none +/// registered. +/// +/// For Firebase packages that must be reachable through +/// [FirebaseApp.getService] before the app has used them, such as the Auth +/// implementation handing out the token of a user restored from a previous +/// launch. Plugin registrants call this before `main`, when no [FirebaseApp] +/// exists yet. Not for app code. +/// +/// [create] runs on the first `getService()` on an app, and the result is +/// registered for that app as if by [FirebaseApp.registerService], so later +/// lookups return the same instance and [FirebaseApp.delete] calls [dispose] +/// on it. A service registered with [FirebaseApp.registerService] always takes +/// precedence. +void registerFirebaseServiceFactory( + T Function(FirebaseApp app) create, { + Future Function(T service)? dispose, +}) { + _serviceFactories[T] = _FirebaseServiceFactory(create, dispose); +} + class _RegisteredFirebaseService { _RegisteredFirebaseService(this.service, this._dispose); @@ -116,3 +155,18 @@ class _RegisteredFirebaseService { await _dispose?.call(); } } + +class _FirebaseServiceFactory { + _FirebaseServiceFactory(this.create, this._dispose); + + final T Function(FirebaseApp app) create; + final Future Function(T service)? _dispose; + + /// The dispose callback for [service], bound the way + /// [FirebaseApp.registerService] binds its own, or `null` when the factory + /// registered none. + Future Function()? disposer(FirebaseService service) { + final dispose = _dispose; + return dispose == null ? null : () => dispose(service as T); + } +} diff --git a/packages/firebase_core/firebase_core_interface/lib/src/token_providers.dart b/packages/firebase_core/firebase_core_interface/lib/src/token_providers.dart new file mode 100644 index 000000000000..1fa52d0099a6 --- /dev/null +++ b/packages/firebase_core/firebase_core_interface/lib/src/token_providers.dart @@ -0,0 +1,78 @@ +// 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 'app_check_interop_token.dart'; +import 'firebase.dart'; + +/// Hands out the signed-in user's ID token for one [FirebaseApp]. +/// +/// The package that implements Auth for an app registers one, so that +/// Firebase packages that attach the token to their own requests (as the +/// Functions SDKs do) can ask `app.getService()` without +/// depending on that package. `null` from `getService` means no Auth +/// implementation is registered for the app. +/// +/// Not for app code: use the Auth package's own API instead. +abstract interface class AuthTokenProvider implements FirebaseService { + /// The signed-in user's ID token, or `null` when nobody is signed in. + /// + /// With [forceRefresh], a fresh token is fetched even when the cached one + /// is still valid. + /// + /// Throws the Auth implementation's exception when it can't produce a + /// token: a failed ID token is a real error the consumer should surface, + /// as the native Functions SDKs fail the call (the JS SDK sends it without + /// the token). The App Check and Messaging providers never throw; the + /// three contracts differ on purpose, each matching its native shape. + Future getIdToken({bool forceRefresh = false}); +} + +/// Hands out App Check tokens for one [FirebaseApp]. +/// +/// The package that implements App Check for an app registers one, so that +/// Firebase packages that attach the token to their own requests can ask +/// `app.getService()` without depending on that +/// package. `null` from `getService` means no App Check implementation is +/// registered for the app. +/// +/// Not for app code: use the App Check package's own API instead. +abstract interface class AppCheckTokenProvider implements FirebaseService { + /// The App Check implementation's answer, or `null` when it has no token to + /// give. + /// + /// Never throws, unlike [AuthTokenProvider.getIdToken]: the native interop + /// shape is a token plus an optional error. When no token can be produced, + /// the answer carries [AppCheckInteropToken.placeholderToken] and the + /// reason in [AppCheckInteropToken.error], exactly as the native interop + /// APIs report it, so consumers can follow the Functions SDKs (send the + /// placeholder on Android and Apple, omit the header on web) without each + /// knowing the placeholder. + /// + /// With [limitedUse], the answer is a limited-use token rather than a + /// cached one. + Future getToken({bool limitedUse = false}); +} + +/// Hands out the FCM registration token for one [FirebaseApp]. +/// +/// The package that implements Messaging for an app registers one, so that +/// Firebase packages that attach the token to their own requests (as the +/// Functions SDKs do) can ask `app.getService()` +/// without depending on that package. `null` from `getService` means no +/// Messaging implementation is registered for the app. +/// +/// Not for app code: use the Messaging package's own API instead. +abstract interface class MessagingTokenProvider implements FirebaseService { + /// The FCM registration token the Messaging implementation holds, or + /// `null` when it has none. + /// + /// Never prompts for notification permission. On Apple platforms this is a + /// cached read only; on Android and web it may register a token when none + /// is stored, as native Functions does. Never throws, unlike + /// [AuthTokenProvider.getIdToken]: when the token can't be read the answer + /// is `null`, as the FCM header is best-effort in the native Functions + /// SDKs too. Messaging serves the default app only, in FlutterFire as in + /// native FCM, so the answer is `null` for any other app. + Future getFcmToken(); +} diff --git a/packages/firebase_core/firebase_core_interface/test/firebase_app_services_test.dart b/packages/firebase_core/firebase_core_interface/test/firebase_app_services_test.dart new file mode 100644 index 000000000000..b9a61ad3ec96 --- /dev/null +++ b/packages/firebase_core/firebase_core_interface/test/firebase_app_services_test.dart @@ -0,0 +1,173 @@ +// Copyright 2026, the Chromium project authors. Please see the AUTHORS file +// 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_core_interface/firebase_core_interface.dart'; +import 'package:test/test.dart'; + +class _FakeFirebasePlatform extends FirebasePlatform { + final Map _apps = {}; + + @override + List get apps => _apps.values.toList(); + + @override + Future initializeApp({ + String? name, + FirebaseOptions? options, + }) async { + final appName = name ?? defaultFirebaseAppName; + return _apps[appName] = _FakeFirebaseAppPlatform(appName, options!); + } + + @override + FirebaseAppPlatform app([String name = defaultFirebaseAppName]) { + return _apps[name] ?? (throw noAppExists(name)); + } +} + +class _FakeFirebaseAppPlatform extends FirebaseAppPlatform { + _FakeFirebaseAppPlatform(super.name, super.options); + + @override + Future delete() async {} +} + +// Each test registers its own service type: the factories are static. +class _Registered implements FirebaseService {} + +class _Created implements FirebaseService { + _Created(this.app); + + final FirebaseApp app; +} + +class _Overridden implements FirebaseService {} + +class _Disposable implements FirebaseService {} + +class _PerApp implements FirebaseService {} + +class _Unknown implements FirebaseService {} + +class _AuthTokens implements AuthTokenProvider { + @override + Future getIdToken({bool forceRefresh = false}) async => 'id-token'; +} + +const _options = FirebaseOptions( + apiKey: 'apiKey', + appId: '1:1:web:1', + messagingSenderId: '1', + projectId: 'project', +); + +void main() { + setUpAll(() => FirebasePlatform.instance = _FakeFirebasePlatform()); + + group('FirebaseApp services', () { + late FirebaseApp app; + + setUpAll(() async { + app = await Firebase.initializeApp(name: 'services', options: _options); + }); + + test('getService returns a registered service', () { + final service = _Registered(); + app.registerService(service); + + expect(app.getService<_Registered>(), same(service)); + }); + + test('getService is null without a service or a factory', () { + expect(app.getService<_Unknown>(), isNull); + }); + + test('getService creates from a factory once per app', () { + var created = 0; + registerFirebaseServiceFactory<_Created>((app) { + created++; + return _Created(app); + }); + + final service = app.getService<_Created>(); + + expect(service, isNotNull); + expect(service!.app, app); + expect(app.getService<_Created>(), same(service)); + expect(created, 1); + }); + + test('a registered service takes precedence over a factory', () { + final registered = _Overridden(); + registerFirebaseServiceFactory<_Overridden>((_) => _Overridden()); + app.registerService(registered); + + expect(app.getService<_Overridden>(), same(registered)); + }); + + test('each app gets its own instance from a factory', () async { + final other = await Firebase.initializeApp( + name: 'services-other', + options: _options, + ); + registerFirebaseServiceFactory<_PerApp>((_) => _PerApp()); + + expect( + app.getService<_PerApp>(), + isNot(same(other.getService<_PerApp>())), + ); + }); + + test('delete disposes a service created from a factory', () async { + final deleted = await Firebase.initializeApp( + name: 'services-deleted', + options: _options, + ); + _Disposable? disposed; + registerFirebaseServiceFactory<_Disposable>( + (_) => _Disposable(), + dispose: (service) async => disposed = service, + ); + final service = deleted.getService<_Disposable>(); + + await deleted.delete(); + + expect(disposed, same(service)); + }); + + test('token providers are services', () { + final tokens = _AuthTokens(); + app.registerService(tokens); + + expect(app.getService(), same(tokens)); + }); + }); + + group('AppCheckInteropToken', () { + test('failure carries the placeholder and the reason', () { + const answer = AppCheckInteropToken.failure('not activated'); + + expect(answer.token, AppCheckInteropToken.placeholderToken); + expect(answer.error, 'not activated'); + }); + + test('is a value', () { + expect( + const AppCheckInteropToken(token: 'token'), + const AppCheckInteropToken(token: 'token'), + ); + expect( + const AppCheckInteropToken(token: 'token'), + isNot(const AppCheckInteropToken.failure('error')), + ); + }); + + test('does not print the token', () { + expect( + const AppCheckInteropToken(token: 'secret').toString(), + isNot(contains('secret')), + ); + }); + }); +} 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 e23f2704ba82..07d8cc425a51 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 @@ -16,20 +16,26 @@ import 'package:flutter/services.dart'; // The pure-Dart types and contracts live in `firebase_core_interface`, so that // Dart apps without Flutter can use them. They stay importable from here. The // list is explicit so that names it adds later do not clash with other imports -// in the plugins. +// in the plugins. The token providers are contracts between Firebase packages, +// not for app code, which is why `firebase_core` does not re-export them. export 'package:firebase_core_interface/firebase_core_interface.dart' show + AppCheckInteropToken, + AppCheckTokenProvider, + AuthTokenProvider, FirebaseAppPlatform, FirebaseException, FirebaseOptions, FirebasePlatform, FirebasePlugin, + MessagingTokenProvider, coreNotInitialized, defaultFirebaseAppName, duplicateApp, noAppExists, noDefaultAppDelete, - noDefaultAppInitialization; + noDefaultAppInitialization, + registerFirebaseServiceFactory; part 'src/method_channel/method_channel_firebase.dart'; part 'src/method_channel/method_channel_firebase_app.dart'; From b2e8e94432ed19b5d75f4f8c0fcca312602090e6 Mon Sep 17 00:00:00 2001 From: jonathanedey Date: Mon, 23 Nov 2026 18:13:28 -0500 Subject: [PATCH 2/6] feat(auth, app_check): register the Auth and App Check token providers firebase_auth and firebase_app_check register an AuthTokenProvider and an AppCheckTokenProvider for every app before main, through a dartPluginClass registrant on Android, Apple platforms and Windows, and their web packages do so in registerWith. Other Firebase packages can then get the ID token of a user restored from a previous launch, or an App Check token, before the app has used FirebaseAuth or FirebaseAppCheck itself. A failed App Check request, including one made before the app activates App Check, answers with the placeholder token of the SDKs and the reason, as the native interop APIs do. On web, every App Check delegate of an app now shares the activated JS instance of the app, so the provider sees the activation the app did through FirebaseAppCheck. --- .../lib/src/registrant.dart | 66 +++++++ .../firebase_app_check/pubspec.yaml | 11 ++ .../test/registrant_test.dart | 163 ++++++++++++++++++ .../firebase_app_check_web/CHANGELOG.md | 4 + .../lib/firebase_app_check_web.dart | 41 +++-- ...firebase_app_check_web_token_provider.dart | 43 +++++ .../firebase_app_check_web/pubspec.yaml | 2 +- .../test/activate_test.dart | 124 +++++++++++++ .../firebase_auth/lib/src/registrant.dart | 48 ++++++ .../firebase_auth/firebase_auth/pubspec.yaml | 11 ++ .../firebase_auth/test/registrant_test.dart | 152 ++++++++++++++++ .../lib/firebase_auth_web.dart | 7 + .../src/firebase_auth_web_token_provider.dart | 38 ++++ .../firebase_auth_web/pubspec.yaml | 1 + 14 files changed, 700 insertions(+), 11 deletions(-) create mode 100644 packages/firebase_app_check/firebase_app_check/lib/src/registrant.dart create mode 100644 packages/firebase_app_check/firebase_app_check/test/registrant_test.dart create mode 100644 packages/firebase_app_check/firebase_app_check_web/lib/src/firebase_app_check_web_token_provider.dart create mode 100644 packages/firebase_app_check/firebase_app_check_web/test/activate_test.dart create mode 100644 packages/firebase_auth/firebase_auth/lib/src/registrant.dart create mode 100644 packages/firebase_auth/firebase_auth/test/registrant_test.dart create mode 100644 packages/firebase_auth/firebase_auth_web/lib/src/firebase_auth_web_token_provider.dart diff --git a/packages/firebase_app_check/firebase_app_check/lib/src/registrant.dart b/packages/firebase_app_check/firebase_app_check/lib/src/registrant.dart new file mode 100644 index 000000000000..71faf7917c4e --- /dev/null +++ b/packages/firebase_app_check/firebase_app_check/lib/src/registrant.dart @@ -0,0 +1,66 @@ +// Copyright 2026, the Chromium project authors. Please see the AUTHORS file +// 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_app_check/firebase_app_check.dart'; +import 'package:firebase_core/firebase_core.dart'; +import 'package:firebase_core_platform_interface/firebase_core_platform_interface.dart' + show + AppCheckInteropToken, + AppCheckTokenProvider, + registerFirebaseServiceFactory; + +/// Registers [FirebaseAppCheck] as the [AppCheckTokenProvider] of every app. +/// +/// The Flutter plugin registrant calls [registerWith] before `main` on +/// Android, Apple platforms and Windows (see `dartPluginClass` in +/// pubspec.yaml), so other Firebase packages can ask an app for an App Check +/// token before the app has used [FirebaseAppCheck] itself. +/// `firebase_app_check_web` registers its own provider. +class FirebaseAppCheckRegistrant { + // Not meant to be instantiated. + FirebaseAppCheckRegistrant._(); + + /// Registers the [AppCheckTokenProvider] factory with [FirebaseApp]. + static void registerWith() { + registerFirebaseServiceFactory( + FirebaseAppCheckTokenProvider.new, + ); + } +} + +/// Hands out [FirebaseAppCheck]'s tokens for [app] in the shape the Firebase +/// SDKs hand each other. +/// +/// Resolved per app through `app.getService()`; not for +/// app code. +class FirebaseAppCheckTokenProvider implements AppCheckTokenProvider { + /// Creates the provider for [app]. + FirebaseAppCheckTokenProvider(this.app); + + /// The app whose App Check instance supplies the token. + final FirebaseApp app; + + @override + Future getToken({bool limitedUse = false}) async { + // Creating the App Check instance here is what the app would do itself; + // until the app activates it, the SDK has no provider and the request + // below fails. + final appCheck = FirebaseAppCheck.instanceFor(app: app); + try { + final token = limitedUse + ? await appCheck.getLimitedUseToken() + : await appCheck.getToken(); + return token == null ? null : AppCheckInteropToken(token: token); + } catch (error) { + // The SDKs answer a failed request, including one before activation, + // with their placeholder token and the reason; the plugin's public API + // throws instead. + return AppCheckInteropToken.failure(switch (error) { + FirebaseException(:final message?) => message, + FirebaseException(:final code) => code, + _ => '$error', + }); + } + } +} diff --git a/packages/firebase_app_check/firebase_app_check/pubspec.yaml b/packages/firebase_app_check/firebase_app_check/pubspec.yaml index da6034096417..8e74ffa1ef48 100644 --- a/packages/firebase_app_check/firebase_app_check/pubspec.yaml +++ b/packages/firebase_app_check/firebase_app_check/pubspec.yaml @@ -33,16 +33,27 @@ dev_dependencies: plugin_platform_interface: ^2.1.3 flutter: + # `dartPluginClass` registers App Check as the app's `AppCheckTokenProvider` + # before `main` (and in background isolates the engine starts), so other + # Firebase packages can ask for a token before the app uses App Check. plugin: platforms: android: package: io.flutter.plugins.firebase.appcheck pluginClass: FirebaseAppCheckPlugin + dartPluginClass: FirebaseAppCheckRegistrant + dartFileName: src/registrant.dart ios: pluginClass: FirebaseAppCheckPlugin + dartPluginClass: FirebaseAppCheckRegistrant + dartFileName: src/registrant.dart macos: pluginClass: FirebaseAppCheckPlugin + dartPluginClass: FirebaseAppCheckRegistrant + dartFileName: src/registrant.dart web: default_package: firebase_app_check_web windows: pluginClass: FirebaseAppCheckPluginCApi + dartPluginClass: FirebaseAppCheckRegistrant + dartFileName: src/registrant.dart diff --git a/packages/firebase_app_check/firebase_app_check/test/registrant_test.dart b/packages/firebase_app_check/firebase_app_check/test/registrant_test.dart new file mode 100644 index 000000000000..bfac3e5737e5 --- /dev/null +++ b/packages/firebase_app_check/firebase_app_check/test/registrant_test.dart @@ -0,0 +1,163 @@ +// Copyright 2026, the Chromium project authors. Please see the AUTHORS file +// 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_app_check/src/registrant.dart'; +import 'package:firebase_app_check_platform_interface/firebase_app_check_platform_interface.dart'; +import 'package:firebase_core/firebase_core.dart'; +import 'package:firebase_core_platform_interface/firebase_core_platform_interface.dart' + show AppCheckInteropToken, AppCheckTokenProvider; +import 'package:flutter_test/flutter_test.dart'; + +import './mock.dart'; + +void main() { + setupFirebaseAppCheckMocks(); + + late _FakeFirebaseAppCheckPlatform platform; + var appCount = 0; + + setUpAll(() async { + await Firebase.initializeApp(); + FirebaseAppCheckRegistrant.registerWith(); + }); + + setUp( + () => FirebaseAppCheckPlatform.instance = platform = + _FakeFirebaseAppCheckPlatform(), + ); + + Future newApp() => Firebase.initializeApp( + name: 'token-provider-${appCount++}', + options: const FirebaseOptions( + appId: '1:1234567890:ios:42424242424242', + apiKey: '123', + projectId: '123', + messagingSenderId: '1234567890', + ), + ); + + group('$FirebaseAppCheckRegistrant', () { + test( + 'registers an AppCheckTokenProvider before the app uses App Check', + () async { + final app = await newApp(); + + final provider = app.getService(); + + expect(provider, isA()); + expect(app.getService(), same(provider)); + expect(platform.requests, isEmpty); + }, + ); + }); + + group('$FirebaseAppCheckTokenProvider', () { + test('is the App Check token', () async { + final app = await newApp(); + platform.token = 'app-check-token'; + + final answer = await FirebaseAppCheckTokenProvider(app).getToken(); + + expect(answer, const AppCheckInteropToken(token: 'app-check-token')); + expect(platform.requests, ['getToken(false)']); + }); + + test('is null when App Check has no token', () async { + final app = await newApp(); + + expect(await FirebaseAppCheckTokenProvider(app).getToken(), isNull); + }); + + test('asks for a limited-use token with limitedUse', () async { + final app = await newApp(); + platform.limitedUseToken = 'limited-use-token'; + + final answer = await FirebaseAppCheckTokenProvider( + app, + ).getToken(limitedUse: true); + + expect(answer, const AppCheckInteropToken(token: 'limited-use-token')); + expect(platform.requests, ['getLimitedUseToken()']); + }); + + test( + 'answers with the placeholder and the reason before activate()', + () async { + final app = await newApp(); + platform.error = FirebaseException( + plugin: 'firebase_app_check', + code: 'no-provider', + message: 'No AppCheckProvider installed.', + ); + + final answer = await FirebaseAppCheckTokenProvider(app).getToken(); + + expect( + answer, + const AppCheckInteropToken.failure('No AppCheckProvider installed.'), + ); + expect(answer!.token, AppCheckInteropToken.placeholderToken); + }, + ); + + test('describes a failure without a message by its code', () async { + final app = await newApp(); + platform.error = FirebaseException( + plugin: 'firebase_app_check', + code: 'unknown', + ); + + final answer = await FirebaseAppCheckTokenProvider( + app, + ).getToken(limitedUse: true); + + expect(answer, const AppCheckInteropToken.failure('unknown')); + }); + + test('describes any other error by its string', () async { + final app = await newApp(); + platform.error = StateError('not activated'); + + final answer = await FirebaseAppCheckTokenProvider(app).getToken(); + + expect( + answer, + const AppCheckInteropToken.failure('Bad state: not activated'), + ); + }); + }); +} + +class _FakeFirebaseAppCheckPlatform extends FirebaseAppCheckPlatform { + _FakeFirebaseAppCheckPlatform() : super(); + + String? token; + String limitedUseToken = ''; + Object? error; + final List requests = []; + + @override + FirebaseAppCheckPlatform delegateFor({required FirebaseApp app}) => this; + + @override + FirebaseAppCheckPlatform setInitialValues() => this; + + @override + Future getToken(bool forceRefresh) async { + requests.add('getToken($forceRefresh)'); + if (error case final error?) { + throw error; + } + return token; + } + + @override + Future getLimitedUseToken() async { + requests.add('getLimitedUseToken()'); + if (error case final error?) { + throw error; + } + return limitedUseToken; + } +} diff --git a/packages/firebase_app_check/firebase_app_check_web/CHANGELOG.md b/packages/firebase_app_check/firebase_app_check_web/CHANGELOG.md index 5d11bc285adb..d22895c83f5b 100644 --- a/packages/firebase_app_check/firebase_app_check_web/CHANGELOG.md +++ b/packages/firebase_app_check/firebase_app_check_web/CHANGELOG.md @@ -1,3 +1,7 @@ +## NEXT + + - Every `FirebaseAppCheckWeb` delegate of an app now shares the app's activated JS App Check instance, instead of each delegate activating its own. A delegate created after `activate()` ran, such as the app's `AppCheckTokenProvider` or `FirebaseAppCheck.instance` after `registerWith` re-activated App Check from the provider saved in local storage, now uses that instance rather than failing with "activate() must be called first". Activating an app that is already activated keeps its instance and does not initialize App Check again. + ## 0.3.2+4 - **FIX**(core,appcheck,web): start when the browser blocks web storage ([#18946](https://github.com/firebase/flutterfire/issues/18946)). ([229e08e8](https://github.com/firebase/flutterfire/commit/229e08e8f0b197c1eef240db73a716d7f948c2a1)) diff --git a/packages/firebase_app_check/firebase_app_check_web/lib/firebase_app_check_web.dart b/packages/firebase_app_check/firebase_app_check_web/lib/firebase_app_check_web.dart index 49e6e2a10a8a..c587dcaf0ab2 100644 --- a/packages/firebase_app_check/firebase_app_check_web/lib/firebase_app_check_web.dart +++ b/packages/firebase_app_check/firebase_app_check_web/lib/firebase_app_check_web.dart @@ -7,6 +7,8 @@ import 'dart:js_interop'; import 'package:firebase_app_check_platform_interface/firebase_app_check_platform_interface.dart'; import 'package:firebase_core/firebase_core.dart'; +import 'package:firebase_core_platform_interface/firebase_core_platform_interface.dart' + show AppCheckTokenProvider, registerFirebaseServiceFactory; import 'package:firebase_core_web/firebase_core_web.dart'; import 'package:firebase_core_web/firebase_core_web_interop.dart' as core_interop; @@ -17,6 +19,7 @@ import 'src/internals.dart'; import 'src/interop/app_check.dart' as app_check_interop; import 'src/firebase_app_check_version.dart'; +import 'src/firebase_app_check_web_token_provider.dart'; class FirebaseAppCheckWeb extends FirebaseAppCheckPlatform { static const String _libraryName = 'flutter-fire-app-check'; @@ -27,7 +30,7 @@ class FirebaseAppCheckWeb extends FirebaseAppCheckPlatform { /// Stub initializer to allow the [registerWith] to create an instance without /// registering the web delegates or listeners. - FirebaseAppCheckWeb._() : _webAppCheck = null, super(appInstance: null); + FirebaseAppCheckWeb._() : super(appInstance: null); /// The entry point for the [FirebaseAuthWeb] class. FirebaseAppCheckWeb({required FirebaseApp app}) : super(appInstance: app); @@ -93,6 +96,10 @@ class FirebaseAppCheckWeb extends FirebaseAppCheckPlatform { ); FirebaseAppCheckPlatform.instance = FirebaseAppCheckWeb.instance; + // Other Firebase packages get App Check tokens from here. + registerFirebaseServiceFactory( + FirebaseAppCheckWebTokenProvider.new, + ); } /// Initializes a stub instance to allow the class to be registered. @@ -108,17 +115,21 @@ class FirebaseAppCheckWeb extends FirebaseAppCheckPlatform { return 'FlutterFire-$appName-recaptchaSiteKey'; } - /// instance of AppCheck from the web plugin - app_check_interop.AppCheck? _webAppCheck; + /// The activated JS App Check instance of each app, shared by every + /// delegate for that app: the one `FirebaseAppCheck` holds, the one + /// `registerWith` activates from storage, and the app's + /// `AppCheckTokenProvider`. + static final Map _webAppChecks = {}; - /// Lazily initialize [_webAppCheck] on first method call + /// The app's JS App Check instance; activation creates it. app_check_interop.AppCheck? get _delegate { - if (_webAppCheck == null) { + final webAppCheck = _webAppChecks[app.name]; + if (webAppCheck == null) { throw Exception( "Before using other Firebase App Check APIs, FirebaseAppCheck.instance.activate() must be called first once you've initialized your Firebase app.", ); } - return _webAppCheck; + return webAppCheck; } @override @@ -131,6 +142,11 @@ class FirebaseAppCheckWeb extends FirebaseAppCheckPlatform { return this; } + @override + Future dispose() async { + _webAppChecks.remove(app.name); + } + @override Future activate({ WebProvider? providerWeb, @@ -169,10 +185,15 @@ class FirebaseAppCheckWeb extends FirebaseAppCheckPlatform { // activate API no longer exists, recaptcha key has to be passed on initialization of app-check instance. return convertWebExceptions>(() async { - _webAppCheck ??= app_check_interop.getAppCheckInstance( - core_interop.app(app.name), - providerWeb, - ); + final webAppCheck = + _webAppChecks[app.name] ?? + app_check_interop.getAppCheckInstance( + core_interop.app(app.name), + providerWeb, + ); + if (webAppCheck != null) { + _webAppChecks[app.name] = webAppCheck; + } _initialiseStreamController(); }); } diff --git a/packages/firebase_app_check/firebase_app_check_web/lib/src/firebase_app_check_web_token_provider.dart b/packages/firebase_app_check/firebase_app_check_web/lib/src/firebase_app_check_web_token_provider.dart new file mode 100644 index 000000000000..2c1f608211dd --- /dev/null +++ b/packages/firebase_app_check/firebase_app_check_web/lib/src/firebase_app_check_web_token_provider.dart @@ -0,0 +1,43 @@ +// Copyright 2026, the Chromium project authors. Please see the AUTHORS file +// 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_app_check_platform_interface/firebase_app_check_platform_interface.dart'; +import 'package:firebase_core/firebase_core.dart'; +import 'package:firebase_core_platform_interface/firebase_core_platform_interface.dart' + show AppCheckInteropToken, AppCheckTokenProvider; + +/// Hands out the App Check tokens of [app] in the shape the Firebase SDKs +/// hand each other. +/// +/// `FirebaseAppCheckWeb.registerWith` registers it as the app's +/// [AppCheckTokenProvider]. Resolved per app through +/// `app.getService()`; not for app code. +class FirebaseAppCheckWebTokenProvider implements AppCheckTokenProvider { + /// Creates the provider for [app]. + FirebaseAppCheckWebTokenProvider(this.app); + + /// The app whose App Check instance supplies the token. + final FirebaseApp app; + + @override + Future getToken({bool limitedUse = false}) async { + // Every web delegate for an app shares its activated JS instance, so this + // sees the activation the app did through FirebaseAppCheck. + final appCheck = FirebaseAppCheckPlatform.instanceFor(app: app); + try { + final token = limitedUse + ? await appCheck.getLimitedUseToken() + : await appCheck.getToken(false); + return token == null ? null : AppCheckInteropToken(token: token); + } catch (error) { + // Before activation, and on any other failure, the plugin throws; the + // SDKs answer each other with the placeholder and the reason. + return AppCheckInteropToken.failure(switch (error) { + FirebaseException(:final message?) => message, + FirebaseException(:final code) => code, + _ => '$error', + }); + } + } +} diff --git a/packages/firebase_app_check/firebase_app_check_web/pubspec.yaml b/packages/firebase_app_check/firebase_app_check_web/pubspec.yaml index 3f336059821e..c92225ae2cea 100644 --- a/packages/firebase_app_check/firebase_app_check_web/pubspec.yaml +++ b/packages/firebase_app_check/firebase_app_check_web/pubspec.yaml @@ -12,6 +12,7 @@ dependencies: _flutterfire_internals: ^1.3.79 firebase_app_check_platform_interface: ^0.5.1+3 firebase_core: ^5.1.0 + firebase_core_platform_interface: ^8.1.1 firebase_core_web: ^4.1.0 flutter: sdk: flutter @@ -21,7 +22,6 @@ dependencies: dev_dependencies: build_runner: ^2.3.3 - firebase_core_platform_interface: ^8.1.1 flutter_test: sdk: flutter mockito: ^5.0.0 diff --git a/packages/firebase_app_check/firebase_app_check_web/test/activate_test.dart b/packages/firebase_app_check/firebase_app_check_web/test/activate_test.dart new file mode 100644 index 000000000000..65a14d468f0e --- /dev/null +++ b/packages/firebase_app_check/firebase_app_check_web/test/activate_test.dart @@ -0,0 +1,124 @@ +// Copyright 2026, the Chromium project authors. Please see the AUTHORS file +// 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. + +@TestOn('chrome') +library; + +import 'dart:js_interop'; +import 'dart:js_interop_unsafe'; + +import 'package:firebase_app_check_platform_interface/firebase_app_check_platform_interface.dart'; +import 'package:firebase_app_check_web/firebase_app_check_web.dart'; +import 'package:firebase_core/firebase_core.dart'; +import 'package:firebase_core_platform_interface/test.dart'; +import 'package:flutter_test/flutter_test.dart'; + +/// Stands in for the parts of the Firebase JS SDK that `activate` and +/// `getToken` reach, recording every `initializeAppCheck` call. +const _fakeJsSdk = ''' +globalThis.__initializeAppCheckCalls = []; +globalThis.firebase_core = { getApp: (name) => ({ name }) }; +globalThis.firebase_app_check = { + initializeAppCheck: (app, options) => { + globalThis.__initializeAppCheckCalls.push(app.name); + return { app }; + }, + getToken: (appCheck) => + Promise.resolve({ token: 'token for ' + appCheck.app.name }), + onTokenChanged: () => () => {}, + ReCaptchaV3Provider: function (siteKey) { this.siteKey = siteKey; }, + ReCaptchaEnterpriseProvider: function (siteKey) { this.siteKey = siteKey; }, +}; +'''; + +List get _initializeAppCheckCalls => globalContext + .getProperty>('__initializeAppCheckCalls'.toJS) + .toDart + .map((name) => name.toDart) + .toList(); + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + setupFirebaseCoreMocks(); + + var appCount = 0; + + setUpAll(() => globalContext.callMethod('eval'.toJS, _fakeJsSdk.toJS)); + + tearDownAll(() { + for (final name in [ + 'firebase_core', + 'firebase_app_check', + '__initializeAppCheckCalls', + ]) { + globalContext.delete(name.toJS); + } + }); + + setUp( + () => globalContext.setProperty( + '__initializeAppCheckCalls'.toJS, + JSArray(), + ), + ); + + Future newApp() => Firebase.initializeApp( + name: 'activate-${appCount++}', + options: const FirebaseOptions( + apiKey: '', + appId: '', + messagingSenderId: '', + projectId: '', + ), + ); + + group('$FirebaseAppCheckWeb.activate', () { + test('initializes the JS App Check of an app once, however many times ' + 'and from however many delegates it is activated', () async { + final app = await newApp(); + // What FirebaseAppCheck, registerWith and the app's AppCheckTokenProvider + // each hold. + final first = FirebaseAppCheckWeb(app: app); + final second = FirebaseAppCheckWeb(app: app); + + await first.activate(providerWeb: ReCaptchaV3Provider('site-key')); + await first.activate(providerWeb: ReCaptchaV3Provider('site-key')); + await second.activate(providerWeb: ReCaptchaV3Provider('site-key')); + + expect(_initializeAppCheckCalls, [app.name]); + expect(await second.getToken(false), 'token for ${app.name}'); + }); + + test('lets a delegate created after activation use the instance', () async { + final app = await newApp(); + await FirebaseAppCheckWeb( + app: app, + ).activate(providerWeb: ReCaptchaV3Provider('site-key')); + + expect( + await FirebaseAppCheckWeb(app: app).getToken(false), + 'token for ${app.name}', + ); + expect(_initializeAppCheckCalls, [app.name]); + }); + + test('keeps the instances of different apps apart', () async { + final app = await newApp(); + final other = await newApp(); + + await FirebaseAppCheckWeb( + app: app, + ).activate(providerWeb: ReCaptchaV3Provider('site-key')); + await FirebaseAppCheckWeb( + app: other, + ).activate(providerWeb: ReCaptchaV3Provider('site-key')); + + expect(_initializeAppCheckCalls, [app.name, other.name]); + expect( + await FirebaseAppCheckWeb(app: other).getToken(false), + 'token for ${other.name}', + ); + }); + }); +} diff --git a/packages/firebase_auth/firebase_auth/lib/src/registrant.dart b/packages/firebase_auth/firebase_auth/lib/src/registrant.dart new file mode 100644 index 000000000000..663cbafc0791 --- /dev/null +++ b/packages/firebase_auth/firebase_auth/lib/src/registrant.dart @@ -0,0 +1,48 @@ +// Copyright 2026, the Chromium project authors. Please see the AUTHORS file +// 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' + show AuthTokenProvider, registerFirebaseServiceFactory; + +/// Registers [FirebaseAuth] as the [AuthTokenProvider] of every app. +/// +/// The Flutter plugin registrant calls [registerWith] before `main` on +/// Android, Apple platforms and Windows (see `dartPluginClass` in +/// pubspec.yaml), so other Firebase packages can ask an app for the ID token +/// of a user restored from a previous launch before the app has used +/// [FirebaseAuth] itself. `firebase_auth_web` registers its own provider. +class FirebaseAuthRegistrant { + // Not meant to be instantiated. + FirebaseAuthRegistrant._(); + + /// Registers the [AuthTokenProvider] factory with [FirebaseApp]. + static void registerWith() { + registerFirebaseServiceFactory( + FirebaseAuthTokenProvider.new, + ); + } +} + +/// Hands out the ID token of the user signed in to [FirebaseAuth] for [app]. +/// +/// Resolved per app through `app.getService()`; not for +/// app code. +class FirebaseAuthTokenProvider implements AuthTokenProvider { + /// Creates the provider for [app]. + FirebaseAuthTokenProvider(this.app); + + /// The app whose Auth instance supplies the token. + final FirebaseApp app; + + @override + Future getIdToken({bool forceRefresh = false}) async { + // Creating the Auth instance here is what the app would do itself; on + // Android, Apple and Windows the native Auth SDK already exists and the + // restored user is available synchronously. + final user = FirebaseAuth.instanceFor(app: app).currentUser; + return user?.getIdToken(forceRefresh); + } +} diff --git a/packages/firebase_auth/firebase_auth/pubspec.yaml b/packages/firebase_auth/firebase_auth/pubspec.yaml index bdea7035605a..0a2462cab92c 100755 --- a/packages/firebase_auth/firebase_auth/pubspec.yaml +++ b/packages/firebase_auth/firebase_auth/pubspec.yaml @@ -36,17 +36,28 @@ dev_dependencies: plugin_platform_interface: ^2.1.3 flutter: + # `dartPluginClass` registers Auth as the app's `AuthTokenProvider` before + # `main` (and in background isolates the engine starts), so other Firebase + # packages can get a restored user's ID token before the app uses Auth. plugin: platforms: android: package: io.flutter.plugins.firebase.auth pluginClass: FlutterFirebaseAuthPlugin + dartPluginClass: FirebaseAuthRegistrant + dartFileName: src/registrant.dart ios: pluginClass: FLTFirebaseAuthPlugin + dartPluginClass: FirebaseAuthRegistrant + dartFileName: src/registrant.dart macos: pluginClass: FLTFirebaseAuthPlugin + dartPluginClass: FirebaseAuthRegistrant + dartFileName: src/registrant.dart web: default_package: firebase_auth_web windows: pluginClass: FirebaseAuthPluginCApi + dartPluginClass: FirebaseAuthRegistrant + dartFileName: src/registrant.dart diff --git a/packages/firebase_auth/firebase_auth/test/registrant_test.dart b/packages/firebase_auth/firebase_auth/test/registrant_test.dart new file mode 100644 index 000000000000..62149b72e8e5 --- /dev/null +++ b/packages/firebase_auth/firebase_auth/test/registrant_test.dart @@ -0,0 +1,152 @@ +// Copyright 2026, the Chromium project authors. Please see the AUTHORS file +// 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/src/registrant.dart'; +import 'package:firebase_auth_platform_interface/firebase_auth_platform_interface.dart'; +import 'package:firebase_core/firebase_core.dart'; +import 'package:firebase_core_platform_interface/firebase_core_platform_interface.dart' + show AuthTokenProvider; +import 'package:flutter_test/flutter_test.dart'; + +import './mock.dart'; + +void main() { + setupFirebaseAuthMocks(); + + late _FakeFirebaseAuthPlatform platform; + var appCount = 0; + + setUpAll(() async { + await Firebase.initializeApp(); + FirebaseAuthRegistrant.registerWith(); + }); + + setUp( + () => + FirebaseAuthPlatform.instance = platform = _FakeFirebaseAuthPlatform(), + ); + + Future newApp() => Firebase.initializeApp( + name: 'token-provider-${appCount++}', + options: const FirebaseOptions( + apiKey: '', + appId: '', + messagingSenderId: '', + projectId: '', + ), + ); + + group('$FirebaseAuthRegistrant', () { + test( + 'registers an AuthTokenProvider before the app uses FirebaseAuth', + () async { + final app = await newApp(); + + final provider = app.getService(); + + expect(provider, isA()); + expect(app.getService(), same(provider)); + }, + ); + }); + + group('$FirebaseAuthTokenProvider', () { + test('is null when nobody is signed in', () async { + final app = await newApp(); + + expect(await FirebaseAuthTokenProvider(app).getIdToken(), isNull); + }); + + test("is the signed-in user's ID token", () async { + final app = await newApp(); + platform.user = _FakeUserPlatform(platform, token: 'id-token'); + + expect(await FirebaseAuthTokenProvider(app).getIdToken(), 'id-token'); + expect(platform.user!.forceRefreshRequests, [false]); + }); + + test('passes forceRefresh through', () async { + final app = await newApp(); + platform.user = _FakeUserPlatform(platform, token: 'fresh-token'); + + final token = await FirebaseAuthTokenProvider( + app, + ).getIdToken(forceRefresh: true); + + expect(token, 'fresh-token'); + expect(platform.user!.forceRefreshRequests, [true]); + }); + + test("propagates Auth's exception", () async { + final app = await newApp(); + platform.user = _FakeUserPlatform( + platform, + error: FirebaseAuthException(code: 'network-request-failed'), + ); + + await expectLater( + FirebaseAuthTokenProvider(app).getIdToken(), + throwsA( + isA().having( + (e) => e.code, + 'code', + 'network-request-failed', + ), + ), + ); + }); + }); +} + +class _FakeFirebaseAuthPlatform extends FirebaseAuthPlatform { + _FakeFirebaseAuthPlatform() : super(); + + _FakeUserPlatform? user; + + @override + FirebaseAuthPlatform delegateFor({ + FirebaseApp? app, + Persistence? persistence, + }) => this; + + @override + FirebaseAuthPlatform setInitialValues({ + InternalUserDetails? currentUser, + String? languageCode, + }) => this; + + @override + UserPlatform? get currentUser => user; +} + +class _FakeUserPlatform extends UserPlatform { + _FakeUserPlatform(FirebaseAuthPlatform auth, {this.token, this.error}) + : super(auth, _FakeMultiFactorPlatform(auth), _details); + + final String? token; + final Object? error; + final List forceRefreshRequests = []; + + @override + Future getIdToken(bool forceRefresh) async { + forceRefreshRequests.add(forceRefresh); + if (error case final error?) { + throw error; + } + return token; + } +} + +class _FakeMultiFactorPlatform extends MultiFactorPlatform { + _FakeMultiFactorPlatform(super.auth); +} + +final _details = InternalUserDetails( + userInfo: InternalUserInfo( + uid: 'uid', + isAnonymous: true, + isEmailVerified: false, + ), + providerData: const [], +); diff --git a/packages/firebase_auth/firebase_auth_web/lib/firebase_auth_web.dart b/packages/firebase_auth/firebase_auth_web/lib/firebase_auth_web.dart index f94c06a0483e..4a1343c4d0b2 100644 --- a/packages/firebase_auth/firebase_auth_web/lib/firebase_auth_web.dart +++ b/packages/firebase_auth/firebase_auth_web/lib/firebase_auth_web.dart @@ -11,6 +11,8 @@ import 'package:firebase_auth_platform_interface/firebase_auth_platform_interfac import 'package:firebase_auth_web/src/firebase_auth_web_multi_factor.dart'; import 'package:firebase_auth_web/src/utils/web_utils.dart'; import 'package:firebase_core/firebase_core.dart'; +import 'package:firebase_core_platform_interface/firebase_core_platform_interface.dart' + show AuthTokenProvider, registerFirebaseServiceFactory; import 'package:firebase_core_web/firebase_core_web.dart'; import 'package:firebase_core_web/firebase_core_web_interop.dart' as core_interop; @@ -23,6 +25,7 @@ import 'src/firebase_auth_version.dart'; import 'src/auth_emulator.dart'; import 'src/firebase_auth_web_confirmation_result.dart'; import 'src/firebase_auth_web_recaptcha_verifier_factory.dart'; +import 'src/firebase_auth_web_token_provider.dart'; import 'src/firebase_auth_web_user.dart'; import 'src/firebase_auth_web_user_credential.dart'; import 'src/interop/auth.dart' as auth_interop; @@ -107,6 +110,10 @@ class FirebaseAuthWeb extends FirebaseAuthPlatform { }, ); FirebaseAuthPlatform.instance = FirebaseAuthWeb.instance; + // Other Firebase packages get the signed-in user's ID token from here. + registerFirebaseServiceFactory( + FirebaseAuthWebTokenProvider.new, + ); PhoneMultiFactorGeneratorPlatform.instance = PhoneMultiFactorGeneratorWeb(); TotpMultiFactorGeneratorPlatform.instance = TotpMultiFactorGeneratorWeb(); RecaptchaVerifierFactoryPlatform.instance = diff --git a/packages/firebase_auth/firebase_auth_web/lib/src/firebase_auth_web_token_provider.dart b/packages/firebase_auth/firebase_auth_web/lib/src/firebase_auth_web_token_provider.dart new file mode 100644 index 000000000000..07e751a83299 --- /dev/null +++ b/packages/firebase_auth/firebase_auth_web/lib/src/firebase_auth_web_token_provider.dart @@ -0,0 +1,38 @@ +// Copyright 2026, the Chromium project authors. Please see the AUTHORS file +// 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_core/firebase_core.dart'; +import 'package:firebase_core_platform_interface/firebase_core_platform_interface.dart' + show AuthTokenProvider; +import 'package:firebase_core_web/firebase_core_web_interop.dart' + as core_interop; + +import 'interop/auth.dart' as auth_interop; +import 'utils/web_utils.dart'; + +/// Hands out the ID token of the user signed in to the JS Auth instance of +/// [app]. +/// +/// `FirebaseAuthWeb.registerWith` registers it as the app's +/// [AuthTokenProvider]. Resolved per app through +/// `app.getService()`; not for app code. +class FirebaseAuthWebTokenProvider implements AuthTokenProvider { + /// Creates the provider for [app]. + FirebaseAuthWebTokenProvider(this.app); + + /// The app whose Auth instance supplies the token. + final FirebaseApp app; + + @override + Future getIdToken({bool forceRefresh = false}) async { + // The JS Auth instance exists since Firebase.initializeApp: the web plugin + // initializes it there and waits for the restored user. + final auth = auth_interop.getAuthInstance(core_interop.app(app.name)); + final user = auth.currentUser; + if (user == null) { + return null; + } + return guardAuthExceptions(() => user.getIdToken(forceRefresh), auth: auth); + } +} diff --git a/packages/firebase_auth/firebase_auth_web/pubspec.yaml b/packages/firebase_auth/firebase_auth_web/pubspec.yaml index bc1ba6469dc2..eb12cb3ecd03 100644 --- a/packages/firebase_auth/firebase_auth_web/pubspec.yaml +++ b/packages/firebase_auth/firebase_auth_web/pubspec.yaml @@ -12,6 +12,7 @@ environment: dependencies: firebase_auth_platform_interface: ^9.1.2 firebase_core: ^5.1.0 + firebase_core_platform_interface: ^8.1.1 firebase_core_web: ^4.1.0 flutter: sdk: flutter From 37bcbbe5e8826d3e175ee5366edb5bcd19aa961a Mon Sep 17 00:00:00 2001 From: jonathanedey Date: Mon, 23 Nov 2026 18:13:29 -0500 Subject: [PATCH 3/6] feat(messaging): register a MessagingTokenProvider for the FCM token firebase_messaging registers a MessagingTokenProvider for every app before main through a dartPluginClass registrant on Android and Apple platforms, and firebase_messaging_web does so in registerWith, so other Firebase packages can attach the FCM registration token to their own requests, as the Functions SDKs do. The provider reads the token through the new FirebaseMessagingPlatform.getCachedToken rather than getToken, so it never requests notification permission, and answers null when there is no token or the read fails. Apple platforms read the token the SDK holds; the Android token read returns the stored token and registers one only when none is stored, as the Instance ID read the native Functions SDK uses does; web reads it only once notification permission is already granted, as the JS Functions SDK does. Messaging serves the default app only, so the provider answers null for any other app. --- .../FlutterFirebaseMessagingPlugin.java | 7 ++ .../FLTFirebaseMessagingPlugin.m | 10 ++ .../lib/src/registrant.dart | 59 +++++++++ .../firebase_messaging/pubspec.yaml | 9 ++ .../test/registrant_test.dart | 116 ++++++++++++++++++ .../method_channel_messaging.dart | 15 +++ .../platform_interface_messaging.dart | 14 +++ .../method_channel_messaging_test.dart | 19 +++ .../platform_interface_messaging_test.dart | 10 ++ .../lib/firebase_messaging_web.dart | 34 +++++ ...firebase_messaging_web_token_provider.dart | 35 ++++++ .../firebase_messaging_web/pubspec.yaml | 2 +- 12 files changed, 329 insertions(+), 1 deletion(-) create mode 100644 packages/firebase_messaging/firebase_messaging/lib/src/registrant.dart create mode 100644 packages/firebase_messaging/firebase_messaging/test/registrant_test.dart create mode 100644 packages/firebase_messaging/firebase_messaging_web/lib/src/firebase_messaging_web_token_provider.dart diff --git a/packages/firebase_messaging/firebase_messaging/android/src/main/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingPlugin.java b/packages/firebase_messaging/firebase_messaging/android/src/main/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingPlugin.java index 12021ee2ed6c..5c2fb8f5bf6b 100644 --- a/packages/firebase_messaging/firebase_messaging/android/src/main/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingPlugin.java +++ b/packages/firebase_messaging/firebase_messaging/android/src/main/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingPlugin.java @@ -615,6 +615,13 @@ public void onMethodCall(final MethodCall call, @NonNull final Result result) { case "Messaging#getToken": methodCallTask = getToken(); break; + case "Messaging#getCachedToken": + // The SDK has no read that returns only a stored token: getToken() + // returns the stored token when it is valid and registers one + // otherwise, as the Instance ID read the native Functions SDK uses + // does. Neither asks for notification permission. + methodCallTask = getToken(); + break; case "Messaging#register": methodCallTask = register(); break; diff --git a/packages/firebase_messaging/firebase_messaging/ios/firebase_messaging/Sources/firebase_messaging/FLTFirebaseMessagingPlugin.m b/packages/firebase_messaging/firebase_messaging/ios/firebase_messaging/Sources/firebase_messaging/FLTFirebaseMessagingPlugin.m index 06fee23c5929..341a231ae6bb 100644 --- a/packages/firebase_messaging/firebase_messaging/ios/firebase_messaging/Sources/firebase_messaging/FLTFirebaseMessagingPlugin.m +++ b/packages/firebase_messaging/firebase_messaging/ios/firebase_messaging/Sources/firebase_messaging/FLTFirebaseMessagingPlugin.m @@ -249,6 +249,8 @@ - (void)handleMethodCall:(FlutterMethodCall *)call result:(FlutterResult)flutter withMethodCallResult:methodCallResult]; } else if ([@"Messaging#getToken" isEqualToString:call.method]) { [self messagingGetToken:call.arguments withMethodCallResult:methodCallResult]; + } else if ([@"Messaging#getCachedToken" isEqualToString:call.method]) { + [self messagingGetCachedToken:call.arguments withMethodCallResult:methodCallResult]; } else if ([@"Messaging#register" isEqualToString:call.method]) { [self messagingRegister:call.arguments withMethodCallResult:methodCallResult]; } else if ([@"Messaging#unregister" isEqualToString:call.method]) { @@ -1103,6 +1105,14 @@ - (void)messagingGetToken:(id)arguments withMethodCallResult:(FLTFirebaseMethodC }]; } +- (void)messagingGetCachedToken:(id)arguments + withMethodCallResult:(FLTFirebaseMethodCallResult *)result { + // The token the SDK already holds. Unlike tokenWithCompletion: this never + // registers one, which is how the native Functions SDK reads it. + NSString *token = [FIRMessaging messaging].FCMToken; + result.success(@{@"token" : token ?: [NSNull null]}); +} + - (void)messagingGetAPNSToken:(id)arguments withMethodCallResult:(FLTFirebaseMethodCallResult *)result { NSData *apnsToken = [FIRMessaging messaging].APNSToken; diff --git a/packages/firebase_messaging/firebase_messaging/lib/src/registrant.dart b/packages/firebase_messaging/firebase_messaging/lib/src/registrant.dart new file mode 100644 index 000000000000..b7c9f2f69fe1 --- /dev/null +++ b/packages/firebase_messaging/firebase_messaging/lib/src/registrant.dart @@ -0,0 +1,59 @@ +// Copyright 2026, the Chromium project authors. Please see the AUTHORS file +// 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_core/firebase_core.dart'; +import 'package:firebase_core_platform_interface/firebase_core_platform_interface.dart' + show MessagingTokenProvider, registerFirebaseServiceFactory; +import 'package:firebase_messaging_platform_interface/firebase_messaging_platform_interface.dart'; + +/// Registers Messaging as the [MessagingTokenProvider] of every app. +/// +/// The Flutter plugin registrant calls [registerWith] before `main` on +/// Android and Apple platforms (see `dartPluginClass` in pubspec.yaml), so +/// other Firebase packages can ask an app for the FCM token before the app +/// has used Messaging itself. `firebase_messaging_web` registers its own +/// provider. +class FirebaseMessagingRegistrant { + // Not meant to be instantiated. + FirebaseMessagingRegistrant._(); + + /// Registers the [MessagingTokenProvider] factory with [FirebaseApp]. + static void registerWith() { + registerFirebaseServiceFactory( + FirebaseMessagingTokenProvider.new, + ); + } +} + +/// Hands out the FCM registration token Messaging holds for [app]. +/// +/// Resolved per app through `app.getService()`; not +/// for app code. +class FirebaseMessagingTokenProvider implements MessagingTokenProvider { + /// Creates the provider for [app]. + FirebaseMessagingTokenProvider(this.app); + + /// The app whose Messaging instance supplies the token. + final FirebaseApp app; + + @override + Future getFcmToken() async { + // Messaging serves the default app only. + if (app.name != defaultFirebaseAppName) { + return null; + } + try { + // A delegate of its own, rather than FirebaseMessaging.instance, whose + // getter has a foreground-message side effect. The read doesn't depend + // on the plugin constants. + return await FirebaseMessagingPlatform.instanceFor( + app: app, + pluginConstants: const {}, + ).getCachedToken(); + } catch (_) { + // The Functions SDKs send no token when Messaging can't read one. + return null; + } + } +} diff --git a/packages/firebase_messaging/firebase_messaging/pubspec.yaml b/packages/firebase_messaging/firebase_messaging/pubspec.yaml index 51a2caa626c1..091f9980b2a3 100644 --- a/packages/firebase_messaging/firebase_messaging/pubspec.yaml +++ b/packages/firebase_messaging/firebase_messaging/pubspec.yaml @@ -34,14 +34,23 @@ dev_dependencies: plugin_platform_interface: ^2.1.3 flutter: + # `dartPluginClass` registers Messaging as the app's `MessagingTokenProvider` + # before `main` (and in background isolates the engine starts), so other + # Firebase packages can read the FCM token before the app uses Messaging. plugin: platforms: android: package: io.flutter.plugins.firebase.messaging pluginClass: FlutterFirebaseMessagingPlugin + dartPluginClass: FirebaseMessagingRegistrant + dartFileName: src/registrant.dart ios: pluginClass: FLTFirebaseMessagingPlugin + dartPluginClass: FirebaseMessagingRegistrant + dartFileName: src/registrant.dart macos: pluginClass: FLTFirebaseMessagingPlugin + dartPluginClass: FirebaseMessagingRegistrant + dartFileName: src/registrant.dart web: default_package: firebase_messaging_web diff --git a/packages/firebase_messaging/firebase_messaging/test/registrant_test.dart b/packages/firebase_messaging/firebase_messaging/test/registrant_test.dart new file mode 100644 index 000000000000..0e432baefe00 --- /dev/null +++ b/packages/firebase_messaging/firebase_messaging/test/registrant_test.dart @@ -0,0 +1,116 @@ +// Copyright 2026, the Chromium project authors. Please see the AUTHORS file +// 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_core/firebase_core.dart'; +import 'package:firebase_core_platform_interface/firebase_core_platform_interface.dart' + show MessagingTokenProvider; +import 'package:firebase_messaging/src/registrant.dart'; +import 'package:firebase_messaging_platform_interface/firebase_messaging_platform_interface.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import './mock.dart'; + +void main() { + setupFirebaseMessagingMocks(); + + late _FakeFirebaseMessagingPlatform platform; + late FirebaseApp defaultApp; + var appCount = 0; + + setUpAll(() async { + defaultApp = await Firebase.initializeApp(); + FirebaseMessagingRegistrant.registerWith(); + }); + + setUp( + () => FirebaseMessagingPlatform.instance = platform = + _FakeFirebaseMessagingPlatform(), + ); + + Future newApp() => Firebase.initializeApp( + name: 'token-provider-${appCount++}', + options: const FirebaseOptions( + apiKey: '', + appId: '', + messagingSenderId: '', + projectId: '', + ), + ); + + group('$FirebaseMessagingRegistrant', () { + test( + 'registers a MessagingTokenProvider before the app uses Messaging', + () async { + final provider = defaultApp.getService(); + + expect(provider, isA()); + expect(defaultApp.getService(), same(provider)); + expect(platform.reads, 0); + }, + ); + }); + + group('$FirebaseMessagingTokenProvider', () { + test('is null when nothing is cached', () async { + expect( + await FirebaseMessagingTokenProvider(defaultApp).getFcmToken(), + isNull, + ); + expect(platform.reads, 1); + }); + + test('is the cached token', () async { + platform.token = 'fcm-token'; + + expect( + await FirebaseMessagingTokenProvider(defaultApp).getFcmToken(), + 'fcm-token', + ); + }); + + test('is null for an app other than the default, without asking', () async { + final app = await newApp(); + platform.token = 'fcm-token'; + + expect(await FirebaseMessagingTokenProvider(app).getFcmToken(), isNull); + expect(platform.reads, 0); + }); + + test("is null when the token can't be read", () async { + platform.error = FirebaseException( + plugin: 'firebase_messaging', + code: 'unknown', + message: 'SERVICE_NOT_AVAILABLE', + ); + + expect( + await FirebaseMessagingTokenProvider(defaultApp).getFcmToken(), + isNull, + ); + }); + }); +} + +class _FakeFirebaseMessagingPlatform extends FirebaseMessagingPlatform { + _FakeFirebaseMessagingPlatform() : super(); + + String? token; + Object? error; + int reads = 0; + + @override + FirebaseMessagingPlatform delegateFor({required FirebaseApp app}) => this; + + @override + FirebaseMessagingPlatform setInitialValues({bool? isAutoInitEnabled}) => this; + + @override + Future getCachedToken() async { + reads++; + if (error case final error?) { + throw error; + } + return token; + } +} diff --git a/packages/firebase_messaging/firebase_messaging_platform_interface/lib/src/method_channel/method_channel_messaging.dart b/packages/firebase_messaging/firebase_messaging_platform_interface/lib/src/method_channel/method_channel_messaging.dart index 80c60c8ba62e..7486b761d866 100644 --- a/packages/firebase_messaging/firebase_messaging_platform_interface/lib/src/method_channel/method_channel_messaging.dart +++ b/packages/firebase_messaging/firebase_messaging_platform_interface/lib/src/method_channel/method_channel_messaging.dart @@ -368,6 +368,21 @@ class MethodChannelFirebaseMessaging extends FirebaseMessagingPlatform { } } + @override + Future getCachedToken() async { + // No APNs check: a missing APNs token just means no FCM token is cached. + try { + Map? data = await channel + .invokeMapMethod('Messaging#getCachedToken', { + 'appName': app.name, + }); + + return data?['token']; + } catch (e, stack) { + convertPlatformException(e, stack); + } + } + @override @Deprecated('Use register() and onRegistered instead.') Future getToken({ diff --git a/packages/firebase_messaging/firebase_messaging_platform_interface/lib/src/platform_interface/platform_interface_messaging.dart b/packages/firebase_messaging/firebase_messaging_platform_interface/lib/src/platform_interface/platform_interface_messaging.dart index b27a4016dbaf..1affdfb549fc 100644 --- a/packages/firebase_messaging/firebase_messaging_platform_interface/lib/src/platform_interface/platform_interface_messaging.dart +++ b/packages/firebase_messaging/firebase_messaging_platform_interface/lib/src/platform_interface/platform_interface_messaging.dart @@ -183,6 +183,20 @@ abstract class FirebaseMessagingPlatform extends PlatformInterface { throw UnimplementedError('getAPNSToken() is not implemented'); } + /// The FCM registration token this app instance already holds, or `null` + /// when there is none. + /// + /// For other Firebase packages that attach the token to their own requests, + /// as the Functions SDKs do. Unlike [register], this never prompts for + /// notification permission. On Apple platforms it reads the token the SDK + /// has cached. On Android the SDK's token read returns the stored token and + /// registers one only when none is stored, as the Instance ID read the + /// native Functions SDK uses does. On web the token is read only when + /// notification permission is already granted. + Future getCachedToken() { + throw UnimplementedError('getCachedToken() is not implemented'); + } + /// Registers the current app instance with Firebase Cloud Messaging. /// /// Once registration completes, [onRegistered] provides the Firebase diff --git a/packages/firebase_messaging/firebase_messaging_platform_interface/test/method_channel_tests/method_channel_messaging_test.dart b/packages/firebase_messaging/firebase_messaging_platform_interface/test/method_channel_tests/method_channel_messaging_test.dart index fb57c95cf5d2..c74f66178c69 100644 --- a/packages/firebase_messaging/firebase_messaging_platform_interface/test/method_channel_tests/method_channel_messaging_test.dart +++ b/packages/firebase_messaging/firebase_messaging_platform_interface/test/method_channel_tests/method_channel_messaging_test.dart @@ -37,6 +37,8 @@ void main() { case 'Messaging#getAPNSToken': case 'Messaging#getToken': return {'token': 'test_token'}; + case 'Messaging#getCachedToken': + return {'token': 'cached_token'}; case 'Messaging#hasPermission': case 'Messaging#requestPermission': case 'Messaging#getNotificationSettings': @@ -165,6 +167,19 @@ void main() { ]); }); + test('getCachedToken', () async { + final token = await messaging.getCachedToken(); + + expect(token, 'cached_token'); + // check native method was called + expect(log, [ + isMethodCall( + 'Messaging#getCachedToken', + arguments: {'appName': defaultFirebaseAppName}, + ), + ]); + }); + test('getNotificationSettings', () async { final settings = await messaging.getNotificationSettings(); expect(settings, isA()); @@ -226,6 +241,8 @@ void main() { case 'Messaging#getAPNSToken': case 'Messaging#getToken': return {'token': 'test_token'}; + case 'Messaging#getCachedToken': + return {'token': 'cached_token'}; case 'Messaging#hasPermission': case 'Messaging#requestPermission': case 'Messaging#getNotificationSettings': @@ -294,6 +311,8 @@ void main() { case 'Messaging#getAPNSToken': case 'Messaging#getToken': return {'token': 'test_token'}; + case 'Messaging#getCachedToken': + return {'token': 'cached_token'}; case 'Messaging#hasPermission': case 'Messaging#requestPermission': case 'Messaging#getNotificationSettings': diff --git a/packages/firebase_messaging/firebase_messaging_platform_interface/test/platform_interface_tests/platform_interface_messaging_test.dart b/packages/firebase_messaging/firebase_messaging_platform_interface/test/platform_interface_tests/platform_interface_messaging_test.dart index 3c2cd43d6640..5545d099d94c 100644 --- a/packages/firebase_messaging/firebase_messaging_platform_interface/test/platform_interface_tests/platform_interface_messaging_test.dart +++ b/packages/firebase_messaging/firebase_messaging_platform_interface/test/platform_interface_tests/platform_interface_messaging_test.dart @@ -150,6 +150,16 @@ void main() { fail('Should have thrown an [UnimplementedError]'); }); + test('throws if getCachedToken()', () async { + try { + await firebaseMessagingPlatform.getCachedToken(); + } on UnimplementedError catch (e) { + expect(e.message, equals('getCachedToken() is not implemented')); + return; + } + fail('Should have thrown an [UnimplementedError]'); + }); + test('throws if register()', () async { try { await firebaseMessagingPlatform.register(); diff --git a/packages/firebase_messaging/firebase_messaging_web/lib/firebase_messaging_web.dart b/packages/firebase_messaging/firebase_messaging_web/lib/firebase_messaging_web.dart index cc8ec31773d6..46866241ea4d 100644 --- a/packages/firebase_messaging/firebase_messaging_web/lib/firebase_messaging_web.dart +++ b/packages/firebase_messaging/firebase_messaging_web/lib/firebase_messaging_web.dart @@ -5,8 +5,11 @@ import 'dart:async'; import 'dart:js_interop'; +import 'dart:js_interop_unsafe'; import 'package:firebase_core/firebase_core.dart'; +import 'package:firebase_core_platform_interface/firebase_core_platform_interface.dart' + show MessagingTokenProvider, registerFirebaseServiceFactory; import 'package:firebase_core_web/firebase_core_web.dart'; import 'package:firebase_core_web/firebase_core_web_interop.dart' as core_interop; @@ -19,6 +22,7 @@ import 'src/interop/messaging.dart' as messaging_interop; import 'src/utils.dart' as utils; import 'src/firebase_messaging_version.dart'; +import 'src/firebase_messaging_web_token_provider.dart'; /// Web implementation for [FirebaseMessagingPlatform] /// delegates calls to messaging web plugin. @@ -55,6 +59,10 @@ class FirebaseMessagingWeb extends FirebaseMessagingPlatform { FirebaseCoreWeb.registerService('messaging'); FirebaseMessagingPlatform.instance = FirebaseMessagingWeb(); + // Other Firebase packages get the FCM token from here. + registerFirebaseServiceFactory( + FirebaseMessagingWebTokenProvider.new, + ); } Stream? _noopOnTokenRefreshStream; @@ -157,6 +165,32 @@ class FirebaseMessagingWeb extends FirebaseMessagingPlatform { return _delegate.onUnregistered; } + @override + Future getCachedToken() async { + // Asking Messaging for a token prompts for permission while it is + // undecided, so only ask once it is granted, as the JS Functions SDK does. + // Messaging then returns the stored token, creating one only when there + // is none. + if (!globalContext.has('Notification') || + web.Notification.permission != 'granted') { + return null; + } + + _delegate; + + if (!_initialized) { + // no-op for unsupported browsers + return null; + } + + try { + return await _delegate.getToken(); + } catch (_) { + // The JS Functions SDK sends no token when Messaging can't produce one. + return null; + } + } + @override @Deprecated('Use register() and onRegistered instead.') Future getToken({ diff --git a/packages/firebase_messaging/firebase_messaging_web/lib/src/firebase_messaging_web_token_provider.dart b/packages/firebase_messaging/firebase_messaging_web/lib/src/firebase_messaging_web_token_provider.dart new file mode 100644 index 000000000000..d61a651242e9 --- /dev/null +++ b/packages/firebase_messaging/firebase_messaging_web/lib/src/firebase_messaging_web_token_provider.dart @@ -0,0 +1,35 @@ +// Copyright 2026, the Chromium project authors. Please see the AUTHORS file +// 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_core/firebase_core.dart'; +import 'package:firebase_core_platform_interface/firebase_core_platform_interface.dart' + show MessagingTokenProvider; +import 'package:firebase_messaging_web/firebase_messaging_web.dart'; + +/// Hands out the FCM registration token Messaging holds for [app]. +/// +/// `FirebaseMessagingWeb.registerWith` registers it as the app's +/// [MessagingTokenProvider]. Resolved per app through +/// `app.getService()`; not for app code. +class FirebaseMessagingWebTokenProvider implements MessagingTokenProvider { + /// Creates the provider for [app]. + FirebaseMessagingWebTokenProvider(this.app); + + /// The app whose Messaging instance supplies the token. + final FirebaseApp app; + + @override + Future getFcmToken() async { + // Messaging serves the default app only. + if (app.name != defaultFirebaseAppName) { + return null; + } + try { + return await FirebaseMessagingWeb(app: app).getCachedToken(); + } catch (_) { + // The Functions SDKs send no token when Messaging can't read one. + return null; + } + } +} diff --git a/packages/firebase_messaging/firebase_messaging_web/pubspec.yaml b/packages/firebase_messaging/firebase_messaging_web/pubspec.yaml index a0d44e8e7839..599305b382d0 100644 --- a/packages/firebase_messaging/firebase_messaging_web/pubspec.yaml +++ b/packages/firebase_messaging/firebase_messaging_web/pubspec.yaml @@ -12,6 +12,7 @@ environment: dependencies: _flutterfire_internals: ^1.3.79 firebase_core: ^5.1.0 + firebase_core_platform_interface: ^8.1.1 firebase_core_web: ^4.1.0 firebase_messaging_platform_interface: ^4.11.1 flutter: @@ -22,7 +23,6 @@ dependencies: web: ^1.0.0 dev_dependencies: - firebase_core_platform_interface: ^8.1.1 flutter_test: sdk: flutter mockito: ^5.0.0 From 058cab357be23ca42e92a320fc8156a4cca967e2 Mon Sep 17 00:00:00 2001 From: jonathanedey Date: Mon, 23 Nov 2026 18:13:29 -0500 Subject: [PATCH 4/6] test(core): cover the token providers in the tests app core suite The tests app links the Auth, App Check and Messaging plugins: each provider is registered before the suite touches its plugin; the Auth provider answers null when signed out and the ID token of the user signed in against the emulator; the App Check provider answers with the placeholder and the reason before activation and stays the same provider once the app uses App Check; the Messaging provider answers null or the token the SDK holds without prompting for permission. --- .../firebase_core/firebase_core_e2e_test.dart | 118 ++++++++++++++++++ 1 file changed, 118 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..4178540fbbc1 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,8 @@ // 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_app_check/firebase_app_check.dart'; +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 +86,121 @@ void main() { expect(app.name, demoProjectId); expect(app.options.projectId, demoProjectId); }); + + // The tests app links the Auth, App Check and Messaging plugins, so their + // token providers are available to any package that asks the app for + // them. Auth runs against the emulator that CI starts around this suite. + group('token providers', () { + late FirebaseApp defaultApp; + + setUpAll(() => defaultApp = Firebase.app()); + + // Declared before anything in this suite touches FirebaseAuth, + // FirebaseAppCheck or FirebaseMessaging: the plugins register their + // providers before main (dartPluginClass on Android, Apple and Windows; + // registerWith on web), so a user restored from a previous launch, or a + // token the SDK holds, is reachable before the app uses the plugin. + test('AuthTokenProvider is registered before the app uses Auth', () { + expect(defaultApp.getService(), isNotNull); + }); + + test( + 'AppCheckTokenProvider is registered before the app uses App Check', + () { + expect(defaultApp.getService(), isNotNull); + }, + ); + + test( + 'MessagingTokenProvider is registered before the app uses Messaging', + () { + expect(defaultApp.getService(), isNotNull); + }, + // There is no Messaging plugin on Windows. + skip: !kIsWeb && defaultTargetPlatform == TargetPlatform.windows, + ); + + group('AuthTokenProvider', () { + late AuthTokenProvider provider; + + setUpAll(() async { + provider = defaultApp.getService()!; + await FirebaseAuth.instance.useAuthEmulator( + defaultTargetPlatform == TargetPlatform.android && !kIsWeb + ? '10.0.2.2' + : 'localhost', + 9099, + ); + }); + + tearDown(() => FirebaseAuth.instance.signOut()); + + test('getIdToken is null when nobody is signed in', () async { + await FirebaseAuth.instance.signOut(); + + expect(await provider.getIdToken(), isNull); + }); + + test( + "getIdToken is the signed-in user's ID token", + () async { + final credential = await FirebaseAuth.instance.signInAnonymously(); + final idToken = await credential.user!.getIdToken(); + + expect(await provider.getIdToken(), 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: !kIsWeb && defaultTargetPlatform == TargetPlatform.macOS, + ); + }); + + group('AppCheckTokenProvider', () { + test( + 'getToken answers with the placeholder before activation', + () async { + // App Check is linked but never activated in this app, so the + // plugin can't produce a token; the provider answers the way the + // SDKs answer each other, with the placeholder and the reason. + final answer = await defaultApp + .getService()! + .getToken(); + + expect(answer, isNotNull); + expect(answer!.token, AppCheckInteropToken.placeholderToken); + expect(answer.error, isNotNull); + }, + ); + + test('stays the same provider once the app uses FirebaseAppCheck', () { + // Using App Check after the provider exists must not replace it. + final provider = defaultApp.getService(); + FirebaseAppCheck.instanceFor(app: defaultApp); + + expect( + defaultApp.getService(), + same(provider), + ); + }); + }); + + group('MessagingTokenProvider', () { + test('getFcmToken answers null or the token the SDK holds', () async { + // Nothing in this suite requests notification permission, so on + // web and on fresh simulators there is no token; the call must + // answer without prompting or throwing either way. + final token = await defaultApp + .getService()! + .getFcmToken(); + + expect(token, anyOf(isNull, isA())); + if (kIsWeb) { + // CI's browser never grants notification permission. + expect(token, isNull); + } + }, skip: !kIsWeb && defaultTargetPlatform == TargetPlatform.windows); + }); + }); }); } From 7289e46c1207106fc793c89d60643fdb88b70375 Mon Sep 17 00:00:00 2001 From: jonathanedey Date: Thu, 26 Nov 2026 16:01:22 -0500 Subject: [PATCH 5/6] fix(messaging,android): honor firebase_messaging_installation_id_enabled Messaging#getCachedToken called getToken() unconditionally, so an app that sends to the installation ID got a legacy token, and with it a second registration, on its first callable; FCM then rejects sends to the installation ID. Native Functions reads the manifest meta-data firebase_messaging_installation_id_enabled and sends no token when it is true. Do the same: read the key with PackageManager.GET_META_DATA, as FlutterFirebaseMessagingBackgroundGate does, answer null when it is true, and warn and fall through when the package manager cannot read the manifest. The tests app sets the flag, so the Android e2e now expects null from the provider. Apple and web are unaffected. --- .../lib/src/token_providers.dart | 6 +- .../FlutterFirebaseMessagingPlugin.java | 47 +++++- ...irebaseMessagingPluginCachedTokenTest.java | 138 ++++++++++++++++++ .../platform_interface_messaging.dart | 7 +- .../firebase_core/firebase_core_e2e_test.dart | 5 + 5 files changed, 195 insertions(+), 8 deletions(-) create mode 100644 packages/firebase_messaging/firebase_messaging/android/src/test/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingPluginCachedTokenTest.java diff --git a/packages/firebase_core/firebase_core_interface/lib/src/token_providers.dart b/packages/firebase_core/firebase_core_interface/lib/src/token_providers.dart index 1fa52d0099a6..59e427851e55 100644 --- a/packages/firebase_core/firebase_core_interface/lib/src/token_providers.dart +++ b/packages/firebase_core/firebase_core_interface/lib/src/token_providers.dart @@ -69,7 +69,11 @@ abstract interface class MessagingTokenProvider implements FirebaseService { /// /// Never prompts for notification permission. On Apple platforms this is a /// cached read only; on Android and web it may register a token when none - /// is stored, as native Functions does. Never throws, unlike + /// is stored, as native Functions does. On Android the answer is `null` + /// when the manifest enables the installation ID + /// (`firebase_messaging_installation_id_enabled`), as native Functions + /// does: fetching a legacy token then creates a second registration, and + /// FCM rejects sends to the installation ID. Never throws, unlike /// [AuthTokenProvider.getIdToken]: when the token can't be read the answer /// is `null`, as the FCM header is best-effort in the native Functions /// SDKs too. Messaging serves the default app only, in FlutterFire as in diff --git a/packages/firebase_messaging/firebase_messaging/android/src/main/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingPlugin.java b/packages/firebase_messaging/firebase_messaging/android/src/main/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingPlugin.java index 5c2fb8f5bf6b..381b235a5513 100644 --- a/packages/firebase_messaging/firebase_messaging/android/src/main/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingPlugin.java +++ b/packages/firebase_messaging/firebase_messaging/android/src/main/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingPlugin.java @@ -11,6 +11,7 @@ import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; +import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; @@ -57,6 +58,10 @@ public class FlutterFirebaseMessagingPlugin private static final String TAG = "FLTFireMsgPlugin"; + /** Manifest meta-data of apps that send to the installation ID; native Functions reads it too. */ + @VisibleForTesting + static final String INSTALLATION_ID_ENABLED_KEY = "firebase_messaging_installation_id_enabled"; + // Messages sent to Dart before it has set up its handler on the channel, e.g. the token or a // message received while the engine starts. Flutter only keeps one by default. private static final int CHANNEL_BUFFER_SIZE = 64; @@ -208,6 +213,42 @@ private Task> getToken() { return taskCompletionSource.getTask(); } + private Task> getCachedToken() { + // An app that sends to the installation ID must not get a legacy token: fetching one creates a + // second registration and FCM rejects sends to the installation ID, so native Functions sends + // no token for such apps. Otherwise the SDK has no read that returns only a stored token: + // getToken() returns the stored token when it is valid and registers one otherwise, as the + // Instance ID read native Functions uses does. Neither asks for notification permission. + if (installationIdEnabled(ContextHolder.getApplicationContext())) { + Map noToken = new HashMap<>(); + noToken.put("token", null); + return Tasks.forResult(noToken); + } + return getToken(); + } + + /** Whether the manifest enables the installation ID; a manifest that can't be read doesn't. */ + @VisibleForTesting + static boolean installationIdEnabled(@Nullable Context context) { + if (context == null) { + return false; + } + try { + ApplicationInfo info = + context + .getPackageManager() + .getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA); + return info.metaData != null + && Boolean.TRUE.equals( + BackgroundHandlerStartDecision.manifestValue( + info.metaData.get(INSTALLATION_ID_ENABLED_KEY))); + } catch (PackageManager.NameNotFoundException exception) { + Log.w( + TAG, "Could not read " + INSTALLATION_ID_ENABLED_KEY + " from the manifest.", exception); + return false; + } + } + private Task register() { TaskCompletionSource taskCompletionSource = new TaskCompletionSource<>(); @@ -616,11 +657,7 @@ public void onMethodCall(final MethodCall call, @NonNull final Result result) { methodCallTask = getToken(); break; case "Messaging#getCachedToken": - // The SDK has no read that returns only a stored token: getToken() - // returns the stored token when it is valid and registers one - // otherwise, as the Instance ID read the native Functions SDK uses - // does. Neither asks for notification permission. - methodCallTask = getToken(); + methodCallTask = getCachedToken(); break; case "Messaging#register": methodCallTask = register(); diff --git a/packages/firebase_messaging/firebase_messaging/android/src/test/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingPluginCachedTokenTest.java b/packages/firebase_messaging/firebase_messaging/android/src/test/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingPluginCachedTokenTest.java new file mode 100644 index 000000000000..faba2ac3f293 --- /dev/null +++ b/packages/firebase_messaging/firebase_messaging/android/src/test/java/io/flutter/plugins/firebase/messaging/FlutterFirebaseMessagingPluginCachedTokenTest.java @@ -0,0 +1,138 @@ +// Copyright 2026, the Chromium project authors. Please see the AUTHORS file +// 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. + +package io.flutter.plugins.firebase.messaging; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import android.content.Context; +import android.content.pm.PackageInfo; +import android.os.Bundle; +import android.os.Looper; +import io.flutter.plugin.common.MethodCall; +import io.flutter.plugin.common.MethodChannel; +import java.util.Map; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.RobolectricTestRunner; +import org.robolectric.RuntimeEnvironment; +import org.robolectric.Shadows; +import org.robolectric.annotation.Config; + +/** {@code Messaging#getCachedToken} and the installation ID manifest flag. */ +@RunWith(RobolectricTestRunner.class) +@Config(sdk = 28) +public class FlutterFirebaseMessagingPluginCachedTokenTest { + private Context context; + + @Before + public void setUp() { + context = RuntimeEnvironment.getApplication(); + ContextHolder.setApplicationContext(context); + } + + @After + public void tearDown() { + setManifestValue(null); + ContextHolder.setApplicationContext(null); + } + + @Test + public void installationIdIsEnabledWhenTheManifestSaysTrue() { + setManifestValue(Boolean.TRUE); + + assertTrue(FlutterFirebaseMessagingPlugin.installationIdEnabled(context)); + } + + @Test + public void installationIdIsEnabledWhenTheManifestSaysTrueAsAString() { + setManifestValue("true"); + + assertTrue(FlutterFirebaseMessagingPlugin.installationIdEnabled(context)); + } + + @Test + public void installationIdIsDisabledWhenTheManifestSaysFalse() { + setManifestValue(Boolean.FALSE); + + assertFalse(FlutterFirebaseMessagingPlugin.installationIdEnabled(context)); + } + + @Test + public void installationIdIsDisabledWhenTheManifestHasNoEntry() { + assertFalse(FlutterFirebaseMessagingPlugin.installationIdEnabled(context)); + } + + @Test + public void installationIdIsDisabledWhenThePackageManagerCannotReadTheManifest() { + setManifestValue(Boolean.TRUE); + Shadows.shadowOf(context.getPackageManager()).removePackage(context.getPackageName()); + + assertFalse(FlutterFirebaseMessagingPlugin.installationIdEnabled(context)); + } + + @Test + public void getCachedTokenAnswersNoTokenWhenTheInstallationIdIsEnabled() { + setManifestValue(Boolean.TRUE); + RecordingResult result = new RecordingResult(); + + new FlutterFirebaseMessagingPlugin() + .onMethodCall(new MethodCall("Messaging#getCachedToken", null), result); + Shadows.shadowOf(Looper.getMainLooper()).idle(); + + assertNull(result.error); + assertTrue(result.succeeded); + Map answer = (Map) result.value; + assertTrue(answer.containsKey("token")); + assertNull(answer.get("token")); + } + + private void setManifestValue(Object value) { + PackageInfo info = + Shadows.shadowOf(context.getPackageManager()) + .getInternalMutablePackageInfo(context.getPackageName()); + if (info == null) { + // Removed by the PackageManager failure test. + return; + } + if (info.applicationInfo.metaData == null) { + info.applicationInfo.metaData = new Bundle(); + } + info.applicationInfo.metaData.remove( + FlutterFirebaseMessagingPlugin.INSTALLATION_ID_ENABLED_KEY); + if (value instanceof Boolean) { + info.applicationInfo.metaData.putBoolean( + FlutterFirebaseMessagingPlugin.INSTALLATION_ID_ENABLED_KEY, (Boolean) value); + } else if (value instanceof String) { + info.applicationInfo.metaData.putString( + FlutterFirebaseMessagingPlugin.INSTALLATION_ID_ENABLED_KEY, (String) value); + } + } + + private static final class RecordingResult implements MethodChannel.Result { + boolean succeeded; + Object value; + String error; + + @Override + public void success(Object result) { + succeeded = true; + value = result; + } + + @Override + public void error(String code, String message, Object details) { + error = code + ": " + message; + } + + @Override + public void notImplemented() { + error = "notImplemented"; + } + } +} diff --git a/packages/firebase_messaging/firebase_messaging_platform_interface/lib/src/platform_interface/platform_interface_messaging.dart b/packages/firebase_messaging/firebase_messaging_platform_interface/lib/src/platform_interface/platform_interface_messaging.dart index 1affdfb549fc..6887e8678ecd 100644 --- a/packages/firebase_messaging/firebase_messaging_platform_interface/lib/src/platform_interface/platform_interface_messaging.dart +++ b/packages/firebase_messaging/firebase_messaging_platform_interface/lib/src/platform_interface/platform_interface_messaging.dart @@ -191,8 +191,11 @@ abstract class FirebaseMessagingPlatform extends PlatformInterface { /// notification permission. On Apple platforms it reads the token the SDK /// has cached. On Android the SDK's token read returns the stored token and /// registers one only when none is stored, as the Instance ID read the - /// native Functions SDK uses does. On web the token is read only when - /// notification permission is already granted. + /// native Functions SDK uses does, and the answer is `null` when the + /// manifest enables the installation ID + /// (`firebase_messaging_installation_id_enabled`), as native Functions + /// then sends no token. On web the token is read only when notification + /// permission is already granted. Future getCachedToken() { throw UnimplementedError('getCachedToken() is not implemented'); } 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 4178540fbbc1..31d6418ba097 100644 --- a/tests/integration_test/firebase_core/firebase_core_e2e_test.dart +++ b/tests/integration_test/firebase_core/firebase_core_e2e_test.dart @@ -199,6 +199,11 @@ void main() { // CI's browser never grants notification permission. expect(token, isNull); } + if (!kIsWeb && defaultTargetPlatform == TargetPlatform.android) { + // The tests app enables the installation ID in its manifest, so + // no legacy token may be fetched for it. + expect(token, isNull); + } }, skip: !kIsWeb && defaultTargetPlatform == TargetPlatform.windows); }); }); From e16ef3deaf571a211105fbc0f6b3ddb654c1df54 Mon Sep 17 00:00:00 2001 From: jonathanedey Date: Thu, 26 Nov 2026 16:06:09 -0500 Subject: [PATCH 6/6] chore(app_check,web): drop the manual CHANGELOG entry melos writes the CHANGELOG sections at release from the commit subjects that touch each package, so a hand-written section above the generated ones would be left stranded. The shared App Check instance is described in the commit that introduces it and in the PR. --- .../firebase_app_check/firebase_app_check_web/CHANGELOG.md | 4 ---- 1 file changed, 4 deletions(-) diff --git a/packages/firebase_app_check/firebase_app_check_web/CHANGELOG.md b/packages/firebase_app_check/firebase_app_check_web/CHANGELOG.md index d22895c83f5b..5d11bc285adb 100644 --- a/packages/firebase_app_check/firebase_app_check_web/CHANGELOG.md +++ b/packages/firebase_app_check/firebase_app_check_web/CHANGELOG.md @@ -1,7 +1,3 @@ -## NEXT - - - Every `FirebaseAppCheckWeb` delegate of an app now shares the app's activated JS App Check instance, instead of each delegate activating its own. A delegate created after `activate()` ran, such as the app's `AppCheckTokenProvider` or `FirebaseAppCheck.instance` after `registerWith` re-activated App Check from the provider saved in local storage, now uses that instance rather than failing with "activate() must be called first". Activating an app that is already activated keeps its instance and does not initialize App Check again. - ## 0.3.2+4 - **FIX**(core,appcheck,web): start when the browser blocks web storage ([#18946](https://github.com/firebase/flutterfire/issues/18946)). ([229e08e8](https://github.com/firebase/flutterfire/commit/229e08e8f0b197c1eef240db73a716d7f948c2a1))