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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
// Copyright 2026, the Chromium project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'package:firebase_app_check/firebase_app_check.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_core_platform_interface/firebase_core_platform_interface.dart'
show
AppCheckInteropToken,
AppCheckTokenProvider,
registerFirebaseServiceFactory;

/// Registers [FirebaseAppCheck] as the [AppCheckTokenProvider] of every app.
///
/// The Flutter plugin registrant calls [registerWith] before `main` on
/// Android, Apple platforms and Windows (see `dartPluginClass` in
/// pubspec.yaml), so other Firebase packages can ask an app for an App Check
/// token before the app has used [FirebaseAppCheck] itself.
/// `firebase_app_check_web` registers its own provider.
class FirebaseAppCheckRegistrant {
// Not meant to be instantiated.
FirebaseAppCheckRegistrant._();

/// Registers the [AppCheckTokenProvider] factory with [FirebaseApp].
static void registerWith() {
registerFirebaseServiceFactory<AppCheckTokenProvider>(
FirebaseAppCheckTokenProvider.new,
);
}
}

/// Hands out [FirebaseAppCheck]'s tokens for [app] in the shape the Firebase
/// SDKs hand each other.
///
/// Resolved per app through `app.getService<AppCheckTokenProvider>()`; not for
/// app code.
class FirebaseAppCheckTokenProvider implements AppCheckTokenProvider {
/// Creates the provider for [app].
FirebaseAppCheckTokenProvider(this.app);

/// The app whose App Check instance supplies the token.
final FirebaseApp app;

@override
Future<AppCheckInteropToken?> getToken({bool limitedUse = false}) async {
// Creating the App Check instance here is what the app would do itself;
// until the app activates it, the SDK has no provider and the request
// below fails.
final appCheck = FirebaseAppCheck.instanceFor(app: app);
try {
final token = limitedUse
? await appCheck.getLimitedUseToken()
: await appCheck.getToken();
return token == null ? null : AppCheckInteropToken(token: token);
} catch (error) {
// The SDKs answer a failed request, including one before activation,
// with their placeholder token and the reason; the plugin's public API
// throws instead.
return AppCheckInteropToken.failure(switch (error) {
FirebaseException(:final message?) => message,
FirebaseException(:final code) => code,
_ => '$error',
});
}
}
}
11 changes: 11 additions & 0 deletions packages/firebase_app_check/firebase_app_check/pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
// Copyright 2026, the Chromium project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'package:firebase_app_check/src/registrant.dart';
import 'package:firebase_app_check_platform_interface/firebase_app_check_platform_interface.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_core_platform_interface/firebase_core_platform_interface.dart'
show AppCheckInteropToken, AppCheckTokenProvider;
import 'package:flutter_test/flutter_test.dart';

import './mock.dart';

void main() {
setupFirebaseAppCheckMocks();

late _FakeFirebaseAppCheckPlatform platform;
var appCount = 0;

setUpAll(() async {
await Firebase.initializeApp();
FirebaseAppCheckRegistrant.registerWith();
});

setUp(
() => FirebaseAppCheckPlatform.instance = platform =
_FakeFirebaseAppCheckPlatform(),
);

Future<FirebaseApp> 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<AppCheckTokenProvider>();

expect(provider, isA<FirebaseAppCheckTokenProvider>());
expect(app.getService<AppCheckTokenProvider>(), same(provider));
expect(platform.requests, isEmpty);
},
);
});

