What Keychain storage covers, and what it does not
The Keychain is the operating system's encrypted credential store. An app hands over a secret and a set of attributes; the system encrypts it, stores it, and returns it only to code that matches the item's access rules. The app never manages the encryption key, never chooses a cipher, and never touches the raw database. That division of labour is why the Keychain is the default answer for API tokens, refresh tokens, licence keys, and small private blobs on Apple platforms.
Open source changes one part of the threat model and leaves the rest intact. Because the code is public, nobody should rely on hidden storage locations or obfuscated key names, since any reviewer can read where secrets are written. What stays private is the per-install key material the system holds. The useful question is therefore not whether the source is visible, but whether the visible code writes secrets where the operating system protects them, with the narrowest attributes that still work.
The Keychain is also not a vault for arbitrary data. It is designed for small secrets: a token, a password, a short key. Multi-megabyte blobs belong in a file encrypted with a key that lives in the Keychain, not in the Keychain itself.
Four decisions to settle before the first SecItemAdd
Before writing any SecItemAdd call, settle four decisions in this order: item class, accessibility class, sync behaviour, and access group. Each decision narrows the next, and none of them is visible in a review that only reads the happy path.

Item class. Generic passwords cover most app secrets: a service identifier plus an account identifier. Internet passwords are for server credentials that carry a protocol, host, and port. Cryptographic keys use SecKey for asymmetric material, while certificates and identities wrap those keys. Most open-source apps need only the generic-password class, but a signing or encryption key belongs in the key class so that the private half never leaves the secure store.
Accessibility. This attribute decides when the item can be decrypted at all. It is the single most misconfigured field in code that otherwise looks careful.
Sync. kSecAttrSynchronizable moves an item into iCloud Keychain, where the same app can read it on the user's other devices. That is right for a user's own login and wrong for a device-bound session token.
Access group. The keychain-access-groups entitlement controls which binaries may read the item. It is the mechanism behind app-to-extension sharing, and it is where ad-hoc builds and changed signing identities break in confusing ways.
Choose an accessibility class on purpose
Attribute | Readable when | Reasonable use |
|---|---|---|
kSecAttrAccessibleWhenUnlocked | Device unlocked | Interactive secrets used only while the app is in front of the user |
kSecAttrAccessibleAfterFirstUnlock | After the first unlock since boot | Refresh tokens that a background task may need |
kSecAttrAccessibleAlways | Always | Deprecated and rarely justified; treat any use as a finding |
kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly | Unlocked, with a passcode set | High-value secrets that must never migrate |
kSecAttrAccessibleWhenUnlockedThisDeviceOnly | Unlocked, this device only | Device-bound secrets that must not enter backups or sync |
The ThisDeviceOnly variants exclude the item from backup migration and from iCloud Keychain. That is a real trade-off: an item that cannot migrate is also an item that disappears when the user moves to a new device, so the recovery path has to be a fresh login rather than a restore. Choosing a migratable class because migration is convenient quietly widens where the secret can exist.
For anything that unlocks a payment, a private repository, or an admin surface, pair the item with an access-control flag such as biometryCurrentSet or userPresence through SecAccessControlCreateWithFlags. The flag is enforced by the system at read time. A LocalAuthentication prompt drawn by the app before the read is a user-interface choice, not the enforcement point.
A minimal implementation worth reviewing
The smallest correct implementation handles the duplicate case, because SecItemAdd fails when an item already exists, and a surprising number of apps silently drop the new value instead of updating the old one.
import Foundation
import Security
struct KeychainStore {
let service: String
func save(_ secret: Data, account: String) throws {
let base: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: service,
kSecAttrAccount as String: account,
kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
]
let status = SecItemAdd(base.merging([kSecValueData as String: secret]) { $1 } as CFDictionary, nil)
if status == errSecDuplicateItem {
let update = [kSecValueData as String: secret]
let query = base.merging([kSecAttrSynchronizable as String: kCFBooleanFalse as Any]) { $1 }
let updateStatus = SecItemUpdate(query as CFDictionary, update as CFDictionary)
guard updateStatus == errSecSuccess else { throw KeychainError(status: updateStatus) }
} else if status != errSecSuccess {
throw KeychainError(status: status)
}
}
func read(account: String) throws -> Data? {
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: service,
kSecAttrAccount as String: account,
kSecReturnData as String: true,
kSecMatchLimit as String: kSecMatchLimitOne
]
var item: CFTypeRef?
let status = SecItemCopyMatching(query as CFDictionary, &item)
if status == errSecItemNotFound { return nil }
guard status == errSecSuccess else { throw KeychainError(status: status) }
return item as? Data
}
func delete(account: String) throws {
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: service,
kSecAttrAccount as String: account
]
let status = SecItemDelete(query as CFDictionary)
guard status == errSecSuccess || status == errSecItemNotFound else {
throw KeychainError(status: status)
}
}
}Three details deserve a reviewer's attention. The accessibility attribute is set at creation, so an existing item keeps its old value until it is deleted and re-added. The service string is stable and namespaced by purpose rather than by a display name that might change. And the read path distinguishes "not found" from "failed", because collapsing both into nil is how apps end up silently treating an access error as a logout.
Define the sharing rule before adding an extension
An app extension, a widget, or a second target does not inherit keychain access automatically. Items are scoped to an access group, and the entitlement lists the groups a binary may use. Adding an extension therefore means adding a group in the entitlements of every participating target and passing the same group when the item is created.
Two consequences matter in open-source projects. First, access groups are tied to a signing team, so a contributor building with a different team identifier can see failures that the maintainer never reproduces. Second, ad-hoc signing and some simulator configurations do not carry the entitlement the same way, which surfaces as an entitlement error rather than as a wrong password. On macOS the data-protection keychain is a separate store from the legacy login keychain, and an item written through one path is not visible through the other unless the code asks for that store explicitly.
What to audit in someone else's repository
Reviewing keychain usage is mostly a matter of reading a few specific things rather than understanding the whole app.
- Every SecItemAdd call: which class, which accessibility attribute, which access group, and whether a duplicate is handled.
- Every read: is the status checked, or is any non-success treated as "no credential"?
- Search the tree for tokens in UserDefaults, property lists, environment files, sample projects, and test fixtures.
- Logging: a print, NSLog, or structured log entry that includes the token value undoes everything else on this list.
- Entitlements files: the group list should be exactly what the product needs.
- Client secrets: a public repository cannot keep a shared client secret, so public clients should use a flow that does not require one.
- Cleanup: does revocation or logout delete the item, or does it only clear in-memory state?
A useful test is to write a secret, read back the attributes, delete the app, reinstall, and read again. On Apple platforms, keychain items are not reliably removed when an app is uninstalled, so a token from an old install can still be sitting there. If the product needs a clean first run, it needs an explicit marker outside the keychain plus a deliberate wipe.
Failure modes that survive code review
Most keychain defects are not cryptographic. They are configuration and lifecycle mistakes.

