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
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down Expand Up @@ -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)
Expand All @@ -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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Waiting on the cache is right. The system completion in setBadgeCount still XCTFails on error, and this no longer waits for it, so a late error can fail after the test ends. Drop that assertion from the unawaited completion, or wait on completion in a dedicated test.

waitForCachedBadgeCount(count)
}

private func waitForCachedBadgeCount(_ count: Int) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand All @@ -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)
Expand Down Expand Up @@ -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]
Expand All @@ -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)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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)
}

/**
Expand Down Expand Up @@ -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")
Expand All @@ -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)
}

/**
Expand Down Expand Up @@ -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
Expand All @@ -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
}
}

Expand All @@ -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 }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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 */

Expand Down
85 changes: 75 additions & 10 deletions iOS_SDK/OneSignalSDK/OneSignalUserTests/UserJwtLifecycleTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)"
}
}
Loading