Skip to content

Commit addf79a

Browse files
nan-licursoragent
andauthored
feat: [JWT-6] Identity Verification for the request pipeline (#1711)
Co-authored-by: Cursor <cursoragent@cursor.com>
1 parent b4e8aff commit addf79a

48 files changed

Lines changed: 3783 additions & 400 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

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

Lines changed: 44 additions & 0 deletions
Large diffs are not rendered by default.

‎iOS_SDK/OneSignalSDK/OneSignalCoreMocks/MockOneSignalClient.swift‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -203,12 +203,16 @@ public class MockOneSignalClient: NSObject, IOneSignalClient {
203203
executionQueue.sync {}
204204
}
205205

206+
// A request has one outcome: whichever of these was called for it last. Otherwise a test could not
207+
// override a default its setUp registered, nor let a retry succeed after the first attempt failed.
206208
public func setMockResponseForRequest(request: String, response: [String: Any]) {
207209
mockResponses[request] = response
210+
mockFailureResponses.removeValue(forKey: request)
208211
}
209212

210213
public func setMockFailureResponseForRequest(request: String, error: OneSignalClientError) {
211214
mockFailureResponses[request] = error
215+
mockResponses.removeValue(forKey: request)
212216
}
213217
}
214218

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/*
2+
Modified MIT License
3+
4+
Copyright 2026 OneSignal
5+
6+
Permission is hereby granted, free of charge, to any person obtaining a copy
7+
of this software and associated documentation files (the "Software"), to deal
8+
in the Software without restriction, including without limitation the rights
9+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10+
copies of the Software, and to permit persons to whom the Software is
11+
furnished to do so, subject to the following conditions:
12+
13+
1. The above copyright notice and this permission notice shall be included in
14+
all copies or substantial portions of the Software.
15+
16+
2. All copies of substantial portions of the Software may only be used in connection
17+
with services provided by OneSignal.
18+
19+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25+
THE SOFTWARE.
26+
*/
27+
28+
/**
29+
Requests address a user by one alias or the other depending on Identity Verification: `external_id`
30+
when it is active, `onesignal_id` otherwise.
31+
*/
32+
@objc public class OSAliasPair: NSObject {
33+
@objc public let label: String
34+
@objc public let id: String
35+
36+
public init(_ label: String, _ id: String) {
37+
self.label = label
38+
self.id = id
39+
}
40+
}

‎iOS_SDK/OneSignalSDK/OneSignalOSCore/Source/OSOperationExecutor.swift‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,4 +36,10 @@ public protocol OSOperationExecutor {
3636
func enqueueDelta(_ delta: OSDelta)
3737
func cacheDeltaQueue()
3838
func processDeltaQueue(inBackground: Bool)
39+
40+
/**
41+
Drop queued Deltas and Requests that belong to an anonymous user. Driven by `OSOperationRepo`
42+
so the policy stays there; only the storage is per-executor.
43+
*/
44+
func removeOperationsWithoutExternalId()
3945
}

‎iOS_SDK/OneSignalSDK/OneSignalOSCore/Source/OSOperationRepo.swift‎

Lines changed: 158 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -29,17 +29,26 @@ import Foundation
2929
import OneSignalCore
3030

