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
32 changes: 32 additions & 0 deletions iOS_SDK/OneSignalSDK/OneSignal.xcodeproj/project.pbxproj

Large diffs are not rendered by default.

10 changes: 10 additions & 0 deletions iOS_SDK/OneSignalSDK/OneSignalOSCoreMocks/OSCoreMocks.swift
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,16 @@ public class OSCoreMocks: NSObject {
public static func resetOperationRepo() {
OSOperationRepo.sharedInstance.reset()
}

/// Puts the shared JWT config back to unhydrated.
public static func resetSharedJwtConfig() {
OSUserJwtConfig.shared.resetRequirementToUnknownForTests()
}

/// Hydrates the shared JWT config. Non-IV tests hydrate `false` so the Operation Repo will flush.
public static func hydrateSharedJwtConfig(requiresUserAuth: Bool) {
OSUserJwtConfig.shared.hydrate(requiresUserAuth: requiresUserAuth)
}
}

extension OSOperationRepo {
Expand Down
79 changes: 65 additions & 14 deletions iOS_SDK/OneSignalSDK/OneSignalUser/Source/OSIdentityModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -38,12 +38,55 @@ class OSIdentityModel: OSModel {
return internalGetAlias(OS_EXTERNAL_ID)
}

// All access to aliases should go through helper methods with locking
// All access to aliases and the JWT bearer token must go through the lock
var aliases: [String: String] = [:]
private let aliasesLock = NSRecursiveLock()
private let lock = NSRecursiveLock()

// TODO: We need to make this token secure
public var jwtBearerToken: String?
// MARK: - JWT

private var jwtBearerTokenLocked: String?
public var jwtBearerToken: String? {
get {
lock.withLock { jwtBearerTokenLocked }
}
set {
// Notify outside the lock: the change notifier fires synchronously into listeners that
// take locks of their own.
let changed = lock.withLock {
guard newValue != jwtBearerTokenLocked else { return false }
jwtBearerTokenLocked = newValue
return true
}
if changed {
self.set(property: OS_JWT_BEARER_TOKEN, newValue: newValue, preventServerUpdate: true)
}
}
}

/// Returns the bearer token if it is valid, otherwise nil, snapshots once
func getValidJwt() -> String? {
let token = jwtBearerToken
guard let token = token, !token.isEmpty, token != OS_JWT_TOKEN_INVALID else {
return nil
}
return token
}

/// Returns `true` if the transition occurred, `false` if `rejectedToken` is no longer the stored
/// token. Comparing against the rejected token rather than the sentinel is what keeps a failure
/// response that was already in flight from parking the replacement supplied after it left.
@discardableResult
func invalidateJwtBearerToken(rejectedToken: String) -> Bool {
let changed = lock.withLock {
guard jwtBearerTokenLocked == rejectedToken else { return false }
jwtBearerTokenLocked = OS_JWT_TOKEN_INVALID
return true
}
if changed {
self.set(property: OS_JWT_BEARER_TOKEN, newValue: OS_JWT_TOKEN_INVALID, preventServerUpdate: true)
}
return changed
}

// MARK: - Initialization

Expand All @@ -54,9 +97,10 @@ class OSIdentityModel: OSModel {
}

override func encode(with coder: NSCoder) {
aliasesLock.withLock {
lock.withLock {
super.encode(with: coder)
coder.encode(aliases, forKey: "aliases")
coder.encode(jwtBearerTokenLocked, forKey: OS_JWT_BEARER_TOKEN)
Comment thread
nan-li marked this conversation as resolved.
}
}

Expand All @@ -66,19 +110,20 @@ class OSIdentityModel: OSModel {
// log error
return nil
}
self.jwtBearerTokenLocked = coder.decodeObject(forKey: OS_JWT_BEARER_TOKEN) as? String
self.aliases = aliases
}

/** Threadsafe getter for an alias */
private func internalGetAlias(_ label: String) -> String? {
aliasesLock.withLock {
lock.withLock {
return self.aliases[label]
}
}

/** Threadsafe setter or removal for aliases */
private func internalAddAliases(_ aliases: [String: String]) {
aliasesLock.withLock {
lock.withLock {
for (label, id) in aliases {
// Remove the alias if the ID field is ""
self.aliases[label] = id.isEmpty ? nil : id
Expand All @@ -91,7 +136,7 @@ class OSIdentityModel: OSModel {
Called to clear the model's data in preparation for hydration via a fetch user call.
*/
func clearData() {
aliasesLock.withLock {
lock.withLock {
self.aliases = [:]
}
}
Expand Down Expand Up @@ -120,14 +165,20 @@ class OSIdentityModel: OSModel {
let newExternalId = remoteAliases[OS_EXTERNAL_ID]

internalAddAliases(remoteAliases)
fireUserStateChanged(newOnesignalId: newOnesignalId, newExternalId: newExternalId)
OSUserStateSnapshot.fireUserStateChanged(newOnesignalId: newOnesignalId, newExternalId: newExternalId)
}
}

/**
Fires the user observer if `onesignal_id` OR `external_id` has changed from the previous snapshot (previous hydration).
*/
private func fireUserStateChanged(newOnesignalId: String?, newExternalId: String?) {
let prevOnesignalId = OneSignalUserDefaults.initShared().getSavedString(forKey: OS_SNAPSHOT_ONESIGNAL_ID, defaultValue: nil)
/**
Owns the last user state the app was told about, so the observer only hears real changes.

Hydration is the usual source, but `logout` under Identity Verification also reports here: it creates
no user on the server, so there is no hydration to carry the news that nobody is signed in.
*/
enum OSUserStateSnapshot {
/// Fires the user observer if `onesignal_id` OR `external_id` differs from the last reported pair.
static func fireUserStateChanged(newOnesignalId: String?, newExternalId: String?) {
let prevOnesignalId = OneSignalUserDefaults.initShared().getSavedString(forKey: OS_SNAPSHOT_ONESIGNAL_ID, defaultValue: nil)
let prevExternalId = OneSignalUserDefaults.initShared().getSavedString(forKey: OS_SNAPSHOT_EXTERNAL_ID, defaultValue: nil)

guard prevOnesignalId != newOnesignalId || prevExternalId != newExternalId else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
*/

import Foundation
import OneSignalCore

/**
This class stores all Identity Models that are being used during an app session.
Expand All @@ -52,4 +53,64 @@ class OSIdentityModelRepo {
return models[modelId]
}
}

func get(externalId: String) -> OSIdentityModel? {
lock.withLock {
return models.values.first { $0.externalId == externalId }
}
}

/**
Repeated logins as the same user each create an Identity Model, so update them all.
This can be optimized in the future to re-use an Identity Model if multiple logins are made for the same user.

Returns `false` if no Identity Model carries this external ID, in which case the token was not stored
anywhere and nothing can sign with it.
*/
@discardableResult
func updateJwtToken(externalId: String, token: String) -> Bool {
let matchingModels = modelsMatching(externalId: externalId)
guard !matchingModels.isEmpty else {
OneSignalLog.onesignalLog(.LL_ERROR, message: "OSIdentityModelRepo.updateJwtToken called for unknown external ID \(externalId)")
return false
}
for model in matchingModels {
model.jwtBearerToken = token
}
return true
}

/// The token this user can currently sign with, or nil if there is none.
func validJwt(externalId: String) -> String? {
return modelsMatching(externalId: externalId).lazy.compactMap { $0.getValidJwt() }.first
}

/**
Invalidates the token on every Identity Model with this external ID, since repeated logins as the
same user each create one. Only the models still holding `rejectedToken` transition, so a
replacement that landed while the rejected request was in flight survives.

Returns `false` if no Identity Model carries this external ID, in which case there was nothing
to park and nothing to tell the app about.
*/
@discardableResult
func invalidateJwtToken(externalId: String, rejectedToken: String) -> Bool {
let matchingModels = modelsMatching(externalId: externalId)
guard !matchingModels.isEmpty else {
OneSignalLog.onesignalLog(.LL_ERROR, message: "OSIdentityModelRepo.invalidateJwtToken called for unknown external ID \(externalId)")
return false
}
for model in matchingModels {
model.invalidateJwtBearerToken(rejectedToken: rejectedToken)
}
return true
}

/// Snapshot before touching the tokens: writing one fires the model's change notifier
/// synchronously into listeners that take locks of their own.
private func modelsMatching(externalId: String) -> [OSIdentityModel] {
lock.withLock {
models.values.filter { $0.externalId == externalId }
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/*
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.
*/

/**
Tells the app that the JWT it supplied for `externalId` is no longer accepted, so it should mint a
fresh one and hand it back through `OneSignal.updateUserJwt(externalId:token:)`.
*/
@objc public class OSUserJwtInvalidatedEvent: NSObject {
@objc public let externalId: String

init(externalId: String) {
self.externalId = externalId
}

@objc public func jsonRepresentation() -> NSDictionary {
return [
"externalId": externalId
]
}
}

@objc public protocol OSUserJwtInvalidatedListener {
@objc func onUserJwtInvalidated(event: OSUserJwtInvalidatedEvent)
}
128 changes: 128 additions & 0 deletions iOS_SDK/OneSignalSDK/OneSignalUser/Source/OSUserJwtRepo.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
/*
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 Foundation
import OneSignalCore

/**
Identity Verification token access, keyed by `external_id`. Executors depend on this rather than on
the User Manager so that no JWT lookup reaches for a singleton.
*/
protocol OSUserJwtProviding: AnyObject {
/// The token this user can sign with, or nil if the SDK holds none.
func validJwt(externalId: String) -> String?

/**
Asks the app for a token for `externalId`.

Returns `true` if this call is the one that asked, which happens at most once per external ID
per session so a burst of concurrent callers does not fire the event repeatedly.
*/
@discardableResult
func askForToken(externalId: String) -> Bool

/// Parks the rejected token and asks the app for a replacement. Returns `true` if this call asked.
@discardableResult
func invalidateJwt(externalId: String, rejectedToken: String) -> Bool
}

final class OSUserJwtRepo: OSUserJwtProviding {
private let identityModelRepo: OSIdentityModelRepo
private let notifyInvalidated: (String) -> Void

let lock = NSLock()
/**
External IDs the app has already been asked to re-sign.

In memory only. A model decoded at launch can already hold the invalid sentinel, leaving nothing
to transition, so a fresh session has to be able to ask again — otherwise an app that was asked
in a previous run is never told it still owes a token.
*/
var askedForToken: Set<String> = []

init(identityModelRepo: OSIdentityModelRepo, notifyInvalidated: @escaping (String) -> Void) {
self.identityModelRepo = identityModelRepo
self.notifyInvalidated = notifyInvalidated
}

func validJwt(externalId: String) -> String? {
return identityModelRepo.validJwt(externalId: externalId)
}

/**
Stores a token supplied by the app, and lets this user be asked again if it is ever rejected.
Returns `false` for a token that was not stored, so callers do not go looking for held work to release.

An unusable token is ignored rather than stored: it would replace a good token with nothing to sign
with, and clearing the ask for it would have the SDK and the app trade asks and replies on every flush.
A token for an external ID the SDK has no Identity Model for lands nowhere, so it is not treated as an
answer either.
*/
@discardableResult
func updateJwt(externalId: String, token: String) -> Bool {
guard !token.isEmpty, token != OS_JWT_TOKEN_INVALID else {
OneSignalLog.onesignalLog(.LL_ERROR, message: "OSUserJwtRepo.updateJwt ignored an unusable token for \(externalId)")
return false
}
guard identityModelRepo.updateJwtToken(externalId: externalId, token: token) else {
return false
}
lock.withLock { _ = askedForToken.remove(externalId) }
return true
}

@discardableResult
func askForToken(externalId: String) -> Bool {
guard lock.withLock({ askedForToken.insert(externalId).inserted }) else {
return false
}
notifyInvalidated(externalId)
return true
}

/// External IDs already asked this session; cleared when a usable token is stored.
func pendingTokenAsks() -> [String] {
return lock.withLock { Array(askedForToken) }
}

@discardableResult
func invalidateJwt(externalId: String, rejectedToken: String) -> Bool {
// No model for this user means the token could not have come from here. A Request stamped
// with an owner whose model was cleared for hydration lands here, and it retries once the
// aliases come back.
guard identityModelRepo.invalidateJwtToken(externalId: externalId, rejectedToken: rejectedToken) else {
return false
}
OneSignalLog.onesignalLog(.LL_DEBUG, message: "OSUserJwtRepo invalidated JWT for externalId: \(externalId)")
// A replacement that landed while the rejected Request was in flight leaves the token above
// untouched, and the retry signs with it, so there is nothing to ask the app for.
guard identityModelRepo.validJwt(externalId: externalId) == nil else {
return false
}
return askForToken(externalId: externalId)
Comment thread
nan-li marked this conversation as resolved.
}
}
Loading
Loading