From c04e966e8543cb08ad0b69af5c6808afc9ce39a4 Mon Sep 17 00:00:00 2001 From: Guillaume Bernos Date: Mon, 9 Nov 2026 14:40:43 +0100 Subject: [PATCH 1/4] fix(cloud_functions,web): rethrow non-Firebase errors instead of crashing in the error mapper The catch blocks in `call()`, `stream()` and the abort-signal helper cast every caught error to `JSObject`, so a Dart error became a `TypeError`. `convertFirebaseFunctionsException` also force-unwrapped `code` and `message`, so a JS rejection without them (a plain `Error`, `{}`, or the `TypeError` from `AbortSignal.timeout()` with a negative delay) became a null-check error. Only JS objects with a string `code` are now converted. Anything else is rethrown with its original stack trace, and `code`/`message` are read null-safely. --- .../lib/https_callable_web.dart | 3 + .../cloud_functions_web/lib/utils.dart | 26 ++- .../test/https_callable_web_test.dart | 165 ++++++++++++++++++ 3 files changed, 190 insertions(+), 4 deletions(-) create mode 100644 packages/cloud_functions/cloud_functions_web/test/https_callable_web_test.dart diff --git a/packages/cloud_functions/cloud_functions_web/lib/https_callable_web.dart b/packages/cloud_functions/cloud_functions_web/lib/https_callable_web.dart index bebcfb23e24f..90cd4f2ae158 100644 --- a/packages/cloud_functions/cloud_functions_web/lib/https_callable_web.dart +++ b/packages/cloud_functions/cloud_functions_web/lib/https_callable_web.dart @@ -58,6 +58,7 @@ class HttpsCallableWeb extends HttpsCallablePlatform { try { response = await callable.call(parametersJS); } catch (e, s) { + if (!isFirebaseFunctionsError(e)) rethrow; throw convertFirebaseFunctionsException(e as JSObject, s); } @@ -100,6 +101,7 @@ class HttpsCallableWeb extends HttpsCallablePlatform { yield value; } } catch (e, s) { + if (!isFirebaseFunctionsError(e)) rethrow; throw convertFirebaseFunctionsException(e as JSObject, s); } } @@ -116,6 +118,7 @@ class HttpsCallableWeb extends HttpsCallablePlatform { return web.AbortSignal.any(jsSignals); } } catch (e, s) { + if (!isFirebaseFunctionsError(e)) rethrow; throw convertFirebaseFunctionsException(e as JSObject, s); } } diff --git a/packages/cloud_functions/cloud_functions_web/lib/utils.dart b/packages/cloud_functions/cloud_functions_web/lib/utils.dart index a3538e1589e3..106079eb2976 100644 --- a/packages/cloud_functions/cloud_functions_web/lib/utils.dart +++ b/packages/cloud_functions/cloud_functions_web/lib/utils.dart @@ -8,16 +8,34 @@ import 'dart:js_interop_unsafe'; import 'package:cloud_functions_platform_interface/cloud_functions_platform_interface.dart'; +/// Whether [error] is a JS error from the Functions SDK, that is a JS object +/// with a string `code`. +/// +/// Dart errors and other JS errors return `false` and should be rethrown +/// as they are. +bool isFirebaseFunctionsError(Object? error) { + // `is JSObject` is false for Dart objects on both dart2js and dart2wasm. + // ignore: invalid_runtime_check_with_js_interop_types + return error is JSObject && error.getProperty('code'.toJS).isA(); +} + +/// Returns the string value of [property] on [object], or `null`. +String? _stringProperty(JSObject object, String property) { + final value = object.getProperty(property.toJS); + return value.isA() ? (value! as JSString).toDart : null; +} + /// Given a web error, a [FirebaseFunctionsException] is returned. FirebaseFunctionsException convertFirebaseFunctionsException( JSObject exception, [ StackTrace? stackTrace, ]) { - String originalCode = - (exception.getProperty('code'.toJS)! as JSString).toDart; + String originalCode = _stringProperty(exception, 'code') ?? 'unknown'; String code = originalCode.replaceFirst('functions/', ''); - String message = (exception.getProperty('message'.toJS)! as JSString).toDart - .replaceFirst('($originalCode)', ''); + String message = (_stringProperty(exception, 'message') ?? '').replaceFirst( + '($originalCode)', + '', + ); return FirebaseFunctionsException( code: code, diff --git a/packages/cloud_functions/cloud_functions_web/test/https_callable_web_test.dart b/packages/cloud_functions/cloud_functions_web/test/https_callable_web_test.dart new file mode 100644 index 000000000000..0ce8c5b5e80c --- /dev/null +++ b/packages/cloud_functions/cloud_functions_web/test/https_callable_web_test.dart @@ -0,0 +1,165 @@ +// 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:cloud_functions_platform_interface/cloud_functions_platform_interface.dart'; +import 'package:cloud_functions_web/https_callable_web.dart'; +import 'package:cloud_functions_web/interop/functions.dart' + as functions_interop; +import 'package:cloud_functions_web/interop/functions_interop.dart' + show FunctionsJsImpl; +import 'package:flutter_test/flutter_test.dart'; + +class _FakeFunctions extends FirebaseFunctionsPlatform { + _FakeFunctions() : super(null, 'us-central1'); +} + +/// A JS error shaped like the `FunctionsError` the JS SDK rejects with. +JSObject _functionsError() { + final error = (globalContext['Error']! as JSFunction) + .callAsConstructor('not allowed'.toJS); + error['name'] = 'FirebaseError'.toJS; + error['code'] = 'functions/permission-denied'.toJS; + error['details'] = {'reason': 'quota'}.jsify(); + return error; +} + +JSPromise _rejectWith(JSAny error) => (globalContext['Promise']! as JSObject) + .callMethod('reject'.toJS, error); + +/// Matches the exact JS value [expected], not a wrapper around it. +Matcher _isJsValue(JSAny expected) => predicate( + // ignore: invalid_runtime_check_with_js_interop_types + (e) => e is JSObject && e.strictEquals(expected).toDart, + 'is the original JS error', +); + +void main() { + /// Points the JS SDK's `httpsCallable()` at [callable]. + HttpsCallableWeb callableReturning( + JSFunction callable, { + HttpsCallableOptions? options, + }) { + final sdk = JSObject(); + // `stream()` calls `httpsCallable()` without options, `call()` with them. + sdk['httpsCallable'] = + ((JSAny? functions, JSAny? name, [JSAny? options]) => callable).toJS; + globalContext['firebase_functions'] = sdk; + + return HttpsCallableWeb( + _FakeFunctions(), + functions_interop.Functions.getInstance(JSObject() as FunctionsJsImpl), + null, + 'fn', + options ?? HttpsCallableOptions(), + null, + ); + } + + /// A callable whose `call()` and `stream()` both run [onCall]. + JSFunction callable(JSAny? Function() onCall) { + final fn = ((JSAny? data) => onCall()).toJS; + fn['stream'] = ((JSAny? data, JSAny? options) => onCall()).toJS; + return fn; + } + + group('call()', () { + test('maps a FunctionsError to FirebaseFunctionsException', () async { + final web = callableReturning( + callable(() => _rejectWith(_functionsError())), + ); + + await expectLater( + web.call(), + throwsA( + isA() + .having((e) => e.code, 'code', 'permission-denied') + .having((e) => e.message, 'message', 'not allowed') + .having((e) => e.details, 'details', {'reason': 'quota'}), + ), + ); + }); + + test('rethrows a JS rejection that has no code or message', () async { + final error = JSObject(); + final web = callableReturning(callable(() => _rejectWith(error))); + + await expectLater(web.call(), throwsA(_isJsValue(error))); + }); + + test('rethrows a plain JS Error that has no code', () async { + final error = (globalContext['Error']! as JSFunction) + .callAsConstructor('network down'.toJS); + final web = callableReturning(callable(() => _rejectWith(error))); + + await expectLater(web.call(), throwsA(_isJsValue(error))); + }); + + test('rethrows a Dart error unchanged', () async { + final web = callableReturning(callable(() => throw StateError('boom'))); + + await expectLater( + web.call(), + throwsA(isA().having((e) => e.message, 'message', 'boom')), + ); + }); + }); + + group('stream()', () { + test('maps a FunctionsError to FirebaseFunctionsException', () async { + final web = callableReturning( + callable(() => _rejectWith(_functionsError())), + ); + + await expectLater( + web.stream(null), + emitsError( + isA().having( + (e) => e.code, + 'code', + 'permission-denied', + ), + ), + ); + }); + + test('rethrows a JS rejection that has no code or message', () async { + final error = JSObject(); + final web = callableReturning(callable(() => _rejectWith(error))); + + await expectLater(web.stream(null), emitsError(_isJsValue(error))); + }); + + test('rethrows a Dart error unchanged', () async { + final web = callableReturning(callable(() => throw StateError('boom'))); + + await expectLater(web.stream(null), emitsError(isA())); + }); + + test('rethrows the error from an invalid abort signal', () async { + // `AbortSignal.timeout()` rejects a negative delay with a JS TypeError. + final web = callableReturning( + callable(() => _rejectWith(_functionsError())), + options: HttpsCallableOptions( + webAbortSignal: TimeLimit(const Duration(milliseconds: -1)), + ), + ); + + await expectLater( + web.stream(null), + emitsError( + predicate( + (e) => e.toString().contains('AbortSignal'), + 'is the original AbortSignal error', + ), + ), + ); + }); + }); +} From 4da93637ea0702deb40c770ff65a60a3ecf80eae Mon Sep 17 00:00:00 2001 From: Guillaume Bernos Date: Mon, 9 Nov 2026 14:40:43 +0100 Subject: [PATCH 2/4] fix(auth,web): rethrow Dart errors instead of casting them to JSError `guardAuthExceptions` cast every sync error to `JSError`, and its Future path passed every error to `getFirebaseAuthException`, which did the same cast. A Dart error thrown inside a guarded call therefore became a `TypeError` and lost its stack trace. `useAuthEmulator` checked `e is AuthError`, which is true for any JS object because `@staticInterop` types are erased at runtime, then read the non-nullable `code`, so a JS error without `code` crashed. Dart errors are now rethrown unchanged (the Future path uses `catchError(test:)`), `getFirebaseAuthException` returns an `unknown` error for non-JS input, and `useAuthEmulator` compares `code` in JS. Firebase Auth errors and other JS errors are mapped as before. --- .../lib/firebase_auth_web.dart | 21 +-- .../lib/src/utils/web_utils.dart | 34 ++++- .../firebase_auth_web/pubspec.yaml | 1 + .../get_firebase_auth_exception_test.dart | 7 + .../test/guard_auth_exceptions_test.dart | 115 +++++++++++++++++ .../test/use_auth_emulator_test.dart | 122 ++++++++++++++++++ 6 files changed, 284 insertions(+), 16 deletions(-) create mode 100644 packages/firebase_auth/firebase_auth_web/test/guard_auth_exceptions_test.dart create mode 100644 packages/firebase_auth/firebase_auth_web/test/use_auth_emulator_test.dart 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 66fc4d6513a6..1c76227822a1 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 @@ -5,6 +5,7 @@ import 'dart:async'; 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_multi_factor.dart'; @@ -527,16 +528,18 @@ class FirebaseAuthWeb extends FirebaseAuthPlatform { ); } } catch (e) { - // Cannot be done with 3.2 constraints + // `is AuthError` would match any JS object, so check for one directly. + // `is JSObject` is false for Dart objects on both dart2js and dart2wasm. // ignore: invalid_runtime_check_with_js_interop_types - if (e is auth_interop.AuthError) { - final String code = e.code.toDart; - // this catches Firebase Error from web that occurs after hot reloading & hot restarting - if (code != 'auth/emulator-config-failed') { - throw getFirebaseAuthException(e); - } - } else { - rethrow; + if (e is! JSObject) rethrow; + // Not every JS error has a string `code`, so compare it in JS. + final isEmulatorConfigFailed = e + .getProperty('code'.toJS) + .strictEquals('auth/emulator-config-failed'.toJS) + .toDart; + // this catches Firebase Error from web that occurs after hot reloading & hot restarting + if (!isEmulatorConfigFailed) { + throw getFirebaseAuthException(e); } } } diff --git a/packages/firebase_auth/firebase_auth_web/lib/src/utils/web_utils.dart b/packages/firebase_auth/firebase_auth_web/lib/src/utils/web_utils.dart index 24db8f844fbd..dc987e3b7e39 100644 --- a/packages/firebase_auth/firebase_auth_web/lib/src/utils/web_utils.dart +++ b/packages/firebase_auth/firebase_auth_web/lib/src/utils/web_utils.dart @@ -28,26 +28,39 @@ bool _hasFirebaseAuthErrorCodeAndMessage(JSError e) { } } +/// Whether [error] is a JS object, as opposed to a Dart error. +/// +/// `@staticInterop` types such as [JSError] match any JS object at runtime, so +/// this is the check to make before casting a caught error to one. +bool _isJSObject(Object? error) { + // `is JSObject` is false for Dart objects on both dart2js and dart2wasm. + // ignore: invalid_runtime_check_with_js_interop_types + return error is JSObject; +} + R guardAuthExceptions(R Function() cb, {auth_interop.Auth? auth}) { try { final value = cb(); if (value is Future) { - return value.catchError((err, stack) { - final exception = getFirebaseAuthException(err, auth); - return Error.throwWithStackTrace(exception, stack); - }) + return value.catchError( + (Object err, StackTrace stack) => Error.throwWithStackTrace( + getFirebaseAuthException(err, auth), + stack, + ), + // Dart errors are rethrown as they are, with their stack trace. + test: _isJSObject, + ) as R; } return value; } catch (e, stackTrace) { - final exception = e as JSError; - if (!_hasFirebaseAuthErrorCodeAndMessage(e)) { + if (!_isJSObject(e) || !_hasFirebaseAuthErrorCodeAndMessage(e as JSError)) { // Not a firebase auth exception, rethrow & make sure to preserve the stacktrace rethrow; } - final error = getFirebaseAuthException(exception, auth); + final error = getFirebaseAuthException(e, auth); Error.throwWithStackTrace(error, stackTrace); } @@ -61,6 +74,13 @@ FirebaseAuthException getFirebaseAuthException( Object objectException, [ auth_interop.Auth? auth, ]) { + if (!_isJSObject(objectException)) { + return FirebaseAuthException( + code: 'unknown', + message: 'An unknown error occurred: $objectException', + ); + } + final exception = objectException as JSError; final authJsCredential = auth_interop.OAuthProviderJsImpl.credentialFromError( exception, diff --git a/packages/firebase_auth/firebase_auth_web/pubspec.yaml b/packages/firebase_auth/firebase_auth_web/pubspec.yaml index e18156e790a5..48ecd0a8bd5c 100644 --- a/packages/firebase_auth/firebase_auth_web/pubspec.yaml +++ b/packages/firebase_auth/firebase_auth_web/pubspec.yaml @@ -22,6 +22,7 @@ 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/get_firebase_auth_exception_test.dart b/packages/firebase_auth/firebase_auth_web/test/get_firebase_auth_exception_test.dart index c62f8fa1fac3..52a8bbd82edc 100644 --- a/packages/firebase_auth/firebase_auth_web/test/get_firebase_auth_exception_test.dart +++ b/packages/firebase_auth/firebase_auth_web/test/get_firebase_auth_exception_test.dart @@ -58,4 +58,11 @@ void main() { expect(exception.code, 'invalid-credential'); expect(exception.email, 'user@example.com'); }); + + test('returns an unknown error for a Dart error instead of throwing', () { + final exception = getFirebaseAuthException(StateError('boom')); + + expect(exception.code, 'unknown'); + expect(exception.message, contains('boom')); + }); } diff --git a/packages/firebase_auth/firebase_auth_web/test/guard_auth_exceptions_test.dart b/packages/firebase_auth/firebase_auth_web/test/guard_auth_exceptions_test.dart new file mode 100644 index 000000000000..9cb0619f2887 --- /dev/null +++ b/packages/firebase_auth/firebase_auth_web/test/guard_auth_exceptions_test.dart @@ -0,0 +1,115 @@ +// 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/utils/web_utils.dart'; +import 'package:flutter_test/flutter_test.dart'; + +/// A JS error shaped like the `FirebaseError` the Auth JS SDK throws. +JSObject _firebaseAuthError() { + final error = (globalContext['Error']! as JSFunction) + .callAsConstructor( + 'Firebase: Error (auth/user-disabled).'.toJS, + ); + error['name'] = 'FirebaseError'.toJS; + error['code'] = 'auth/user-disabled'.toJS; + return error; +} + +/// Matches the exact JS value [expected], not a wrapper around it. +Matcher _isJsValue(JSAny expected) => predicate( + // ignore: invalid_runtime_check_with_js_interop_types + (e) => e is JSObject && e.strictEquals(expected).toDart, + 'is the original JS error', +); + +void main() { + setUp(() { + // getFirebaseAuthException always calls OAuthProvider.credentialFromError. + // Stub it so this test does not need the full Auth JS SDK. + final oauthProvider = JSObject(); + oauthProvider['credentialFromError'] = ((JSAny _) => null).toJS; + final firebaseAuth = JSObject(); + firebaseAuth['OAuthProvider'] = oauthProvider; + globalContext['firebase_auth'] = firebaseAuth; + }); + + group('guardAuthExceptions with a sync callback', () { + test('maps a Firebase Auth error to FirebaseAuthException', () { + expect( + () => guardAuthExceptions(() => throw _firebaseAuthError()), + throwsA( + isA().having( + (e) => e.code, + 'code', + 'user-disabled', + ), + ), + ); + }); + + test('rethrows a JS error without code or message unchanged', () { + final error = JSObject(); + + expect( + () => guardAuthExceptions(() => throw error), + throwsA(_isJsValue(error)), + ); + }); + + test('rethrows a Dart error unchanged', () { + expect( + () => guardAuthExceptions(() => throw StateError('boom')), + throwsA(isA().having((e) => e.message, 'message', 'boom')), + ); + }); + }); + + group('guardAuthExceptions with a Future callback', () { + test('maps a Firebase Auth error to FirebaseAuthException', () async { + await expectLater( + guardAuthExceptions(() => Future.error(_firebaseAuthError())), + throwsA( + isA().having( + (e) => e.code, + 'code', + 'user-disabled', + ), + ), + ); + }); + + test('maps a JS error without code or message to unknown', () async { + await expectLater( + guardAuthExceptions(() => Future.error(JSObject())), + throwsA( + isA().having((e) => e.code, 'code', 'unknown'), + ), + ); + }); + + test('rethrows a Dart error with its stack trace', () async { + final error = StateError('boom'); + final stackTrace = StackTrace.current; + + Object? caught; + StackTrace? caughtStackTrace; + try { + await guardAuthExceptions(() => Future.error(error, stackTrace)); + } catch (e, s) { + caught = e; + caughtStackTrace = s; + } + + expect(caught, same(error)); + expect(caughtStackTrace.toString(), stackTrace.toString()); + }); + }); +} diff --git a/packages/firebase_auth/firebase_auth_web/test/use_auth_emulator_test.dart b/packages/firebase_auth/firebase_auth_web/test/use_auth_emulator_test.dart new file mode 100644 index 000000000000..3df773f9fe58 --- /dev/null +++ b/packages/firebase_auth/firebase_auth_web/test/use_auth_emulator_test.dart @@ -0,0 +1,122 @@ +// 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/firebase_auth_web.dart'; +import 'package:firebase_core_platform_interface/firebase_core_platform_interface.dart'; +import 'package:flutter_test/flutter_test.dart'; + +class _FakeFirebase extends FirebasePlatform { + @override + FirebaseAppPlatform app([String name = defaultFirebaseAppName]) { + return FirebaseAppPlatform( + name, + const FirebaseOptions( + apiKey: 'api-key', + appId: 'app-id', + messagingSenderId: 'sender-id', + projectId: 'project-id', + ), + ); + } +} + +JSObject _jsError(String message, {String? code}) { + final error = (globalContext['Error']! as JSFunction) + .callAsConstructor(message.toJS); + if (code != null) { + error['name'] = 'FirebaseError'.toJS; + error['code'] = code.toJS; + } + return error; +} + +void main() { + setUpAll(() { + FirebasePlatform.instance = _FakeFirebase(); + }); + + /// Stubs the JS SDK so that `connectAuthEmulator()` throws [error]. + void connectAuthEmulatorThrows(Object error) { + final core = JSObject(); + core['getApp'] = (([JSAny? name]) => JSObject()).toJS; + globalContext['firebase_core'] = core; + + final oauthProvider = JSObject(); + oauthProvider['credentialFromError'] = ((JSAny _) => null).toJS; + + final auth = JSObject(); + for (final name in [ + 'indexedDBLocalPersistence', + 'browserLocalPersistence', + 'browserSessionPersistence', + 'debugErrorMap', + 'browserPopupRedirectResolver', + ]) { + auth[name] = JSObject(); + } + auth['OAuthProvider'] = oauthProvider; + auth['initializeAuth'] = ((JSAny? app, JSAny? options) => JSObject()).toJS; + void connectAuthEmulator(JSAny? auth, JSAny? origin) => throw error; + auth['connectAuthEmulator'] = connectAuthEmulator.toJS; + globalContext['firebase_auth'] = auth; + } + + test('ignores auth/emulator-config-failed after a hot restart', () async { + connectAuthEmulatorThrows( + _jsError( + 'Firebase: Error (auth/emulator-config-failed).', + code: 'auth/emulator-config-failed', + ), + ); + + await FirebaseAuthWeb.instance.useAuthEmulator('localhost', 9099); + }); + + test('maps a Firebase Auth error to FirebaseAuthException', () async { + connectAuthEmulatorThrows( + _jsError( + 'Firebase: Error (auth/invalid-emulator-scheme).', + code: 'auth/invalid-emulator-scheme', + ), + ); + + await expectLater( + FirebaseAuthWeb.instance.useAuthEmulator('localhost', 9099), + throwsA( + isA().having( + (e) => e.code, + 'code', + 'invalid-emulator-scheme', + ), + ), + ); + }); + + test('maps a JS error without code to an unknown error', () async { + connectAuthEmulatorThrows(_jsError('storage is disabled')); + + await expectLater( + FirebaseAuthWeb.instance.useAuthEmulator('localhost', 9099), + throwsA( + isA().having((e) => e.code, 'code', 'unknown'), + ), + ); + }); + + test('rethrows a Dart error unchanged', () async { + connectAuthEmulatorThrows(StateError('boom')); + + await expectLater( + FirebaseAuthWeb.instance.useAuthEmulator('localhost', 9099), + throwsA(isA()), + ); + }); +} From 3a4aa275b4a4720f4945aa578c6707e6263f75b3 Mon Sep 17 00:00:00 2001 From: Guillaume Bernos Date: Mon, 9 Nov 2026 15:53:58 +0100 Subject: [PATCH 3/4] refactor(auth,functions,web): avoid null assertions in error mapping and tests --- .../cloud_functions/cloud_functions_web/lib/utils.dart | 5 ++++- .../test/https_callable_web_test.dart | 9 ++++++--- .../test/guard_auth_exceptions_test.dart | 3 ++- .../firebase_auth_web/test/use_auth_emulator_test.dart | 3 ++- 4 files changed, 14 insertions(+), 6 deletions(-) diff --git a/packages/cloud_functions/cloud_functions_web/lib/utils.dart b/packages/cloud_functions/cloud_functions_web/lib/utils.dart index 106079eb2976..18971c5c9a4e 100644 --- a/packages/cloud_functions/cloud_functions_web/lib/utils.dart +++ b/packages/cloud_functions/cloud_functions_web/lib/utils.dart @@ -22,7 +22,10 @@ bool isFirebaseFunctionsError(Object? error) { /// Returns the string value of [property] on [object], or `null`. String? _stringProperty(JSObject object, String property) { final value = object.getProperty(property.toJS); - return value.isA() ? (value! as JSString).toDart : null; + if (value != null && value.isA()) { + return (value as JSString).toDart; + } + return null; } /// Given a web error, a [FirebaseFunctionsException] is returned. diff --git a/packages/cloud_functions/cloud_functions_web/test/https_callable_web_test.dart b/packages/cloud_functions/cloud_functions_web/test/https_callable_web_test.dart index 0ce8c5b5e80c..e6fb5331307b 100644 --- a/packages/cloud_functions/cloud_functions_web/test/https_callable_web_test.dart +++ b/packages/cloud_functions/cloud_functions_web/test/https_callable_web_test.dart @@ -22,7 +22,8 @@ class _FakeFunctions extends FirebaseFunctionsPlatform { /// A JS error shaped like the `FunctionsError` the JS SDK rejects with. JSObject _functionsError() { - final error = (globalContext['Error']! as JSFunction) + final error = globalContext + .getProperty('Error'.toJS) .callAsConstructor('not allowed'.toJS); error['name'] = 'FirebaseError'.toJS; error['code'] = 'functions/permission-denied'.toJS; @@ -30,7 +31,8 @@ JSObject _functionsError() { return error; } -JSPromise _rejectWith(JSAny error) => (globalContext['Promise']! as JSObject) +JSPromise _rejectWith(JSAny error) => globalContext + .getProperty('Promise'.toJS) .callMethod('reject'.toJS, error); /// Matches the exact JS value [expected], not a wrapper around it. @@ -94,7 +96,8 @@ void main() { }); test('rethrows a plain JS Error that has no code', () async { - final error = (globalContext['Error']! as JSFunction) + final error = globalContext + .getProperty('Error'.toJS) .callAsConstructor('network down'.toJS); final web = callableReturning(callable(() => _rejectWith(error))); diff --git a/packages/firebase_auth/firebase_auth_web/test/guard_auth_exceptions_test.dart b/packages/firebase_auth/firebase_auth_web/test/guard_auth_exceptions_test.dart index 9cb0619f2887..e76ecd92884b 100644 --- a/packages/firebase_auth/firebase_auth_web/test/guard_auth_exceptions_test.dart +++ b/packages/firebase_auth/firebase_auth_web/test/guard_auth_exceptions_test.dart @@ -14,7 +14,8 @@ import 'package:flutter_test/flutter_test.dart'; /// A JS error shaped like the `FirebaseError` the Auth JS SDK throws. JSObject _firebaseAuthError() { - final error = (globalContext['Error']! as JSFunction) + final error = globalContext + .getProperty('Error'.toJS) .callAsConstructor( 'Firebase: Error (auth/user-disabled).'.toJS, ); diff --git a/packages/firebase_auth/firebase_auth_web/test/use_auth_emulator_test.dart b/packages/firebase_auth/firebase_auth_web/test/use_auth_emulator_test.dart index 3df773f9fe58..0efa2cdda42b 100644 --- a/packages/firebase_auth/firebase_auth_web/test/use_auth_emulator_test.dart +++ b/packages/firebase_auth/firebase_auth_web/test/use_auth_emulator_test.dart @@ -29,7 +29,8 @@ class _FakeFirebase extends FirebasePlatform { } JSObject _jsError(String message, {String? code}) { - final error = (globalContext['Error']! as JSFunction) + final error = globalContext + .getProperty('Error'.toJS) .callAsConstructor(message.toJS); if (code != null) { error['name'] = 'FirebaseError'.toJS; From cf28c5c2a927d4bd24067672f08b70c5caf30ddc Mon Sep 17 00:00:00 2001 From: Guillaume Bernos Date: Mon, 9 Nov 2026 16:45:07 +0100 Subject: [PATCH 4/4] fix(auth,web): rethrow Dart errors from verifyPhoneNumber and the reCAPTCHA verifier `verifyPhoneNumber` passed every caught error to `verificationFailed`, so a Dart error thrown by `codeSent`, or the cast of a `multiFactorSession` from another platform, was reported as an `unknown` failure and the Future completed. `RecaptchaVerifierFactoryWeb.render()` and `verify()` turned a Dart error into an `unknown` FirebaseAuthException the same way. These catch blocks now rethrow anything that is not a JS object with `Error.throwWithStackTrace`, and leave JS errors to the mapper. --- .../lib/firebase_auth_web.dart | 5 +- ...e_auth_web_recaptcha_verifier_factory.dart | 6 +- .../lib/src/utils/web_utils.dart | 11 +- .../test/fake_auth_js_sdk.dart | 86 ++++++++++ .../test/phone_verification_errors_test.dart | 152 ++++++++++++++++++ .../test/use_auth_emulator_test.dart | 56 +------ 6 files changed, 258 insertions(+), 58 deletions(-) create mode 100644 packages/firebase_auth/firebase_auth_web/test/fake_auth_js_sdk.dart create mode 100644 packages/firebase_auth/firebase_auth_web/test/phone_verification_errors_test.dart 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 1c76227822a1..916feba0ced2 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 @@ -592,7 +592,10 @@ class FirebaseAuthWeb extends FirebaseAuthPlatform { ); codeSent(verificationId, null); - } catch (e) { + } catch (e, stackTrace) { + // A Dart error, for example from `codeSent`, is not a failed + // verification: rethrow it. + if (!isJSObject(e)) Error.throwWithStackTrace(e, stackTrace); verificationFailed(getFirebaseAuthException(e)); } } diff --git a/packages/firebase_auth/firebase_auth_web/lib/src/firebase_auth_web_recaptcha_verifier_factory.dart b/packages/firebase_auth/firebase_auth_web/lib/src/firebase_auth_web_recaptcha_verifier_factory.dart index 80e380c3d47c..7089924af969 100644 --- a/packages/firebase_auth/firebase_auth_web/lib/src/firebase_auth_web_recaptcha_verifier_factory.dart +++ b/packages/firebase_auth/firebase_auth_web/lib/src/firebase_auth_web_recaptcha_verifier_factory.dart @@ -147,7 +147,8 @@ class RecaptchaVerifierFactoryWeb extends RecaptchaVerifierFactoryPlatform { Future verify() { try { return _delegate.verify(); - } catch (e) { + } catch (e, stackTrace) { + if (!isJSObject(e)) Error.throwWithStackTrace(e, stackTrace); throw getFirebaseAuthException(e); } } @@ -156,7 +157,8 @@ class RecaptchaVerifierFactoryWeb extends RecaptchaVerifierFactoryPlatform { Future render() async { try { return await _delegate.render(); - } catch (e) { + } catch (e, stackTrace) { + if (!isJSObject(e)) Error.throwWithStackTrace(e, stackTrace); throw getFirebaseAuthException(e); } } diff --git a/packages/firebase_auth/firebase_auth_web/lib/src/utils/web_utils.dart b/packages/firebase_auth/firebase_auth_web/lib/src/utils/web_utils.dart index dc987e3b7e39..2e84389ba8c6 100644 --- a/packages/firebase_auth/firebase_auth_web/lib/src/utils/web_utils.dart +++ b/packages/firebase_auth/firebase_auth_web/lib/src/utils/web_utils.dart @@ -31,8 +31,9 @@ bool _hasFirebaseAuthErrorCodeAndMessage(JSError e) { /// Whether [error] is a JS object, as opposed to a Dart error. /// /// `@staticInterop` types such as [JSError] match any JS object at runtime, so -/// this is the check to make before casting a caught error to one. -bool _isJSObject(Object? error) { +/// this is the check to make before casting a caught error to one. Callers +/// should rethrow anything else unchanged. +bool isJSObject(Object? error) { // `is JSObject` is false for Dart objects on both dart2js and dart2wasm. // ignore: invalid_runtime_check_with_js_interop_types return error is JSObject; @@ -48,14 +49,14 @@ R guardAuthExceptions(R Function() cb, {auth_interop.Auth? auth}) { stack, ), // Dart errors are rethrown as they are, with their stack trace. - test: _isJSObject, + test: isJSObject, ) as R; } return value; } catch (e, stackTrace) { - if (!_isJSObject(e) || !_hasFirebaseAuthErrorCodeAndMessage(e as JSError)) { + if (!isJSObject(e) || !_hasFirebaseAuthErrorCodeAndMessage(e as JSError)) { // Not a firebase auth exception, rethrow & make sure to preserve the stacktrace rethrow; } @@ -74,7 +75,7 @@ FirebaseAuthException getFirebaseAuthException( Object objectException, [ auth_interop.Auth? auth, ]) { - if (!_isJSObject(objectException)) { + if (!isJSObject(objectException)) { return FirebaseAuthException( code: 'unknown', message: 'An unknown error occurred: $objectException', diff --git a/packages/firebase_auth/firebase_auth_web/test/fake_auth_js_sdk.dart b/packages/firebase_auth/firebase_auth_web/test/fake_auth_js_sdk.dart new file mode 100644 index 000000000000..8cd2fef678f1 --- /dev/null +++ b/packages/firebase_auth/firebase_auth_web/test/fake_auth_js_sdk.dart @@ -0,0 +1,86 @@ +// 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 'dart:js_interop_unsafe'; + +import 'package:firebase_core_platform_interface/firebase_core_platform_interface.dart'; + +/// Makes `Firebase.app()` return an app without `Firebase.initializeApp()`, +/// so `FirebaseAuthWeb.instance` can be used in tests. +class FakeFirebase extends FirebasePlatform { + @override + FirebaseAppPlatform app([String name = defaultFirebaseAppName]) { + return FirebaseAppPlatform( + name, + const FirebaseOptions( + apiKey: 'api-key', + appId: 'app-id', + messagingSenderId: 'sender-id', + projectId: 'project-id', + ), + ); + } +} + +/// A JS `Error`. With a [code], it is shaped like the `FirebaseError` the +/// Auth JS SDK throws. +JSObject jsError(String message, {String? code}) { + final error = globalContext + .getProperty('Error'.toJS) + .callAsConstructor(message.toJS); + if (code != null) { + error['name'] = 'FirebaseError'.toJS; + error['code'] = code.toJS; + } + return error; +} + +/// A JS promise that rejects with [error]. +JSPromise rejectWith(JSAny error) => globalContext + .getProperty('Promise'.toJS) + .callMethod('reject'.toJS, error); + +/// A JS promise that resolves with [value]. +JSPromise resolveWith(JSAny? value) => globalContext + .getProperty('Promise'.toJS) + .callMethod('resolve'.toJS, value); + +/// A JS function that returns [instance] when called with `new`. +JSFunction jsConstructor(JSObject instance) => globalContext + .getProperty('Function'.toJS) + .callAsConstructor( + 'instance'.toJS, + 'return function () { return instance; };'.toJS, + ) + // `callMethod` drops arguments after the first `null`, so pass a `this`. + .callMethod('call'.toJS, globalContext, instance); + +/// Installs the parts of the `firebase_core` and `firebase_auth` JS SDKs that +/// `FirebaseAuthWeb.delegate` needs, and returns the `firebase_auth` object so +/// a test can add the functions it calls. +JSObject stubFirebaseAuthJsSdk() { + final core = JSObject(); + core['getApp'] = (([JSAny? name]) => JSObject()).toJS; + globalContext['firebase_core'] = core; + + // getFirebaseAuthException always calls OAuthProvider.credentialFromError. + final oauthProvider = JSObject(); + oauthProvider['credentialFromError'] = ((JSAny _) => null).toJS; + + final auth = JSObject(); + for (final name in [ + 'indexedDBLocalPersistence', + 'browserLocalPersistence', + 'browserSessionPersistence', + 'debugErrorMap', + 'browserPopupRedirectResolver', + ]) { + auth[name] = JSObject(); + } + auth['OAuthProvider'] = oauthProvider; + auth['initializeAuth'] = ((JSAny? app, JSAny? options) => JSObject()).toJS; + globalContext['firebase_auth'] = auth; + return auth; +} diff --git a/packages/firebase_auth/firebase_auth_web/test/phone_verification_errors_test.dart b/packages/firebase_auth/firebase_auth_web/test/phone_verification_errors_test.dart new file mode 100644 index 000000000000..5ab6cff5a5b6 --- /dev/null +++ b/packages/firebase_auth/firebase_auth_web/test/phone_verification_errors_test.dart @@ -0,0 +1,152 @@ +// Copyright 2026, the Chromium project authors. Please see the AUTHORS file +// for details. All rights reserved. Use of this source code is governed by a +// BSD-style license that can be found in the LICENSE file. + +@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/firebase_auth_web.dart'; +import 'package:firebase_auth_web/src/firebase_auth_web_recaptcha_verifier_factory.dart'; +import 'package:firebase_core_platform_interface/firebase_core_platform_interface.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'fake_auth_js_sdk.dart'; + +void main() { + setUpAll(() { + FirebasePlatform.instance = FakeFirebase(); + }); + + /// Installs the JS SDK, where `new RecaptchaVerifier()` returns + /// [recaptchaVerifier] and `PhoneAuthProvider.verifyPhoneNumber()` runs + /// [verifyPhoneNumber]. + void stubSdk({ + JSObject? recaptchaVerifier, + JSPromise Function()? verifyPhoneNumber, + }) { + final phoneAuthProvider = JSObject(); + if (verifyPhoneNumber != null) { + phoneAuthProvider['verifyPhoneNumber'] = + ((JSAny? options, JSAny? verifier) => verifyPhoneNumber()).toJS; + } + + final auth = stubFirebaseAuthJsSdk(); + auth['PhoneAuthProvider'] = jsConstructor(phoneAuthProvider); + auth['RecaptchaVerifier'] = jsConstructor(recaptchaVerifier ?? JSObject()); + } + + group('verifyPhoneNumber', () { + final failures = []; + + setUp(failures.clear); + + Future verifyPhoneNumber({ + PhoneCodeSent? codeSent, + MultiFactorSession? multiFactorSession, + }) { + return FirebaseAuthWeb.instance.verifyPhoneNumber( + phoneNumber: '+15555550100', + multiFactorSession: multiFactorSession, + verificationCompleted: (_) {}, + verificationFailed: failures.add, + codeSent: codeSent ?? (_, __) {}, + codeAutoRetrievalTimeout: (_) {}, + ); + } + + test('reports a Firebase Auth error to verificationFailed', () async { + stubSdk( + verifyPhoneNumber: () => rejectWith( + jsError( + 'Firebase: Error (auth/invalid-phone-number).', + code: 'auth/invalid-phone-number', + ), + ), + ); + + await verifyPhoneNumber(); + + expect(failures.single.code, 'invalid-phone-number'); + }); + + test('rethrows a Dart error thrown by codeSent', () async { + stubSdk(verifyPhoneNumber: () => resolveWith('verification-id'.toJS)); + + await expectLater( + verifyPhoneNumber(codeSent: (_, __) => throw StateError('boom')), + throwsA(isA()), + ); + expect(failures, isEmpty); + }); + + test( + 'rethrows the cast error for a multiFactorSession from another platform', + () async { + stubSdk(); + + await expectLater( + verifyPhoneNumber(multiFactorSession: MultiFactorSession('id')), + throwsA(isA()), + ); + expect(failures, isEmpty); + }, + ); + }); + + group('RecaptchaVerifierFactoryWeb', () { + RecaptchaVerifierFactoryWeb verifierWith(JSObject recaptchaVerifier) { + stubSdk(recaptchaVerifier: recaptchaVerifier); + return RecaptchaVerifierFactoryWeb(auth: FirebaseAuthWeb.instance); + } + + test( + 'render maps a Firebase Auth error to FirebaseAuthException', + () async { + final recaptchaVerifier = JSObject(); + recaptchaVerifier['render'] = (() => rejectWith( + jsError( + 'Firebase: Error (auth/captcha-check-failed).', + code: 'auth/captcha-check-failed', + ), + )).toJS; + + await expectLater( + verifierWith(recaptchaVerifier).render(), + throwsA( + isA().having( + (e) => e.code, + 'code', + 'captcha-check-failed', + ), + ), + ); + }, + ); + + test('render rethrows a Dart error unchanged', () async { + JSPromise render() => throw StateError('boom'); + final recaptchaVerifier = JSObject(); + recaptchaVerifier['render'] = render.toJS; + + await expectLater( + verifierWith(recaptchaVerifier).render(), + throwsA(isA()), + ); + }); + + test('verify rethrows a Dart error unchanged', () { + JSPromise verify() => throw StateError('boom'); + final recaptchaVerifier = JSObject(); + recaptchaVerifier['verify'] = verify.toJS; + + expect( + () => verifierWith(recaptchaVerifier).verify(), + throwsA(isA()), + ); + }); + }); +} diff --git a/packages/firebase_auth/firebase_auth_web/test/use_auth_emulator_test.dart b/packages/firebase_auth/firebase_auth_web/test/use_auth_emulator_test.dart index 0efa2cdda42b..447438d47543 100644 --- a/packages/firebase_auth/firebase_auth_web/test/use_auth_emulator_test.dart +++ b/packages/firebase_auth/firebase_auth_web/test/use_auth_emulator_test.dart @@ -13,66 +13,22 @@ import 'package:firebase_auth_web/firebase_auth_web.dart'; import 'package:firebase_core_platform_interface/firebase_core_platform_interface.dart'; import 'package:flutter_test/flutter_test.dart'; -class _FakeFirebase extends FirebasePlatform { - @override - FirebaseAppPlatform app([String name = defaultFirebaseAppName]) { - return FirebaseAppPlatform( - name, - const FirebaseOptions( - apiKey: 'api-key', - appId: 'app-id', - messagingSenderId: 'sender-id', - projectId: 'project-id', - ), - ); - } -} - -JSObject _jsError(String message, {String? code}) { - final error = globalContext - .getProperty('Error'.toJS) - .callAsConstructor(message.toJS); - if (code != null) { - error['name'] = 'FirebaseError'.toJS; - error['code'] = code.toJS; - } - return error; -} +import 'fake_auth_js_sdk.dart'; void main() { setUpAll(() { - FirebasePlatform.instance = _FakeFirebase(); + FirebasePlatform.instance = FakeFirebase(); }); /// Stubs the JS SDK so that `connectAuthEmulator()` throws [error]. void connectAuthEmulatorThrows(Object error) { - final core = JSObject(); - core['getApp'] = (([JSAny? name]) => JSObject()).toJS; - globalContext['firebase_core'] = core; - - final oauthProvider = JSObject(); - oauthProvider['credentialFromError'] = ((JSAny _) => null).toJS; - - final auth = JSObject(); - for (final name in [ - 'indexedDBLocalPersistence', - 'browserLocalPersistence', - 'browserSessionPersistence', - 'debugErrorMap', - 'browserPopupRedirectResolver', - ]) { - auth[name] = JSObject(); - } - auth['OAuthProvider'] = oauthProvider; - auth['initializeAuth'] = ((JSAny? app, JSAny? options) => JSObject()).toJS; void connectAuthEmulator(JSAny? auth, JSAny? origin) => throw error; - auth['connectAuthEmulator'] = connectAuthEmulator.toJS; - globalContext['firebase_auth'] = auth; + stubFirebaseAuthJsSdk()['connectAuthEmulator'] = connectAuthEmulator.toJS; } test('ignores auth/emulator-config-failed after a hot restart', () async { connectAuthEmulatorThrows( - _jsError( + jsError( 'Firebase: Error (auth/emulator-config-failed).', code: 'auth/emulator-config-failed', ), @@ -83,7 +39,7 @@ void main() { test('maps a Firebase Auth error to FirebaseAuthException', () async { connectAuthEmulatorThrows( - _jsError( + jsError( 'Firebase: Error (auth/invalid-emulator-scheme).', code: 'auth/invalid-emulator-scheme', ), @@ -102,7 +58,7 @@ void main() { }); test('maps a JS error without code to an unknown error', () async { - connectAuthEmulatorThrows(_jsError('storage is disabled')); + connectAuthEmulatorThrows(jsError('storage is disabled')); await expectLater( FirebaseAuthWeb.instance.useAuthEmulator('localhost', 9099),