3131
/**
32-
The OSOperationRepo is a static singleton.
33-
OSDeltas are enqueued when model store observers observe changes to their models, and sorted to their appropriate executors.
32+
Enqueues OSDeltas from model-store observers and routes them to executors.
33+
34+
Also owns Identity Verification decisions for queued work: hold flushes until `requirement` is known,
35+
and drop anonymous Deltas while IV is active — except push subscription updates, which stay unsigned
36+
and have to keep flowing with or without an identified user.
3437
*/
3538
public class OSOperationRepo: NSObject {
36-
public static let sharedInstance = OSOperationRepo()
37-
private var hasCalledStart = false
39+
private let identityVerificationService: OSIdentityVerificationService
40+
41+
/**
42+
Serial, and the only place `deltaQueue`, the executor registry, and the two start flags may be
43+
touched once this instance is handed out — `init` runs before anything else can reach it. Every
44+
private method here assumes it is already running on this queue.
45+
Non-private so test helpers can synchronize with it.
46+
*/
47+
let dispatchQueue = DispatchQueue(label: "OneSignal.OSOperationRepo", target: .global())
3848

39-
// The Operation Repo dispatch queue, serial. This synchronizes access to `deltaQueue` and flushing behavior.
40-
private let dispatchQueue = DispatchQueue(label: "OneSignal.OSOperationRepo", target: .global())
49+
private var hasCalledStart = false
50+
private var hasBegunObserving = false
4151

42-
// Maps delta names to the interfaces for the operation executors
4352
var deltasToExecutorMap: [String: OSOperationExecutor] = [:]
4453
var executors: [OSOperationExecutor] = []
4554
var deltaQueue: [OSDelta] = [] // non-private for unit test access
@@ -48,35 +57,96 @@ public class OSOperationRepo: NSObject {
4857
var pollIntervalMilliseconds = Int(POLL_INTERVAL_MS)
4958
public var paused = false
5059

60+
// Uncache in init so an enqueue before start cannot persist over a previous session's queue.
61+
public init(identityVerificationService: OSIdentityVerificationService) {
62+
self.identityVerificationService = identityVerificationService
63+
super.init()
64+
uncacheDeltaQueue()
65+
}
66+
5167
/**
52-
Initilize this Operation Repo. Read from the cache. Executors may not be available by this time.
53-
If everything starts up on initialize(), order can matter, ideally not but it can.
54-
Likely call init on this from oneSignal but exeuctors can come from diff modules.
68+
Re-reads the cache while the in-memory queue is still empty. `init` can run during prewarm before
69+
first unlock, when UserDefaults silently returns nothing — same gap as `OSModelStore.refresh`.
5570
*/
71+
public func refreshIfEmpty() {
72+
dispatchQueue.async {
73+
guard self.deltaQueue.isEmpty else {
74+
return
75+
}
76+
self.uncacheDeltaQueue()
77+
}
78+
}
79+
80+
private func uncacheDeltaQueue() {
81+
guard let cached = OneSignalUserDefaults.initShared().getSavedCodeableData(forKey: OS_OPERATION_REPO_DELTA_QUEUE_KEY, defaultValue: []) as? [OSDelta] else {
82+
OneSignalLog.onesignalLog(.LL_ERROR, message: "OSOperationRepo is unable to uncache the OSDelta queue.")
83+
return
84+
}
85+
deltaQueue = cached
86+
OneSignalLog.onesignalLog(.LL_VERBOSE, message: "OSOperationRepo uncached deltaQueue: \(cached)")
87+
}
88+
5689
public func start() {
5790
guard !OneSignalConfig.shouldAwaitAppIdAndLogMissingPrivacyConsent(forMethod: nil) else {
5891
return
5992
}
93+
dispatchQueue.async {
94+
self.startPolling()
95+
}
96+
}
97+
98+
/**
99+
While `requirement` is unknown, returns without setting `hasCalledStart` so hydration can call
100+
`start()` again once remote params answer.
101+
*/
102+
private func startPolling() {
60103
guard !hasCalledStart else {
61104
return
62105
}
106+
107+
beginObserving()
108+
109+
guard identityVerificationService.requirement != .unknown else {
110+
OneSignalLog.onesignalLog(.LL_DEBUG, message: "OSOperationRepo.start() deferred until the Identity Verification requirement is known")
111+
return
112+
}
63113
hasCalledStart = true
64114

65115
OneSignalLog.onesignalLog(.LL_VERBOSE, message: "OSOperationRepo calling start()")
66-
// register as user observer
116+
pollFlushQueue()
117+
}
118+
119+
// Subscribe ahead of the requirement gate so a never-hydrated session still hears late hydration.
120+
private func beginObserving() {
121+
guard !hasBegunObserving else {
122+
return
123+
}
124+
hasBegunObserving = true
125+
67126
NotificationCenter.default.addObserver(self,
68127
selector: #selector(self.addFlushDeltaQueueToDispatchQueue),
69128
name: Notification.Name(OS_ON_USER_WILL_CHANGE),
70129
object: nil)
71-
// Read the Deltas from cache, if any...
72-
if let deltaQueue = OneSignalUserDefaults.initShared().getSavedCodeableData(forKey: OS_OPERATION_REPO_DELTA_QUEUE_KEY, defaultValue: []) as? [OSDelta] {
73-
self.deltaQueue = deltaQueue
74-
OneSignalLog.onesignalLog(.LL_VERBOSE, message: "OSOperationRepo.start() with deltaQueue: \(deltaQueue)")
75-
} else {
76-
OneSignalLog.onesignalLog(.LL_ERROR, message: "OSOperationRepo.start() is unable to uncache the OSDelta queue.")
130+
131+
// Callback rather than a repo dependency, which would cycle.
132+
identityVerificationService.addOnJwtConfigHydratedHandler(for: .operationRepo) { [weak self] _ in
133+
self?.onJwtConfigHydrated()
77134
}
135+
}
78136

79-
pollFlushQueue()
137+
/**
138+
Runs on every hydration, including an unchanged value — deferred work is waiting on it.
139+
140+
Hop onto `dispatchQueue`: `hydrate` calls this from whichever thread received remote params, and a
141+
handler registered when the requirement is already cached fires synchronously from inside
142+
`startPolling()`, where the hop defers this until that call finishes.
143+
*/
144+
private func onJwtConfigHydrated() {
145+
dispatchQueue.async {
146+
// Flush now rather than wait out a poll interval for work held since launch.
147+
self.startPolling()
148+
self.flushDeltaQueue()
149+
}
80150
}
81151

82152
private func pollFlushQueue() {
@@ -87,36 +157,46 @@ public class OSOperationRepo: NSObject {
87157
}
88158

89159
/**
90-
Add and start an executor.
160+
Registers before starting rather than after: once remote params are cached, `startPolling()` fires
161+
the hydration handler synchronously and that flush reads the registry being written here.
91162
*/
92163
public func addExecutor(_ executor: OSOperationExecutor) {
93164
guard !OneSignalConfig.shouldAwaitAppIdAndLogMissingPrivacyConsent(forMethod: nil) else {
94165
return
95166
}
96-
start()
97-
executors.append(executor)
98-
for delta in executor.supportedDeltas {
99-
deltasToExecutorMap[delta] = executor
167+
dispatchQueue.async {
168+
self.executors.append(executor)
169+
for delta in executor.supportedDeltas {
170+
self.deltasToExecutorMap[delta] = executor
171+
}
172+
self.startPolling()
100173
}
101174
}
102175

103176
/**
104177
Enqueueing is driven by model changes and called manually by the User Manager to
105178
add session time, session count and purchase data.
106-
179+
107180
// TODO: We can make this method internal once there is no manual adding of a Delta except through stores.
108181
This can happen when session data and purchase data use the model / store / listener infrastructure.
109182
*/
110183
public func enqueueDelta(_ delta: OSDelta, flush: Bool = false) {
111184
guard !OneSignalConfig.shouldAwaitAppIdAndLogMissingPrivacyConsent(forMethod: nil) else {
112185
return
113186
}
114-
start()
187+
115188
self.dispatchQueue.async {
189+
self.startPolling()
190+
191+
// Drop here too so it is never persisted; flush still covers deltas restored from cache.
192+
guard !self.shouldDropAnonymousDelta(delta, ivActive: self.shouldDropAnonymousDeltas) else {
193+
OneSignalLog.onesignalLog(.LL_DEBUG, message: "OSOperationRepo dropping anonymous Delta, Identity Verification is required: \(delta)")
194+
return
195+
}
196+
116197
OneSignalLog.onesignalLog(.LL_VERBOSE, message: "OSOperationRepo enqueueDelta: \(delta)")
117198
self.deltaQueue.append(delta)
118199

119-
// Persist the deltas (including new delta) to storage
120200
OneSignalUserDefaults.initShared().saveCodeableData(forKey: OS_OPERATION_REPO_DELTA_QUEUE_KEY, withValue: self.deltaQueue)
121201

122202
if flush {
@@ -137,6 +217,26 @@ public class OSOperationRepo: NSObject {
137217
}
138218
}
139219

220+
/// An anonymous Delta can never be signed, so drop it while Identity Verification is active.
221+
private var shouldDropAnonymousDeltas: Bool {
222+
return identityVerificationService.ivBehaviorActive
223+
}
224+
225+
/**
226+
`OS_UPDATE_SUBSCRIPTION_DELTA` is exempt. In practice it is only ever the device's own push
227+
subscription — nothing updates an email or SMS subscription model — and that channel exists before
228+
any login and outlives every logout, so its token and device state have to keep flowing whether or
229+
not a user is identified. Its endpoint is addressed by subscription ID and takes no user JWT.
230+
231+
That leaves the exemption resting on the invariant that email and SMS subscriptions are only ever
232+
added and removed, never updated. Should an update path for them appear, this has to narrow to the
233+
push type, which the repo cannot see from here: `OSSubscriptionModel` lives in OneSignalUser, so
234+
the Delta would have to carry the distinction the way it carries `externalId`.
235+
*/
236+
private func shouldDropAnonymousDelta(_ delta: OSDelta, ivActive: Bool) -> Bool {
237+
return ivActive && delta.externalId == nil && delta.name != OS_UPDATE_SUBSCRIPTION_DELTA
238+
}
239+
140240
private func flushDeltaQueue(inBackground: Bool = false) {
141241
guard !paused else {
142242
OneSignalLog.onesignalLog(.LL_DEBUG, message: "OSOperationRepo not flushing queue due to being paused")
@@ -147,29 +247,55 @@ public class OSOperationRepo: NSObject {
147247
return
148248
}
149249

250+
// Before the requirement gate so a first flush still registers the hydration handler.
251+
self.startPolling()
252+
253+
/*
254+
Hold until `requirement` is known. `newCodePathsRun` / `ivBehaviorActive` both read false while
255+
it is unknown.
256+
*/
257+
guard identityVerificationService.requirement != .unknown else {
258+
let heldCount = self.deltaQueue.count
259+
if heldCount > 0 {
260+
OneSignalLog.onesignalLog(.LL_DEBUG, message: "OSOperationRepo holding \(heldCount) Deltas until the requirement is known")
261+
}
262+
return
263+
}
264+
150265
if inBackground {
151266
OSBackgroundTaskManager.beginBackgroundTask(OPERATION_REPO_BACKGROUND_TASK)
152267
}
153268

154-
self.start()
155-
156269
if !self.deltaQueue.isEmpty {
157270
OneSignalLog.onesignalLog(.LL_VERBOSE, message: "OSOperationRepo flushDeltaQueue in background: \(inBackground) with queue: \(self.deltaQueue)")
158271
}
159272

273+
// Snapshot once so every Delta in this pass sees the same gate values.
274+
let dropAnonymous = shouldDropAnonymousDeltas
275+
160276
var unmatched: [OSDelta] = []
161277
for delta in self.deltaQueue {
162-
if let executor = self.deltasToExecutorMap[delta.name] {
278+
if shouldDropAnonymousDelta(delta, ivActive: dropAnonymous) {
279+
OneSignalLog.onesignalLog(.LL_DEBUG, message: "OSOperationRepo dropping anonymous Delta, Identity Verification is required: \(delta)")
280+
} else if let executor = self.deltasToExecutorMap[delta.name] {
163281
executor.enqueueDelta(delta)
164282
} else {
165283
// Keep if no executor matches yet (module may not have started).
166284
unmatched.append(delta)
167285
}
168286
}
169-
self.deltaQueue = unmatched
287+
// Persist only when the queue changed: a no-op write before `refreshIfEmpty` can clobber a
288+
// cache that prewarm failed to read.
289+
if unmatched.count != self.deltaQueue.count {
290+
self.deltaQueue = unmatched
291+
OneSignalUserDefaults.initShared().saveCodeableData(forKey: OS_OPERATION_REPO_DELTA_QUEUE_KEY, withValue: self.deltaQueue)
292+
}
170293

171-
// Persist the deltas (including removed deltas) to storage after they are divvy'd up to executors.
172-
OneSignalUserDefaults.initShared().saveCodeableData(forKey: OS_OPERATION_REPO_DELTA_QUEUE_KEY, withValue: self.deltaQueue)
294+
if dropAnonymous {
295+
for executor in self.executors {
296+
executor.removeOperationsWithoutExternalId()
297+
}
298+
}
173299

174300
for executor in self.executors {
175301
executor.cacheDeltaQueue()

0 commit comments

Comments
 (0)