-
Notifications
You must be signed in to change notification settings - Fork 264
wip #1668
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
Open
nan-li
wants to merge
10
commits into
nan/identifier-accessors
Choose a base branch
from
nan/sdk-4725-v2
base: nan/identifier-accessors
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
wip #1668
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
d589e34
wip
nan-li 309da62
asdf
nan-li ae07b4e
fddsgdgsdg
nan-li 2c9b980
wip
nan-li fa929fd
add tests
nan-li ff7567b
checking
nan-li b4c2d8f
asfdafasfdasfd
nan-li 2e86852
asdfsdf
nan-li fbf6e27
fasdafdsf
nan-li 50e82b2
init
nan-li File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
164 changes: 164 additions & 0 deletions
164
iOS_SDK/OneSignalSDK/OneSignalOSCore/Source/OSResilientStorage.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,164 @@ | ||
| /* | ||
| 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 | ||
|
|
||
| /// File-backed mirror of OneSignal SDK identifiers, written with `NSFileProtectionNone` | ||
| /// so it's readable before first unlock, when shared `UserDefaults` reads silently return nil. | ||
| /// | ||
| /// Stored in the App Group container, so it's shared across any targets (main app, NSE, etc.) | ||
| /// configured with the same App Group entitlement. Opaque identifiers only: no PII or credentials. | ||
| @objc(OSResilientStorage) | ||
| public final class OSResilientStorage: NSObject { | ||
|
|
||
| // MARK: - Public key constants | ||
|
|
||
| @objc public static let keyAppId = "app_id" | ||
| @objc public static let keySubscriptionId = "subscription_id" | ||
| /// Needed because the NSE reads this flag from shared UserDefaults while the device may be locked | ||
| /// and the read silently returns the default (NO). Stored as "1" / "0". | ||
| @objc public static let keyReceiveReceiptsEnabled = "receive_receipts_enabled" | ||
| /// Set to `"1"` once `OneSignalUserManagerImpl.start()` has completed on this device at least once. | ||
| /// Used by the main app's protected-data seed to distinguish "fresh install" from | ||
| /// "prior session exists but UserDefaults isn't readable yet (iOS prewarm before first | ||
| /// unlock)". Cleared on app-id change so a new app's first launch behaves like a fresh install. | ||
| @objc public static let keyDidStart = "did_start" | ||
|
|
||
| // MARK: - Internal | ||
|
|
||
| private static let fileName = "onesignal_identity.json" | ||
|
|
||
| /// Serial queue used to serialize all file reads/writes. | ||
| private static let queue = DispatchQueue(label: "com.onesignal.resilient-storage") | ||
|
|
||
| /// Resolve a writable container URL. App Group container is preferred so | ||
| /// the NSE can read the same file. Falls back to the app's private | ||
| /// Application Support directory when no App Group is entitled. | ||
| private static func fileURL() -> URL? { | ||
| let fm = FileManager.default | ||
|
|
||
| let groupName = OneSignalUserDefaults.appGroupName() | ||
| if let container = fm.containerURL(forSecurityApplicationGroupIdentifier: groupName) { | ||
| return container.appendingPathComponent(fileName) | ||
| } | ||
|
|
||
| do { | ||
| let support = try fm.url( | ||
| for: .applicationSupportDirectory, | ||
| in: .userDomainMask, | ||
| appropriateFor: nil, | ||
| create: true | ||
| ) | ||
| return support.appendingPathComponent(fileName) | ||
| } catch { | ||
| OneSignalLog.onesignalLog(.LL_ERROR, message: "OSResilientStorage could not resolve a container URL: \(error)") | ||
| return nil | ||
| } | ||
| } | ||
|
|
||
| /// Reads the cache file. Caller is responsible for queue-serialization. | ||
| /// Returns an empty dict if the file is missing or unreadable. | ||
| private static func loadUnsafe() -> [String: String] { | ||
| guard let url = fileURL() else { return [:] } | ||
| guard FileManager.default.fileExists(atPath: url.path) else { return [:] } | ||
|
|
||
| do { | ||
| let data = try Data(contentsOf: url) | ||
| if data.isEmpty { return [:] } | ||
| let object = try JSONSerialization.jsonObject(with: data, options: []) | ||
| return (object as? [String: String]) ?? [:] | ||
| } catch { | ||
| OneSignalLog.onesignalLog(.LL_WARN, message: "OSResilientStorage could not read file: \(error)") | ||
| return [:] | ||
| } | ||
| } | ||
|
|
||
| /// Writes the cache file atomically with `.none` file protection. | ||
| /// Caller is responsible for queue-serialization. | ||
| private static func writeUnsafe(_ contents: [String: String]) { | ||
| guard let url = fileURL() else { return } | ||
|
|
||
| do { | ||
| let data = try JSONSerialization.data(withJSONObject: contents, options: []) | ||
| try data.write(to: url, options: [.atomic, .noFileProtection]) | ||
|
|
||
| // Explicitly re-apply protection class. The atomic write performs a rename which | ||
| // has been observed to reset attributes on some iOS versions. | ||
| try FileManager.default.setAttributes( | ||
| [.protectionKey: FileProtectionType.none], | ||
| ofItemAtPath: url.path | ||
| ) | ||
| } catch { | ||
| OneSignalLog.onesignalLog(.LL_ERROR, message: "OSResilientStorage write failed: \(error)") | ||
| } | ||
| } | ||
|
|
||
| // MARK: - Public API | ||
|
|
||
| /// Returns the full current contents of the cache. Empty dict if absent. | ||
| @objc public static func snapshot() -> [String: String] { | ||
| return queue.sync { loadUnsafe() } | ||
| } | ||
|
|
||
| /// Reads a single value. Returns nil when missing or unreadable. | ||
| @objc public static func string(forKey key: String) -> String? { | ||
| let dict = snapshot() | ||
| guard let value = dict[key], !value.isEmpty else { return nil } | ||
| return value | ||
| } | ||
|
|
||
| /// Atomically updates a single value. Passing nil or an empty string removes the key. | ||
| @objc public static func setString(_ value: String?, forKey key: String) { | ||
| queue.async { | ||
| var current = loadUnsafe() | ||
| if let value = value, !value.isEmpty { | ||
| current[key] = value | ||
| } else { | ||
| current.removeValue(forKey: key) | ||
| } | ||
| writeUnsafe(current) | ||
| } | ||
| } | ||
|
|
||
| /// Atomically updates multiple values, preserving keys not in `values`. | ||
| /// An empty-string value removes the corresponding key. | ||
| @objc public static func setStrings(_ values: [String: String]) { | ||
| guard !values.isEmpty else { return } | ||
| queue.async { | ||
| var current = loadUnsafe() | ||
| for (key, value) in values { | ||
| if value.isEmpty { | ||
| current.removeValue(forKey: key) | ||
| } else { | ||
| current[key] = value | ||
| } | ||
| } | ||
| writeUnsafe(current) | ||
| } | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🟡 🟡 Minor consistency window in
isReceiveReceiptsEnabled(OneSignalReceiveReceiptsController.m:38-46): when the server flipsIOS_RECEIVE_RECEIPTS_ENABLEfrom YES→NO indownloadIOSParamsWithAppId, the UserDefaults write is synchronous butOSResilientStorage.setStringisqueue.async— between those two writes an NSE reading the flag sees UD=NO, falls back to the cache, reads stale"1", and returns YES. The window is microseconds-to-milliseconds and the worst-case impact is one extrareceive_receiptrequest the server is free to ignore. Easy mitigation if you want it tight: write OSResilientStorage before UserDefaults at OneSignal.m:631-637 so the race direction is safe, or make this specificsetStringsynchronous.Extended reasoning...
The race. The new fallback in
isReceiveReceiptsEnabledtreats a UD value of NO as ambiguous and consultsOSResilientStorageas a tiebreaker — this is the right call for the locked-NSE case where cfprefsd returns nil underNSFileProtectionCompleteUntilFirstUserAuthentication. But UD can also legitimately be NO because the server just disabled the flag. The two storage layers are not updated atomically:OneSignalUserDefaults.saveBoolForKeyis-setBool:forKey:+synchronize— synchronous from the caller's view, and cross-process visible after cfprefsd propagation.OSResilientStorage.setString(OSResilientStorage.swift:132-142) hops to a serial queue, then does aData(contentsOf:)→ mutate → atomicdata.writecycle.Step-by-step proof of a stale YES.
OSUD_RECEIVE_RECEIPTS_ENABLED = YES, file saysreceive_receipts_enabled = "1". NSE returns YES correctly.downloadIOSParamsWithAppIdresponse.saveBoolForKey:withValue:NO. UD now says NO; cfprefsd propagates this to the NSE within microseconds.[OSResilientStorage setString:@"0" ...]. The work is enqueued on the serial queue but not yet executed — the file on disk still says"1".isReceiveReceiptsEnabledreads UD → getsNO(enabled = NO, falls through theif (enabled) return YESearly-out).OSResilientStorage.stringForKey:keyReceiveReceiptsEnabled→ file still says"1"→ returns YES.report_received, which the server has just disabled.Why existing code doesn't prevent it. The whole point of the fallback added at OneSignalReceiveReceiptsController.m:38-46 is to not trust UD's NO. So the fallback unconditionally consults the file, with no way to distinguish "UD was unreadable" from "UD was explicitly set to NO."
OSResilientStorage.setString'squeue.asyncensures the file write isn't synchronous with the UD write that just preceded it — there is no barrier between the two stores.Why this is a nit, not a blocker. The refutation captures it well and I agree:
report_receivedrequest per occurrence — server-idempotent, no data corruption, no user-visible effect, no security implication. The server is the authoritative source and will reject the receipt if it cares.Cheap mitigation if you want a clean story. Reverse the write order in
downloadIOSParamsWithAppIdso the cache is updated before UD — then the race direction becomes "UD still says YES, file already says 0" → the early-return at line 40 still hits and the fallback isn't consulted, so the stale read can't manifest. Or, only for this one key, dispatch theOSResilientStoragewrite viaqueue.sync. Either is a one-line change and neither affects the locked-NSE fix.Not a merge blocker.