Skip to content

Commit c79bba3

Browse files
authored
[in_app_purchase_android] Guard async billing callbacks against duplicate listener responses (#12640)
The Play Billing library can invoke the response listener of a single async call more than once (observed in production via its internal watchdog/timeout path, `zzaf.run → zzan.run`, with the real response also arriving). A pigeon reply may only be submitted once; the second completion throws `IllegalStateException: Reply already submitted` on the main thread and kills the process. `startConnection` already guards against a double `onBillingSetupFinished` with its `alreadyFinished` flag; this PR extends the same protection to the other 9 async methods via a `replyOnce(methodName, callback)` wrapper — an `AtomicBoolean.getAndSet(true)` single-shot around the pigeon callback. The first completion wins; duplicates are dropped with a `Log.d`. Call sites bind the pigeon parameter as `rawCallback` and rebind `callback` to the wrapper, so the method bodies are otherwise unchanged and every completion path (null-client error, null-activity error, listener response, RuntimeException catch) is single-shot. Listener side effects (`updateCachedProducts`) still run on dropped duplicates, so if an error response lands first and the real one second, the product cache still receives real data for a later `launchBillingFlow`. Two JUnit regression tests fire a captured listener twice with distinct results and assert exactly one pigeon completion holding the first result. *Developed with AI assistance; tested and verified by the submitter.* Fixes flutter/flutter#191832 Related: flutter/flutter#103432, flutter/flutter#134967 ## Pre-Review Checklist Note: this PR and #12639 both bump the package to 0.5.3; whichever lands second will be rebased and re-bumped. [^1]: Regular contributors who have demonstrated familiarity with the repository guidelines only need to comment if the PR is not auto-exempted by repo tooling.
1 parent 63bc5cd commit c79bba3

4 files changed

Lines changed: 130 additions & 10 deletions

File tree

‎packages/in_app_purchase/in_app_purchase_android/CHANGELOG.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,9 @@
1+
## 0.5.4
2+
3+
* Fixes a crash (`IllegalStateException: Reply already submitted`) when the
4+
Play Billing library invokes a response listener more than once for a single
5+
call.
6+
17
## 0.5.3+1
28

39
* Updates Robolectric to 4.17 and adds the JVM arguments it requires for unit tests.

‎packages/in_app_purchase/in_app_purchase_android/android/src/main/java/io/flutter/plugins/inapppurchase/MethodCallHandlerImpl.java‎

Lines changed: 50 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@
3939
import java.util.ArrayList;
4040
import java.util.HashMap;
4141
import java.util.List;
42+
import java.util.concurrent.atomic.AtomicBoolean;
4243
import kotlin.Result;
4344
import kotlin.Unit;
4445
import kotlin.jvm.functions.Function1;
@@ -117,7 +118,9 @@ void onDetachedFromActivity() {
117118

118119
@Override
119120
public void showAlternativeBillingOnlyInformationDialog(
120-
@NonNull Function1<? super Result<PlatformBillingResult>, Unit> callback) {
121+
@NonNull Function1<? super Result<PlatformBillingResult>, Unit> rawCallback) {
122+
final Function1<? super Result<PlatformBillingResult>, Unit> callback =
123+
replyOnce("showAlternativeBillingOnlyInformationDialog", rawCallback);
121124
if (billingClient == null) {
122125
ResultUtilsKt.completeWithError(callback, getNullBillingClientError());
123126
return;
@@ -141,7 +144,9 @@ public void showAlternativeBillingOnlyInformationDialog(
141144
public void createAlternativeBillingOnlyReportingDetailsAsync(
142145
@NonNull
143146
Function1<? super Result<PlatformAlternativeBillingOnlyReportingDetailsResponse>, Unit>
144-
callback) {
147+
rawCallback) {
148+
final Function1<? super Result<PlatformAlternativeBillingOnlyReportingDetailsResponse>, Unit>
149+
callback = replyOnce("createAlternativeBillingOnlyReportingDetailsAsync", rawCallback);
145150
if (billingClient == null) {
146151
ResultUtilsKt.completeWithError(callback, getNullBillingClientError());
147152
return;
@@ -161,7 +166,9 @@ public void createAlternativeBillingOnlyReportingDetailsAsync(
161166

162167
@Override
163168
public void isAlternativeBillingOnlyAvailableAsync(
164-
@NonNull Function1<? super Result<PlatformBillingResult>, Unit> callback) {
169+
@NonNull Function1<? super Result<PlatformBillingResult>, Unit> rawCallback) {
170+
final Function1<? super Result<PlatformBillingResult>, Unit> callback =
171+
replyOnce("isAlternativeBillingOnlyAvailableAsync", rawCallback);
165172
if (billingClient == null) {
166173
ResultUtilsKt.completeWithError(callback, getNullBillingClientError());
167174
return;
@@ -179,7 +186,9 @@ public void isAlternativeBillingOnlyAvailableAsync(
179186
public void showInAppMessages(
180187
@NotNull
181188
Function1<? super @NotNull Result<@NotNull PlatformInAppMessageResult>, @NotNull Unit>
182-
callback) {
189+
rawCallback) {
190+
final Function1<? super Result<PlatformInAppMessageResult>, Unit> callback =
191+
replyOnce("showInAppMessages", rawCallback);
183192
if (billingClient == null) {
184193
ResultUtilsKt.completeWithError(callback, getNullBillingClientError());
185194
return;
@@ -204,7 +213,9 @@ public void showInAppMessages(
204213

205214
@Override
206215
public void getBillingConfigAsync(
207-
@NonNull Function1<? super Result<PlatformBillingConfigResponse>, Unit> callback) {
216+
@NonNull Function1<? super Result<PlatformBillingConfigResponse>, Unit> rawCallback) {
217+
final Function1<? super Result<PlatformBillingConfigResponse>, Unit> callback =
218+
replyOnce("getBillingConfigAsync", rawCallback);
208219
if (billingClient == null) {
209220
ResultUtilsKt.completeWithError(callback, getNullBillingClientError());
210221
return;
@@ -243,7 +254,9 @@ public boolean isReady() {
243254
@Override
244255
public void queryProductDetailsAsync(
245256
@NonNull List<PlatformQueryProduct> products,
246-
@NonNull Function1<? super Result<PlatformProductDetailsResponse>, Unit> callback) {
257+
@NonNull Function1<? super Result<PlatformProductDetailsResponse>, Unit> rawCallback) {
258+
final Function1<? super Result<PlatformProductDetailsResponse>, Unit> callback =
259+
replyOnce("queryProductDetailsAsync", rawCallback);
247260
if (billingClient == null) {
248261
ResultUtilsKt.completeWithError(callback, getNullBillingClientError());
249262
return;
@@ -384,7 +397,9 @@ public void queryProductDetailsAsync(
384397
@Override
385398
public void consumeAsync(
386399
@NonNull String purchaseToken,
387-
@NonNull Function1<? super Result<PlatformBillingResult>, Unit> callback) {
400+
@NonNull Function1<? super Result<PlatformBillingResult>, Unit> rawCallback) {
401+
final Function1<? super Result<PlatformBillingResult>, Unit> callback =
402+
replyOnce("consumeAsync", rawCallback);
388403
if (billingClient == null) {
389404
ResultUtilsKt.completeWithError(callback, getNullBillingClientError());
390405
return;
@@ -408,7 +423,9 @@ public void consumeAsync(
408423
@Override
409424
public void queryPurchasesAsync(
410425
@NonNull PlatformProductType productType,
411-
@NonNull Function1<? super Result<PlatformPurchasesResponse>, Unit> callback) {
426+
@NonNull Function1<? super Result<PlatformPurchasesResponse>, Unit> rawCallback) {
427+
final Function1<? super Result<PlatformPurchasesResponse>, Unit> callback =
428+
replyOnce("queryPurchasesAsync", rawCallback);
412429
if (billingClient == null) {
413430
ResultUtilsKt.completeWithError(callback, getNullBillingClientError());
414431
return;
@@ -487,7 +504,9 @@ public void onBillingServiceDisconnected() {
487504
@Override
488505
public void acknowledgePurchase(
489506
@NonNull String purchaseToken,
490-
@NonNull Function1<? super Result<PlatformBillingResult>, Unit> callback) {
507+
@NonNull Function1<? super Result<PlatformBillingResult>, Unit> rawCallback) {
508+
final Function1<? super Result<PlatformBillingResult>, Unit> callback =
509+
replyOnce("acknowledgePurchase", rawCallback);
491510
if (billingClient == null) {
492511
ResultUtilsKt.completeWithError(callback, getNullBillingClientError());
493512
return;
@@ -514,6 +533,28 @@ protected void updateCachedProducts(@Nullable List<ProductDetails> productDetail
514533
}
515534
}
516535

536+
// The Play Billing library can invoke a response listener more than once for
537+
// a single call (e.g. via its internal watchdog/timeout path). The pigeon
538+
// reply may only be submitted once; a second completion throws
539+
// "IllegalStateException: Reply already submitted" on the main thread and
540+
// crashes the app (https://github.com/flutter/flutter/issues/103432).
541+
// startConnection already guards this with its own alreadyFinished flag;
542+
// this wraps the other async methods' callbacks so the first completion wins
543+
// and duplicates are dropped. Call sites bind the pigeon parameter as
544+
// rawCallback and rebind `callback` to this wrapper, keeping the method
545+
// bodies otherwise unchanged.
546+
private static <T> @NonNull Function1<? super Result<T>, Unit> replyOnce(
547+
@NonNull String methodName, @NonNull Function1<? super Result<T>, Unit> callback) {
548+
final AtomicBoolean replied = new AtomicBoolean(false);
549+
return result -> {
550+
if (replied.getAndSet(true)) {
551+
Log.d(TAG, "Ignoring duplicate billing response for " + methodName + ".");
552+
return Unit.INSTANCE;
553+
}
554+
return callback.invoke(result);
555+
};
556+
}
557+
517558
private @NonNull FlutterError getNullBillingClientError() {
518559
return new FlutterError("UNAVAILABLE", "BillingClient is unset. Try reconnecting.", null);
519560
}

‎packages/in_app_purchase/in_app_purchase_android/android/src/test/java/io/flutter/plugins/inapppurchase/MethodCallHandlerTest.java‎

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -635,6 +635,48 @@ public void queryProductDetailsAsync_clientDisconnected() {
635635
assertTrue(Objects.requireNonNull(flutterError.getMessage()).contains("BillingClient"));
636636
}
637637

638+
// Regression test for https://github.com/flutter/flutter/issues/103432: the
639+
// Play Billing library can invoke a response listener twice for one call
640+
// (its internal watchdog/timeout path); the second pigeon reply must be
641+
// dropped instead of throwing "Reply already submitted".
642+
@Test
643+
public void queryProductDetailsAsync_duplicateListenerResponseIsIgnored() {
644+
establishConnectedBillingClient();
645+
final List<PlatformQueryProduct> productList =
646+
buildProductList(asList("id1", "id2"), PlatformProductType.INAPP);
647+
648+
methodChannelHandler.queryProductDetailsAsync(
649+
productList, platformProductDetailsResult.asCallback());
650+
651+
ArgumentCaptor<ProductDetailsResponseListener> listenerCaptor =
652+
ArgumentCaptor.forClass(ProductDetailsResponseListener.class);
653+
verify(mockBillingClient).queryProductDetailsAsync(any(), listenerCaptor.capture());
654+
655+
List<ProductDetails> firstProducts = singletonList(buildProductDetails("foo"));
656+
BillingResult firstResult = buildBillingResult();
657+
QueryProductDetailsResult firstDetailsResult = mock(QueryProductDetailsResult.class);
658+
when(firstDetailsResult.getProductDetailsList()).thenReturn(firstProducts);
659+
when(firstDetailsResult.getUnfetchedProductList())
660+
.thenReturn(java.util.Collections.emptyList());
661+
662+
BillingResult secondResult = buildBillingResult(200);
663+
QueryProductDetailsResult secondDetailsResult = mock(QueryProductDetailsResult.class);
664+
when(secondDetailsResult.getProductDetailsList())
665+
.thenReturn(singletonList(buildProductDetails("bar")));
666+
when(secondDetailsResult.getUnfetchedProductList())
667+
.thenReturn(java.util.Collections.emptyList());
668+
669+
listenerCaptor.getValue().onProductDetailsResponse(firstResult, firstDetailsResult);
670+
// The second (watchdog) invocation of the SAME listener must not reach the
671+
// pigeon callback. (updateCachedProducts still runs, by design.)
672+
listenerCaptor.getValue().onProductDetailsResponse(secondResult, secondDetailsResult);
673+
674+
assertEquals(1, platformProductDetailsResult.callCount);
675+
PlatformProductDetailsResponse resultData = platformProductDetailsResult.result.getOrNull();
676+
assertResultsMatch(resultData.getBillingResult(), firstResult);
677+
assertDetailListsMatch(firstProducts, resultData.getProductDetails());
678+
}
679+
638680
// Test launchBillingFlow not crash if `accountId` is `null`
639681
// Ideally, we should check if the `accountId` is null in the parameter; however,
640682
// since PBL 3.0, the `accountId` variable is not public.
@@ -1021,6 +1063,32 @@ public void acknowledgePurchase() {
10211063
assertResultsMatch(platformBillingResult.result.getOrNull(), billingResult);
10221064
}
10231065

1066+
// Same duplicate-listener-response scenario as
1067+
// queryProductDetailsAsync_duplicateListenerResponseIsIgnored, for a
1068+
// listener that carries only a BillingResult.
1069+
@Test
1070+
public void acknowledgePurchase_duplicateListenerResponseIsIgnored() {
1071+
establishConnectedBillingClient();
1072+
final String purchaseToken = "mockToken";
1073+
ArgumentCaptor<AcknowledgePurchaseResponseListener> listenerCaptor =
1074+
ArgumentCaptor.forClass(AcknowledgePurchaseResponseListener.class);
1075+
1076+
methodChannelHandler.acknowledgePurchase(purchaseToken, platformBillingResult.asCallback());
1077+
1078+
AcknowledgePurchaseParams params =
1079+
AcknowledgePurchaseParams.newBuilder().setPurchaseToken(purchaseToken).build();
1080+
1081+
verify(mockBillingClient).acknowledgePurchase(refEq(params), listenerCaptor.capture());
1082+
1083+
BillingResult firstResult = buildBillingResult();
1084+
BillingResult secondResult = buildBillingResult(200);
1085+
listenerCaptor.getValue().onAcknowledgePurchaseResponse(firstResult);
1086+
listenerCaptor.getValue().onAcknowledgePurchaseResponse(secondResult);
1087+
1088+
assertEquals(1, platformBillingResult.callCount);
1089+
assertResultsMatch(platformBillingResult.result.getOrNull(), firstResult);
1090+
}
1091+
10241092
@Test
10251093
public void endConnection_if_activity_detached() {
10261094
InAppPurchasePlugin plugin = new InAppPurchasePlugin();
@@ -1226,11 +1294,16 @@ private void assertDetailsMatch(ProductDetails expected, PlatformProductDetails
12261294
private static class TestResult<T> implements Function1<ResultCompat<T>, Unit> {
12271295
ResultCompat<T> result;
12281296
boolean called = false;
1297+
// Lets the duplicate-listener-response regression tests assert that the
1298+
// pigeon callback completed exactly once (result alone only stores the
1299+
// last value).
1300+
int callCount = 0;
12291301

12301302
@Override
12311303
public Unit invoke(ResultCompat<T> reply) {
12321304
this.result = reply;
12331305
this.called = true;
1306+
this.callCount++;
12341307
return Unit.INSTANCE;
12351308
}
12361309

‎packages/in_app_purchase/in_app_purchase_android/pubspec.yaml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ description: An implementation for the Android platform of the Flutter `in_app_p
33
repository: https://github.com/flutter/packages/tree/main/packages/in_app_purchase/in_app_purchase_android
44
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+in_app_purchase%22
55

6-
version: 0.5.3+1
6+
version: 0.5.4
77

88
environment:
99
sdk: ^3.12.0

0 commit comments

Comments
 (0)