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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 must call push notification completion handlers themselves when integrating `IterableAppIntegration` with Iterable-iOS-SDK 6.7.5 (native SDK may omit the 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.

Expand Down
27 changes: 27 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 (Iterable-iOS-SDK 6.7.5):** If the native SDK is not initialized when a push arrives, `IterableAppIntegration` may not call your completion handlers. Pass **`nil`** for the integration method's completion-handler parameter (as Iterable's native iOS SDK docs describe for passing a nil value) and call the system completion handler yourself. **Tradeoff:** your app typically invokes the fetch/response completion handler immediately after forwarding the notification (for example `completionHandler(.noData)`), so iOS may grant less background execution time for Iterable's own work than when the native SDK holds the handler and calls it when finished.

```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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Original file line number Diff line number Diff line change
@@ -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<Throwable> 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<String> result,
AtomicReference<Throwable> 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<String> result = new AtomicReference<>();
AtomicReference<Throwable> 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<String> result = new AtomicReference<>();
AtomicReference<Throwable> 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<String> result = new AtomicReference<>();
AtomicReference<Throwable> 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());
}
}
12 changes: 10 additions & 2 deletions example/ios/ReactNativeSdkExample/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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()
}
}
4 changes: 4 additions & 0 deletions ios/RNIterableAPI/ReactIterableAPI.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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?)
Expand Down
106 changes: 99 additions & 7 deletions src/core/classes/Iterable.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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();
});
});
});
});
Expand Down
Loading
Loading