Skip to content
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

[Core] Keychain migration #1203

Merged
merged 4 commits into from
Nov 1, 2023
Merged
Changes from 1 commit
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
40 changes: 38 additions & 2 deletions Sources/WalletConnectKMS/Keychain/KeychainStorage.swift
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,8 @@ public final class KeychainStorage: KeychainStorageProtocol {
case errSecSuccess:
return item as? Data
case errSecItemNotFound:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is it the error case we are getting when app is in background?

return nil
// TODO: Replace with nil once migration period ends
return try tryMigrateAttrAccessible(key: key)
default:
throw KeychainError(status)
}
Expand Down Expand Up @@ -100,11 +101,46 @@ public final class KeychainStorage: KeychainStorageProtocol {
private func buildBaseServiceQuery(for key: String) -> [CFString: Any] {
return [
kSecClass: kSecClassGenericPassword,
kSecAttrAccessible: kSecAttrAccessibleWhenUnlockedThisDeviceOnly,
kSecAttrAccessible: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly,
kSecAttrIsInvisible: true,
kSecUseDataProtectionKeychain: true,
kSecAttrService: service,
kSecAttrAccount: key
]
}

private func tryMigrateAttrAccessible(key: String) throws -> Data? {
var query = buildBaseServiceQuery(for: key)
query[kSecReturnData] = true
query[kSecAttrAccessible] = kSecAttrAccessibleWhenUnlockedThisDeviceOnly

var item: CFTypeRef?
let status = secItem.copyMatching(query as CFDictionary, &item)

switch status {
case errSecSuccess: // Migration needed
guard let data = item as? Data else { return nil }

// Fetching old value
var deleteQuery = buildBaseServiceQuery(for: key)
deleteQuery[kSecAttrAccessible] = kSecAttrAccessibleWhenUnlockedThisDeviceOnly
Copy link
Contributor

@llbartekll llbartekll Oct 31, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if read failed for kSecAttrAccessibleWhenUnlockedThisDeviceOnly why delete won't?


// Deleting old value
let status = secItem.delete(deleteQuery as CFDictionary)

guard status == errSecSuccess || status == errSecItemNotFound else {
throw KeychainError(status)
}

// Replacing with new value
try add(data: data, forKey: key)

// Continue `readData` execution
return item as? Data
case errSecItemNotFound:
return nil
default:
throw KeychainError(status)
}
}
}