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..5577bdc2f69b --- /dev/null +++ b/packages/firebase_app_check/firebase_app_check/lib/src/registrant.dart @@ -0,0 +1,83 @@ +// 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_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; + +/// Registers App Check 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, + dispose: (provider) => + (provider as FirebaseAppCheckTokenProvider)._dispose(), + ); + } +} + +/// Hands out the App Check tokens of [app]. +/// +/// Each member forwards to the platform delegate that [FirebaseAppCheck] uses +/// for the app, so it returns and throws what the [FirebaseAppCheck] member +/// of the same name does. +/// +/// It does not go through [FirebaseAppCheck] itself. Creating that registers +/// it as a service of the app, and other packages read +/// `app.getService()` as a sign that the app uses App Check. +/// +/// 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; + + // Set on first use, so that an app whose provider is never asked for a + // token gets no delegate from here. + FirebaseAppCheckPlatform? _delegate; + + // The platform keeps one delegate per app, so this is the one + // FirebaseAppCheck uses and it sees the activation the app did there. + FirebaseAppCheckPlatform get _appCheck => + _delegate ??= FirebaseAppCheckPlatform.instanceFor(app: app); + + // Both are async so that an error always arrives through the returned + // Future, as the contract says, and is never thrown by the call itself. + @override + Future getToken([bool? forceRefresh]) async => + _appCheck.getToken(forceRefresh ?? false); + + @override + Future getLimitedUseToken() async => _appCheck.getLimitedUseToken(); + + @override + Stream get onTokenChange => _appCheck.onTokenChange; + + // Runs when the app is deleted. Disposes the delegate this provider used, + // unless the app has a FirebaseAppCheck: that one disposes the delegate it + // shares with this provider, and the delegate must not be disposed twice. + Future _dispose() async { + final delegate = _delegate; + _delegate = null; + if (delegate == null || app.getService() != null) { + return; + } + await delegate.dispose(); + } +} 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..2ff2cc43f909 --- /dev/null +++ b/packages/firebase_app_check/firebase_app_check/test/registrant_test.dart @@ -0,0 +1,253 @@ +// 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 'dart:async'; + +import 'package:firebase_app_check/firebase_app_check.dart'; +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 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(), + ); + + tearDown(() => platform.close()); + + 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); + }, + ); + + test('disposes the delegate the provider used with the app', () async { + final app = await newApp(); + await app.getService()!.getToken(); + + await app.delete(); + + expect(platform.disposals, 1); + }); + + test('creates no delegate for a provider that is never used', () async { + final app = await newApp(); + app.getService(); + + await app.delete(); + + expect(platform.delegates, 0); + expect(platform.disposals, 0); + }); + + test( + 'leaves the delegate to FirebaseAppCheck when the app uses it', + () async { + // Both share the app's delegate; it must be disposed only once. + final app = await newApp(); + await app.getService()!.getToken(); + await FirebaseAppCheck.instanceFor(app: app).getToken(); + + await app.delete(); + + expect(platform.disposals, 1); + }, + ); + }); + + group('$FirebaseAppCheckTokenProvider', () { + group('getToken', () { + test('is the App Check token', () async { + final app = await newApp(); + platform.token = 'app-check-token'; + + final token = await FirebaseAppCheckTokenProvider(app).getToken(); + + expect(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('passes forceRefresh through', () async { + final app = await newApp(); + platform.token = 'fresh-token'; + + final token = await FirebaseAppCheckTokenProvider(app).getToken(true); + + expect(token, 'fresh-token'); + expect(platform.requests, ['getToken(true)']); + }); + + test("propagates App Check's exception before activate()", () async { + final app = await newApp(); + platform.error = FirebaseException( + plugin: 'firebase_app_check', + code: 'no-provider', + message: 'No AppCheckProvider installed.', + ); + + await expectLater( + FirebaseAppCheckTokenProvider(app).getToken(), + throwsA( + isA() + .having((e) => e.code, 'code', 'no-provider') + .having( + (e) => e.message, + 'message', + 'No AppCheckProvider installed.', + ), + ), + ); + }); + }); + + group('getLimitedUseToken', () { + test('is a limited-use token', () async { + final app = await newApp(); + platform.limitedUseToken = 'limited-use-token'; + + final token = await FirebaseAppCheckTokenProvider( + app, + ).getLimitedUseToken(); + + expect(token, 'limited-use-token'); + expect(platform.requests, ['getLimitedUseToken()']); + }); + + test("propagates App Check's exception", () async { + final app = await newApp(); + platform.error = FirebaseException( + plugin: 'firebase_app_check', + code: 'unknown', + ); + + await expectLater( + FirebaseAppCheckTokenProvider(app).getLimitedUseToken(), + throwsA( + isA().having((e) => e.code, 'code', 'unknown'), + ), + ); + }); + }); + + test('onTokenChange is each token App Check reports', () async { + final app = await newApp(); + final tokens = []; + final subscription = FirebaseAppCheckTokenProvider( + app, + ).onTokenChange.listen(tokens.add); + addTearDown(subscription.cancel); + + platform.tokenChanges + ..add('first-token') + ..add('second-token'); + await pumpEventQueue(); + + expect(tokens, ['first-token', 'second-token']); + }); + + test('does not register FirebaseAppCheck for the app', () async { + // Other packages read a registered FirebaseAppCheck as a sign that the + // app uses App Check; asking the provider for a token must not set it. + final app = await newApp(); + final provider = app.getService()!; + + await provider.getToken(); + await provider.getLimitedUseToken(); + final subscription = provider.onTokenChange.listen((_) {}); + addTearDown(subscription.cancel); + + expect(app.getService(), isNull); + }); + }); +} + +class _FakeFirebaseAppCheckPlatform extends FirebaseAppCheckPlatform { + _FakeFirebaseAppCheckPlatform() : super(); + + String? token; + String limitedUseToken = ''; + Object? error; + final List requests = []; + + /// How often a delegate was asked for, and how often it was disposed. + int delegates = 0; + int disposals = 0; + + @override + FirebaseAppCheckPlatform delegateFor({required FirebaseApp app}) { + delegates++; + return this; + } + + @override + Future dispose() async => disposals++; + + @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; + } + + final tokenChanges = StreamController.broadcast(); + + @override + Stream get onTokenChange => tokenChanges.stream; + + Future close() => tokenChanges.close(); +} 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..27e1a11ab8a0 --- /dev/null +++ b/packages/firebase_app_check/firebase_app_check_web/lib/src/firebase_app_check_web_token_provider.dart @@ -0,0 +1,41 @@ +// 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 AppCheckTokenProvider; + +/// Hands out the App Check tokens of [app]. +/// +/// Each member forwards to the web App Check delegate, so it returns and +/// throws what `FirebaseAppCheck` does on web. +/// +/// `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; + + // Every web delegate for an app shares its activated JS instance, so this + // sees the activation the app did through FirebaseAppCheck. + FirebaseAppCheckPlatform get _appCheck => + FirebaseAppCheckPlatform.instanceFor(app: app); + + @override + Future getToken([bool? forceRefresh]) => + _appCheck.getToken(forceRefresh ?? false); + + @override + Future getLimitedUseToken() => _appCheck.getLimitedUseToken(); + + // The delegate's stream is the one FirebaseAppCheck's listeners share for + // the app, so it lasts until the last of them all cancels. + @override + Stream get onTokenChange => _appCheck.onTokenChange; +} 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..79db32731f4a --- /dev/null +++ b/packages/firebase_auth/firebase_auth/lib/src/registrant.dart @@ -0,0 +1,62 @@ +// 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 and uid of the user signed in to [FirebaseAuth] for +/// [app]. +/// +/// [getIdToken] and [uid] forward to the [User] member of the same name, and +/// [onIdTokenChange] to [FirebaseAuth.idTokenChanges], so each returns and +/// throws what that member does. +/// +/// 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; + + // 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. + FirebaseAuth get _auth => FirebaseAuth.instanceFor(app: app); + + @override + Future getIdToken([bool forceRefresh = false]) async => + _auth.currentUser?.getIdToken(forceRefresh); + + @override + String? get uid => _auth.currentUser?.uid; + + // The uid of every event, without `distinct()`: a refreshed token repeats + // the uid, and consumers rely on that event. + @override + Stream get onIdTokenChange => + _auth.idTokenChanges().map((user) => user?.uid); +} 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..4fd9b9468e62 --- /dev/null +++ b/packages/firebase_auth/firebase_auth/test/registrant_test.dart @@ -0,0 +1,200 @@ +// 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 'dart:async'; + +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(), + ); + + tearDown(() => platform.close()); + + 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(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', + ), + ), + ); + }); + + test('uid is null when nobody is signed in', () async { + final app = await newApp(); + + expect(FirebaseAuthTokenProvider(app).uid, isNull); + }); + + test("uid is the signed-in user's uid", () async { + final app = await newApp(); + platform.user = _FakeUserPlatform(platform, uid: 'alice'); + + expect(FirebaseAuthTokenProvider(app).uid, 'alice'); + }); + + test( + 'onIdTokenChange is the uid at each sign-in, token refresh and sign-out', + () async { + final app = await newApp(); + final alice = _FakeUserPlatform(platform, uid: 'alice'); + final uids = []; + final subscription = FirebaseAuthTokenProvider( + app, + ).onIdTokenChange.listen(uids.add); + addTearDown(subscription.cancel); + + // The second event is a token refresh: the uid repeats. + platform.idTokens + ..add(alice) + ..add(alice) + ..add(null); + await pumpEventQueue(); + + expect(uids, ['alice', 'alice', null]); + }, + ); + }); +} + +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; + + final idTokens = StreamController.broadcast(); + + @override + Stream idTokenChanges() => idTokens.stream; + + Future close() => idTokens.close(); +} + +class _FakeUserPlatform extends UserPlatform { + _FakeUserPlatform( + FirebaseAuthPlatform auth, { + this.token, + this.error, + String uid = 'uid', + }) : super(auth, _FakeMultiFactorPlatform(auth), _detailsFor(uid)); + + 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); +} + +InternalUserDetails _detailsFor(String uid) => 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..deecbedaa272 --- /dev/null +++ b/packages/firebase_auth/firebase_auth_web/lib/src/firebase_auth_web_token_provider.dart @@ -0,0 +1,84 @@ +// 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 'dart:js_interop'; + +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 and uid 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; + + // Numbers the change-stream listeners, so each has its own key for the + // hot-restart cleanup in [onIdTokenChange]. + static int _changeListeners = 0; + + // The JS Auth instance exists since Firebase.initializeApp: the web plugin + // initializes it there and waits for the restored user. + auth_interop.Auth get _auth => + auth_interop.getAuthInstance(core_interop.app(app.name)); + + @override + Future getIdToken([bool forceRefresh = false]) async { + final auth = _auth; + final user = auth.currentUser; + if (user == null) { + return null; + } + return guardAuthExceptions(() => user.getIdToken(forceRefresh), auth: auth); + } + + @override + String? get uid => _auth.currentUser?.uid; + + // The uid the JS SDK reports through `onIdTokenChanged`: the current user + // first, then every sign-in, sign-out and token refresh. + // + // Each listener of the stream has its own JS listener for as long as it + // listens, so each gets the current user first. The stream does not reuse + // the one `FirebaseAuthWeb` shares with the app, as that one ends when the + // app's last listener cancels. + @override + Stream get onIdTokenChange { + return Stream.multi((controller) { + final auth = _auth; + // A hot restart keeps the JS SDK and its listeners but not this Dart + // state. In debug mode the unsubscribe function is kept on `window` + // under this key, so the next run can drop the listener this one left + // behind. + final key = + 'flutterfire-${app.name}_tokenProvider_onIdTokenChange-' + '${_changeListeners++}'; + void next(auth_interop.UserJsImpl? user) => + controller.add(user?.uid.toDart); + void error(JSAny error) => + controller.addError(getFirebaseAuthException(error, auth)); + + core_interop.unsubscribeWindowsListener(key); + final unsubscribe = auth.jsObject.onIdTokenChanged(next.toJS, error.toJS); + core_interop.setWindowsListener(key, unsubscribe); + + controller.onCancel = () { + unsubscribe.callAsFunction(); + core_interop.removeWindowsListener(key); + }; + }); + } +} diff --git a/packages/firebase_auth/firebase_auth_web/pubspec.yaml b/packages/firebase_auth/firebase_auth_web/pubspec.yaml index bc1ba6469dc2..9fa9f07cad37 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 @@ -22,7 +23,6 @@ dependencies: web: ^1.0.0 dev_dependencies: - firebase_core_platform_interface: ^8.1.1 flutter_test: sdk: flutter diff --git a/packages/firebase_auth/firebase_auth_web/test/token_provider_test.dart b/packages/firebase_auth/firebase_auth_web/test/token_provider_test.dart new file mode 100644 index 000000000000..c601914a3902 --- /dev/null +++ b/packages/firebase_auth/firebase_auth_web/test/token_provider_test.dart @@ -0,0 +1,188 @@ +// 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('browser') +library; + +import 'dart:js_interop'; +import 'dart:js_interop_unsafe'; + +import 'package:firebase_auth_platform_interface/firebase_auth_platform_interface.dart'; +import 'package:firebase_auth_web/src/firebase_auth_web_token_provider.dart'; +import 'package:firebase_core/firebase_core.dart'; +import 'package:firebase_core_platform_interface/firebase_core_platform_interface.dart' + show FirebasePlatform; +import 'package:flutter_test/flutter_test.dart'; + +import 'fake_auth_js_sdk.dart'; + +void main() { + late _FakeJsAuth jsAuth; + late FirebaseAuthWebTokenProvider provider; + + setUpAll(() => FirebasePlatform.instance = FakeFirebase()); + + setUp(() { + jsAuth = _FakeJsAuth(); + final fake = jsAuth.jsObject; + stubFirebaseAuthJsSdk()['initializeAuth'] = + ((JSAny? app, JSAny? options) => fake).toJS; + provider = FirebaseAuthWebTokenProvider(Firebase.app()); + }); + + group('uid', () { + test('is null when nobody is signed in', () { + expect(provider.uid, isNull); + }); + + test("is the signed-in user's uid", () { + jsAuth.signIn('alice'); + + expect(provider.uid, 'alice'); + }); + }); + + group('onIdTokenChange', () { + test('is the uid of each user the JS SDK reports', () async { + final uids = []; + final subscription = provider.onIdTokenChange.listen(uids.add); + addTearDown(subscription.cancel); + + // The second event is a token refresh: the uid repeats. + jsAuth.idTokenListeners.single + ..report('alice') + ..report('alice') + ..report(null); + await pumpEventQueue(); + + expect(uids, ['alice', 'alice', null]); + }); + + test( + 'gives every listener its own JS listener, while it listens', + () async { + final stream = provider.onIdTokenChange; + expect(jsAuth.idTokenListeners, isEmpty); + + final first = stream.listen((_) {}); + final second = stream.listen((_) {}); + expect(jsAuth.idTokenListeners, hasLength(2)); + + await first.cancel(); + expect(jsAuth.idTokenListeners, hasLength(1)); + await second.cancel(); + expect(jsAuth.idTokenListeners, isEmpty); + }, + ); + + test('outlives another stream of the same provider', () async { + // The app's own Auth listeners come and go; they must not end a + // stream another package still holds. + final first = provider.onIdTokenChange.listen((_) {}); + final uids = []; + final second = provider.onIdTokenChange.listen(uids.add); + addTearDown(second.cancel); + + await first.cancel(); + jsAuth.idTokenListeners.single.report('alice'); + await pumpEventQueue(); + + expect(uids, ['alice']); + }); + + test("reports the JS SDK's error as a FirebaseAuthException", () async { + final errors = []; + final subscription = provider.onIdTokenChange.listen( + (_) {}, + onError: errors.add, + ); + addTearDown(subscription.cancel); + + jsAuth.idTokenListeners.single.fail( + jsError( + 'Firebase: Error (auth/network-request-failed).', + code: 'auth/network-request-failed', + ), + ); + await pumpEventQueue(); + + expect( + errors.single, + isA().having( + (e) => e.code, + 'code', + 'network-request-failed', + ), + ); + }); + + test('a hot restart can drop the JS listener it leaves behind', () async { + Iterable windowKeys() => _windowKeys.where( + (key) => key.startsWith( + 'flutterfire-[DEFAULT]_tokenProvider_onIdTokenChange-', + ), + ); + expect(windowKeys(), isEmpty); + + final subscription = provider.onIdTokenChange.listen((_) {}); + expect(windowKeys(), hasLength(1)); + + // What the next run does with the key it finds on `window`. + globalContext.callMethod(windowKeys().single.toJS); + expect(jsAuth.idTokenListeners, isEmpty); + + await subscription.cancel(); + expect(windowKeys(), isEmpty); + }); + }); +} + +List get _windowKeys => globalContext + .getProperty('Object'.toJS) + .callMethod>('keys'.toJS, globalContext) + .toDart + .map((key) => key.toDart) + .toList(); + +JSObject _jsUser(String uid) => JSObject()..['uid'] = uid.toJS; + +/// Stands in for the JS `Auth` object: records the listeners installed on it +/// and lets a test report users and errors to them. +class _FakeJsAuth { + _FakeJsAuth() { + jsObject['app'] = JSObject()..['name'] = '[DEFAULT]'.toJS; + jsObject['currentUser'] = null; + jsObject['onIdTokenChanged'] = _installInto(idTokenListeners); + } + + final JSObject jsObject = JSObject(); + final List<_JsListener> idTokenListeners = []; + + /// Signs in the user with [uid], as far as `currentUser` goes. + void signIn(String uid) => jsObject['currentUser'] = _jsUser(uid); + + /// A JS function shaped like `onIdTokenChanged`: it records the listener + /// in [listeners] and returns the function that removes it again. + JSFunction _installInto(List<_JsListener> listeners) => + ((JSFunction next, JSFunction? error) { + final listener = _JsListener(next, error); + listeners.add(listener); + return (() { + listeners.remove(listener); + }).toJS; + }).toJS; +} + +class _JsListener { + _JsListener(this._next, this._error); + + final JSFunction _next; + final JSFunction? _error; + + /// Reports the user with [uid], or nobody signed in for `null`. + void report(String? uid) => + _next.callAsFunction(null, uid == null ? null : _jsUser(uid)); + + void fail(JSObject error) => _error!.callAsFunction(null, error); +} 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..815f3c42cba0 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 @@ -15,3 +15,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/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..b8af7d90c3be --- /dev/null +++ b/packages/firebase_core/firebase_core_interface/lib/src/token_providers.dart @@ -0,0 +1,149 @@ +// 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 '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. +/// +/// The members mirror the Auth package's own token API, with the uid in +/// place of the user, so a package that moves from that API to this provider +/// keeps the same behavior and the same failures. +/// +/// 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, as `User.getIdToken` does. + Future getIdToken([bool forceRefresh = false]); + + /// The signed-in user's uid, or `null` when nobody is signed in. + /// + /// For state a package keeps per user, such as a local cache. + String? get uid; + + /// The signed-in user's uid, now and whenever the user or the user's ID + /// token changes. + /// + /// The first event is the current state. After that there is an event on + /// sign-in, on sign-out and on every ID token refresh. `null` means nobody + /// is signed in. + /// + /// The uid repeats when only the token changed. An event is never dropped + /// because the uid is unchanged. A consumer that only cares about sign-in + /// and sign-out can use `.distinct()`. + /// + /// The event does not carry the token. A consumer calls [getIdToken] after + /// the event, and reads [uid] again after the await, because the user can + /// change in between. + /// + /// This mirrors `FirebaseAuth.idTokenChanges`, with the uid in place of the + /// user. + Stream get onIdTokenChange; +} + +/// 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. +/// +/// The members mirror the App Check package's own token API: each one +/// returns and throws what the `FirebaseAppCheck` member of the same name +/// does. A package that moves from that API to this provider keeps the same +/// calls and the same failures. +/// +/// An app that never activated App Check is not a separate state in this +/// contract. On Android and web it shows up as a failed call. On Apple +/// platforms the plugin installs a default DeviceCheck provider, so a real +/// attempt is made. +/// +/// A failure is not always a `FirebaseException`: on web, a call before +/// activation throws a plain `Exception`. Consumers should catch broadly. +/// +/// What to send when a call fails is up to the consumer. The native +/// Functions SDKs send a placeholder token, the JS Functions SDK omits the +/// header. Consumers that send the placeholder can use +/// [appCheckPlaceholderToken]. +/// +/// Not for app code: use the App Check package's own API instead. +abstract interface class AppCheckTokenProvider implements FirebaseService { + /// The App Check token, or `null` when App Check has none to give. + /// + /// With [forceRefresh], a fresh token is fetched even when the cached one + /// is still valid. + /// + /// Throws what `FirebaseAppCheck.getToken` throws when App Check can't + /// produce a token, for example before App Check is activated on Android + /// and web. + Future getToken([bool? forceRefresh]); + + /// A limited-use App Check token, for backends that enforce replay + /// protection. + /// + /// Throws what `FirebaseAppCheck.getLimitedUseToken` throws when App Check + /// can't produce a token, for example before App Check is activated on + /// Android and web. + Future getLimitedUseToken(); + + /// The App Check token, whenever it changes. + /// + /// For packages that keep a connection open and re-send the token when it + /// is refreshed. Behaves as `FirebaseAppCheck.onTokenChange` does. On web, + /// reading it throws a plain `Exception` until App Check is activated. + Stream get onTokenChange; +} + +/// 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. +/// +/// For consumers of [AppCheckTokenProvider] that send the placeholder when a +/// token request fails, as the native SDKs do. +const String appCheckPlaceholderToken = 'eyJlcnJvciI6IlVOS05PV05fRVJST1IifQ=='; + +/// 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. On Android that differs from native Functions, whose + /// Instance ID read returns the stored token or `null` at once and only + /// starts a sync in the background: the Messaging SDK has no public read + /// that returns only a stored token. 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] and [AppCheckTokenProvider.getToken]: + /// 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..c645957b490c --- /dev/null +++ b/packages/firebase_core/firebase_core_interface/test/firebase_app_services_test.dart @@ -0,0 +1,161 @@ +// 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 'dart:convert'; + +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'; + + @override + String? get uid => 'uid'; + + @override + Stream get onIdTokenChange => Stream.value(uid); +} + +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)); + }); + }); + + test('appCheckPlaceholderToken is the error payload the SDKs send', () { + expect( + utf8.decode(base64.decode(appCheckPlaceholderToken)), + '{"error":"UNKNOWN_ERROR"}', + ); + }); +} 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..038d4de433bd 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 + AppCheckTokenProvider, + AuthTokenProvider, FirebaseAppPlatform, FirebaseException, FirebaseOptions, FirebasePlatform, FirebasePlugin, + MessagingTokenProvider, + appCheckPlaceholderToken, 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'; 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..d3364e37935d 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,43 @@ 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 Messaging SDK has no public read that returns only a + // stored token: getToken(), which this plugin awaits, waits for a registration when nothing is + // stored. The Instance ID read native Functions uses is different: it returns the stored token + // or null at once and only starts a background sync. 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<>(); @@ -615,6 +657,9 @@ public void onMethodCall(final MethodCall call, @NonNull final Result result) { case "Messaging#getToken": methodCallTask = getToken(); break; + case "Messaging#getCachedToken": + methodCallTask = getCachedToken(); + break; case "Messaging#register": methodCallTask = register(); break; 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/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..07d29effff45 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,24 @@ 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 has no read that returns only a stored + /// token: its token read returns the stored token, and waits for a + /// registration when none is stored. The Instance ID read the native + /// Functions SDK uses returns the stored token or nothing at once. On + /// Android 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, and one is created when none is stored. + 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 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..23e7b36fc530 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,145 @@ 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, + ); + + test( + 'uid and onIdTokenChange are null when nobody is signed in', + () async { + await FirebaseAuth.instance.signOut(); + + expect(provider.uid, isNull); + // The stream starts with the current state. + expect(await provider.onIdTokenChange.first, isNull); + }, + ); + + test( + "uid and onIdTokenChange are the signed-in user's uid", + () async { + final credential = await FirebaseAuth.instance.signInAnonymously(); + final uid = credential.user!.uid; + + expect(provider.uid, uid); + expect(await provider.onIdTokenChange.first, uid); + }, + // The unsigned macOS test app cannot sign in, see above. + skip: !kIsWeb && defaultTargetPlatform == TargetPlatform.macOS, + ); + }); + + group('AppCheckTokenProvider', () { + test('getToken throws before activation', () async { + // App Check is linked but never activated in this app, so the + // plugin can't produce a token; the provider fails the way + // FirebaseAppCheck.getToken does, and the consumer decides what to + // send instead. + await expectLater( + defaultApp.getService()!.getToken(), + throwsA(isA()), + ); + }); + + 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); + } + 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); + }); + }); }); }