Skip to content

Commit f38ef06

Browse files
nan-licursoragent
andcommitted
feat: [PR7] in-app messages under Identity Verification
The in-app message fetch is user-scoped, so under Identity Verification it has to name the user by external_id and sign the call. It asks the user manager how to address the current user rather than assembling that itself, which keeps the alias and the token consistent with every other user-scoped call. The fetch deliberately does not invalidate a JWT. Getting this request right means getting both the push subscription ID and the user in the URL right, so a 401 here is at least as likely to mean the request was mismatched as it is to mean the token is bad. Treating it as proof would let a malformed fetch invalidate a token that works everywhere else. It handles the rejection and stops; the request pipeline remains the only thing that decides a token is no longer good. This follows Android. A fetch that cannot yet be addressed waits rather than going out unsigned, and is reattempted when the requirement hydrates or the app supplies a token. Co-authored-by: Cursor <cursoragent@cursor.com>
1 parent 1d08c49 commit f38ef06

9 files changed

Lines changed: 492 additions & 37 deletions

File tree

‎iOS_SDK/OneSignalSDK/OneSignal.xcodeproj/project.pbxproj‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -298,6 +298,7 @@
298298
5BC1DE602C90B83900CA8807 /* OSConsistencyKeyEnum.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5BC1DE5F2C90B83900CA8807 /* OSConsistencyKeyEnum.swift */; };
299299
5BC1DE622C90B85A00CA8807 /* OSIamFetchOffsetKey.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5BC1DE612C90B85A00CA8807 /* OSIamFetchOffsetKey.swift */; };
300300
5BC1DE642C90BB9000CA8807 /* OSIamFetchReadyCondition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5BC1DE632C90BB9000CA8807 /* OSIamFetchReadyCondition.swift */; };
301+
6F894909CB6D09258DCCA1C9 /* IamFetchIdentityVerificationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 67ECA2928D863073B785F93F /* IamFetchIdentityVerificationTests.swift */; };
301302
7A123295235DFE3B002B6CE3 /* OutcomeTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 7A123294235DFE3B002B6CE3 /* OutcomeTests.m */; };
302303
7A1232A2235E1743002B6CE3 /* OneSignal.m in Sources */ = {isa = PBXBuildFile; fileRef = 912411F11E73342200E41FD7 /* OneSignal.m */; };
303304
7A2E90622460DA1500B3428C /* OutcomeIntegrationV2Tests.m in Sources */ = {isa = PBXBuildFile; fileRef = 7A2E90612460DA1500B3428C /* OutcomeIntegrationV2Tests.m */; };
@@ -1572,6 +1573,7 @@
15721573
5BC1DE672C90C23E00CA8807 /* OSConsistencyManagerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OSConsistencyManagerTests.swift; sourceTree = "<group>"; };
15731574
5BFE2F960129386AFA6D5F41 /* UserJwtLifecycleTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = UserJwtLifecycleTests.swift; sourceTree = "<group>"; };
15741575
6552F2A6DF7776B0582CFAEF /* OSUserJwtConfig.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = OSUserJwtConfig.swift; sourceTree = "<group>"; };
1576+
67ECA2928D863073B785F93F /* IamFetchIdentityVerificationTests.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = IamFetchIdentityVerificationTests.swift; sourceTree = "<group>"; };
15751577
6A8BBA843AFC81A4940CF7CC /* OSUserJwtRepo.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; path = OSUserJwtRepo.swift; sourceTree = "<group>"; };
15761578
7A123294235DFE3B002B6CE3 /* OutcomeTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = OutcomeTests.m; sourceTree = "<group>"; };
15771579
7A12EBD523060A6F005C4FA5 /* OSSessionManager.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = OSSessionManager.m; sourceTree = "<group>"; };
@@ -2292,6 +2294,7 @@
22922294
3C30FE352F21FBE1001B9C25 /* EarlyTriggerTrackingTests.swift */,
22932295
3CB35FCA2F0FA20B000E6E0F /* OSMessagingControllerUserStateTests.swift */,
22942296
3C7021E72ECF0CF3001768C6 /* OneSignalInAppMessagesTests-Bridging-Header.h */,
2297+
67ECA2928D863073B785F93F /* IamFetchIdentityVerificationTests.swift */,
22952298
);
22962299
path = OneSignalInAppMessagesTests;
22972300
sourceTree = "<group>";
@@ -4521,6 +4524,7 @@
45214524
3C7021E92ECF0CF4001768C6 /* IAMIntegrationTests.swift in Sources */,
45224525
3C01519C2C2E29F90079E076 /* IAMRequestTests.m in Sources */,
45234526
3CB35FCB2F0FA20B000E6E0F /* OSMessagingControllerUserStateTests.swift in Sources */,
4527+
6F894909CB6D09258DCCA1C9 /* IamFetchIdentityVerificationTests.swift in Sources */,
45244528
);
45254529
runOnlyForDeploymentPostprocessing = 0;
45264530
};

