From 4e060a14c758fe00b70dd017b334ebfbd69572fe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Ferr=C3=A3o?= Date: Mon, 23 Nov 2026 18:06:05 +0000 Subject: [PATCH 1/2] fix(SDK-876): prevent stale JWT on auth handler failures Clear stale tokens on Android/iOS auth waits, notify native when JS authHandler fails, and document iOS push completion handler duty. --- CHANGELOG.md | 2 + README.md | 27 +++++ .../reactnative/RNIterableAPIModuleImpl.java | 1 + .../RNIterableAPIModuleImplAuthTokenTest.java | 111 ++++++++++++++++++ .../ReactNativeSdkExample/AppDelegate.swift | 12 +- ios/RNIterableAPI/ReactIterableAPI.swift | 4 + src/core/classes/Iterable.test.ts | 106 +++++++++++++++-- src/core/classes/Iterable.ts | 15 ++- 8 files changed, 268 insertions(+), 10 deletions(-) create mode 100644 android/src/test/java/com/iterable/iterableapi/RNIterableAPIModuleImplAuthTokenTest.java diff --git a/CHANGELOG.md b/CHANGELOG.md index 0ca6e4516..ff000158a 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 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. diff --git a/README.md b/README.md index 3a58c6796..8df883e06 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 (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) 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..433d24075 --- /dev/null +++ b/android/src/test/java/com/iterable/iterableapi/RNIterableAPIModuleImplAuthTokenTest.java @@ -0,0 +1,111 @@ +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.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.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)); + } + + @Test + public void onAuthTokenRequested_clearsStaleTokenBeforeWaiting() throws Exception { + module.passAlongAuthToken("stale-token"); + + AtomicReference result = new AtomicReference<>(); + Thread requestThread = new Thread(() -> result.set(module.onAuthTokenRequested())); + requestThread.start(); + waitUntilAuthLatchArmed(module, 5000); + module.passAlongAuthToken("fresh-token"); + requestThread.join(5000); + + assertEquals("fresh-token", result.get()); + } + + @Test + public void onAuthTokenRequested_returnsNullAfterTimeoutWithoutReply() throws Exception { + module.passAlongAuthToken("stale-token"); + + AtomicReference result = new AtomicReference<>(); + Thread requestThread = new Thread(() -> result.set(module.onAuthTokenRequested())); + requestThread.start(); + requestThread.join(35_000); + + assertNull(result.get()); + } + + /** + * Criterion 3: a late JS reply after a prior timeout must not satisfy the next + * request when that request receives no new reply. Without clearing + * passedAuthToken at request start, this returns the stale late token after the + * wait expires instead of null. + */ + @Test + public void onAuthTokenRequested_doesNotReturnLateTokenAfterPriorTimeoutWhenUnanswered() + throws Exception { + module.passAlongAuthToken("late-from-timed-out-request"); + + AtomicReference result = new AtomicReference<>(); + Thread requestThread = new Thread(() -> result.set(module.onAuthTokenRequested())); + requestThread.start(); + requestThread.join(35_000); + + assertNull(result.get()); + } + + @Test + public void onAuthTokenRequested_waitsForOwnReplyAfterLateTokenFromPriorTimeout() + throws Exception { + module.passAlongAuthToken("late-from-timed-out-request"); + + AtomicReference result = new AtomicReference<>(); + Thread requestThread = new Thread(() -> result.set(module.onAuthTokenRequested())); + requestThread.start(); + waitUntilAuthLatchArmed(module, 5000); + module.passAlongAuthToken("current-request-token"); + requestThread.join(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(); }); }); From f30c735aaf1b180afff523e42f89aa5bd79196a2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Ferr=C3=A3o?= Date: Mon, 23 Nov 2026 18:32:18 +0000 Subject: [PATCH 2/2] test(SDK-876): harden Android auth token tests The timeout case drives the real 30 s await expiry and rejects the test if onAuthTokenRequested throws or does not return normally before asserting null. Reply-path tests synchronize on the auth latch instead of sleeping. --- .../RNIterableAPIModuleImplAuthTokenTest.java | 106 ++++++++++++------ 1 file changed, 74 insertions(+), 32 deletions(-) diff --git a/android/src/test/java/com/iterable/iterableapi/RNIterableAPIModuleImplAuthTokenTest.java b/android/src/test/java/com/iterable/iterableapi/RNIterableAPIModuleImplAuthTokenTest.java index 433d24075..6d5c0e3f7 100644 --- a/android/src/test/java/com/iterable/iterableapi/RNIterableAPIModuleImplAuthTokenTest.java +++ b/android/src/test/java/com/iterable/iterableapi/RNIterableAPIModuleImplAuthTokenTest.java @@ -3,6 +3,7 @@ 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; @@ -17,6 +18,7 @@ import org.robolectric.annotation.Config; import java.lang.reflect.Field; +import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicReference; @RunWith(RobolectricTestRunner.class) @@ -35,8 +37,8 @@ public void setUp() { module = new RNIterableAPIModuleImpl(reactContext); } - private static void waitUntilAuthLatchArmed( - RNIterableAPIModuleImpl module, long timeoutMs) throws Exception { + private static void waitUntilAuthLatchArmed( + RNIterableAPIModuleImpl module, long timeoutMs) throws Exception { Field latchField = RNIterableAPIModuleImpl.class.getDeclaredField("authHandlerCallbackLatch"); latchField.setAccessible(true); @@ -49,49 +51,87 @@ private static void waitUntilAuthLatchArmed( latchField.get(module)); } - @Test - public void onAuthTokenRequested_clearsStaleTokenBeforeWaiting() throws Exception { - module.passAlongAuthToken("stale-token"); + 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)"); + } + } - AtomicReference result = new AtomicReference<>(); - Thread requestThread = new Thread(() -> result.set(module.onAuthTokenRequested())); + 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(); - waitUntilAuthLatchArmed(module, 5000); - module.passAlongAuthToken("fresh-token"); - requestThread.join(5000); - - assertEquals("fresh-token", result.get()); + return requestThread; } @Test - public void onAuthTokenRequested_returnsNullAfterTimeoutWithoutReply() throws Exception { + public void onAuthTokenRequested_clearsStaleTokenBeforeWaiting() throws Exception { module.passAlongAuthToken("stale-token"); AtomicReference result = new AtomicReference<>(); - Thread requestThread = new Thread(() -> result.set(module.onAuthTokenRequested())); - requestThread.start(); - requestThread.join(35_000); + 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); - assertNull(result.get()); + assertEquals("fresh-token", result.get()); } /** - * Criterion 3: a late JS reply after a prior timeout must not satisfy the next - * request when that request receives no new reply. Without clearing - * passedAuthToken at request start, this returns the stale late token after the - * wait expires instead of null. + * 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_doesNotReturnLateTokenAfterPriorTimeoutWhenUnanswered() - throws Exception { - module.passAlongAuthToken("late-from-timed-out-request"); + public void onAuthTokenRequested_returnsNullAfterTimeoutWithoutReply() throws Exception { + module.passAlongAuthToken("stale-token"); AtomicReference result = new AtomicReference<>(); - Thread requestThread = new Thread(() -> result.set(module.onAuthTokenRequested())); - requestThread.start(); - requestThread.join(35_000); - - assertNull(result.get()); + 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 @@ -100,11 +140,13 @@ public void onAuthTokenRequested_waitsForOwnReplyAfterLateTokenFromPriorTimeout( module.passAlongAuthToken("late-from-timed-out-request"); AtomicReference result = new AtomicReference<>(); - Thread requestThread = new Thread(() -> result.set(module.onAuthTokenRequested())); - requestThread.start(); + AtomicReference requestError = new AtomicReference<>(); + CountDownLatch requestCompleted = new CountDownLatch(1); + Thread requestThread = + startAuthRequestOnNewThread(module, result, requestError, requestCompleted); waitUntilAuthLatchArmed(module, 5000); module.passAlongAuthToken("current-request-token"); - requestThread.join(5000); + assertAuthRequestThreadFinished(requestThread, requestCompleted, requestError, 5000); assertEquals("current-request-token", result.get()); }