generated from StanfordBDHG/SwiftPackageTemplate
-
-
Notifications
You must be signed in to change notification settings - Fork 0
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
Android alignment #25
Open
pauljohanneskraft
wants to merge
15
commits into
main
Choose a base branch
from
android-alignment
base: main
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
Changes from 10 commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
39c9377
Separate SecureStorage into CredentialStorage and KeyStorage
pauljohanneskraft ba89616
Group files
pauljohanneskraft 1b956a5
Update
pauljohanneskraft a8a9c08
lint
pauljohanneskraft 9a543d4
Keep backwards compatibility
pauljohanneskraft 49e8dd0
lint
pauljohanneskraft df1071d
lint
pauljohanneskraft 32aaa0b
Move deprecated API into its own extension
pauljohanneskraft 3a0dcbb
lint
pauljohanneskraft a6d78e8
Remove catch-all rethrowing clauses
pauljohanneskraft f2e2bd3
Update
pauljohanneskraft d964013
Make sure to keep 100% of the original interface of SpeziAccount, whi…
pauljohanneskraft 430fac2
Deprecate more types
pauljohanneskraft e922a4f
REUSE
pauljohanneskraft 3626a28
Fix
pauljohanneskraft 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
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
255 changes: 255 additions & 0 deletions
255
Sources/SpeziSecureStorage/Credentials/CredentialStorage.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,255 @@ | ||
// | ||
// This source file is part of the Stanford Spezi open-source project | ||
// | ||
// SPDX-FileCopyrightText: 2022 Stanford University and the project authors (see CONTRIBUTORS.md) | ||
// | ||
// SPDX-License-Identifier: MIT | ||
// | ||
|
||
import Foundation | ||
import Spezi | ||
|
||
public final class CredentialStorage: Module, DefaultInitializable, EnvironmentAccessible, Sendable { | ||
public required init() {} | ||
|
||
/// Stores credentials in the Keychain. | ||
/// | ||
/// ```swift | ||
/// do { | ||
/// let serverCredentials = Credentials( | ||
/// username: "user", | ||
/// password: "password" | ||
/// ) | ||
/// try secureStorage.store( | ||
/// credentials: serverCredentials, | ||
/// server: "stanford.edu", | ||
/// storageScope: .keychainSynchronizable | ||
/// ) | ||
/// | ||
/// // ... | ||
/// | ||
/// } catch { | ||
/// // Handle creation error here. | ||
/// // ... | ||
/// } | ||
/// ``` | ||
/// | ||
/// - Parameters: | ||
/// - credentials: The ``Credentials`` stored in the Keychain. | ||
/// - server: The server associated with the credentials. | ||
/// - removeDuplicate: A flag indicating if any existing key for the `username` and `server` | ||
/// combination should be overwritten when storing the credentials. | ||
/// - storageScope: The ``SecureStorageScope`` of the stored credentials. | ||
/// The ``SecureStorageScope/secureEnclave(userPresence:)`` option is not supported for credentials. | ||
public func store( | ||
_ credential: Credential, | ||
server: String? = nil, | ||
removeDuplicate: Bool = true, | ||
storageScope: SecureStorageScope = .keychain | ||
) throws { | ||
// This method uses code provided by the Apple Developer documentation at | ||
// https://developer.apple.com/documentation/security/keychain_services/keychain_items/adding_a_password_to_the_keychain. | ||
|
||
assert(!(.secureEnclave ~= storageScope), "Storing of keys in the secure enclave is not supported by Apple.") | ||
|
||
var query = queryFor(credential.username, server: server, accessGroup: storageScope.accessGroup) | ||
query[kSecValueData as String] = Data(credential.password.utf8) | ||
|
||
if case .keychainSynchronizable = storageScope { | ||
query[kSecAttrSynchronizable as String] = true | ||
} else if let accessControl = try storageScope.accessControl { | ||
query[kSecAttrAccessControl as String] = accessControl | ||
} | ||
|
||
do { | ||
try SecureStorageError.execute(SecItemAdd(query as CFDictionary, nil)) | ||
} catch let SecureStorageError.keychainError(status) where status == -25299 && removeDuplicate { | ||
try delete(credential.username, server: server) | ||
try store(credential, server: server, removeDuplicate: false) | ||
} | ||
} | ||
|
||
/// Delete existing credentials stored in the Keychain. | ||
/// | ||
/// ```swift | ||
/// do { | ||
/// try secureStorage.deleteCredentials( | ||
/// "user", | ||
/// server: "spezi.stanford.edu" | ||
/// ) | ||
/// } catch { | ||
/// // Handle deletion error here. | ||
/// // ... | ||
/// } | ||
/// ``` | ||
/// | ||
/// Use to ``deleteAllCredentials(itemTypes:accessGroup:)`` delete all existing credentials stored in the Keychain. | ||
/// | ||
/// - Parameters: | ||
/// - username: The username associated with the credentials. | ||
/// - server: The server associated with the credentials. | ||
/// - accessGroup: The access group associated with the credentials. | ||
public func delete(_ username: String, server: String? = nil, accessGroup: String? = nil) throws { | ||
let query = queryFor(username, server: server, accessGroup: accessGroup) | ||
|
||
try SecureStorageError.execute(SecItemDelete(query as CFDictionary)) | ||
} | ||
|
||
/// Delete all existing credentials stored in the Keychain. | ||
/// - Parameters: | ||
/// - itemTypes: The types of items. | ||
/// - accessGroup: The access group associated with the credentials. | ||
public func deleteAll(types itemTypes: SecureStorageItemTypes = .all, accessGroup: String? = nil) throws { | ||
for kSecClassType in itemTypes.kSecClass { | ||
do { | ||
var query: [String: Any] = [kSecClass as String: kSecClassType] | ||
// Only append the accessGroup attribute if the `CredentialsStore` is configured to use KeyChain access groups | ||
if let accessGroup { | ||
query[kSecAttrAccessGroup as String] = accessGroup | ||
} | ||
|
||
// Use Data protection keychain on macOS | ||
#if os(macOS) | ||
query[kSecUseDataProtectionKeychain as String] = true | ||
#endif | ||
|
||
try SecureStorageError.execute(SecItemDelete(query as CFDictionary)) | ||
} catch SecureStorageError.notFound { | ||
// We are fine it no keychain items have been found and therefore non had been deleted. | ||
continue | ||
} catch { | ||
print(error) | ||
} | ||
} | ||
} | ||
|
||
/// Update existing credentials found in the Keychain. | ||
/// | ||
/// ```swift | ||
/// do { | ||
/// let newCredentials = Credentials( | ||
/// username: "user", | ||
/// password: "newPassword" | ||
/// ) | ||
/// try secureStorage.updateCredentials( | ||
/// "user", | ||
/// server: "stanford.edu", | ||
/// newCredentials: newCredentials, | ||
/// newServer: "spezi.stanford.edu" | ||
/// ) | ||
/// } catch { | ||
/// // Handle update error here. | ||
/// // ... | ||
/// } | ||
/// ``` | ||
/// | ||
/// - Parameters: | ||
/// - username: The username associated with the old credentials. | ||
/// - server: The server associated with the old credentials. | ||
/// - newCredentials: The new ``Credentials`` that should be stored in the Keychain. | ||
/// - newServer: The server associated with the new credentials. | ||
/// - removeDuplicate: A flag indicating if any existing key for the `username` of the new credentials and `newServer` | ||
/// combination should be overwritten when storing the credentials. | ||
/// - storageScope: The ``SecureStorageScope`` of the newly stored credentials. | ||
public func update( // swiftlint:disable:this function_default_parameter_at_end | ||
// The server parameter belongs to the `username` and therefore should be located next to the `username`. | ||
_ username: String, | ||
server: String? = nil, | ||
newCredential: Credential, | ||
newServer: String? = nil, | ||
removeDuplicate: Bool = true, | ||
storageScope: SecureStorageScope = .keychain | ||
) throws { | ||
try delete(username, server: server) | ||
try store(newCredential, server: newServer, removeDuplicate: removeDuplicate, storageScope: storageScope) | ||
} | ||
|
||
/// Retrieve existing credentials stored in the Keychain. | ||
/// | ||
/// ```swift | ||
/// guard let serverCredentials = secureStorage.retrieveCredentials("user", server: "stanford.edu") else { | ||
/// // Handle errors here. | ||
/// } | ||
/// | ||
/// // Use the credentials | ||
/// ``` | ||
/// | ||
/// Use ``retrieveAllCredentials(forServer:accessGroup:)`` to retrieve all existing credentials stored in the Keychain for a specific server. | ||
/// | ||
/// - Parameters: | ||
/// - username: The username associated with the credentials. | ||
/// - server: The server associated with the credentials. | ||
/// - accessGroup: The access group associated with the credentials. | ||
/// - Returns: Returns the credentials stored in the Keychain identified by the `username`, `server`, and `accessGroup`. | ||
public func retrieve(_ username: String, server: String? = nil, accessGroup: String? = nil) throws -> Credential? { | ||
try retrieveAll(forServer: server, accessGroup: accessGroup) | ||
.first { $0.username == username } | ||
} | ||
|
||
/// Retrieve all existing credentials stored in the Keychain for a specific server. | ||
/// - Parameters: | ||
/// - server: The server associated with the credentials. | ||
/// - accessGroup: The access group associated with the credentials. | ||
/// - Returns: Returns all existing credentials stored in the Keychain identified by the `server` and `accessGroup`. | ||
public func retrieveAll(forServer server: String? = nil, accessGroup: String? = nil) throws -> [Credential] { | ||
// This method uses code provided by the Apple Developer documentation at | ||
// https://developer.apple.com/documentation/security/keychain_services/keychain_items/searching_for_keychain_items | ||
|
||
var query: [String: Any] = queryFor(nil, server: server, accessGroup: accessGroup) | ||
query[kSecMatchLimit as String] = kSecMatchLimitAll | ||
query[kSecReturnAttributes as String] = true | ||
query[kSecReturnData as String] = true | ||
|
||
var item: CFTypeRef? | ||
do { | ||
try SecureStorageError.execute(SecItemCopyMatching(query as CFDictionary, &item)) | ||
} catch SecureStorageError.notFound { | ||
return [] | ||
} | ||
|
||
guard let existingItems = item as? [[String: Any]] else { | ||
throw SecureStorageError.unexpectedCredentialsData | ||
} | ||
|
||
return existingItems.compactMap { existingItem in | ||
guard let passwordData = existingItem[kSecValueData as String] as? Data, | ||
let password = String(data: passwordData, encoding: String.Encoding.utf8), | ||
let account = existingItem[kSecAttrAccount as String] as? String else { | ||
return nil | ||
} | ||
|
||
return Credential(username: account, password: password) | ||
} | ||
} | ||
|
||
private func queryFor(_ account: String?, server: String?, accessGroup: String?) -> [String: Any] { | ||
// This method uses code provided by the Apple Developer documentation at | ||
// https://developer.apple.com/documentation/security/keychain_services/keychain_items/using_the_keychain_to_manage_user_secrets | ||
|
||
var query: [String: Any] = [:] | ||
if let account { | ||
query[kSecAttrAccount as String] = account | ||
} | ||
|
||
// Only append the accessGroup attribute if the `CredentialsStore` is configured to use KeyChain access groups | ||
if let accessGroup { | ||
query[kSecAttrAccessGroup as String] = accessGroup | ||
} | ||
|
||
// Use Data protection keychain on macOS | ||
#if os(macOS) | ||
query[kSecUseDataProtectionKeychain as String] = true | ||
#endif | ||
|
||
// If the user provided us with a server associated with the credentials we assume it is an internet password. | ||
if server == nil { | ||
query[kSecClass as String] = kSecClassGenericPassword | ||
} else { | ||
query[kSecClass as String] = kSecClassInternetPassword | ||
// Only append the server attribute if we assume the credentials to be an internet password. | ||
query[kSecAttrServer as String] = server | ||
} | ||
|
||
return query | ||
} | ||
} |
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.
Should we consider adding
server
parameter as well? It is not a breaking change if you initialize it with nullThere 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 would be the only change that would kind of force us to make a major-version update... Is it really worth it?
Alternatively, we could have those deprecation functions with the server-property being explicit and then we override in the deprecated function just to keep the minor version update. But what behavior should we choose there? Keeping the old struct with the slightly different name but without the server-property, always overriding the struct-property with the function parameter or doing something like
server ?? credential.server
or the other way around?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.
nevermind, changed it and deprecated SecureStorage as a whole. We now don't even have SecureStorage on Android anymore, since it isn't needed and just builds a Façade that isn't really necessary.
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.
I think that would make sense to ensure that we don't have to take a breaking change for now.
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.
But soft-deprecation is fine, right? Like I still kept the implementation of SecureStorage on iOS, but marked the whole class as deprecated. So, one can still use it as-is, but internally we are pretty much just calling the new functions instead.
Credential now has a
server
property, but if you use the deprecated functions, we internally only use the function parameter and ignore what was set in the Credential struct.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.
Exactly; that would be ideal. Once we tag a new major version we can remove all these deprecated function implementations.
Sounds like a good plan!