‎iOS_SDK/OneSignalSDK/OneSignalInAppMessages/Controller/OSMessagingController.m‎

Lines changed: 151 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -146,8 +146,16 @@ @interface OSMessagingController ()
146146

147147
@property (nonatomic) BOOL calledLoadTags;
148148

149-
/// set when we attempt getInAppMessagesFromServer and no onesignal ID is available yet
150-
@property (strong, nonatomic, nullable) NSString *shouldFetchOnUserChangeWithSubscriptionID;
149+
/**
150+
Set when a fetch could not go out: no onesignal ID yet, or Identity Verification has not answered what
151+
the call should be addressed and signed with. Read through `takeDeferredFetchSubscriptionId`, since a
152+
user change, a hydration and a new token can all arrive at once and only one of them should refetch.
153+
*/
154+
@property (strong, nonatomic, nullable) NSString *deferredFetchSubscriptionId;
155+
156+
/// Bumped on every login and logout. A fetch carries the value it started with, so a response that
157+
/// arrives after the user changed is discarded instead of showing one user's messages to another.
158+
@property (nonatomic) NSUInteger userGeneration;
151159

152160
/// Tracks whether the first IAM fetch has completed since this cold start
153161
@property (nonatomic) BOOL hasCompletedFirstFetch;
@@ -242,6 +250,11 @@ - (instancetype)init {
242250
_isInAppMessagingPaused = false;
243251

244252
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleIAMPreview:) name:ONESIGNAL_POST_PREVIEW_IAM object:nil];
253+
// A deferred fetch waits on how to address it and what to sign it with; hydration answers the
254+
// first, a supplied token the second.
255+
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(retryDeferredFetch) name:OS_ON_JWT_CONFIG_HYDRATED object:nil];
256+
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(retryDeferredFetch) name:OS_ON_USER_JWT_UPDATED object:nil];
257+
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onUserWillChange) name:OS_ON_USER_WILL_CHANGE object:nil];
245258
}
246259

247260
return self;
@@ -255,7 +268,15 @@ - (void)initializeTriggerController {
255268
dateFromString:timeSinceLastMessage]];
256269
}
257270

271+
/**
272+
Fetches in-app messages for `subscriptionId`, addressed as whoever is the current user.
273+
274+
Nothing checks that the server has those two paired — the subscription comes from the caller and can
275+
predate a login, while the alias is read here — so a well-formed fetch can still be refused. Pairing
276+
them would mean tracking subscription ownership, which the SDK does not do.
277+
*/
258278
- (void)getInAppMessagesFromServer:(NSString *)subscriptionId {
279+
NSUInteger generation = [self currentUserGeneration];
259280
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
260281
[OneSignalLog onesignalLog:ONE_S_LL_VERBOSE message:@"getInAppMessagesFromServer"];
261282

@@ -269,7 +290,16 @@ - (void)getInAppMessagesFromServer:(NSString *)subscriptionId {
269290
// NOTE: Check for subscription ID above first, before checking for OneSignal ID next
270291
if (!onesignalId) {
271292
[OneSignalLog onesignalLog:ONE_S_LL_VERBOSE message:@"Failed to get in app messages due to no OneSignal ID, will reattempt"];
272-
self.shouldFetchOnUserChangeWithSubscriptionID = subscriptionId;
293+
[self deferFetchWithSubscriptionId:subscriptionId];
294+
return;
295+
}
296+
297+
// Resolved before the read-your-write wait, which can hold this thread for as long as it takes
298+
// the user requests to come back.
299+
OSUserRequestAuthorization *authorization = [OneSignalUserManagerImpl.sharedInstance authorizationForCurrentUser];
300+
if (!authorization) {
301+
[OneSignalLog onesignalLog:ONE_S_LL_VERBOSE message:@"Failed to get in app messages due to Identity Verification, will reattempt"];
302+
[self deferFetchWithSubscriptionId:subscriptionId];
273303
return;
274304
}
275305

@@ -288,24 +318,101 @@ - (void)getInAppMessagesFromServer:(NSString *)subscriptionId {
288318

289319
// Initial request
290320
[self attemptFetchWithRetries:subscriptionId
321+
authorization:authorization
291322
rywData:rywData
292323
attempts:@0 // Starting with 0 attempts
293-
retryLimit:nil]; // Retry limit to be set dynamically on first failure
324+
retryLimit:nil // Retry limit to be set dynamically on first failure
325+
userGeneration:generation];
294326
});
295327
});
296328
}
297329

