Add support for multiple Valets within the same access group (#297)
Fix warning about missing global source in Gemfile
Commit Xcode-generated changes
These changes happened automatically as a result of using a newer Xcode version
- Add support for multiple Valets within the same access group
Previously, the shared access group identifier was used for both the access group itself, as well as the uniqueness identifier for the given Valet. This adds an optional additional
identifier
parameter that can be specified when creating a shared access group Valet. The identifier adds an additional element of uniqueness, so two Valets with the same shared access group can exist, and their data will not overlap, so long as they have different identifiers.The default for this value is
nil
, which keeps the existing behavior for full backward compatibility.
- Bump version to 4.2.0
Co-authored-by: Dan Federman dfed@me.com
Valet
Valet lets you securely store data in the iOS, tvOS, watchOS, or macOS Keychain without knowing a thing about how the Keychain works. It’s easy. We promise.
Getting Started
CocoaPods
Install with CocoaPods by adding the following to your
Podfile
:on iOS:
on tvOS:
on watchOS:
on macOS:
Carthage
Install with Carthage by adding the following to your
Cartfile
:Run
carthage
to build the framework and drag the builtValet.framework
into your Xcode project.Swift Package Manager
Install with Swift Package Manager by adding the following to your
Package.swift
:Submodules
Or manually checkout the submodule with
git submodule add git@github.com:Square/Valet.git
, drag Valet.xcodeproj to your project, and add Valet as a build dependency.Usage
Prefer to learn via watching a video? Check out this video tutorial.
Basic Initialization
To begin storing data securely using Valet, you need to create a Valet instance with:
Identifier
wrapper class to enforce the non-empty constraint.This
myValet
instance can be used to store and retrieve data securely on this device, but only when the device is unlocked.Choosing the Best Identifier
The identifier you choose for your Valet is used to create a sandbox for the data your Valet writes to the keychain. Two Valets of the same type created via the same initializer, accessibility value, and identifier will be able to read and write the same key:value pairs; Valets with different identifiers each have their own sandbox. Choose an identifier that describes the kind of data your Valet will protect. You do not need to include your application name or bundle identifier in your Valet’s identifier.
Choosing a User-friendly Identifier on macOS
Mac apps signed with a developer ID may see their Valet’s identifier shown to their users. ⚠️⚠️ While it is possible to explicitly set a user-friendly identifier, note that doing so bypasses this project’s guarantee that one Valet type will not have access to one another type’s key:value pairs ⚠️⚠️. To maintain this guarantee, ensure that each Valet’s identifier is globally unique.
Choosing the Best Accessibility Value
The Accessibility enum is used to determine when your secrets can be accessed. It’s a good idea to use the strictest accessibility possible that will allow your app to function. For example, if your app does not run in the background you will want to ensure the secrets can only be read when the phone is unlocked by using
.whenUnlocked
or.whenUnlockedThisDeviceOnly
.Changing an Accessibility Value After Persisting Data
The Valet type, identifier, accessibility value, and initializer chosen to create a Valet are combined to create a sandbox within the keychain. This behavior ensures that different Valets can not read or write one another’s key:value pairs. If you change a Valet’s accessibility after persisting key:value pairs, you must migrate the key:value pairs from the Valet with the no-longer-desired accessibility to the Valet with the desired accessibility to avoid data loss.
Reading and Writing
In addition to allowing the storage of strings, Valet allows the storage of
Data
objects viasetObject(_ object: Data, forKey key: Key)
andobject(forKey key: String)
. Valets created with a different class type, via a different initializer, or with a different accessibility attribute will not be able to read or modify values inmyValet
.Sharing Secrets Among Multiple Applications Using a Keychain Sharing Entitlement
This instance can be used to store and retrieve data securely across any app written by the same developer that has
AppID12345.Druidia
(or$(AppIdentifierPrefix)Druidia
) set as a value for thekeychain-access-groups
key in the app’sEntitlements
, whereAppID12345
is the application’s App ID prefix. This Valet is accessible when the device is unlocked. Note thatmyValet
andmySharedValet
can not read or modify one another’s values because the two Valets were created with different initializers. All Valet types can share secrets across applications written by the same developer by using thesharedGroupValet
initializer.Sharing Secrets Among Multiple Applications Using an App Groups Entitlement
This instance can be used to store and retrieve data securely across any app written by the same developer that has
group.Druidia
set as a value for thecom.apple.security.application-groups
key in the app’sEntitlements
. This Valet is accessible when the device is unlocked. Note thatmyValet
andmySharedValet
cannot read or modify one another’s values because the two Valets were created with different initializers. All Valet types can share secrets across applications written by the same developer by using thesharedGroupValet
initializer. Note that on macOS, thegroupPrefix
must be the App ID prefix.As with Valets, shared iCloud Valets can be created with an additional identifier, allowing multiple independently sandboxed keychains to exist within the same shared group.
Sharing Secrets Across Devices with iCloud
This instance can be used to store and retrieve data that can be retrieved by this app on other devices logged into the same iCloud account with iCloud Keychain enabled. If iCloud Keychain is not enabled on this device, secrets can still be read and written, but will not sync to other devices. Note that
myCloudValet
can not read or modify values in eithermyValet
ormySharedValet
becausemyCloudValet
was created a different initializer.Shared iCloud Valets can be created with an additional identifier, allowing multiple independently sandboxed keychains to exist within the same iCloud shared group.
Protecting Secrets with Face ID, Touch ID, or device Passcode
This instance can be used to store and retrieve data in the Secure Enclave. Each time data is retrieved from this Valet, the user will be prompted to confirm their presence via Face ID, Touch ID, or by entering their device passcode. If no passcode is set on the device, this instance will be unable to access or store data. Data is removed from the Secure Enclave when the user removes a passcode from the device. Storing data using
SecureEnclaveValet
is the most secure way to store data on iOS, tvOS, watchOS, and macOS.This instance also stores and retrieves data in the Secure Enclave, but does not require the user to confirm their presence each time data is retrieved. Instead, the user will be prompted to confirm their presence only on the first data retrieval. A
SinglePromptSecureEnclaveValet
instance can be forced to prompt the user on the next data retrieval by calling the instance methodrequirePromptOnNextAccess()
.In order for your customers not to receive a prompt that your app does not yet support Face ID, you must set a value for the Privacy - Face ID Usage Description (NSFaceIDUsageDescription) key in your app’s Info.plist.
Thread Safety
Valet is built to be thread safe: it is possible to use a Valet instance on any queue or thread. Valet instances ensure that code that talks to the Keychain is atomic – it is impossible to corrupt data in Valet by reading and writing on multiple queues simultaneously.
However, because the Keychain is effectively disk storage, there is no guarantee that reading and writing items is fast - accessing a Valet instance from the main queue can result in choppy animations or blocked UI. As a result, we recommend utilizing your Valet instance on a background queue; treat Valet like you treat other code that reads from and writes to disk.
Migrating Existing Keychain Values into Valet
Already using the Keychain and no longer want to maintain your own Keychain code? We feel you. That’s why we wrote
migrateObjects(matching query: [String : AnyHashable], removeOnCompletion: Bool)
. This method allows you to migrate all your existing Keychain entries to a Valet instance in one line. Just pass in a Dictionary with thekSecClass
,kSecAttrService
, and any otherkSecAttr*
attributes you use – we’ll migrate the data for you. If you need more control over how your data is migrated, usemigrateObjects(matching query: [String : AnyHashable], compactMap: (MigratableKeyValuePair<AnyHashable>) throws -> MigratableKeyValuePair<String>?)
to filter or remap key:value pairs as part of your migration.Integrating Valet into a macOS application
Your macOS application must have the Keychain Sharing entitlement in order to use Valet, even if your application does not intend to share keychain data between applications. For instructions on how to add a Keychain Sharing entitlement to your application, read Apple’s documentation on the subject. For more information on why this requirement exists, see issue #213.
If your macOS application supports macOS 10.14 or prior, you must run
myValet.migrateObjectsFromPreCatalina()
before reading values from a Valet. macOS Catalina introduced a breaking change to the macOS keychain, requiring that macOS keychain items that utilizekSecAttrAccessible
orkSecAttrAccessGroup
setkSecUseDataProtectionKeychain
totrue
when writing or accessing these items. Valet’smigrateObjectsFromPreCatalina()
upgrades items entered into the keychain on older macOS devices or other operating systems to include the key:value pairkSecUseDataProtectionKeychain:true
. Note that Valets that share keychain items between devices with iCloud are exempt from this requirement. Similarly,SecureEnclaveValet
andSinglePromptSecureEnclaveValet
are exempt from this requirement.Debugging
Valet guarantees that reading and writing operations will succeed as long as written data is valid and
canAccessKeychain()
returnstrue
. There are only a few cases that can lead to the keychain being inaccessible:Accessibility
for your use case. Examples of improper use include using.whenPasscodeSetThisDeviceOnly
when there is no passcode set on the device, or using.whenUnlocked
when running in the background.SecureEnclaveValet
on an iOS device that doesn’t have a Secure Enclave. The Secure Enclave was introduced with the A7 chip, which first appeared in the iPhone 5S, iPad Air, and iPad Mini 2.Requirements
Migrating from prior Valet versions
The good news: most Valet configurations do not have to migrate keychain data when upgrading from an older version of Valet. All Valet objects are backwards compatible with their counterparts from prior versions. We have exhaustive unit tests to prove it (search for
test_backwardsCompatibility
). Valets that have had their configurations deprecated by Apple will need to migrate stored data.The bad news: there are multiple source-breaking API changes from prior versions.
Both guides below explain the changes required to upgrade to Valet 4.
Migrating from Valet 2
VALSynchronizableValet
(which allowed keychains to be synced to iCloud) has been replaced by aValet.iCloudValet(with:accessibility:)
(or+[VALValet iCloudValetWithIdentifier:accessibility:]
in Objective-C). See examples above.VALAccessControl
has been renamed toSecureEnclaveAccessControl
(VALSecureEnclaveAccessControl
in Objective-C). This enum no longer referencesTouchID
; instead it refers to unlocking withbiometric
due to the introduction of Face ID.Valet
,SecureEnclaveValet
, andSinglePromptSecureEnclaveValet
are no longer in the same inheritance tree. All three now inherit directly fromNSObject
and use composition to share code. If you were relying on the subclass hierarchy before, 1) that might be a code smell 2) consider declaring a protocol for the shared behavior you were expecting to make your migration to Valet 3 easier.You’ll also need to continue reading through the migration from Valet 3 section below.
Migrating from Valet 3
always
andalwaysThisDeviceOnly
have been removed from Valet, because Apple has deprecated their counterparts (see the documentation for kSecAttrAccessibleAlways and kSecAttrAccessibleAlwaysThisDeviceOnly). To migrate values stored withalways
accessibility, use the methodmigrateObjectsFromAlwaysAccessibleValet(removeOnCompletion:)
on a Valet with your new preferred accessibility. To migrate values stored withalwaysThisDeviceOnly
accessibility, use the methodmigrateObjectsFromAlwaysAccessibleThisDeviceOnlyValet(removeOnCompletion:)
on a Valet with your new preferred accessibility.Bool
values have been migrated to returning a nonoptional and throwing if an error is encountered. Ignoring the error that can be thrown by each API will keep your code flow behaving the same as it did before. Walking through one example: in Swift,let secret: String? = myValet.string(forKey: myKey)
becomeslet secret: String? = try? myValet.string(forKey: myKey)
. In Objective-C,NSString *const secret = [myValet stringForKey:myKey];
becomesNSString *const secret = [myValet stringForKey:myKey error:nil];
. If you’re interested in the reason data wasn’t returned, use a do-catch statement in Swift, or pass in anNSError
to each API call and inspect the output in Objective-C. Each method clearly documents theError
type it canthrow
. See examples above.SharedGroupIdentifier(appIDPrefix:nonEmptyGroup:)
. See examples above.Contributing
We’re glad you’re interested in Valet, and we’d love to see where you take it. Please read our contributing guidelines prior to submitting a Pull Request.
Thanks, and please do take it for a joyride!