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
4 changes: 4 additions & 0 deletions iOS_SDK/OneSignalSDK/OneSignal.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -298,6 +298,7 @@
5BC1DE602C90B83900CA8807 /* OSConsistencyKeyEnum.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5BC1DE5F2C90B83900CA8807 /* OSConsistencyKeyEnum.swift */; };
5BC1DE622C90B85A00CA8807 /* OSIamFetchOffsetKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5BC1DE612C90B85A00CA8807 /* OSIamFetchOffsetKey.swift */; };
5BC1DE642C90BB9000CA8807 /* OSIamFetchReadyCondition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5BC1DE632C90BB9000CA8807 /* OSIamFetchReadyCondition.swift */; };
6F894909CB6D09258DCCA1C9 /* IamFetchIdentityVerificationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 67ECA2928D863073B785F93F /* IamFetchIdentityVerificationTests.swift */; };
7A123295235DFE3B002B6CE3 /* OutcomeTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 7A123294235DFE3B002B6CE3 /* OutcomeTests.m */; };
7A1232A2235E1743002B6CE3 /* OneSignal.m in Sources */ = {isa = PBXBuildFile; fileRef = 912411F11E73342200E41FD7 /* OneSignal.m */; };
7A2E90622460DA1500B3428C /* OutcomeIntegrationV2Tests.m in Sources */ = {isa = PBXBuildFile; fileRef = 7A2E90612460DA1500B3428C /* OutcomeIntegrationV2Tests.m */; };
Expand Down Expand Up @@ -1572,6 +1573,7 @@
5BC1DE672C90C23E00CA8807 /* OSConsistencyManagerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OSConsistencyManagerTests.swift; sourceTree = "<group>"; };
5BFE2F960129386AFA6D5F41 /* UserJwtLifecycleTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = UserJwtLifecycleTests.swift; sourceTree = "<group>"; };
6552F2A6DF7776B0582CFAEF /* OSUserJwtConfig.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = OSUserJwtConfig.swift; sourceTree = "<group>"; };
67ECA2928D863073B785F93F /* IamFetchIdentityVerificationTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = IamFetchIdentityVerificationTests.swift; sourceTree = "<group>"; };
6A8BBA843AFC81A4940CF7CC /* OSUserJwtRepo.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = OSUserJwtRepo.swift; sourceTree = "<group>"; };
7A123294235DFE3B002B6CE3 /* OutcomeTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = OutcomeTests.m; sourceTree = "<group>"; };
7A12EBD523060A6F005C4FA5 /* OSSessionManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = OSSessionManager.m; sourceTree = "<group>"; };
Expand Down Expand Up @@ -2292,6 +2294,7 @@
3C30FE352F21FBE1001B9C25 /* EarlyTriggerTrackingTests.swift */,
3CB35FCA2F0FA20B000E6E0F /* OSMessagingControllerUserStateTests.swift */,
3C7021E72ECF0CF3001768C6 /* OneSignalInAppMessagesTests-Bridging-Header.h */,
67ECA2928D863073B785F93F /* IamFetchIdentityVerificationTests.swift */,
);
path = OneSignalInAppMessagesTests;
sourceTree = "<group>";
Expand Down Expand Up @@ -4521,6 +4524,7 @@
3C7021E92ECF0CF4001768C6 /* IAMIntegrationTests.swift in Sources */,
3C01519C2C2E29F90079E076 /* IAMRequestTests.m in Sources */,
3CB35FCB2F0FA20B000E6E0F /* OSMessagingControllerUserStateTests.swift in Sources */,
6F894909CB6D09258DCCA1C9 /* IamFetchIdentityVerificationTests.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
Expand Down

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,12 @@
#import <OneSignalCore/OneSignalCore.h>
#import "OSInAppMessageClickResult.h"

@class OSAliasPair;

@interface OSRequestGetInAppMessages : OneSignalRequest
+ (instancetype _Nonnull)withSubscriptionId:(NSString * _Nonnull)subscriptionId withSessionDuration:(NSNumber * _Nonnull)sessionDuration withRetryCount:(NSNumber *)retryCount withRywToken:(NSString *)rywToken;
/// A nil `alias` addresses the subscription on its own, which is how this was addressed before Identity
/// Verification; `userHeaders` carries the Bearer when the call is signed.
+ (instancetype _Nonnull)withSubscriptionId:(NSString * _Nonnull)subscriptionId withAlias:(OSAliasPair * _Nullable)alias withUserHeaders:(NSDictionary<NSString *, NSString *> * _Nullable)userHeaders withSessionDuration:(NSNumber * _Nonnull)sessionDuration withRetryCount:(NSNumber *)retryCount withRywToken:(NSString *)rywToken;
@end

@interface OSRequestInAppMessageViewed : OneSignalRequest
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,13 +35,15 @@ - (NSString *)description {
}

+ (instancetype _Nonnull) withSubscriptionId:(NSString * _Nonnull)subscriptionId
withAlias:(OSAliasPair * _Nullable)alias
withUserHeaders:(NSDictionary<NSString *, NSString *> * _Nullable)userHeaders
withSessionDuration:(NSNumber * _Nonnull)sessionDuration
withRetryCount:(NSNumber *)retryCount
withRywToken:(NSString *)rywToken
{
let request = [OSRequestGetInAppMessages new];
request.method = GET;
let headers = [NSMutableDictionary new];
NSMutableDictionary *headers = userHeaders ? [userHeaders mutableCopy] : [NSMutableDictionary new];

if (sessionDuration != nil) {
// convert to ms & round
Expand All @@ -56,7 +58,17 @@ + (instancetype _Nonnull) withSubscriptionId:(NSString * _Nonnull)subscription
request.additionalHeaders = headers;

NSString *appId = OneSignalIdentifiers.currentAppId;
request.path = [NSString stringWithFormat:@"apps/%@/subscriptions/%@/iams", appId, subscriptionId];
if (alias) {
// Encode so an app-chosen external_id cannot change which endpoint the path names.
NSString *encodedAliasId = [OSUrlPath segment:alias.id];
if (!encodedAliasId) {
[OneSignalLog onesignalLog:ONE_S_LL_ERROR message:@"OSRequestGetInAppMessages: cannot encode alias id for path"];
return request;
}
request.path = [NSString stringWithFormat:@"apps/%@/users/by/%@/%@/subscriptions/%@/iams", appId, alias.label, encodedAliasId, subscriptionId];
} else {
request.path = [NSString stringWithFormat:@"apps/%@/subscriptions/%@/iams", appId, subscriptionId];
}
return request;
}
@end
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,309 @@
/*
Modified MIT License

Copyright 2026 OneSignal

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

1. The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

2. All copies of substantial portions of the Software may only be used in connection
with services provided by OneSignal.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

import XCTest
import OneSignalCore
import OneSignalOSCore
import OneSignalCoreMocks
import OneSignalOSCoreMocks
import OneSignalUserMocks
import OneSignalInAppMessagesMocks
@testable import OneSignalUser

/**
How the in-app message fetch is addressed and signed. It does not travel through the Request queues, so
it makes the Identity Verification decision itself and holds the fetch until the answer arrives.
*/
final class IamFetchIdentityVerificationTests: XCTestCase {
private let appId = "test-app-id"

private var client = MockOneSignalClient()
private var jwtListener = MockUserJwtInvalidatedListener()

private var legacyPath: String { "apps/\(appId)/subscriptions/\(testPushSubId)/iams" }
private var anonymousUserPath: String { userPath(alias: OS_ONESIGNAL_ID, id: anonUserOSID) }
private var identifiedUserPath: String { userPath(alias: OS_EXTERNAL_ID, id: userA_EUID) }

override func setUpWithError() throws {
OneSignalCoreMocks.clearUserDefaults()
OneSignalUserMocks.reset()
ConsistencyManagerTestHelpers.reset()
OSMessagingController.removeInstance()
OneSignalIdentifiers.currentAppId = appId

client = MockOneSignalClient()
MockUserRequests.setDefaultCreateAnonUserResponses(with: client)
MockUserRequests.setDefaultCreateUserResponses(with: client, externalId: userA_EUID)
OneSignalCoreImpl.setSharedClient(client)
for path in [legacyPath, anonymousUserPath, identifiedUserPath] {
respondToFetch(from: path)
}

// Held strongly for the test's lifetime: the observable keeps listeners weakly.
jwtListener = MockUserJwtInvalidatedListener()
OneSignalUserManagerImpl.sharedInstance.addUserJwtInvalidatedListener(jwtListener)

OSMessagingController.start()
}

override func tearDownWithError() throws {
OneSignalUserManagerImpl.sharedInstance.removeUserJwtInvalidatedListener(jwtListener)
OSMessagingController.removeInstance()
OSFeatureManager.shared.setEnabledFeatureKeys([])
OneSignalCoreMocks.clearUserDefaults()
}

// MARK: - Setup helpers

private func userPath(alias: String, id: String) -> String {
return "apps/\(appId)/users/by/\(alias)/\(id)/subscriptions/\(testPushSubId)/iams"
}

private func respondToFetch(from path: String) {
client.setMockResponseForRequest(
request: "<OSRequestGetInAppMessages from \(path)>",
response: IAMTestHelpers.testFetchMessagesResponse(messages: []))
}

private func rejectFetch(from path: String) {
client.setMockFailureResponseForRequest(
request: "<OSRequestGetInAppMessages from \(path)>",
error: OneSignalClientError(code: 401, message: "unauthorized", responseHeaders: nil, response: nil, underlyingError: nil))
}

private func turnOnTheRolloutFlag() {
OSFeatureManager.shared.setEnabledFeatureKeys([OSFeatureFlag.identityVerification.rawValue])
}

/// An anonymous user with an `onesignal_id`, which the fetch needs before it does anything else.
private func startAnonymousUser() {
ConsistencyManagerTestHelpers.setDefaultRywToken(id: anonUserOSID)
OneSignalUserManagerImpl.sharedInstance.start()
OneSignalCoreMocks.waitForBackgroundThreads(seconds: 0.5)
}

private func login(token: String?) {
ConsistencyManagerTestHelpers.setDefaultRywToken(id: userA_OSID)
OneSignalUserManagerImpl.sharedInstance.login(externalId: userA_EUID, token: token)
OneSignalCoreMocks.waitForBackgroundThreads(seconds: 0.5)
}

private func fetch() {
OneSignalInAppMessages.getFromServer(testPushSubId)
OneSignalCoreMocks.waitForBackgroundThreads(seconds: 0.5)
}

// MARK: - Assertion helpers

private func executedFetches() -> [OneSignalRequest] {
return client.executedRequests.filter { $0 is OSRequestGetInAppMessages }
}

private func startedFetches() -> [OneSignalRequest] {
return client.startedRequests.filter { $0 is OSRequestGetInAppMessages }
}

private func lastFetchPath() -> String? {
return executedFetches().last?.path
}

private func lastFetchAuthorization() -> String? {
return executedFetches().last?.additionalHeaders?["Authorization"]
}

private func deferredSubscriptionId() -> String? {
return OSMessagingController.sharedInstance().deferredFetchSubscriptionId
}

// MARK: - How the fetch is addressed

func testTheFetchAddressesTheSubscriptionAloneWhileTheNewCodePathsAreOff() {
startAnonymousUser()

fetch()

XCTAssertEqual(lastFetchPath(), legacyPath)
XCTAssertNil(lastFetchAuthorization())
}

func testTheFetchAddressesTheOnesignalIdWhileIdentityVerificationIsOff() {
turnOnTheRolloutFlag()
startAnonymousUser()

fetch()

XCTAssertEqual(lastFetchPath(), anonymousUserPath)
XCTAssertNil(lastFetchAuthorization())
}

func testTheFetchAddressesTheExternalIdAndIsSignedUnderIdentityVerification() {
OSCoreMocks.hydrateSharedJwtConfig(requiresUserAuth: true)
login(token: "token-a")

fetch()

XCTAssertEqual(lastFetchPath(), identifiedUserPath)
XCTAssertEqual(lastFetchAuthorization(), "Bearer token-a")
}

// MARK: - Holding the fetch until Identity Verification answers

/// An unsigned fetch on behalf of an app that turns out to require auth would be rejected, so a fetch
/// that runs before remote params answer waits for them — including when the rollout flag is off.
func testAFetchHeldForAnUnknownRequirementGoesOutOnHydration() {
startAnonymousUser()
let fetchesBefore = executedFetches().count
OSCoreMocks.resetSharedJwtConfig()

fetch()

XCTAssertEqual(executedFetches().count, fetchesBefore)
XCTAssertEqual(deferredSubscriptionId(), testPushSubId)

OSCoreMocks.hydrateSharedJwtConfig(requiresUserAuth: false)
OneSignalCoreMocks.waitForBackgroundThreads(seconds: 0.5)

XCTAssertEqual(lastFetchPath(), legacyPath)
XCTAssertNil(deferredSubscriptionId())
}

/// A user whose token was rejected has none until the app supplies another, and the fetch has to wait
/// rather than fall back to sending unsigned.
func testAFetchIsHeldRatherThanSentUnsignedWhenTheUserHasNoToken() {
OSCoreMocks.hydrateSharedJwtConfig(requiresUserAuth: true)
login(token: "token-a")
OneSignalUserManagerImpl.sharedInstance.userJwtRepo.invalidateJwt(externalId: userA_EUID, rejectedToken: "token-a")
let fetchesBefore = executedFetches().count

fetch()

XCTAssertEqual(executedFetches().count, fetchesBefore)
XCTAssertEqual(deferredSubscriptionId(), testPushSubId)

OneSignalUserManagerImpl.sharedInstance.updateUserJwt(externalId: userA_EUID, token: "token-b")
OneSignalCoreMocks.waitForBackgroundThreads(seconds: 0.5)

XCTAssertEqual(lastFetchPath(), identifiedUserPath)
XCTAssertEqual(lastFetchAuthorization(), "Bearer token-b")
}

// MARK: - A rejected fetch

/// 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() {
OSCoreMocks.hydrateSharedJwtConfig(requiresUserAuth: true)
login(token: "token-a")
rejectFetch(from: identifiedUserPath)
let fetchesBefore = executedFetches().count

fetch()

XCTAssertEqual(executedFetches().count, fetchesBefore + 1)
XCTAssertEqual(jwtListener.invalidatedExternalIds, [])
XCTAssertEqual(deferredSubscriptionId(), testPushSubId)

// A token the app supplies for its own reasons, since the fetch never asked for one.
respondToFetch(from: identifiedUserPath)
OneSignalUserManagerImpl.sharedInstance.updateUserJwt(externalId: userA_EUID, token: "token-b")
OneSignalCoreMocks.waitForBackgroundThreads(seconds: 0.5)

XCTAssertEqual(executedFetches().count, fetchesBefore + 2)
XCTAssertEqual(lastFetchAuthorization(), "Bearer token-b")
}

