diff --git a/CHANGELOG.md b/CHANGELOG.md index 0ca6e4516..8fa346082 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ ### Fixes +- Fixed stale JWT handoff when `authHandler` fails, times out, or returns an unexpected value. The JS bridge now calls `passAlongAuthToken(null)` on rejection, unexpected results, and synchronous throws, and clears zombie invocations from the pending queue. Android and iOS native auth waits discard any token (and, on iOS, any pending semaphore signal) from a prior request before starting a new one, so a timed-out wait no longer returns a previous token. +- Documented that iOS apps should pass `nil` to `IterableAppIntegration` and call push notification completion handlers themselves (safe whether or not the SDK is initialized; through at least Iterable-iOS-SDK 6.7.5 the integration does not invoke a passed-in handler when not initialized). See the example app `AppDelegate` and README. - Fixed `Iterable.trackPushOpenWithCampaignId` on Android so the `appAlreadyRunning` argument is forwarded to the native SDK instead of always being sent as `false`. - `Iterable.inAppManager.showMessage` now rejects on iOS when the message id is empty or no longer in the native queue, matching Android. Previously the promise never settled. diff --git a/README.md b/README.md index 3a58c6796..efb82954f 100644 --- a/README.md +++ b/README.md @@ -56,6 +56,33 @@ Iterable's React Native SDK relies on: use_frameworks! :linkage => :dynamic ``` - **Xcode 27:** `run-ios` needs `@react-native-community/cli` **20.2.0+** so it opens Device Hub (`DeviceHub.app`) instead of `Simulator.app`. `xcode-select` must point at the Xcode you are using when more than one version is installed. Xcode 27 also refuses CocoaPods resource-bundle targets below iOS **15.0** (this SDK's `IterableSDKResources` bundle still inherits **12.0** from Iterable-iOS-SDK, including **6.7.5** pinned by RN **3.2.0**). Lift generated Pods targets to **15.1** in the app `Podfile` `post_install` — see this repo's `example/ios/Podfile`. That is a **host** workaround until Iterable's iOS SDK publishes a ≥ 15.1 minimum and this SDK depends on it. It does not change the published Iterable iOS support range. + - **Push completion handlers (through at least Iterable-iOS-SDK 6.7.5):** Pass **`nil`** for `IterableAppIntegration`'s completion-handler parameter (as Iterable's native iOS SDK docs describe for passing a nil value) and call the system completion handler yourself—for example `completionHandler(.noData)` on the fetch path and `completionHandler()` on the notification-response path. If the native SDK is not initialized, `IterableAppIntegration` does not invoke a handler you pass in; calling the system handler yourself satisfies iOS either way. When the SDK is initialized, the native integration completes any handler you pass on the same synchronous timing as calling it yourself right after forwarding with `nil`, so this pattern is safe whether or not the SDK is initialized. + + ```swift + func application( + _ application: UIApplication, + didReceiveRemoteNotification userInfo: [AnyHashable: Any], + fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void + ) { + IterableAppIntegration.application( + application, + didReceiveRemoteNotification: userInfo, + fetchCompletionHandler: nil) + completionHandler(.noData) + } + + func userNotificationCenter( + _ center: UNUserNotificationCenter, + didReceive response: UNNotificationResponse, + withCompletionHandler completionHandler: @escaping () -> Void + ) { + IterableAppIntegration.userNotificationCenter( + center, + didReceive: response, + withCompletionHandler: nil) + completionHandler() + } + ``` - **Android** - [`minSdkVersion` 21+, `compileSdkVersion` 31+](https://medium.com/androiddevelopers/picking-your-compilesdkversion-minsdkversion-targetsdkversion-a098a0341ebd) diff --git a/android/src/main/java/com/iterable/reactnative/RNIterableAPIModuleImpl.java b/android/src/main/java/com/iterable/reactnative/RNIterableAPIModuleImpl.java index 2e8c32b23..52f93f449 100644 --- a/android/src/main/java/com/iterable/reactnative/RNIterableAPIModuleImpl.java +++ b/android/src/main/java/com/iterable/reactnative/RNIterableAPIModuleImpl.java @@ -702,6 +702,7 @@ public boolean handleIterableURL(@NonNull Uri uri, @NonNull IterableActionContex @Override public String onAuthTokenRequested() { IterableLogger.printInfo(); + passedAuthToken = null; try { authHandlerCallbackLatch = new CountDownLatch(1); diff --git a/android/src/test/java/com/iterable/iterableapi/RNIterableAPIModuleImplAuthTokenTest.java b/android/src/test/java/com/iterable/iterableapi/RNIterableAPIModuleImplAuthTokenTest.java new file mode 100644 index 000000000..6d5c0e3f7 --- /dev/null +++ b/android/src/test/java/com/iterable/iterableapi/RNIterableAPIModuleImplAuthTokenTest.java @@ -0,0 +1,153 @@ +package com.iterable.iterableapi; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.fail; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import com.facebook.react.bridge.ReactApplicationContext; +import com.facebook.react.modules.core.DeviceEventManagerModule; +import com.iterable.reactnative.RNIterableAPIModuleImpl; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.RobolectricTestRunner; +import org.robolectric.annotation.Config; + +import java.lang.reflect.Field; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.atomic.AtomicReference; + +@RunWith(RobolectricTestRunner.class) +@Config(sdk = 34) +public class RNIterableAPIModuleImplAuthTokenTest { + + private RNIterableAPIModuleImpl module; + + @Before + public void setUp() { + ReactApplicationContext reactContext = mock(ReactApplicationContext.class); + DeviceEventManagerModule.RCTDeviceEventEmitter emitter = + mock(DeviceEventManagerModule.RCTDeviceEventEmitter.class); + when(reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)) + .thenReturn(emitter); + module = new RNIterableAPIModuleImpl(reactContext); + } + + private static void waitUntilAuthLatchArmed( + RNIterableAPIModuleImpl module, long timeoutMs) throws Exception { + Field latchField = + RNIterableAPIModuleImpl.class.getDeclaredField("authHandlerCallbackLatch"); + latchField.setAccessible(true); + long deadline = System.currentTimeMillis() + timeoutMs; + while (latchField.get(module) == null && System.currentTimeMillis() < deadline) { + Thread.yield(); + } + assertNotNull( + "authHandlerCallbackLatch should be armed after onAuthTokenRequested starts", + latchField.get(module)); + } + + private static void assertAuthRequestThreadFinished( + Thread requestThread, + CountDownLatch requestCompleted, + AtomicReference requestError, + long joinTimeoutMs) + throws InterruptedException { + requestThread.join(joinTimeoutMs); + Throwable thrown = requestError.get(); + if (thrown != null) { + AssertionError failure = + new AssertionError( + "onAuthTokenRequested threw instead of returning normally", thrown); + throw failure; + } + if (requestThread.isAlive()) { + fail( + "onAuthTokenRequested thread still alive after " + + joinTimeoutMs + + " ms; join did not prove the call returned"); + } + if (requestCompleted.getCount() > 0) { + fail( + "onAuthTokenRequested did not complete a normal return before the join window " + + "ended (completion latch not released)"); + } + } + + private static Thread startAuthRequestOnNewThread( + RNIterableAPIModuleImpl module, + AtomicReference result, + AtomicReference requestError, + CountDownLatch requestCompleted) { + Thread requestThread = + new Thread( + () -> { + try { + result.set(module.onAuthTokenRequested()); + requestCompleted.countDown(); + } catch (Throwable t) { + requestError.set(t); + } + }); + requestThread.start(); + return requestThread; + } + + @Test + public void onAuthTokenRequested_clearsStaleTokenBeforeWaiting() throws Exception { + module.passAlongAuthToken("stale-token"); + + AtomicReference result = new AtomicReference<>(); + AtomicReference requestError = new AtomicReference<>(); + CountDownLatch requestCompleted = new CountDownLatch(1); + Thread requestThread = + startAuthRequestOnNewThread(module, result, requestError, requestCompleted); + waitUntilAuthLatchArmed(module, 5000); + module.passAlongAuthToken("fresh-token"); + assertAuthRequestThreadFinished(requestThread, requestCompleted, requestError, 5000); + + assertEquals("fresh-token", result.get()); + } + + /** + * Criterion 1: when the production 30 s {@code CountDownLatch.await} expires with no + * JS reply, {@code onAuthTokenRequested} returns null — not the stale token stored + * before the request (cleared at request start). + */ + @Test + public void onAuthTokenRequested_returnsNullAfterTimeoutWithoutReply() throws Exception { + module.passAlongAuthToken("stale-token"); + + AtomicReference result = new AtomicReference<>(); + AtomicReference requestError = new AtomicReference<>(); + CountDownLatch requestCompleted = new CountDownLatch(1); + Thread requestThread = + startAuthRequestOnNewThread(module, result, requestError, requestCompleted); + assertAuthRequestThreadFinished(requestThread, requestCompleted, requestError, 35_000); + + assertNull( + "onAuthTokenRequested must return null after a timed-out wait without a reply", + result.get()); + } + + @Test + public void onAuthTokenRequested_waitsForOwnReplyAfterLateTokenFromPriorTimeout() + throws Exception { + module.passAlongAuthToken("late-from-timed-out-request"); + + AtomicReference result = new AtomicReference<>(); + AtomicReference requestError = new AtomicReference<>(); + CountDownLatch requestCompleted = new CountDownLatch(1); + Thread requestThread = + startAuthRequestOnNewThread(module, result, requestError, requestCompleted); + waitUntilAuthLatchArmed(module, 5000); + module.passAlongAuthToken("current-request-token"); + assertAuthRequestThreadFinished(requestThread, requestCompleted, requestError, 5000); + + assertEquals("current-request-token", result.get()); + } +} \ No newline at end of file diff --git a/example/ios/ReactNativeSdkExample/AppDelegate.swift b/example/ios/ReactNativeSdkExample/AppDelegate.swift index 677a4fa9d..60f62d885 100644 --- a/example/ios/ReactNativeSdkExample/AppDelegate.swift +++ b/example/ios/ReactNativeSdkExample/AppDelegate.swift @@ -59,7 +59,11 @@ class AppDelegate: UIResponder, UIApplicationDelegate { func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { ITBInfo() - IterableAppIntegration.application(application, didReceiveRemoteNotification: userInfo, fetchCompletionHandler: completionHandler) + IterableAppIntegration.application( + application, + didReceiveRemoteNotification: userInfo, + fetchCompletionHandler: nil) + completionHandler(.noData) } func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool { @@ -124,6 +128,10 @@ extension AppDelegate: UNUserNotificationCenterDelegate { // The method will be called on the delegate when the user responded to the notification by opening the application, dismissing the notification or choosing a UNNotificationAction. The delegate must be set before the application returns from applicationDidFinishLaunching:. public func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { - IterableAppIntegration.userNotificationCenter(center, didReceive: response, withCompletionHandler: completionHandler) + IterableAppIntegration.userNotificationCenter( + center, + didReceive: response, + withCompletionHandler: nil) + completionHandler() } } diff --git a/ios/RNIterableAPI/ReactIterableAPI.swift b/ios/RNIterableAPI/ReactIterableAPI.swift index 3a9185774..9656a9fdb 100644 --- a/ios/RNIterableAPI/ReactIterableAPI.swift +++ b/ios/RNIterableAPI/ReactIterableAPI.swift @@ -889,6 +889,10 @@ extension ReactIterableAPI: IterableAuthDelegate { public func onAuthTokenRequested(completion: @escaping AuthTokenRetrievalHandler) { ITBInfo() DispatchQueue.global(qos: .userInitiated).async { + self.passedAuthToken = nil + while self.authHandlerSemaphore.wait(timeout: .now()) == .success { + // Drain stale signals from a prior timed-out auth request. + } self.delegate?.sendEvent( withName: EventName.handleAuthCalled.rawValue, body: nil as Any?) diff --git a/src/core/classes/Iterable.test.ts b/src/core/classes/Iterable.test.ts index 2e2cf5f16..343b7b2aa 100644 --- a/src/core/classes/Iterable.test.ts +++ b/src/core/classes/Iterable.test.ts @@ -1164,7 +1164,7 @@ describe('Iterable', () => { }); }); - it('should call authHandler when handleAuthCalled event is emitted and returns an unexpected response', () => { + it('should call authHandler when handleAuthCalled event is emitted and returns an unexpected response', async () => { // sets up event emitter const nativeEmitter = new NativeEventEmitter(); nativeEmitter.removeAllListeners(IterableEventName.handleAuthCalled); @@ -1176,32 +1176,124 @@ describe('Iterable', () => { | string | IterableAuthResponse); }); + const logSpy = jest.spyOn(IterableLogger, 'log'); // initialize Iterable object Iterable.initialize('apiKey', config); // GIVEN auth handler returns unexpected response // WHEN handleAuthCalled event is emitted nativeEmitter.emit(IterableEventName.handleAuthCalled); - // THEN error is logged (we can't easily test console.log, but we can verify no crash) - expect(MockRNIterableAPI.passAlongAuthToken).not.toBeCalled(); + // THEN passAlongAuthToken(null) notifies native and the invocation is removed + await new Promise((resolve) => setTimeout(resolve, 0)); + expect(MockRNIterableAPI.passAlongAuthToken).toHaveBeenCalledTimes(1); + expect(MockRNIterableAPI.passAlongAuthToken).toHaveBeenCalledWith(null); + const unexpectedLog = logSpy.mock.calls.find( + (args) => + typeof args[0] === 'string' && + args[0].includes('Unexpected promise returned') + ); + expect(unexpectedLog).toBeDefined(); + logSpy.mockRestore(); }); - it('should call authHandler when handleAuthCalled event is emitted and rejects the promise', () => { + it('should call authHandler when handleAuthCalled event is emitted and rejects the promise', async () => { // sets up event emitter const nativeEmitter = new NativeEventEmitter(); nativeEmitter.removeAllListeners(IterableEventName.handleAuthCalled); // sets up config file and authHandler function const config = new IterableConfig(); config.logReactNativeSdkCalls = false; + const authError = new Error('Auth failed'); config.authHandler = jest.fn(() => { - return Promise.reject(new Error('Auth failed')); + return Promise.reject(authError); }); + const logSpy = jest.spyOn(IterableLogger, 'log'); // initialize Iterable object Iterable.initialize('apiKey', config); // GIVEN auth handler rejects promise // WHEN handleAuthCalled event is emitted nativeEmitter.emit(IterableEventName.handleAuthCalled); - // THEN error is logged (we can't easily test console.log, but we can verify no crash) - expect(MockRNIterableAPI.passAlongAuthToken).not.toBeCalled(); + // THEN passAlongAuthToken(null) notifies native and the invocation is removed + await new Promise((resolve) => setTimeout(resolve, 0)); + expect(MockRNIterableAPI.passAlongAuthToken).toHaveBeenCalledTimes(1); + expect(MockRNIterableAPI.passAlongAuthToken).toHaveBeenCalledWith(null); + expect(logSpy).toHaveBeenCalledWith(authError); + logSpy.mockRestore(); + }); + + it('should pass null to native when authHandler throws synchronously', async () => { + const nativeEmitter = new NativeEventEmitter(); + nativeEmitter.removeAllListeners(IterableEventName.handleAuthCalled); + nativeEmitter.removeAllListeners( + IterableEventName.handleAuthSuccessCalled + ); + + const config = new IterableConfig(); + config.logReactNativeSdkCalls = false; + + const successCallback2 = jest.fn(); + const authResponse2 = new IterableAuthResponse(); + authResponse2.authToken = 'after-sync-throw'; + authResponse2.successCallback = successCallback2; + + let callCount = 0; + config.authHandler = jest.fn(() => { + callCount += 1; + if (callCount === 1) { + throw new Error('sync auth failure'); + } + return Promise.resolve(authResponse2); + }); + + Iterable.initialize('apiKey', config); + nativeEmitter.emit(IterableEventName.handleAuthCalled); + expect(MockRNIterableAPI.passAlongAuthToken).toBeCalledWith(null); + + nativeEmitter.emit(IterableEventName.handleAuthCalled); + await new Promise((resolve) => setTimeout(resolve, 0)); + nativeEmitter.emit(IterableEventName.handleAuthSuccessCalled); + + return TestHelper.delayed(50, () => { + expect(successCallback2).toBeCalled(); + }); + }); + + it('should route the next native success to the next invocation after unexpected auth result', async () => { + const nativeEmitter = new NativeEventEmitter(); + nativeEmitter.removeAllListeners(IterableEventName.handleAuthCalled); + nativeEmitter.removeAllListeners( + IterableEventName.handleAuthSuccessCalled + ); + + const config = new IterableConfig(); + config.logReactNativeSdkCalls = false; + + const successCallback2 = jest.fn(); + const authResponse2 = new IterableAuthResponse(); + authResponse2.authToken = 'recovery-token'; + authResponse2.successCallback = successCallback2; + + let callCount = 0; + config.authHandler = jest.fn(() => { + callCount += 1; + if (callCount === 1) { + return Promise.resolve({ bad: true } as unknown as IterableAuthResponse); + } + return Promise.resolve(authResponse2); + }); + + Iterable.initialize('apiKey', config); + + nativeEmitter.emit(IterableEventName.handleAuthCalled); + await new Promise((resolve) => setTimeout(resolve, 0)); + expect(MockRNIterableAPI.passAlongAuthToken).toHaveBeenCalledWith(null); + + nativeEmitter.emit(IterableEventName.handleAuthCalled); + await new Promise((resolve) => setTimeout(resolve, 0)); + nativeEmitter.emit(IterableEventName.handleAuthSuccessCalled); + + return TestHelper.delayed(50, () => { + expect(successCallback2).toBeCalled(); + }); }); }); }); diff --git a/src/core/classes/Iterable.ts b/src/core/classes/Iterable.ts index 5d36fa597..9e746cb53 100644 --- a/src/core/classes/Iterable.ts +++ b/src/core/classes/Iterable.ts @@ -1220,7 +1220,18 @@ export class Iterable { // MOB-10423: Check if we can use chain operator (?.) here instead // Asks frontend of the client/app to pass authToken - Iterable.savedConfig.authHandler!() + let authHandlerPromise: ReturnType< + NonNullable + >; + try { + authHandlerPromise = Iterable.savedConfig.authHandler!(); + } catch (e) { + IterableLogger?.log(e); + Iterable.authManager.passAlongAuthToken(null); + removeInvocation(); + return; + } + authHandlerPromise .then((promiseResult) => { // Promise result can be either just String OR of type AuthResponse. // If type AuthResponse, authToken will be parsed looking for @@ -1300,11 +1311,13 @@ export class Iterable { IterableLogger?.log( 'Unexpected promise returned. Auth token expects promise of String, null, undefined, or AuthResponse type.' ); + Iterable.authManager.passAlongAuthToken(null); removeInvocation(); } }) .catch((e) => { IterableLogger?.log(e); + Iterable.authManager.passAlongAuthToken(null); removeInvocation(); }); });