Entitlement errors appear when the binary's signature does not carry the group it is asking for, and the same configuration can fail on a device while passing in a simulator. Changed bundle identifiers or team identifiers break continuity for existing items. Accessibility attributes cannot always be changed in place, so a tightened policy may apply only to newly created items until the old ones are deleted. Simulator keychains are shared and unprotected in ways a physical device is not, which means a passing interface test proves little about storage. And an item stored with sync enabled is available on every device the account signs into, which may be a feature or an incident depending on what the token authorises.
The honest limit is that the Keychain protects data at rest and controls which code can read it. It does not stop a compromised running process, a malicious library injected into an unsigned build, or a user who approves a prompt without reading it. Treat it as one layer: short-lived tokens, least-privilege scopes, rotation, and server-side revocation still do the work that storage cannot.
A five-minute pre-ship checklist
Write one secret through the real code path, read it back, and print the returned attributes rather than the value. Confirm that the accessibility class and the sync flag are the ones you intended. Verify behaviour on a locked device for anything a background task touches. Reinstall and check whether a stale item survives. Add a second device if sync is enabled, and confirm that the item appears or stays absent as designed. Finally, search the diff for logging statements and for any fallback that writes the same value outside the keychain.
If all six pass, the storage layer is in reasonable shape, and the remaining risk sits in token lifetime, scope, and revocation rather than in where the bytes are kept.