/// A replacement that lands while the fetch is in flight is not parked: `OS_ON_USER_JWT_UPDATED`
/// already fired, and waiting for another would leave the fetch stuck.
func testARejectedFetchRefetchesWhenAReplacementTokenAlreadyLanded() {
OSCoreMocks.hydrateSharedJwtConfig(requiresUserAuth: true)
login(token: "token-a")
rejectFetch(from: identifiedUserPath)
let startedBefore = startedFetches().count
let executedBefore = executedFetches().count

client.holdResponses = true
OneSignalInAppMessages.getFromServer(testPushSubId)
OneSignalCoreMocks.waitForBackgroundThreads(seconds: 0.5)

XCTAssertEqual(startedFetches().count, startedBefore + 1)
XCTAssertEqual(executedFetches().count, executedBefore)

client.holdResponses = false
OneSignalUserManagerImpl.sharedInstance.updateUserJwt(externalId: userA_EUID, token: "token-b")
client.releaseHeldResponses()
respondToFetch(from: identifiedUserPath)
OneSignalCoreMocks.waitForBackgroundThreads(seconds: 0.5)

XCTAssertEqual(executedFetches().count, executedBefore + 2)
XCTAssertEqual(lastFetchAuthorization(), "Bearer token-b")
XCTAssertNil(deferredSubscriptionId())
XCTAssertEqual(jwtListener.invalidatedExternalIds, [])
}