group('$FirebaseAppCheckTokenProvider', () {
test('is the App Check token', () async {
final app = await newApp();
platform.token = 'app-check-token';

final answer = await FirebaseAppCheckTokenProvider(app).getToken();

expect(answer, const AppCheckInteropToken(token: 'app-check-token'));
expect(platform.requests, ['getToken(false)']);
});

test('is null when App Check has no token', () async {
final app = await newApp();

expect(await FirebaseAppCheckTokenProvider(app).getToken(), isNull);
});

test('asks for a limited-use token with limitedUse', () async {
final app = await newApp();
platform.limitedUseToken = 'limited-use-token';

final answer = await FirebaseAppCheckTokenProvider(
app,
).getToken(limitedUse: true);

expect(answer, const AppCheckInteropToken(token: 'limited-use-token'));
expect(platform.requests, ['getLimitedUseToken()']);
});

test(
'answers with the placeholder and the reason before activate()',
() async {
final app = await newApp();
platform.error = FirebaseException(
plugin: 'firebase_app_check',
code: 'no-provider',
message: 'No AppCheckProvider installed.',
);

final answer = await FirebaseAppCheckTokenProvider(app).getToken();

expect(
answer,
const AppCheckInteropToken.failure('No AppCheckProvider installed.'),
);
expect(answer!.token, AppCheckInteropToken.placeholderToken);
},
);

test('describes a failure without a message by its code', () async {
final app = await newApp();
platform.error = FirebaseException(
plugin: 'firebase_app_check',
code: 'unknown',
);

final answer = await FirebaseAppCheckTokenProvider(
app,
).getToken(limitedUse: true);

expect(answer, const AppCheckInteropToken.failure('unknown'));
});

test('describes any other error by its string', () async {
final app = await newApp();
platform.error = StateError('not activated');

final answer = await FirebaseAppCheckTokenProvider(app).getToken();

expect(
answer,
const AppCheckInteropToken.failure('Bad state: not activated'),
);
});
});
}

class _FakeFirebaseAppCheckPlatform extends FirebaseAppCheckPlatform {
_FakeFirebaseAppCheckPlatform() : super();

String? token;
String limitedUseToken = '';
Object? error;
final List<String> requests = [];

@override
FirebaseAppCheckPlatform delegateFor({required FirebaseApp app}) => this;

@override
FirebaseAppCheckPlatform setInitialValues() => this;

@override
Future<String?> getToken(bool forceRefresh) async {
requests.add('getToken($forceRefresh)');
if (error case final error?) {
throw error;
}
return token;
}

@override
Future<String> getLimitedUseToken() async {
requests.add('getLimitedUseToken()');
if (error case final error?) {
throw error;
}
return limitedUseToken;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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';
Expand All @@ -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);
Expand Down Expand Up @@ -93,6 +96,10 @@ class FirebaseAppCheckWeb extends FirebaseAppCheckPlatform {
);

FirebaseAppCheckPlatform.instance = FirebaseAppCheckWeb.instance;
// Other Firebase packages get App Check tokens from here.
registerFirebaseServiceFactory<AppCheckTokenProvider>(
FirebaseAppCheckWebTokenProvider.new,
);
}

/// Initializes a stub instance to allow the class to be registered.
Expand All @@ -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<String, app_check_interop.AppCheck> _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
Expand All @@ -131,6 +142,11 @@ class FirebaseAppCheckWeb extends FirebaseAppCheckPlatform {
return this;
}

@override
Future<void> dispose() async {
_webAppChecks.remove(app.name);
}

@override
Future<void> activate({
WebProvider? providerWeb,
Expand Down Expand Up @@ -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<Future<void>>(() 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();
});
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
// Copyright 2026, the Chromium project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'package:firebase_app_check_platform_interface/firebase_app_check_platform_interface.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_core_platform_interface/firebase_core_platform_interface.dart'
show AppCheckInteropToken, AppCheckTokenProvider;

/// Hands out the App Check tokens of [app] in the shape the Firebase SDKs
/// hand each other.
///
/// `FirebaseAppCheckWeb.registerWith` registers it as the app's
/// [AppCheckTokenProvider]. Resolved per app through
/// `app.getService<AppCheckTokenProvider>()`; not for app code.
class FirebaseAppCheckWebTokenProvider implements AppCheckTokenProvider {
/// Creates the provider for [app].
FirebaseAppCheckWebTokenProvider(this.app);

/// The app whose App Check instance supplies the token.
final FirebaseApp app;

@override
Future<AppCheckInteropToken?> getToken({bool limitedUse = false}) async {
// Every web delegate for an app shares its activated JS instance, so this
// sees the activation the app did through FirebaseAppCheck.
final appCheck = FirebaseAppCheckPlatform.instanceFor(app: app);
try {
final token = limitedUse
? await appCheck.getLimitedUseToken()
: await appCheck.getToken(false);
return token == null ? null : AppCheckInteropToken(token: token);
} catch (error) {
// Before activation, and on any other failure, the plugin throws; the
// SDKs answer each other with the placeholder and the reason.
return AppCheckInteropToken.failure(switch (error) {
FirebaseException(:final message?) => message,
FirebaseException(:final code) => code,
_ => '$error',
});
}
}
}
Loading
Loading