330+
- (NSUInteger)currentUserGeneration {
331+
@synchronized (self) {
332+
return self.userGeneration;
333+
}
334+
}
335+
336+
/// Whether a fetch that started in `generation` is still for the user it was addressed and signed for.
337+
- (BOOL)isCurrentUserGeneration:(NSUInteger)generation {
338+
@synchronized (self) {
339+
return self.userGeneration == generation;
340+
}
341+
}
342+
343+
/**
344+
Drops the outgoing user's in-app messages and invalidates any fetch still in flight for them, then
345+
queues one for whoever is signing in. The new user's fetch goes out from `onUserStateDidChange`, once
346+
there is a `onesignal_id` to address it by.
347+
*/
348+
- (void)onUserWillChange {
349+
@synchronized (self) {
350+
self.userGeneration += 1;
351+
}
352+
[self deferFetchWithSubscriptionId:OneSignalUserManagerImpl.sharedInstance.pushSubscriptionId];
353+
// On main, where every other write to `messages` happens.
354+
dispatch_async(dispatch_get_main_queue(), ^{
355+
self.messages = @[];
356+
});
357+
}
358+
359+
- (void)deferFetchWithSubscriptionId:(NSString *)subscriptionId {
360+
@synchronized (self) {
361+
self.deferredFetchSubscriptionId = subscriptionId;
362+
}
363+
}
364+
365+
/// The deferred subscription ID, if there is one, taken so that two signals arriving together refetch once.
366+
- (NSString * _Nullable)takeDeferredFetchSubscriptionId {
367+
@synchronized (self) {
368+
NSString *subscriptionId = self.deferredFetchSubscriptionId;
369+
self.deferredFetchSubscriptionId = nil;
370+
return subscriptionId;
371+
}
372+
}
373+
374+
- (void)retryDeferredFetch {
375+
NSString *subscriptionId = [self takeDeferredFetchSubscriptionId];
376+
if (subscriptionId) {
377+
[self getInAppMessagesFromServer:subscriptionId];
378+
}
379+
}
380+
381+
/**
382+
Parks the fetch for a later token to reattempt, without reporting the one it was signed with.
383+
384+
A rejection here is ambiguous: the path names a user and a subscription the server may simply not have
385+
paired, and a replacement token would not change that. Invalidating is left to the user requests, which
386+
address a user alone; the token the app supplies after one of those releases what is parked here.
387+
*/
388+
- (void)handleUnauthorizedFetch:(OSUserRequestAuthorization *)authorization subscriptionId:(NSString *)subscriptionId {
389+
// An unsigned fetch has no token to replace, so there would be nothing different to reattempt with.
390+
if (!authorization.token) {
391+
return;
392+
}
393+
[self deferFetchWithSubscriptionId:subscriptionId];
394+
}
395+
298396

