- Swift 6
- iOS · macOS · tvOS · watchOS · visionOS
- swift-dependencies
The keychain,
typed and testable.
Typed keys instead of account strings, a Secret wrapper that won't print what it holds, Secure Enclave signing and key agreement, and in-memory doubles that behave like the real store. Built as swift-dependencies clients, so every feature that reads a secret can be tested without touching Security.framework.
import Dependencies
import Keychain
extension KeychainKey where Value == String {
static let authToken = KeychainKey("auth.token")
}
struct Session {
@Dependency(\.keychain) var keychain
func logIn(token: String) async throws {
try await keychain.save(Secret(token), for: .authToken)
}
func bearer() async throws -> String {
// exposeSecret: the header needs the token.
"Bearer \(try await keychain.load(for: .authToken).exposeSecret())"
}
}
Why
The Security framework works.
Using it safely takes discipline.
SecItemAdd and friends take a CFDictionary of string constants and return an OSStatus. Every call site spells an account name, picks an accessibility class, remembers to update rather than add, decides what -25300 means, and gets a Data back that is one print away from a log. And none of it runs in a unit test.
Declare once
A KeychainKey<Value> holds the account, accessibility, authentication gate and serialization. Call sites name the key, never a string.
Keep it wrapped
Reads return Secret<Value>: redacted in print and dump, not Codable, compared in constant time. exposeSecret() is the one way out.
Swap it in tests
@Dependency(\.keychain) is unimplemented in tests until you choose .inMemory(), .noop or .failing(_:). Prompts are simulated too.
Features
Small surface, sharp edges filed off.
Two clients, KeychainClient and SecureEnclaveClient, and the typed methods on them are the whole public API. Each choice the platform leaves open is written down as a numbered decision.
Typed keys only
String keys store UTF-8, Data keys store bytes, Codable keys store JSON, and anything else passes its own encode/decode. There is no string-keyed save or load to reach for.
Secrets that stay secret
Secret<String>(redacted) in every log. Every exposeSecret() call site carries a comment and is counted in CI, so a new one shows up in review. Errors never carry payload bytes.
Biometrics without surprises
Gate an item on Face ID, Touch ID, Optic ID or the passcode. exists, keys, attributes, rename and a stream's first value never prompt; pass one AuthContext to cover several reads with a single prompt.
Secure Enclave, typed by purpose
P-256 keys created inside the enclave that never leave the device. sign takes only a SecureEnclaveKey<Signing>, sharedSecret only a SecureEnclaveKey<KeyAgreement>: the compiler checks the purpose.
Doubles that tell the truth
The in-memory keychain has the same errors, stream order and label/comment rules as the live one, and an authenticate closure decides each simulated prompt. The Secure Enclave double makes signatures that verify.
Interface without Security
Feature modules link Keychain, which never imports Security and builds on Linux. Only the app links KeychainLive. Streams, rename without reading, typed labels and comments come with it.
Code tour
What it looks like in an app.
Declare keys as static constants. Each carries its protection and serialization, so a call site can't pair an account with the wrong decoder.
import Keychain
struct Credentials: Codable, Sendable { var username: String; var pin: String }
extension KeychainKey where Value == Credentials {
static let credentials = KeychainKey("user.credentials") // stored as JSON
}
extension KeychainKey where Value == Data {
static let encryptionKey = KeychainKey(
"crypto.encryption-key", accessibility: .whenUnlockedThisDeviceOnly)
}
let saved = Secret(Credentials(username: "ada", pin: "1815"))
try await keychain.save(saved, for: .credentials, attributes: .init(label: "My App"))
let credentials = try await keychain.loadIfPresent(for: .credentials) // Secret<Credentials>?
print(credentials as Any) // Optional(Secret<Credentials>(redacted))Gate an item on the user. Evaluate an LAContext once to cover several reads; a cancelled prompt throws KeychainError.authenticationFailed.
import Keychain
import LocalAuthentication
extension KeychainKey where Value == String {
static let vaultPassword = KeychainKey("vault.password", authentication: .biometricOrPasscode)
}
let context = LAContext()
try await context.evaluatePolicy(.deviceOwnerAuthentication, localizedReason: "Unlock your vault")
let password = try await keychain.load(for: .vaultPassword, context: AuthContext(context))
// Never prompts, even for the gated item:
let present = await keychain.exists(for: .vaultPassword)
let label = try await keychain.attributes(for: .vaultPassword)?.labelCreate a P-256 key inside the Secure Enclave and sign with it. The keychain stores only the key's encrypted handle.
import Dependencies
import Keychain
extension SecureEnclaveKey<Signing> {
static let paymentApproval = SecureEnclaveKey("payment.approval", authentication: .biometricCurrentSet)
}
struct DeviceRegistration {
@Dependency(\.secureEnclave) var secureEnclave
func register() async throws -> SecureEnclavePublicKey {
guard secureEnclave.isAvailable() else { throw KeychainError.secureEnclaveUnavailable }
return try await secureEnclave.publicKeyCreatingIfNeeded(for: .paymentApproval)
}
func approve(_ payment: Data) async throws -> Data {
try await secureEnclave.sign(payment, with: .paymentApproval) // DER ECDSA over SHA-256
}
}Tests get an unimplemented client that fails on any call you didn't expect. Choose the store each test needs, prompts included.
import DependenciesTestSupport
import Keychain
import Testing
@Suite(.dependencies { $0.keychain = .inMemory() })
struct SessionTests {
@Test func bearerUsesTheSavedToken() async throws {
let session = Session()
try await session.logIn(token: "t0k3n")
#expect(try await session.bearer() == "Bearer t0k3n")
}
@Test func aRefusedPromptThrows() async throws {
let keychain = try KeychainClient.inMemory(authenticate: { _, _ in false }) {
try KeychainEntry(Secret("open sesame"), for: .vaultPassword)
}
await #expect(throws: KeychainError.authenticationFailed) {
try await keychain.load(for: .vaultPassword)
}
}
}Held to its own rules
Checked on every pull request.
exists on the login keychain (benchmarks)Install
Add it with Swift Package Manager.
.package(url: "https://github.com/mackoj/swift-keychain", from: "0.4.1"),
Keychain: every module that reads or writes secrets, and their tests. Links only swift-dependencies.KeychainLive: the app target only. Links Security and CryptoKit.- iOS 16, macOS 13, tvOS 16, watchOS 9, visionOS 1. Swift 6.2 tools.
- On macOS the live client uses the data protection keychain, which needs the
keychain-access-groupsentitlement; passdataProtection: falsefor an unsigned tool.
Read the guide for every method and test double, the spec for what the package is and is not.