-
Notifications
You must be signed in to change notification settings - Fork 265
feat: [JWT-4] identity model JWT, the JWT repo, and the public API #1709
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: nan/jwt-pr3-iv-gate
Are you sure you want to change the base?
Changes from all commits
bbb8151
e5ca7ee
ccefb84
7b27c60
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Large diffs are not rendered by default.
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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 | ||
|
|
||
|
|
@@ -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) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This archives the live bearer into shared UserDefaults with identity and request caches. Pre-IV the token was not on that path. I would not persist the live bearer at all. Memory-only for the real token; persist only the invalid sentinel if you need that across launch so a fresh session can ask again ( Extra footgun: Update Subscription archives a full |
||
| } | ||
| } | ||
|
|
||
|
|
@@ -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 | ||
|
|
@@ -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 = [:] | ||
| } | ||
| } | ||
|
|
@@ -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 { | ||
|
|
||
| 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) | ||
| } |
| 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) | ||
|
nan-li marked this conversation as resolved.
|
||
| } | ||
| } | ||
Uh oh!
There was an error while loading. Please reload this page.