/// The token the fetch was signed with stays usable, so everything else keeps going out signed.
func testARejectedFetchLeavesTheTokenInPlaceForTheRequests() {
OSCoreMocks.hydrateSharedJwtConfig(requiresUserAuth: true)
login(token: "token-a")
rejectFetch(from: identifiedUserPath)

fetch()

XCTAssertEqual(lastFetchAuthorization(), "Bearer token-a")
XCTAssertEqual(OneSignalUserManagerImpl.sharedInstance.user.identityModel.jwtBearerToken, "token-a")
}

/// With the gate off a 401 stays as it was: logged and dropped, with no reattempt left pending.
func testARejectedFetchIsLeftAloneWhileTheNewCodePathsAreOff() {
startAnonymousUser()
rejectFetch(from: legacyPath)
let fetchesBefore = executedFetches().count

fetch()

XCTAssertEqual(executedFetches().count, fetchesBefore + 1)
XCTAssertNil(deferredSubscriptionId())
}

/// Under Identity Verification the alias id is an app-chosen external_id, so it has to be encoded.
func testTheFetchPathPercentEncodesTheAliasId() {
OneSignalIdentifiers.currentAppId = appId
let externalId = "us er/a?b#c%d"
let request = OSRequestGetInAppMessages.withSubscriptionId(
testPushSubId,
withAlias: OSAliasPair(OS_EXTERNAL_ID, externalId),
withUserHeaders: nil,
withSessionDuration: 0,
withRetryCount: 0,
withRywToken: nil
)

XCTAssertEqual(
request.path,
"apps/\(appId)/users/by/\(OS_EXTERNAL_ID)/us%20er%2Fa%3Fb%23c%25d/subscriptions/\(testPushSubId)/iams"
)
}
}
Comment thread
nan-li marked this conversation as resolved.
Loading
Loading