diff --git a/CHANGELOG.md b/CHANGELOG.md index a4499a9..3e5412a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,13 @@ - Added `const` constructor to `SmartAuthSms` and the `@immutable` annotation to `SmartAuthResult` - Documentation: redesigned README, documented `getAppSignature`, added a 4.x migration note and the version requirements +**Fixes** + +- `removeSmsRetrieverApiListener` and `removeUserConsentApiListener` now finish a waiting SMS call as canceled instead of leaving its Future pending forever +- Starting a new SMS call now finishes the previous waiting one as canceled instead of leaving it pending forever +- `getSmsWithRetrieverApi` can now return `SmartAuthResult.canceled` +- `requestPhoneNumberHint` and the SMS calls no longer share a result, so an SMS can't be returned as the phone number + **Android** - Migrated Android to built-in Kotlin and removed the Kotlin Gradle Plugin classpath from the plugin's `build.gradle` (AGP 9 support) diff --git a/README.md b/README.md index 3253084..207cd84 100644 --- a/README.md +++ b/README.md @@ -187,6 +187,7 @@ if (prepared.hasData) { await smartAuth.clearCredentialState(); ``` +- Saving a password or creating a passkey needs a credential provider on the device, such as Google Password Manager with a signed-in Google account. Without one the call fails with `TYPE_NO_CREATE_OPTIONS`, which is common on emulators. Treat it as "not saved", not as a failed sign-in. - `prepareGetCredential` and `getPreparedCredential` need Android 14 or higher. Below that they fail with `UNSUPPORTED`. - Only privileged apps can see which credentials `prepareGetCredential` found. The `has*` fields of `SmartAuthPreparedCredential` are `null` for other apps. It still makes the next `getPreparedCredential` faster. diff --git a/android/src/main/kotlin/dev/tornike/smart_auth/SmartAuthPlugin.kt b/android/src/main/kotlin/dev/tornike/smart_auth/SmartAuthPlugin.kt index 281df8d..bfd2c3b 100644 --- a/android/src/main/kotlin/dev/tornike/smart_auth/SmartAuthPlugin.kt +++ b/android/src/main/kotlin/dev/tornike/smart_auth/SmartAuthPlugin.kt @@ -4,6 +4,8 @@ import android.app.Activity import android.app.Activity.RESULT_CANCELED import android.app.Activity.RESULT_OK import android.content.* +import android.os.Handler +import android.os.Looper import android.util.Log import androidx.core.app.ActivityCompat.startIntentSenderForResult import androidx.core.content.ContextCompat @@ -24,9 +26,11 @@ class SmartAuthPlugin : FlutterPlugin, ActivityAware, PluginRegistry.ActivityRes SmartAuthApi { private lateinit var mContext: Context private lateinit var credentialManager: CredentialManagerHelper + private val mainHandler = Handler(Looper.getMainLooper()) private var mActivity: Activity? = null private var mBinding: ActivityPluginBinding? = null - private var pendingResult: ((Result) -> Unit)? = null + private var pendingSmsResult: ((Result) -> Unit)? = null + private var pendingHintResult: ((Result) -> Unit)? = null private var smsReceiver: SmsBroadcastReceiver? = null private var consentReceiver: ConsentBroadcastReceiver? = null @@ -80,11 +84,11 @@ class SmartAuthPlugin : FlutterPlugin, ActivityAware, PluginRegistry.ActivityRes override suspend fun getSmsWithRetrieverApi(): String = suspendCancellableCoroutine { cont -> - unregisterAllReceivers() - pendingResult = { cont.resumeWith(it) } + cancelPendingSmsRequest() + pendingSmsResult = { cont.resumeWith(it) } cont.invokeOnCancellation { - consumePendingResult() - removeSmsRetrieverListener() + consumeSmsResult() + unregisterSmsReceiver() } smsReceiver = SmsBroadcastReceiver() val intentFilter = IntentFilter(SmsRetriever.SMS_RETRIEVED_ACTION) @@ -101,11 +105,11 @@ class SmartAuthPlugin : FlutterPlugin, ActivityAware, PluginRegistry.ActivityRes override suspend fun getSmsWithUserConsentApi(phoneNumber: String?): String = suspendCancellableCoroutine { cont -> - unregisterAllReceivers() - pendingResult = { cont.resumeWith(it) } + cancelPendingSmsRequest() + pendingSmsResult = { cont.resumeWith(it) } cont.invokeOnCancellation { - consumePendingResult() - removeUserConsentListener() + consumeSmsResult() + unregisterConsentReceiver() } consentReceiver = ConsentBroadcastReceiver() val intentFilter = IntentFilter(SmsRetriever.SMS_RETRIEVED_ACTION) @@ -121,17 +125,22 @@ class SmartAuthPlugin : FlutterPlugin, ActivityAware, PluginRegistry.ActivityRes } + // The SMS calls are suspend functions, which start on a later main thread + // tick. Queue the removal behind them, otherwise a call made right before + // it would start after the removal and never finish. override fun removeSmsRetrieverListener() { - if (smsReceiver != null) { - unregisterReceiver(smsReceiver) - smsReceiver = null + mainHandler.post { + if (smsReceiver != null) { + cancelPendingSmsRequest() + } } } override fun removeUserConsentListener() { - if (consentReceiver != null) { - unregisterReceiver(consentReceiver) - consentReceiver = null + mainHandler.post { + if (consentReceiver != null) { + cancelPendingSmsRequest() + } } } @@ -150,9 +159,10 @@ class SmartAuthPlugin : FlutterPlugin, ActivityAware, PluginRegistry.ActivityRes ) return@suspendCancellableCoroutine } - pendingResult = { cont.resumeWith(it) } + ignoreIllegalState { consumeHintResult()?.invoke(Result.failure(hintCanceledError())) } + pendingHintResult = { cont.resumeWith(it) } cont.invokeOnCancellation { - consumePendingResult() + consumeHintResult() } val hintRequest = GetPhoneNumberHintIntentRequest.builder().build() @@ -174,12 +184,12 @@ class SmartAuthPlugin : FlutterPlugin, ActivityAware, PluginRegistry.ActivityRes } catch (e: Exception) { val message = "Failed to start phone number hint intent: ${e.message}" Log.e(PLUGIN_TAG, message) - consumePendingResult()?.invoke(Result.failure(Exception(message))) + consumeHintResult()?.invoke(Result.failure(Exception(message))) } } else { val message = "Activity was detached before launching phone number hint intent." Log.e(PLUGIN_TAG, message) - consumePendingResult()?.invoke( + consumeHintResult()?.invoke( Result.failure( FlutterError( "NO_ACTIVITY", @@ -192,7 +202,7 @@ class SmartAuthPlugin : FlutterPlugin, ActivityAware, PluginRegistry.ActivityRes }.addOnFailureListener { exception -> val message = "Failed to get phone number hint intent: ${exception.message}" Log.e(PLUGIN_TAG, message) - consumePendingResult()?.invoke(Result.failure(Exception(message))) + consumeHintResult()?.invoke(Result.failure(Exception(message))) } } @@ -213,19 +223,47 @@ class SmartAuthPlugin : FlutterPlugin, ActivityAware, PluginRegistry.ActivityRes override suspend fun clearCredentialState() = credentialManager.clearCredentialState() - private fun consumePendingResult(): ((Result) -> Unit)? { - val result = pendingResult - pendingResult = null + private fun consumeSmsResult(): ((Result) -> Unit)? { + val result = pendingSmsResult + pendingSmsResult = null return result } + private fun consumeHintResult(): ((Result) -> Unit)? { + val result = pendingHintResult + pendingHintResult = null + return result + } + + /** Stops listening and finishes a waiting SMS call, so its Future doesn't hang. */ + private fun cancelPendingSmsRequest() { + unregisterAllReceivers() + ignoreIllegalState { + consumeSmsResult()?.invoke( + Result.failure( + FlutterError( + "SMS_REQUEST_CANCELED", + "SMS request was canceled.", + SmartAuthRequestCanceled() + ) + ) + ) + } + } + + private fun hintCanceledError() = FlutterError( + "PHONE_NUMBER_HINT_CANCELED", + "User canceled phone number hint request.", + SmartAuthRequestCanceled() + ) + /// Callbacks private fun onSmsConsentRequest(resultCode: Int, data: Intent?) { if (resultCode == RESULT_OK && data != null) { val message = data.getStringExtra(SmsRetriever.EXTRA_SMS_MESSAGE) if (message == null) { ignoreIllegalState { - consumePendingResult()?.invoke( + consumeSmsResult()?.invoke( Result.failure( Exception("Failed to get SMS with user consent.") ) @@ -233,13 +271,13 @@ class SmartAuthPlugin : FlutterPlugin, ActivityAware, PluginRegistry.ActivityRes } return } - ignoreIllegalState { consumePendingResult()?.invoke(Result.success(message)) } + ignoreIllegalState { consumeSmsResult()?.invoke(Result.success(message)) } return } if (resultCode == RESULT_CANCELED) { ignoreIllegalState { - consumePendingResult()?.invoke( + consumeSmsResult()?.invoke( Result.failure( FlutterError( "USER_CONSENT_CANCELED", @@ -253,7 +291,7 @@ class SmartAuthPlugin : FlutterPlugin, ActivityAware, PluginRegistry.ActivityRes } ignoreIllegalState { - consumePendingResult()?.invoke( + consumeSmsResult()?.invoke( Result.failure( Exception("Failed to get SMS with user consent.") ) @@ -267,13 +305,13 @@ class SmartAuthPlugin : FlutterPlugin, ActivityAware, PluginRegistry.ActivityRes try { val phoneNumber = Identity.getSignInClient(mContext).getPhoneNumberFromIntent(data) ignoreIllegalState { - consumePendingResult()?.invoke(Result.success(phoneNumber)) + consumeHintResult()?.invoke(Result.success(phoneNumber)) } } catch (e: Exception) { val message = "Failed to get phone number from intent: ${e.message}" Log.e(PLUGIN_TAG, message) ignoreIllegalState { - consumePendingResult()?.invoke(Result.failure(Exception(message))) + consumeHintResult()?.invoke(Result.failure(Exception(message))) } } return @@ -281,13 +319,9 @@ class SmartAuthPlugin : FlutterPlugin, ActivityAware, PluginRegistry.ActivityRes if (resultCode == RESULT_CANCELED) { ignoreIllegalState { - consumePendingResult()?.invoke( + consumeHintResult()?.invoke( Result.failure( - FlutterError( - "PHONE_NUMBER_HINT_CANCELED", - "User canceled phone number hint request.", - SmartAuthRequestCanceled() - ) + hintCanceledError() ) ) } @@ -297,7 +331,7 @@ class SmartAuthPlugin : FlutterPlugin, ActivityAware, PluginRegistry.ActivityRes val message = "Failed to get phone number hint with resultCode: $resultCode" Log.e(PLUGIN_TAG, message) ignoreIllegalState { - consumePendingResult()?.invoke( + consumeHintResult()?.invoke( Result.failure( FlutterError( "PHONE_NUMBER_HINT_FAILED", message, null @@ -317,13 +351,28 @@ class SmartAuthPlugin : FlutterPlugin, ActivityAware, PluginRegistry.ActivityRes private fun dispose() { unregisterAllReceivers() credentialManager.dispose() - consumePendingResult() + consumeSmsResult() + consumeHintResult() detachActivity() } private fun unregisterAllReceivers() { - removeSmsRetrieverListener(); - removeUserConsentListener(); + unregisterSmsReceiver() + unregisterConsentReceiver() + } + + private fun unregisterSmsReceiver() { + if (smsReceiver != null) { + unregisterReceiver(smsReceiver) + smsReceiver = null + } + } + + private fun unregisterConsentReceiver() { + if (consentReceiver != null) { + unregisterReceiver(consentReceiver) + consentReceiver = null + } } @@ -350,7 +399,7 @@ class SmartAuthPlugin : FlutterPlugin, ActivityAware, PluginRegistry.ActivityRes inner class SmsBroadcastReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { if (SmsRetriever.SMS_RETRIEVED_ACTION == intent.action) { - removeSmsRetrieverListener() + unregisterSmsReceiver() if (intent.extras != null && intent.extras!!.containsKey(SmsRetriever.EXTRA_STATUS)) { val extras = intent.extras!! val smsRetrieverStatus = extras.get(SmsRetriever.EXTRA_STATUS) as Status @@ -359,7 +408,7 @@ class SmartAuthPlugin : FlutterPlugin, ActivityAware, PluginRegistry.ActivityRes val smsContent = extras.getString(SmsRetriever.EXTRA_SMS_MESSAGE) if (smsContent != null) { ignoreIllegalState { - consumePendingResult()?.invoke( + consumeSmsResult()?.invoke( Result.success(smsContent) ) } @@ -368,7 +417,7 @@ class SmartAuthPlugin : FlutterPlugin, ActivityAware, PluginRegistry.ActivityRes "Retrieved SMS is null, check if SMS contains correct app signature" Log.e(PLUGIN_TAG, message) ignoreIllegalState { - consumePendingResult()?.invoke(Result.failure(Exception(message))) + consumeSmsResult()?.invoke(Result.failure(Exception(message))) } } } @@ -378,7 +427,7 @@ class SmartAuthPlugin : FlutterPlugin, ActivityAware, PluginRegistry.ActivityRes "SMS Retriever API timed out, check if SMS contains correct app signature" Log.e(PLUGIN_TAG, message) ignoreIllegalState { - consumePendingResult()?.invoke(Result.failure(Exception(message))) + consumeSmsResult()?.invoke(Result.failure(Exception(message))) } } @@ -387,7 +436,7 @@ class SmartAuthPlugin : FlutterPlugin, ActivityAware, PluginRegistry.ActivityRes "SMS Retriever API failed with status code: ${smsRetrieverStatus.statusCode}, check if SMS contains correct app signature" Log.e(PLUGIN_TAG, message) ignoreIllegalState { - consumePendingResult()?.invoke(Result.failure(Exception(message))) + consumeSmsResult()?.invoke(Result.failure(Exception(message))) } } } @@ -396,7 +445,7 @@ class SmartAuthPlugin : FlutterPlugin, ActivityAware, PluginRegistry.ActivityRes "SMS Retriever API failed with no status code, check if SMS contains correct app signature" Log.e(PLUGIN_TAG, message) ignoreIllegalState { - consumePendingResult()?.invoke(Result.failure(Exception(message))) + consumeSmsResult()?.invoke(Result.failure(Exception(message))) } } } @@ -410,7 +459,7 @@ class SmartAuthPlugin : FlutterPlugin, ActivityAware, PluginRegistry.ActivityRes inner class ConsentBroadcastReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { if (SmsRetriever.SMS_RETRIEVED_ACTION == intent.action) { - removeUserConsentListener() + unregisterConsentReceiver() if (intent.extras != null && intent.extras!!.containsKey(SmsRetriever.EXTRA_STATUS)) { val extras = intent.extras!! val smsRetrieverStatus = extras.get(SmsRetriever.EXTRA_STATUS) as Status @@ -429,14 +478,14 @@ class SmartAuthPlugin : FlutterPlugin, ActivityAware, PluginRegistry.ActivityRes "ConsentBroadcastReceiver error: Can't start consent intent. consentIntent or mActivity is null" Log.e(PLUGIN_TAG, message) ignoreIllegalState { - consumePendingResult()?.invoke(Result.failure(Exception(message))) + consumeSmsResult()?.invoke(Result.failure(Exception(message))) } } } catch (e: ActivityNotFoundException) { val message = "ConsentBroadcastReceiver error: $e" Log.e(PLUGIN_TAG, message) ignoreIllegalState { - consumePendingResult()?.invoke(Result.failure(Exception(message))) + consumeSmsResult()?.invoke(Result.failure(Exception(message))) } } } @@ -445,7 +494,7 @@ class SmartAuthPlugin : FlutterPlugin, ActivityAware, PluginRegistry.ActivityRes val message = "ConsentBroadcastReceiver Timeout" Log.e(PLUGIN_TAG, message) ignoreIllegalState { - consumePendingResult()?.invoke(Result.failure(Exception(message))) + consumeSmsResult()?.invoke(Result.failure(Exception(message))) } } @@ -454,7 +503,7 @@ class SmartAuthPlugin : FlutterPlugin, ActivityAware, PluginRegistry.ActivityRes "ConsentBroadcastReceiver failed with status code: ${smsRetrieverStatus.statusCode}" Log.e(PLUGIN_TAG, message) ignoreIllegalState { - consumePendingResult()?.invoke(Result.failure(Exception(message))) + consumeSmsResult()?.invoke(Result.failure(Exception(message))) } } @@ -463,7 +512,7 @@ class SmartAuthPlugin : FlutterPlugin, ActivityAware, PluginRegistry.ActivityRes val message = "ConsentBroadcastReceiver failed with no status code" Log.e(PLUGIN_TAG, message) ignoreIllegalState { - consumePendingResult()?.invoke(Result.failure(Exception(message))) + consumeSmsResult()?.invoke(Result.failure(Exception(message))) } } diff --git a/example/integration_test/run_sms_tests.sh b/example/integration_test/run_sms_tests.sh index 2995603..394e652 100755 --- a/example/integration_test/run_sms_tests.sh +++ b/example/integration_test/run_sms_tests.sh @@ -19,6 +19,49 @@ package="dev.tornike.smart_auth_example" # healthy emulator needs a few seconds. startup_timeout="${STARTUP_TIMEOUT:-120}" attempts="${ATTEMPTS:-3}" +sender="5551234" +other_sender="5559876" + +# The console treats a newline as a new command, so keep messages on one line. +send_sms() { + adb -s "$device" emu sms send "$1" "$2" /dev/null + local coords + coords=$(device_shell cat /sdcard/ui.xml \ + | grep -o "text=\"$1\"[^>]*bounds=\"\[[0-9,]*\]\[[0-9,]*\]\"" \ + | grep -o '\[[0-9]*,[0-9]*\]\[[0-9]*,[0-9]*\]' | head -n 1 \ + | sed 's/\]\[/,/; s/[][]//g' | tr ',' ' ' \ + | awk '{print int(($1+$3)/2), int(($2+$4)/2)}' || true) + if [ -n "$coords" ]; then + device_shell input tap $coords + else + echo "Dialog button not found: $1" + fi +} + +# Dismisses the phone number hint dialog. Only presses Back while the dialog +# has focus: it can die on its own on CI emulators, and a stray Back would +# then send the app to the background and stall the rest of the run. +dismiss_hint() { + for _ in 1 2 3 4 5; do + if device_shell dumpsys window 2>/dev/null \ + | grep -E 'mCurrentFocus|mFocusedWindow' | grep -q PhoneNumberHintActivity; then + device_shell input keyevent KEYCODE_BACK + break + fi + sleep 2 + done +} run_attempt() { local flag="$1" @@ -53,37 +96,74 @@ run_attempt() { signature="${line##*SMS_SIGNATURE=}" # Give the retriever time to start listening. sleep 4 - # The console treats a newline as a new command, so keep it on one line. - adb -s "$device" emu sms send 5551234 "<#> Your code is 123456 $signature" + send_sms "$sender" "<#> Your code is 123456 $signature" + ;; + *SMS_UNSIGNED_CHECK=*) + signature="${line##*SMS_UNSIGNED_CHECK=}" + sleep 4 + send_sms "$sender" "<#> Your code is 111111" + sleep 3 + send_sms "$sender" "<#> Your code is 222222 $signature" ;; *HINT_READY*) - # Dismiss the phone number hint dialog. Only press Back while the dialog - # has focus: it can die on its own on CI emulators, and a stray Back would - # then send the app to the background and stall the rest of the run. sleep 4 - for _ in 1 2 3 4 5; do - if adb -s "$device" shell dumpsys window 2>/dev/null \ - | grep -E 'mCurrentFocus|mFocusedWindow' | grep -q PhoneNumberHintActivity; then - adb -s "$device" shell input keyevent KEYCODE_BACK - break - fi - sleep 2 - done + dismiss_hint + ;; + *HINT_SMS_READY=*) + signature="${line##*HINT_SMS_READY=}" + sleep 4 + send_sms "$sender" "<#> Your code is 888888 $signature" + sleep 2 + dismiss_hint ;; *SMS_CONSENT_READY*) sleep 2 - adb -s "$device" emu sms send 5551234 "Your code is 654321" - # Accept the consent dialog. + send_sms "$sender" "Your code is 654321" + sleep 3 + tap_dialog_button Allow + ;; + *SMS_CONSENT_DENY_READY*) + sleep 2 + send_sms "$sender" "Your code is 333333" + sleep 3 + tap_dialog_button Deny + ;; + *SMS_CONSENT_OTHER_SENDER_READY*) + sleep 2 + send_sms "$other_sender" "Your code is 111111" + sleep 3 + send_sms "$sender" "Your code is 444444" + sleep 3 + tap_dialog_button Allow + ;; + *SMS_CONSENT_ANY_SENDER_READY*) + sleep 2 + send_sms "$other_sender" "Your code is 555555" + sleep 3 + tap_dialog_button Allow + ;; + *SMS_CONSENT_ROTATE_READY*) + sleep 2 + send_sms "$sender" "Your code is 666666" + sleep 3 + device_shell settings put system accelerometer_rotation 0 + device_shell settings put system user_rotation 1 + sleep 3 + # Finish rotating before tapping: each rotation recreates the dialog, + # which can lose a tap that lands around the same time. + device_shell settings put system user_rotation 0 + sleep 3 + tap_dialog_button Allow + ;; + *SMS_CONSENT_BACKGROUND_READY*) + sleep 2 + send_sms "$sender" "Your code is 777777" + sleep 3 + device_shell input keyevent KEYCODE_HOME + sleep 2 + device_shell monkey -p "$package" -c android.intent.category.LAUNCHER 1 >/dev/null sleep 3 - adb -s "$device" shell uiautomator dump --windows /sdcard/ui.xml >/dev/null - coords=$(adb -s "$device" shell cat /sdcard/ui.xml \ - | grep -o 'text="Allow"[^>]*bounds="\[[0-9,]*\]\[[0-9,]*\]"' \ - | grep -o '\[[0-9]*,[0-9]*\]\[[0-9]*,[0-9]*\]' | head -n 1 \ - | sed 's/\]\[/,/; s/[][]//g' | tr ',' ' ' \ - | awk '{print int(($1+$3)/2), int(($2+$4)/2)}' || true) - if [ -n "$coords" ]; then - adb -s "$device" shell input tap $coords - fi + tap_dialog_button Allow ;; esac done @@ -102,7 +182,7 @@ for attempt in $(seq 1 "$attempts"); do fi rm -f "$hung" echo "Attempt $attempt of $attempts: the app did not start, trying again." - adb -s "$device" shell am force-stop "$package" >/dev/null 2>&1 || true + device_shell am force-stop "$package" >/dev/null 2>&1 || true done echo "The app did not start after $attempts attempts." exit 1 diff --git a/example/integration_test/smart_auth_test.dart b/example/integration_test/smart_auth_test.dart index e394106..7286d9b 100644 --- a/example/integration_test/smart_auth_test.dart +++ b/example/integration_test/smart_auth_test.dart @@ -260,6 +260,19 @@ void main() { expect(result.requireData.code, '123456'); expect(result.requireData.sms, contains(signature)); }, skip: !smsTests); + + testWidgets('ignores a message without the app signature', (tester) async { + final signature = (await smartAuth.getAppSignature()).requireData; + // ignore: avoid_print for testing + print('SMS_UNSIGNED_CHECK=$signature'); + + final result = await smartAuth.getSmsWithRetrieverApi().timeout( + const Duration(seconds: 60), + ); + + expect(result.hasData, isTrue, reason: '${result.error}'); + expect(result.requireData.code, '222222'); + }, skip: !smsTests); }); group('SMS User Consent API', () { @@ -273,5 +286,139 @@ void main() { expect(result.hasData, isTrue, reason: '${result.error}'); expect(result.requireData.code, '654321'); }, skip: !smsTests); + + testWidgets('is reported as canceled when the user denies', (tester) async { + // ignore: avoid_print for testing + print('SMS_CONSENT_DENY_READY'); + final result = await smartAuth + .getSmsWithUserConsentApi(senderPhoneNumber: _sender) + .timeout(const Duration(seconds: 60)); + + expect(result.isCanceled, isTrue, reason: '${result.error}'); + }, skip: !smsTests); + + testWidgets('ignores a message from another sender', (tester) async { + // ignore: avoid_print for testing + print('SMS_CONSENT_OTHER_SENDER_READY'); + final result = await smartAuth + .getSmsWithUserConsentApi(senderPhoneNumber: _sender) + .timeout(const Duration(seconds: 60)); + + expect(result.hasData, isTrue, reason: '${result.error}'); + expect(result.requireData.code, '444444'); + }, skip: !smsTests); + + testWidgets('accepts any sender when none is given', (tester) async { + // ignore: avoid_print for testing + print('SMS_CONSENT_ANY_SENDER_READY'); + final result = await smartAuth.getSmsWithUserConsentApi().timeout( + const Duration(seconds: 60), + ); + + expect(result.hasData, isTrue, reason: '${result.error}'); + expect(result.requireData.code, '555555'); + }, skip: !smsTests); + + testWidgets('survives a rotation while the dialog is open', (tester) async { + // ignore: avoid_print for testing + print('SMS_CONSENT_ROTATE_READY'); + final result = await smartAuth + .getSmsWithUserConsentApi(senderPhoneNumber: _sender) + .timeout(const Duration(seconds: 60)); + + expect(result.hasData, isTrue, reason: '${result.error}'); + expect(result.requireData.code, '666666'); + }, skip: !smsTests); + + testWidgets('survives the app going to the background', (tester) async { + // ignore: avoid_print for testing + print('SMS_CONSENT_BACKGROUND_READY'); + final result = await smartAuth + .getSmsWithUserConsentApi(senderPhoneNumber: _sender) + .timeout(const Duration(seconds: 60)); + + expect(result.hasData, isTrue, reason: '${result.error}'); + expect(result.requireData.code, '777777'); + }, skip: !smsTests); + }); + + group('Phone Number Hint with an SMS listener', () { + testWidgets('keeps the two results apart', (tester) async { + final signature = (await smartAuth.getAppSignature()).requireData; + final sms = smartAuth.getSmsWithRetrieverApi(); + // ignore: avoid_print for testing + print('HINT_SMS_READY=$signature'); + // See the Phone Number Hint group for why this uses runAsync. + final hint = (await tester.runAsync( + () => smartAuth.requestPhoneNumberHint().timeout( + const Duration(seconds: 60), + ), + ))!; + + expect(hint.hasData, isFalse, reason: 'hint got: ${hint.data}'); + + final result = await sms.timeout(const Duration(seconds: 30)); + + expect(result.hasData, isTrue, reason: '${result.error}'); + expect(result.requireData.code, '888888'); + }, skip: !hintTests || !smsTests); + }); + + // No SMS is sent here. These stay last: a request that is never answered + // stays registered with Play services for 5 minutes, and a stale consent + // request would open a second dialog in the tests above. + group('pending SMS calls', () { + const timeout = Duration(seconds: 10); + + tearDown(() async { + await smartAuth.removeSmsRetrieverApiListener(); + await smartAuth.removeUserConsentApiListener(); + }); + + testWidgets('removeSmsRetrieverApiListener finishes the call', ( + tester, + ) async { + final pending = smartAuth.getSmsWithRetrieverApi(); + await smartAuth.removeSmsRetrieverApiListener(); + + final result = await pending.timeout(timeout); + + expect(result.isCanceled, isTrue, reason: '${result.error}'); + }, skip: !smsTests); + + testWidgets('removeUserConsentApiListener finishes the call', ( + tester, + ) async { + final pending = smartAuth.getSmsWithUserConsentApi(); + await smartAuth.removeUserConsentApiListener(); + + final result = await pending.timeout(timeout); + + expect(result.isCanceled, isTrue, reason: '${result.error}'); + }, skip: !smsTests); + + testWidgets('a second retriever call finishes the first', (tester) async { + final first = smartAuth.getSmsWithRetrieverApi(); + final second = smartAuth.getSmsWithRetrieverApi(); + + final result = await first.timeout(timeout); + + expect(result.isCanceled, isTrue, reason: '${result.error}'); + await smartAuth.removeSmsRetrieverApiListener(); + await second.timeout(timeout); + }, skip: !smsTests); + + testWidgets('a consent call finishes a pending retriever call', ( + tester, + ) async { + final first = smartAuth.getSmsWithRetrieverApi(); + final second = smartAuth.getSmsWithUserConsentApi(); + + final result = await first.timeout(timeout); + + expect(result.isCanceled, isTrue, reason: '${result.error}'); + await smartAuth.removeUserConsentApiListener(); + await second.timeout(timeout); + }, skip: !smsTests); }); } diff --git a/lib/src/smart_auth.dart b/lib/src/smart_auth.dart index 69c2dbc..7a868b9 100644 --- a/lib/src/smart_auth.dart +++ b/lib/src/smart_auth.dart @@ -55,6 +55,9 @@ class SmartAuth { /// the App signature [getAppSignature]in the text /// returns code if it matches with matcher /// More about SMS Retriever API https://developers.google.com/identity/sms-retriever/overview?hl=en + /// + /// Only one SMS call can wait at a time: starting another one finishes + /// this one as canceled. Future> getSmsWithRetrieverApi({ /// used to extract code from SMS String matcher = _defaultCodeMatcher, @@ -63,6 +66,14 @@ class SmartAuth { final result = await _api.getSmsWithRetrieverApi(); return SmartAuthResult.success(SmartAuthSms.fromSms(result, matcher)); } catch (error) { + final isCanceled = + error is PlatformException && + error.details is SmartAuthRequestCanceled; + + if (isCanceled) { + debugPrint('Pinput/SmartAuth: ${error.message}'); + return const SmartAuthResult.canceled(); + } debugPrint('Pinput/SmartAuth: getSmsWithRetrieverApi failed: $error'); return SmartAuthResult.failure( 'Failed to get SMS with retriever API with error: $error', @@ -74,6 +85,9 @@ class SmartAuth { /// Which shows confirmations dialog to user to /// confirm reading the SMS content /// returns code if it matches with matcher + /// + /// Only one SMS call can wait at a time: starting another one finishes + /// this one as canceled. Future> getSmsWithUserConsentApi({ /// used to extract code from SMS String matcher = _defaultCodeMatcher, @@ -101,6 +115,7 @@ class SmartAuth { } /// Removes listener for [getSmsWithUserConsentApi] + /// A call that is still waiting for an SMS finishes as canceled. Future> removeUserConsentApiListener() async { try { await _api.removeUserConsentListener(); @@ -114,6 +129,7 @@ class SmartAuth { } /// Removes listener for [getSmsWithRetrieverApi] + /// A call that is still waiting for an SMS finishes as canceled. Future> removeSmsRetrieverApiListener() async { try { await _api.removeSmsRetrieverListener(); @@ -176,6 +192,10 @@ class SmartAuth { } /// Saves a password to the Credential Manager. + /// + /// Needs a credential provider on the device, such as Google Password + /// Manager with a signed-in Google account. Without one this fails with + /// `TYPE_NO_CREATE_OPTIONS`. Future> createPasswordCredential({ required String id, @@ -204,6 +224,10 @@ class SmartAuth { /// in the WebAuthn JSON format. /// The registration response to send to your server is in /// [SmartAuthCreateCredentialResponse.registrationResponseJson]. + /// + /// Needs a credential provider on the device, such as Google Password + /// Manager with a signed-in Google account. Without one this fails with + /// `TYPE_NO_CREATE_OPTIONS`. Future> createPublicKeyCredential({ required String requestJson, diff --git a/test/sms_api_test.dart b/test/sms_api_test.dart new file mode 100644 index 0000000..07eb259 --- /dev/null +++ b/test/sms_api_test.dart @@ -0,0 +1,186 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:smart_auth/smart_auth.dart'; +import 'package:smart_auth/src/smart_auth_api.g.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + const codec = SmartAuthApi.pigeonChannelCodec; + final messenger = + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; + const prefix = 'dev.flutter.pigeon.smart_auth.SmartAuthApi'; + const methods = [ + 'getAppSignature', + 'getSmsWithRetrieverApi', + 'getSmsWithUserConsentApi', + 'removeSmsRetrieverListener', + 'removeUserConsentListener', + 'requestPhoneNumberHint', + ]; + + void reply(String method, Object? value) { + messenger.setMockMessageHandler('$prefix.$method', (_) async { + return codec.encodeMessage([value]); + }); + } + + void fail(String method, String code, {Object? details}) { + messenger.setMockMessageHandler('$prefix.$method', (_) async { + return codec.encodeMessage([code, 'message', details]); + }); + } + + tearDown(() { + for (final method in methods) { + messenger.setMockMessageHandler('$prefix.$method', null); + } + }); + + group('getSmsWithRetrieverApi', () { + test('extracts the code with the default matcher', () async { + reply('getSmsWithRetrieverApi', 'Your code is 123456'); + + final result = await SmartAuth.instance.getSmsWithRetrieverApi(); + + expect(result.requireData.code, '123456'); + }); + + test('extracts the code with a custom matcher', () async { + reply('getSmsWithRetrieverApi', 'Code AB-12 expires in 123456 seconds'); + + final result = await SmartAuth.instance.getSmsWithRetrieverApi( + matcher: r'[A-Z]{2}-\d{2}', + ); + + expect(result.requireData.code, 'AB-12'); + }); + + test('keeps the SMS when the matcher finds nothing', () async { + reply('getSmsWithRetrieverApi', 'No digits here'); + + final result = await SmartAuth.instance.getSmsWithRetrieverApi(); + + expect(result.requireData.sms, 'No digits here'); + expect(result.requireData.code, isNull); + }); + + test('keeps the SMS when the matcher is an invalid regex', () async { + reply('getSmsWithRetrieverApi', 'Your code is 123456'); + + final result = await SmartAuth.instance.getSmsWithRetrieverApi( + matcher: '(', + ); + + expect(result.requireData.sms, 'Your code is 123456'); + expect(result.requireData.code, isNull); + }); + + test('cancellation is reported as canceled', () async { + fail( + 'getSmsWithRetrieverApi', + 'SMS_REQUEST_CANCELED', + details: SmartAuthRequestCanceled(), + ); + + final result = await SmartAuth.instance.getSmsWithRetrieverApi(); + + expect(result.isCanceled, isTrue); + expect(result.hasError, isFalse); + }); + + test('failures are reported as errors', () async { + fail('getSmsWithRetrieverApi', 'FAILED'); + + final result = await SmartAuth.instance.getSmsWithRetrieverApi(); + + expect(result.hasError, isTrue); + expect(result.isCanceled, isFalse); + }); + }); + + group('getSmsWithUserConsentApi', () { + test('sends the sender phone number', () async { + Object? sender; + messenger.setMockMessageHandler('$prefix.getSmsWithUserConsentApi', ( + message, + ) async { + sender = (codec.decodeMessage(message) as List).first; + return codec.encodeMessage(['Your code is 123456']); + }); + + final result = await SmartAuth.instance.getSmsWithUserConsentApi( + senderPhoneNumber: '5551234', + ); + + expect(sender, '5551234'); + expect(result.requireData.code, '123456'); + }); + + test('cancellation is reported as canceled', () async { + fail( + 'getSmsWithUserConsentApi', + 'USER_CONSENT_CANCELED', + details: SmartAuthRequestCanceled(), + ); + + final result = await SmartAuth.instance.getSmsWithUserConsentApi(); + + expect(result.isCanceled, isTrue); + expect(result.hasError, isFalse); + }); + + test('failures are reported as errors', () async { + fail('getSmsWithUserConsentApi', 'FAILED'); + + final result = await SmartAuth.instance.getSmsWithUserConsentApi(); + + expect(result.hasError, isTrue); + expect(result.isCanceled, isFalse); + }); + }); + + group('requestPhoneNumberHint', () { + test('returns the phone number', () async { + reply('requestPhoneNumberHint', '+15551234'); + + final result = await SmartAuth.instance.requestPhoneNumberHint(); + + expect(result.requireData, '+15551234'); + }); + + test('cancellation is reported as canceled', () async { + fail( + 'requestPhoneNumberHint', + 'PHONE_NUMBER_HINT_CANCELED', + details: SmartAuthRequestCanceled(), + ); + + final result = await SmartAuth.instance.requestPhoneNumberHint(); + + expect(result.isCanceled, isTrue); + expect(result.hasError, isFalse); + }); + + test('failures are reported as errors', () async { + fail('requestPhoneNumberHint', 'PHONE_NUMBER_HINT_FAILED'); + + final result = await SmartAuth.instance.requestPhoneNumberHint(); + + expect(result.hasError, isTrue); + expect(result.isCanceled, isFalse); + }); + }); + + // Other platforms have no native side, the calls must not throw there. + group('without a native implementation', () { + test('every call reports an error', () async { + final auth = SmartAuth.instance; + + expect((await auth.getAppSignature()).hasError, isTrue); + expect((await auth.getSmsWithRetrieverApi()).hasError, isTrue); + expect((await auth.getSmsWithUserConsentApi()).hasError, isTrue); + expect((await auth.removeSmsRetrieverApiListener()).hasError, isTrue); + expect((await auth.removeUserConsentApiListener()).hasError, isTrue); + expect((await auth.requestPhoneNumberHint()).hasError, isTrue); + }); + }); +}