299397
- (void)attemptFetchWithRetries:(NSString *)subscriptionId
398+
authorization:(OSUserRequestAuthorization *)authorization
300399
rywData:(OSReadYourWriteData *)rywData
301400
attempts:(NSNumber *)attempts
302-
retryLimit:(NSNumber *)retryLimit {
401+
retryLimit:(NSNumber *)retryLimit
402+
userGeneration:(NSUInteger)generation {
403+
if (![self isCurrentUserGeneration:generation]) {
404+
[OneSignalLog onesignalLog:ONE_S_LL_VERBOSE message:@"Abandoning an in app message fetch for a previous user"];
405+
return;
406+
}
407+
303408
NSNumber *sessionDuration = @([OSSessionManager.sharedSessionManager getTimeFocusedElapsed]);
304409
NSString *rywToken = rywData.rywToken;
305410
NSNumber *rywDelay = rywData.rywDelay;
306411

307412
// Create the request with the current attempt count
308413
OSRequestGetInAppMessages *request = [OSRequestGetInAppMessages withSubscriptionId:subscriptionId
414+
withAlias:authorization.alias
415+
withUserHeaders:authorization.headers
309416
withSessionDuration:sessionDuration
310417
withRetryCount:attempts
311418
withRywToken:rywToken];
@@ -316,6 +423,10 @@ - (void)attemptFetchWithRetries:(NSString *)subscriptionId
316423
onSuccess:^(NSDictionary *result) {
317424
dispatch_async(dispatch_get_main_queue(), ^{
318425
[OneSignalLog onesignalLog:ONE_S_LL_VERBOSE message:@"getInAppMessagesFromServer success"];
426+
if (![self isCurrentUserGeneration:generation]) {
427+
[OneSignalLog onesignalLog:ONE_S_LL_VERBOSE message:@"Discarding in app messages fetched for a previous user"];
428+
return;
429+
}
319430
if (result[@"in_app_messages"]) {
320431
NSMutableArray *messages = [NSMutableArray new];
321432

@@ -335,7 +446,12 @@ - (void)attemptFetchWithRetries:(NSString *)subscriptionId
335446
NSDictionary* responseHeaders = error.responseHeaders;
336447

337448
[OneSignalLog onesignalLog:ONE_S_LL_VERBOSE message:[NSString stringWithFormat:@"getInAppMessagesFromServer failure: %@", error.description]];
338-
449+
450+
// A retry, and the token this was signed with, both belong to the user it started for.
451+
if (![self isCurrentUserGeneration:generation]) {
452+
return;
453+
}
454+
339455
if (error.code == 425 || error.code == 429) { // 425 Too Early or 429 Too Many Requests
340456
NSInteger retryAfter = [responseHeaders[@"Retry-After"] integerValue] ?: DEFAULT_RETRY_AFTER_SECONDS;
341457

@@ -348,13 +464,17 @@ - (void)attemptFetchWithRetries:(NSString *)subscriptionId
348464
NSInteger nextAttempt = [attempts integerValue] + 1; // Increment attempts
349465
[self retryAfterDelay:retryAfter
350466
subscriptionId:subscriptionId
467+
authorization:authorization
351468
rywData:rywData
352469
attempts:@(nextAttempt)
353-
retryLimit:blockRetryLimit];
470+
retryLimit:blockRetryLimit
471+
userGeneration:generation];
354472
} else {
355473
// Final attempt without rywToken
356-
[self fetchInAppMessagesWithoutToken:subscriptionId];
474+
[self fetchInAppMessagesWithoutToken:subscriptionId authorization:authorization userGeneration:generation];
357475
}
476+
} else if ([OSNetworkingUtils getResponseStatusType:error.code] == OSResponseStatusUnauthorized) {
477+
[self handleUnauthorizedFetch:authorization subscriptionId:subscriptionId];
358478
} else if (error.code >= 500 && error.code <= 599) {
359479
[OneSignalLog onesignalLog:ONE_S_LL_VERBOSE message:@"Server error, skipping retries"];
360480
}
@@ -363,23 +483,31 @@ - (void)attemptFetchWithRetries:(NSString *)subscriptionId
363483

364484
- (void)retryAfterDelay:(NSInteger)retryAfter
365485
subscriptionId:(NSString *)subscriptionId
486+
authorization:(OSUserRequestAuthorization *)authorization
366487
rywData:(OSReadYourWriteData *)rywData
367488
attempts:(NSNumber *)attempts
368-
retryLimit:(NSNumber *)retryLimit {
489+
retryLimit:(NSNumber *)retryLimit
490+
userGeneration:(NSUInteger)generation {
369491

370492
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(retryAfter * NSEC_PER_SEC)), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
371493

372494
[self attemptFetchWithRetries:subscriptionId
495+
authorization:authorization
373496
rywData:rywData
374497
attempts:attempts
375-
retryLimit:retryLimit];
498+
retryLimit:retryLimit
499+
userGeneration:generation];
376500
});
377501
}
378502

379-
- (void)fetchInAppMessagesWithoutToken:(NSString *)subscriptionId {
503+
- (void)fetchInAppMessagesWithoutToken:(NSString *)subscriptionId
504+
authorization:(OSUserRequestAuthorization *)authorization
505+
userGeneration:(NSUInteger)generation {
380506
NSNumber *sessionDuration = @([OSSessionManager.sharedSessionManager getTimeFocusedElapsed]);
381507

382508
OSRequestGetInAppMessages *request = [OSRequestGetInAppMessages withSubscriptionId:subscriptionId
509+
withAlias:authorization.alias
510+
withUserHeaders:authorization.headers
383511
withSessionDuration:sessionDuration
384512
withRetryCount:nil
385513
withRywToken:nil]; // No retries for the final attempt
@@ -388,6 +516,10 @@ - (void)fetchInAppMessagesWithoutToken:(NSString *)subscriptionId {
388516
onSuccess:^(NSDictionary *result) {
389517
dispatch_async(dispatch_get_main_queue(), ^{
390518
[OneSignalLog onesignalLog:ONE_S_LL_VERBOSE message:@"Final attempt without token success"];
519+
if (![self isCurrentUserGeneration:generation]) {
520+
[OneSignalLog onesignalLog:ONE_S_LL_VERBOSE message:@"Discarding in app messages fetched for a previous user"];
521+
return;
522+
}
391523
if (result[@"in_app_messages"]) {
392524
NSMutableArray *messages = [NSMutableArray new];
393525

@@ -404,6 +536,12 @@ - (void)fetchInAppMessagesWithoutToken:(NSString *)subscriptionId {
404536
});
405537
} onFailure:^(OneSignalClientError *error) {
406538
[OneSignalLog onesignalLog:ONE_S_LL_VERBOSE message:[NSString stringWithFormat:@"getInAppMessagesFromServer failure: %@", error.description]];
539+
if (![self isCurrentUserGeneration:generation]) {
540+
return;
541+
}
542+
if ([OSNetworkingUtils getResponseStatusType:error.code] == OSResponseStatusUnauthorized) {
543+
[self handleUnauthorizedFetch:authorization subscriptionId:subscriptionId];
544+
}
407545
}];
408546
}
409547

@@ -1237,11 +1375,9 @@ - (void)onPushSubscriptionDidChangeWithState:(OSPushSubscriptionChangedState * _
12371375
}
12381376

12391377
- (void)onUserStateDidChangeWithState:(OSUserChangedState * _Nonnull)state {
1240-
if (state.current.onesignalId != nil && self.shouldFetchOnUserChangeWithSubscriptionID) {
1378+
if (state.current.onesignalId != nil) {
12411379
[OneSignalLog onesignalLog:ONE_S_LL_VERBOSE message:@"OSMessagingController onUserStateDidChangeWithState: changed to new valid onesignal id"];
1242-
NSString *subscriptionID = self.shouldFetchOnUserChangeWithSubscriptionID;
1243-
self.shouldFetchOnUserChangeWithSubscriptionID = nil;
1244-
[self getInAppMessagesFromServer:subscriptionID];
1380+
[self retryDeferredFetch];
12451381
}
12461382
}
12471383

‎iOS_SDK/OneSignalSDK/OneSignalInAppMessages/Requests/OSInAppMessagingRequests.h‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,8 +28,12 @@
2828
#import <OneSignalCore/OneSignalCore.h>
2929
#import "OSInAppMessageClickResult.h"
3030

31+
@class OSAliasPair;
32+
3133
@interface OSRequestGetInAppMessages : OneSignalRequest
32-
+ (instancetype _Nonnull)withSubscriptionId:(NSString * _Nonnull)subscriptionId withSessionDuration:(NSNumber * _Nonnull)sessionDuration withRetryCount:(NSNumber *)retryCount withRywToken:(NSString *)rywToken;
34+
/// A nil `alias` addresses the subscription on its own, which is how this was addressed before Identity
35+
/// Verification; `userHeaders` carries the Bearer when the call is signed.
36+
+ (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;
3337
@end
3438

3539
@interface OSRequestInAppMessageViewed : OneSignalRequest

0 commit comments

Comments
 (0)