diff --git a/iOS_SDK/OneSignalSDK/OneSignalCoreMocks/OneSignalCoreMocks.swift b/iOS_SDK/OneSignalSDK/OneSignalCoreMocks/OneSignalCoreMocks.swift index a05160c99a..050786df19 100644 --- a/iOS_SDK/OneSignalSDK/OneSignalCoreMocks/OneSignalCoreMocks.swift +++ b/iOS_SDK/OneSignalSDK/OneSignalCoreMocks/OneSignalCoreMocks.swift @@ -43,9 +43,11 @@ public class OneSignalCoreMocks: NSObject { } } + /// The timeout only bounds a failure: a met condition returns at once. CI runners can stall for + /// several seconds at a time, so it is generous. public static func waitUntil( _ description: String, - timeout: TimeInterval = 5, + timeout: TimeInterval = 15, file: StaticString = #filePath, line: UInt = #line, condition: @escaping () -> Bool diff --git a/iOS_SDK/OneSignalSDK/OneSignalInAppMessagesTests/IamFetchIdentityVerificationTests.swift b/iOS_SDK/OneSignalSDK/OneSignalInAppMessagesTests/IamFetchIdentityVerificationTests.swift index ce82ffd259..df83f0b538 100644 --- a/iOS_SDK/OneSignalSDK/OneSignalInAppMessagesTests/IamFetchIdentityVerificationTests.swift +++ b/iOS_SDK/OneSignalSDK/OneSignalInAppMessagesTests/IamFetchIdentityVerificationTests.swift @@ -172,6 +172,14 @@ final class IamFetchIdentityVerificationTests: XCTestCase { return executedFetches().last?.additionalHeaders?["Authorization"] } + /// The current user and what was sent, for a failure that only reproduces in CI. + private func describeCurrentUser() -> String { + let model = OneSignalUserManagerImpl.sharedInstance._user?.identityModel + let sent = client.executedRequests.map { "\($0) auth: \($0.additionalHeaders?["Authorization"] ?? "nil")" } + return "user: \(model?.externalId ?? "nil") \(model?.modelId ?? "nil") token: \(model?.jwtBearerToken ?? "nil"), " + + "pending asks: \(OneSignalUserManagerImpl.sharedInstance.userJwtRepo.pendingTokenAsks()), sent: \(sent)" + } + private func deferredSubscriptionId() -> String? { return OSMessagingController.sharedInstance().deferredFetchSubscriptionId } @@ -257,6 +265,8 @@ final class IamFetchIdentityVerificationTests: XCTestCase { /// The fetch is not a source of truth for whether a token is good, because the server can refuse it /// over a user and subscription it does not have paired. It parks, and the next token releases it. func testARejectedFetchParksWithoutReportingTheTokenItUsed() { + var whenAsked: [String] = [] + jwtListener.setCallback { whenAsked.append(self.describeCurrentUser()) } OSCoreMocks.hydrateSharedJwtConfig(requiresUserAuth: true) login(token: "token-a") rejectFetch(from: identifiedUserPath) @@ -265,7 +275,7 @@ final class IamFetchIdentityVerificationTests: XCTestCase { fetch() XCTAssertEqual(executedFetches().count, fetchesBefore + 1) - XCTAssertEqual(jwtListener.invalidatedExternalIds, []) + XCTAssertEqual(jwtListener.invalidatedExternalIds, [], "when asked: \(whenAsked), now: \(describeCurrentUser())") XCTAssertEqual(deferredSubscriptionId(), testPushSubId) // A token the app supplies for its own reasons, since the fetch never asked for one. diff --git a/iOS_SDK/OneSignalSDK/OneSignalNotificationsTests/OneSignalNotificationsTests.swift b/iOS_SDK/OneSignalSDK/OneSignalNotificationsTests/OneSignalNotificationsTests.swift index a788cb67e8..c4b5226163 100644 --- a/iOS_SDK/OneSignalSDK/OneSignalNotificationsTests/OneSignalNotificationsTests.swift +++ b/iOS_SDK/OneSignalSDK/OneSignalNotificationsTests/OneSignalNotificationsTests.swift @@ -46,27 +46,22 @@ final class OneSignalNotificationsTests: XCTestCase { } /// Helper to set badge count - private func setBadgeCount(_ count: Int, completion: @escaping () -> Void = {}) { + /// Nothing waits for the system's completion, so it must not assert: a late error would fail whichever + /// test is running by then. + private func setBadgeCount(_ count: Int) { if #available(iOS 16.0, *) { - UNUserNotificationCenter.current().setBadgeCount(count) { error in - if let error = error { - XCTFail("Failed to set badge count: \(error)") - } - completion() - } + UNUserNotificationCenter.current().setBadgeCount(count, withCompletionHandler: nil) } else { // Fallback for iOS 15 and earlier UIApplication.shared.applicationIconBadgeNumber = count - completion() } } + /// The swizzled setter caches the count before calling the system, whose completion can take + /// seconds on a freshly booted simulator, so this waits on the cache rather than the completion. private func setBadgeCountAndWait(_ count: Int) { - let badgeSet = expectation(description: "Badge set") - setBadgeCount(count) { - badgeSet.fulfill() - } - wait(for: [badgeSet], timeout: 5) + setBadgeCount(count) + waitForCachedBadgeCount(count) } private func waitForCachedBadgeCount(_ count: Int) { diff --git a/iOS_SDK/OneSignalSDK/OneSignalUser/Source/Executors/OSSubscriptionOperationExecutor.swift b/iOS_SDK/OneSignalSDK/OneSignalUser/Source/Executors/OSSubscriptionOperationExecutor.swift index 538859c837..2982a6b2cd 100644 --- a/iOS_SDK/OneSignalSDK/OneSignalUser/Source/Executors/OSSubscriptionOperationExecutor.swift +++ b/iOS_SDK/OneSignalSDK/OneSignalUser/Source/Executors/OSSubscriptionOperationExecutor.swift @@ -34,14 +34,14 @@ class OSSubscriptionOperationExecutor: OSOperationExecutor { // To simplify uncaching, we maintain separate request queues for each type private var addRequestQueue: [OSRequestCreateSubscription] = [] private var removeRequestQueue: [OSRequestDeleteSubscription] = [] - private var updateRequestQueue: [OSRequestUpdateSubscription] = [] + var updateRequestQueue: [OSRequestUpdateSubscription] = [] // non-private for unit test access private var subscriptionModels: [String: OSSubscriptionModel] = [:] private let newRecordsState: OSNewRecordsState private let auth: OSRequestAuthorizing private let retryBackoff: OSRequestRetryBackoff // The Subscription executor dispatch queue, serial. This synchronizes access to the delta and request queues. - private let dispatchQueue = DispatchQueue(label: "OneSignal.OSSubscriptionOperationExecutor", target: .global()) + let dispatchQueue = DispatchQueue(label: "OneSignal.OSSubscriptionOperationExecutor", target: .global()) init( newRecordsState: OSNewRecordsState, diff --git a/iOS_SDK/OneSignalSDK/OneSignalUser/Source/OneSignalUserManagerImpl.swift b/iOS_SDK/OneSignalSDK/OneSignalUser/Source/OneSignalUserManagerImpl.swift index 3c745e308a..7d4eec479e 100644 --- a/iOS_SDK/OneSignalSDK/OneSignalUser/Source/OneSignalUserManagerImpl.swift +++ b/iOS_SDK/OneSignalSDK/OneSignalUser/Source/OneSignalUserManagerImpl.swift @@ -468,7 +468,7 @@ public class OneSignalUserManagerImpl: NSObject, OneSignalUserManager { prepareForNewUser() } - let newUser = setNewInternalUser(externalId: externalId, pushSubscriptionModel: pushSubscriptionModel) + let newUser = setNewInternalUser(externalId: externalId, pushSubscriptionModel: pushSubscriptionModel, jwtBearerToken: token) if let externalId = externalId { storeJwtOrRearmAsk(externalId: externalId, token: token) } @@ -494,7 +494,7 @@ public class OneSignalUserManagerImpl: NSObject, OneSignalUserManager { // Immediately drop the old user and set a new user in the SDK let pushSubscriptionModel = pushSubscriptionModelStore.getModel(key: OS_PUSH_SUBSCRIPTION_MODEL_KEY) prepareForNewUser() - let newUser = setNewInternalUser(externalId: externalId, pushSubscriptionModel: pushSubscriptionModel) + let newUser = setNewInternalUser(externalId: externalId, pushSubscriptionModel: pushSubscriptionModel, jwtBearerToken: token) // The token belongs on the model that carries `external_id`: the Fetch User this leads to is signed // with it, as is the Create User this becomes if the requirement turns out to be on. storeJwtOrRearmAsk(externalId: externalId, token: token) @@ -608,7 +608,7 @@ extension OneSignalUserManagerImpl { /** Creates and sets a blank new SDK user with the provided externalId, if any. */ - func setNewInternalUser(externalId: String?, pushSubscriptionModel: OSSubscriptionModel?) -> OSUserInternal { + func setNewInternalUser(externalId: String?, pushSubscriptionModel: OSSubscriptionModel?, jwtBearerToken: String? = nil) -> OSUserInternal { let aliases: [String: String]? if let externalIdToUse = externalId { aliases = [OS_EXTERNAL_ID: externalIdToUse] @@ -617,6 +617,11 @@ extension OneSignalUserManagerImpl { } let identityModel = OSIdentityModel(aliases: aliases, changeNotifier: OSEventProducer()) + // Set before `_user` publishes the model: a caller on another queue that reads the current + // user in between would otherwise find it without a token and ask the app for one. + if let token = jwtBearerToken, !token.isEmpty, token != OS_JWT_TOKEN_INVALID { + identityModel.jwtBearerToken = token + } self.identityModelStore.add(id: OS_IDENTITY_MODEL_KEY, model: identityModel, hydrating: false) self.addIdentityModelToRepo(identityModel) diff --git a/iOS_SDK/OneSignalSDK/OneSignalUserTests/Executors/SubscriptionUpdateRaceTests.swift b/iOS_SDK/OneSignalSDK/OneSignalUserTests/Executors/SubscriptionUpdateRaceTests.swift index a90dbf9136..596a0ba90b 100644 --- a/iOS_SDK/OneSignalSDK/OneSignalUserTests/Executors/SubscriptionUpdateRaceTests.swift +++ b/iOS_SDK/OneSignalSDK/OneSignalUserTests/Executors/SubscriptionUpdateRaceTests.swift @@ -100,11 +100,7 @@ final class SubscriptionUpdateRaceTests: XCTestCase { )) executor.processDeltaQueue(inBackground: false) OneSignalCoreMocks.waitUntil("Blocked subscription update was not cached") { - let requests = OneSignalUserDefaults.initShared().getSavedCodeableData( - forKey: OS_SUBSCRIPTION_EXECUTOR_UPDATE_REQUEST_QUEUE_KEY, - defaultValue: [] - ) as? [OSRequestUpdateSubscription] - return requests?.count == 1 + executor.snapshotUpdateRequestQueue().count == 1 } XCTAssertTrue(client.executedRequests.isEmpty, "Update should still be pending without subscriptionId") @@ -141,7 +137,7 @@ final class SubscriptionUpdateRaceTests: XCTestCase { XCTAssertFalse(sentMinus19, "Must not send stale enabled:false / notification_types:-19 after grant") XCTAssertTrue(allSubscribed, "All executed UpdateSubscription payloads should reflect the live subscribed model") XCTAssertEqual(updateRequests.count, 1, "Unsent updates for the same subscription should be coalesced") - waitForUpdateRequestQueueToDrain() + waitForUpdateRequestQueueToDrain(executor) } /** @@ -192,11 +188,7 @@ final class SubscriptionUpdateRaceTests: XCTestCase { )) executor.processDeltaQueue(inBackground: false) OneSignalCoreMocks.waitUntil("Follow-up subscription update was not queued") { - let requests = OneSignalUserDefaults.initShared().getSavedCodeableData( - forKey: OS_SUBSCRIPTION_EXECUTOR_UPDATE_REQUEST_QUEUE_KEY, - defaultValue: [] - ) as? [OSRequestUpdateSubscription] - return requests?.count == 2 + executor.snapshotUpdateRequestQueue().count == 2 } XCTAssertEqual(client.startedRequests.count, 1, "Follow-up must wait for in-flight UpdateSubscription") @@ -209,7 +201,7 @@ final class SubscriptionUpdateRaceTests: XCTestCase { XCTAssertEqual(client.startedRequests.count, 2, "Pending follow-up should send after in-flight completes") try assertSubscribedPayload(client.startedRequests[1]) waitForCompletedUpdateRequests(client, expectedCount: 2) - waitForUpdateRequestQueueToDrain() + waitForUpdateRequestQueueToDrain(executor) } /** @@ -280,7 +272,7 @@ final class SubscriptionUpdateRaceTests: XCTestCase { let lastPayload = try XCTUnwrap(updateRequests.last?.parameters?["subscription"] as? [String: Any]) XCTAssertEqual(lastPayload["notification_types"] as? Int, subscribedNotificationTypes) XCTAssertEqual(lastPayload["enabled"] as? Bool, true) - waitForUpdateRequestQueueToDrain() + waitForUpdateRequestQueueToDrain(executor) } // MARK: - Helpers @@ -298,13 +290,9 @@ final class SubscriptionUpdateRaceTests: XCTestCase { return model } - private func waitForUpdateRequestQueueToDrain() { + private func waitForUpdateRequestQueueToDrain(_ executor: OSSubscriptionOperationExecutor) { OneSignalCoreMocks.waitUntil("Subscription executor cleanup did not complete") { - let requests = OneSignalUserDefaults.initShared().getSavedCodeableData( - forKey: OS_SUBSCRIPTION_EXECUTOR_UPDATE_REQUEST_QUEUE_KEY, - defaultValue: [] - ) as? [OSRequestUpdateSubscription] - return requests?.isEmpty == true + executor.snapshotUpdateRequestQueue().isEmpty } } @@ -322,3 +310,11 @@ final class SubscriptionUpdateRaceTests: XCTestCase { XCTAssertEqual(payload["enabled"] as? Bool, true) } } + +private extension OSSubscriptionOperationExecutor { + /// This executor's queue. The persisted copy is shared with every other executor, including ones + /// earlier tests left running, so a test cannot rely on it naming this executor's requests. + func snapshotUpdateRequestQueue() -> [OSRequestUpdateSubscription] { + return dispatchQueue.sync { updateRequestQueue } + } +} diff --git a/iOS_SDK/OneSignalSDK/OneSignalUserTests/OneSignalUserTests.swift b/iOS_SDK/OneSignalSDK/OneSignalUserTests/OneSignalUserTests.swift index 42b18a85e7..07200a09e6 100644 --- a/iOS_SDK/OneSignalSDK/OneSignalUserTests/OneSignalUserTests.swift +++ b/iOS_SDK/OneSignalSDK/OneSignalUserTests/OneSignalUserTests.swift @@ -205,7 +205,13 @@ final class OneSignalUserTests: XCTestCase { // This adds a `session_count` property with value of 1 // It also sets `refresh_device_metadata` to `true` + // It unpauses the repo before enqueueing that Delta, so a poll in between would split the batch. + // Suspending the repo's queue keeps the poll from running until the repo is paused again. + let operationRepo = OneSignalUserManagerImpl.sharedInstance.operationRepo + operationRepo.dispatchQueue.suspend() OneSignalUserManagerImpl.sharedInstance.startNewSession() + operationRepo.paused = true + operationRepo.dispatchQueue.resume() /* Then */ diff --git a/iOS_SDK/OneSignalSDK/OneSignalUserTests/UserJwtLifecycleTests.swift b/iOS_SDK/OneSignalSDK/OneSignalUserTests/UserJwtLifecycleTests.swift index ec1896a881..941df4e76f 100644 --- a/iOS_SDK/OneSignalSDK/OneSignalUserTests/UserJwtLifecycleTests.swift +++ b/iOS_SDK/OneSignalSDK/OneSignalUserTests/UserJwtLifecycleTests.swift @@ -41,6 +41,31 @@ private class MockUserStateObserver: NSObject, OSUserStateObserver { } } +/// Forwards to the store's own listener, which the producer's single subscriber slot would otherwise drop. +private class IdentityModelAddRecorder: OSModelStoreChangedHandler { + private let forwardee: OSModelStoreChangedHandler? + var tokensWhenAdded: [String?] = [] + + init(forwardingTo forwardee: OSModelStoreChangedHandler?) { + self.forwardee = forwardee + } + + func onAdded(_ model: OSModel) { + if let identityModel = model as? OSIdentityModel, identityModel.externalId == userA_EUID { + tokensWhenAdded.append(identityModel.jwtBearerToken) + } + forwardee?.onAdded(model) + } + + func onUpdated(_ args: OSModelChangedArgs) { + forwardee?.onUpdated(args) + } + + func onRemoved(_ model: OSModel) { + forwardee?.onRemoved(model) + } +} + /** What `login` and `logout` do differently under Identity Verification: no anonymous user is ever sent to the server, so login creates rather than promotes and logout has to silence the push subscription itself. @@ -269,26 +294,32 @@ final class UserJwtLifecycleTests: XCTestCase { func testLoggingInWithATokenAnswersAPendingAskForThatUser() { OSCoreMocks.hydrateSharedJwtConfig(requiresUserAuth: true) let jwtRepo = OneSignalUserManagerImpl.sharedInstance.userJwtRepo - - // The Create User parks for want of a token, which asks the app once. Asking is what the - // assertion reads, so it cannot be polled: the first poll would consume the pending ask. - OneSignalUserManagerImpl.sharedInstance.login(externalId: userA_EUID, token: nil) - allowAsyncWorkToRun() - XCTAssertFalse(jwtRepo.askForToken(externalId: userA_EUID)) + // A user no other test logs in as: an earlier test's executors can still be persisting user A's + // Requests after teardown, and the next `start` uncaches them along with user A's token. + let externalId = "pending-ask-user" + MockUserRequests.setDefaultCreateUserResponses(with: client, externalId: externalId) + + // The Create User parks for want of a token, which asks the app once. `pendingTokenAsks` reads + // the ask without consuming it, unlike `askForToken`. + OneSignalUserManagerImpl.sharedInstance.login(externalId: externalId, token: nil) + let asked = OneSignalCoreMocks.waitUntilForObjC(timeout: 5) { + jwtRepo.pendingTokenAsks().contains(externalId) + } + XCTAssertTrue(asked, "The parked Create User did not ask for a token. \(describeTokenState())") // Log back in as the same user, which builds a new Identity Model rather than reusing the parked one. OneSignalUserManagerImpl.sharedInstance.logout() - OneSignalUserManagerImpl.sharedInstance.login(externalId: userA_EUID, token: "token-a") + OneSignalUserManagerImpl.sharedInstance.login(externalId: externalId, token: "token-a") // Rejecting the token reads the Identity Model the login hydrates, so let the login finish // rather than stopping at the point the token is merely stored. waitForTheLoginToSettle() OneSignalCoreMocks.waitUntil("The replacement token was not stored") { - jwtRepo.validJwt(externalId: userA_EUID) == "token-a" + jwtRepo.validJwt(externalId: externalId) == "token-a" } - XCTAssertEqual(jwtRepo.validJwt(externalId: userA_EUID), "token-a") + XCTAssertEqual(jwtRepo.validJwt(externalId: externalId), "token-a") // `true` means this rejection reached the app, which only happens once the earlier ask was answered. - XCTAssertTrue(jwtRepo.invalidateJwt(externalId: userA_EUID, rejectedToken: "token-a")) + XCTAssertTrue(jwtRepo.invalidateJwt(externalId: externalId, rejectedToken: "token-a")) } // MARK: - a rejected token on the first Create User @@ -537,3 +568,37 @@ final class UserJwtLifecycleTests: XCTestCase { XCTAssertEqual(pushSubscriptionPayload()["notification_types"] as? Int, optedInNotificationTypes) } } + +extension UserJwtLifecycleTests { + /// Another queue, like the in-app message fetch, can read the current user at any point during `login`, + /// so the user has to carry its token from the moment it is published or that reader asks the app for one. + /// The Identity Model enters the store just before the user is published, and the token `login` stores + /// afterwards would land too late to show up here. + func testLoginPublishesTheNewUserWithTheTokenItLoggedInWith() { + OSCoreMocks.hydrateSharedJwtConfig(requiresUserAuth: true) + // `start` subscribes the store's own listener, which would replace the recorder. + OneSignalUserManagerImpl.sharedInstance.start() + let changeSubscription = OneSignalUserManagerImpl.sharedInstance.identityModelStore.changeSubscription + let storeListener = changeSubscription.subscriber + let recorder = IdentityModelAddRecorder(forwardingTo: storeListener) + changeSubscription.subscriber = recorder + defer { changeSubscription.subscriber = storeListener } + + OneSignalUserManagerImpl.sharedInstance.login(externalId: userA_EUID, token: "token-a") + + XCTAssertEqual(recorder.tokensWhenAdded, ["token-a"]) + } +} + +private extension UserJwtLifecycleTests { + func describeTokenState() -> String { + let manager = OneSignalUserManagerImpl.sharedInstance + let model = manager._user?.identityModel + let queued = queuedUserRequests().map { "\($0) sent: \($0.sentToClient)" } + let sent = client.executedRequests.map { "\($0) auth: \($0.additionalHeaders?["Authorization"] ?? "nil")" } + return "requirement: \(manager.identityVerificationService.requirement), " + + "user: \(model?.externalId ?? "nil") \(model?.modelId ?? "nil") token: \(model?.jwtBearerToken ?? "nil"), " + + "pending asks: \(manager.userJwtRepo.pendingTokenAsks()), repo paused: \(manager.operationRepo.paused), " + + "queued: \(queued), sent: \(sent)" + } +} diff --git a/iOS_SDK/OneSignalSDK/OneSignalUserTests/UserStateReportingTests.swift b/iOS_SDK/OneSignalSDK/OneSignalUserTests/UserStateReportingTests.swift index 1af0598be1..e05421999a 100644 --- a/iOS_SDK/OneSignalSDK/OneSignalUserTests/UserStateReportingTests.swift +++ b/iOS_SDK/OneSignalSDK/OneSignalUserTests/UserStateReportingTests.swift @@ -131,13 +131,15 @@ final class UserStateReportingTests: XCTestCase { OneSignalCoreMocks.waitUntil("The Identify User was not started") { self.client.startedRequestCount(ofType: OSRequestIdentifyUser.self) == 1 } + let modelA = OneSignalUserManagerImpl.sharedInstance.user.identityModel // B becomes current while A's Identify User is in flight. OneSignalUserManagerImpl.sharedInstance.login(externalId: userB_EUID, token: nil) client.releaseHeldResponses() waitForTheLoginToSettle() // Still hydrated, for anything queued behind it. - XCTAssertEqual(OneSignalUserManagerImpl.sharedInstance.identityModelRepo.get(externalId: userA_EUID)?.onesignalId, anonUserOSID) + XCTAssertEqual(OneSignalUserManagerImpl.sharedInstance.identityModelRepo.get(externalId: userA_EUID)?.onesignalId, anonUserOSID, + describeModels(for: userA_EUID, loggedIn: modelA)) XCTAssertFalse(observer.states.contains { $0.externalId == userA_EUID }, "the app must not hear about A: \(observer.states)") XCTAssertEqual(observer.states.last?.externalId, userB_EUID) assertPersistedSnapshotNames(externalId: userB_EUID, onesignalId: userB_OSID) @@ -198,6 +200,13 @@ final class UserStateReportingTests: XCTestCase { User starts. A fetch landing later would re-report the current user and hide a wrong report made in between. */ + /// Which models the repo holds for this user, and what was sent, for a failure that only reproduces in CI. + private func describeModels(for externalId: String, loggedIn: OSIdentityModel) -> String { + let models = OneSignalUserManagerImpl.sharedInstance.identityModelRepo.models.values.filter { $0.externalId == externalId } + let described = models.map { "\($0.modelId == loggedIn.modelId ? "login" : "other"): \($0.onesignalId ?? "nil")" } + return "models: \(described), executed: \(client.executedRequests)" + } + private func waitForTheLoginToSettle() { OneSignalCoreMocks.waitUntil("The login did not reach a reported user") { OneSignalUserManagerImpl.sharedInstance.user.identityModel.onesignalId != nil