-
Notifications
You must be signed in to change notification settings - Fork 37
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
Subscription keychain sharing for access token #690
Merged
Merged
Changes from 12 commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
47d98a8
Add separate SubscriptionTokenStorage to store token to be shared
miasma13 d0ae789
Store and read access token from its separate storage
miasma13 34b8871
Refactor how queries are built
miasma13 e46dc51
Clean up
miasma13 a36d662
Update to SubscriptionTokenKeychainStorage to support testString
miasma13 e1ec3ba
wip
graeme 869b209
Remove test string code
graeme 8a0d458
REmove label constant etc
graeme 0255e1f
Fix bug caused by mismatch of key values
graeme dfb8bc3
Add basic migration of token
graeme 1eb0850
Move migration to dedicated public function
graeme 2fa74ad
Fix migration error throwing
graeme cf357d2
appGroup -> subscriptionAppGroup
graeme a5b3ae8
appGroup -> subscriptionAppGroup
graeme a8e8c41
Merge branch 'main' into graeme/subscription-keychain-sharing
miasma13 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 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
186 changes: 186 additions & 0 deletions
186
Sources/Subscription/AccountStorage/SubscriptionTokenKeychainStorage.swift
This file contains 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,186 @@ | ||
// | ||
// SubscriptionTokenKeychainStorage.swift | ||
// | ||
// Copyright © 2024 DuckDuckGo. All rights reserved. | ||
// | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
// | ||
|
||
import Foundation | ||
|
||
public class SubscriptionTokenKeychainStorage: SubscriptionTokenStorage { | ||
|
||
private let keychainType: KeychainType | ||
|
||
public init(keychainType: KeychainType = .dataProtection(.unspecified)) { | ||
self.keychainType = keychainType | ||
} | ||
|
||
public func getAccessToken() throws -> String? { | ||
try getString(forField: .accessToken) | ||
} | ||
|
||
public func store(accessToken: String) throws { | ||
try set(string: accessToken, forField: .accessToken) | ||
} | ||
|
||
public func removeAccessToken() throws { | ||
try deleteItem(forField: .accessToken) | ||
} | ||
} | ||
|
||
private extension SubscriptionTokenKeychainStorage { | ||
|
||
/* | ||
Uses just kSecAttrService as the primary key, since we don't want to store | ||
multiple accounts/tokens at the same time | ||
*/ | ||
enum AccountKeychainField: String, CaseIterable { | ||
case accessToken = "subscription.account.accessToken" | ||
case testString = "subscription.account.testString" | ||
|
||
var keyValue: String { | ||
"com.duckduckgo" + "." + rawValue | ||
} | ||
} | ||
|
||
func getString(forField field: AccountKeychainField) throws -> String? { | ||
guard let data = try retrieveData(forField: field) else { | ||
return nil | ||
} | ||
|
||
if let decodedString = String(data: data, encoding: String.Encoding.utf8) { | ||
return decodedString | ||
} else { | ||
throw AccountKeychainAccessError.failedToDecodeKeychainDataAsString | ||
} | ||
} | ||
func retrieveData(forField field: AccountKeychainField) throws -> Data? { | ||
var query = defaultAttributes() | ||
query[kSecAttrService] = field.keyValue | ||
query[kSecMatchLimit] = kSecMatchLimitOne | ||
query[kSecReturnData] = true | ||
|
||
var item: CFTypeRef? | ||
let status = SecItemCopyMatching(query as CFDictionary, &item) | ||
|
||
if status == errSecSuccess { | ||
if let existingItem = item as? Data { | ||
return existingItem | ||
} else { | ||
throw AccountKeychainAccessError.failedToDecodeKeychainValueAsData | ||
} | ||
} else if status == errSecItemNotFound { | ||
return nil | ||
} else { | ||
throw AccountKeychainAccessError.keychainLookupFailure(status) | ||
} | ||
} | ||
|
||
func set(string: String, forField field: AccountKeychainField) throws { | ||
guard let stringData = string.data(using: .utf8) else { | ||
return | ||
} | ||
|
||
try store(data: stringData, forField: field) | ||
} | ||
|
||
func store(data: Data, forField field: AccountKeychainField) throws { | ||
var query = defaultAttributes() | ||
query[kSecAttrService] = field.keyValue | ||
query[kSecAttrAccessible] = kSecAttrAccessibleAfterFirstUnlock | ||
query[kSecValueData] = data | ||
|
||
let status = SecItemAdd(query as CFDictionary, nil) | ||
|
||
switch status { | ||
case errSecSuccess: | ||
return | ||
case errSecDuplicateItem: | ||
let updateStatus = updateData(data, forField: field) | ||
|
||
if updateStatus != errSecSuccess { | ||
throw AccountKeychainAccessError.keychainSaveFailure(status) | ||
} | ||
default: | ||
throw AccountKeychainAccessError.keychainSaveFailure(status) | ||
} | ||
} | ||
|
||
private func updateData(_ data: Data, forField field: AccountKeychainField) -> OSStatus { | ||
var query = defaultAttributes() | ||
query[kSecAttrService] = field.keyValue | ||
|
||
let newAttributes = [ | ||
kSecValueData: data, | ||
kSecAttrAccessible: kSecAttrAccessibleAfterFirstUnlock | ||
] as [CFString: Any] | ||
|
||
return SecItemUpdate(query as CFDictionary, newAttributes as CFDictionary) | ||
} | ||
|
||
func deleteItem(forField field: AccountKeychainField, useDataProtectionKeychain: Bool = true) throws { | ||
let query = defaultAttributes() | ||
|
||
let status = SecItemDelete(query as CFDictionary) | ||
|
||
if status != errSecSuccess && status != errSecItemNotFound { | ||
throw AccountKeychainAccessError.keychainDeleteFailure(status) | ||
} | ||
} | ||
|
||
private func defaultAttributes() -> [CFString: Any] { | ||
var attributes: [CFString: Any] = [ | ||
kSecClass: kSecClassGenericPassword, | ||
kSecAttrSynchronizable: false | ||
] | ||
|
||
attributes.merge(keychainType.queryAttributes()) { $1 } | ||
|
||
return attributes | ||
} | ||
} | ||
|
||
public enum KeychainType { | ||
case dataProtection(_ accessGroup: AccessGroup) | ||
|
||
/// Uses the system keychain. | ||
/// | ||
case system | ||
|
||
case fileBased | ||
|
||
public enum AccessGroup { | ||
case unspecified | ||
case named(_ name: String) | ||
} | ||
|
||
func queryAttributes() -> [CFString: Any] { | ||
switch self { | ||
case .dataProtection(let accessGroup): | ||
switch accessGroup { | ||
case .unspecified: | ||
return [kSecUseDataProtectionKeychain: true] | ||
case .named(let accessGroup): | ||
return [ | ||
kSecUseDataProtectionKeychain: true, | ||
kSecAttrAccessGroup: accessGroup | ||
] | ||
} | ||
case .system: | ||
return [kSecUseDataProtectionKeychain: false] | ||
case .fileBased: | ||
return [kSecUseDataProtectionKeychain: false] | ||
} | ||
} | ||
} |
25 changes: 25 additions & 0 deletions
25
Sources/Subscription/AccountStorage/SubscriptionTokenStorage.swift
This file contains 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,25 @@ | ||
// | ||
// SubscriptionTokenStorage.swift | ||
// | ||
// Copyright © 2024 DuckDuckGo. All rights reserved. | ||
// | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
// | ||
|
||
import Foundation | ||
|
||
public protocol SubscriptionTokenStorage: AnyObject { | ||
func getAccessToken() throws -> String? | ||
func store(accessToken: String) throws | ||
func removeAccessToken() throws | ||
} |
This file contains 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 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 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 |
---|---|---|
|
@@ -34,15 +34,15 @@ public final class AppStoreRestoreFlow { | |
case subscriptionExpired(accountDetails: RestoredAccountDetails) | ||
} | ||
|
||
public static func restoreAccountFromPastPurchase() async -> Result<Void, AppStoreRestoreFlow.Error> { | ||
public static func restoreAccountFromPastPurchase(appGroup: String) async -> Result<Void, AppStoreRestoreFlow.Error> { | ||
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. @quanganhdo Spotted this discrepancy, the param probably should be |
||
os_log(.info, log: .subscription, "[AppStoreRestoreFlow] restoreAccountFromPastPurchase") | ||
|
||
guard let lastTransactionJWSRepresentation = await PurchaseManager.mostRecentTransaction() else { | ||
os_log(.error, log: .subscription, "[AppStoreRestoreFlow] Error: missingAccountOrTransactions") | ||
return .failure(.missingAccountOrTransactions) | ||
} | ||
|
||
let accountManager = AccountManager() | ||
let accountManager = AccountManager(appGroup: appGroup) | ||
|
||
// Do the store login to get short-lived token | ||
let authToken: String | ||
|
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.
This is no longer needed ;)
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.
Oops!