Skip to main content
3Nsofts logo3Nsofts
Security & Compliance

Fix macOS Keychain Lookups with Consistent SecItem Queries

Use one Data Protection Keychain identity query for add, read, update and delete, then test access groups, helpers and migration from legacy items.

By Ehsan Azish · 3NSOFTS··8 min read

When SecItemAdd succeeds and the next SecItemCopyMatching returns errSecItemNotFound, compare the entire query. On native macOS, the two operations may be targeting different Keychain implementations.

This guide is for a signed native macOS app running in a logged-in user's session. It stores one kind of generic password item in the Data Protection Keychain, with consistent identity and query attributes across add, read, update, and delete.

Two generic-password queries compared, with the Data Protection Keychain flag present only in the successful query.

The image assumes the item was added to the Data Protection Keychain. The flag fixes that particular mismatch. Missing items can also come from different account names, service strings, access groups, signing identities, or execution contexts.

Contents

Choose the implementation for the caller

Ordinary native Mac apps can use file-based or Data Protection Keychain items. The SecItem API's native macOS default targets the file-based implementation; explicitly set kSecUseDataProtectionKeychain for the other implementation. Mac Catalyst and iOS apps running on Mac use Data Protection as their only implementation. A launch daemon outside a user session must use a file-based keychain. A user-session helper still needs suitable signing and access authorization. Apple TN3137

Do not add kSecAttrSynchronizable merely to fix a lookup. Synchronization is an additional product decision. The example below explicitly uses nonsynchronizing items and chooses accessibility when unlocked on this device.

Reuse one identity query

This complete wrapper targets macOS 10.15 or later. It is deliberately synchronous and stateless. Run calls on your existing serialized worker when they may block or prompt. Keep authentication and user interaction policies explicit in the calling feature.

The base query includes the item class, service, account, selected implementation, synchronization policy, and optional access group. Return keys and the new value are added only by the operation that needs them.

import Foundation
import Security

struct KeychainFailure: LocalizedError {
    let operation: String
    let status: OSStatus

    var errorDescription: String? {
        let message = SecCopyErrorMessageString(status, nil)
            as String? ?? "Unknown Keychain error"
        return "\(operation) failed (\(status)): \(message)"
    }

    var recovery: String {
        switch status {
        case errSecItemNotFound:
            return "Check item identity, keychain and access group."
        case errSecDuplicateItem:
            return "Read or update the existing item."
        case errSecMissingEntitlement:
            return "Review this executable's signed entitlements."
        case errSecInteractionNotAllowed:
            return "Retry from an eligible interactive user session."
        case errSecAuthFailed, errSecUserCanceled:
            return "Allow the user to retry authentication."
        default:
            return "Preserve the status and inspect the failing operation."
        }
    }
}

@available(macOS 10.15, *)
struct UserSecretStore {
    let service: String
    var accessGroup: String? = nil

    private func identity(account: String) -> [String: Any] {
        var query: [String: Any] = [
            kSecClass as String: kSecClassGenericPassword,
            kSecAttrService as String: service,
            kSecAttrAccount as String: account,
            kSecUseDataProtectionKeychain as String: true,
            kSecAttrSynchronizable as String: false
        ]
        if let accessGroup {
            query[kSecAttrAccessGroup as String] = accessGroup
        }
        return query
    }

    func add(_ value: Data, account: String) throws {
        var query = identity(account: account)
        query[kSecValueData as String] = value
        query[kSecAttrAccessible as String] =
            kSecAttrAccessibleWhenUnlockedThisDeviceOnly
        let status = SecItemAdd(query as CFDictionary, nil)
        try requireSuccess(status, operation: "Add")
    }

    func read(account: String) throws -> Data {
        var query = identity(account: account)
        query[kSecReturnData as String] = true
        query[kSecMatchLimit as String] = kSecMatchLimitOne
        var result: CFTypeRef?
        let status = SecItemCopyMatching(
            query as CFDictionary, &result
        )
        try requireSuccess(status, operation: "Read")
        guard let data = result as? Data else {
            throw KeychainFailure(
                operation: "Read result", status: errSecDecode
            )
        }
        return data
    }

    func update(_ value: Data, account: String) throws {
        let changes = [kSecValueData as String: value]
        let status = SecItemUpdate(
            identity(account: account) as CFDictionary,
            changes as CFDictionary
        )
        try requireSuccess(status, operation: "Update")
    }

    func delete(account: String) throws {
        let status = SecItemDelete(
            identity(account: account) as CFDictionary
        )
        try requireSuccess(status, operation: "Delete")
    }

    private func requireSuccess(
        _ status: OSStatus, operation: String
    ) throws {
        guard status == errSecSuccess else {
            throw KeychainFailure(
                operation: operation, status: status
            )
        }
    }
}

Keep the service identifier stable across app versions. If you set an access group, use the exact signed value authorized for that executable. Adding a group name in a Swift string does not confer membership. Reads can return item-not-found when an item belongs to a group the caller cannot query. Apple sharing Keychain access

The wrapper reports duplicate add and missing delete as errors. The caller decides whether those conditions are expected. That avoids hiding a wrong account identifier behind an automatic “success.”

Call add read update and delete

Use a unique non-secret fixture account for development. The example is a function to invoke in a properly signed app, not top-level production initialization.

@available(macOS 10.15, *)
func exerciseSecretStore() throws {
    let store = UserSecretStore(
        service: "com.example.SampleApp.session"
    )
    let account = "fixture-" + UUID().uuidString
    try store.add(Data("fixture-A".utf8), account: account)
    // Best-effort cleanup if an assertion or later operation fails.
    defer { try? store.delete(account: account) }

    let first = try store.read(account: account)
    precondition(first == Data("fixture-A".utf8))
    try store.update(Data("fixture-B".utf8), account: account)
    let second = try store.read(account: account)
    precondition(second == Data("fixture-B".utf8))
    try store.delete(account: account)
}

Log the operation and numeric OSStatus when useful. Avoid putting tokens, password bytes, account identifiers, or an entire query dictionary into support logs.

A type-check confirms API usage, but does not grant Keychain authorization. Run this exercise from the signed host that will ship, with its actual capabilities and provisioning profile.

Plan migration deliberately

Changing a query flag does not move an old item.

For an app that previously used file-based items, implement a separate, narrowly targeted legacy reader. Its class, service, account, and keychain search scope must identify your own item. Do not copy the Data Protection query and assume it describes the legacy ACL policy.

A migration should follow these steps.

  1. Read the new Data Protection item first.
  2. Only when it is genuinely absent, ask the legacy reader for the intended old item. Preserve authentication failures as failures.
  3. Add the new item. If another process already added it, read and validate that item instead of overwriting it blindly.
  4. Read back and validate the new value.
  5. Delete the precisely identified legacy item only when the release and rollback policy permit it.
  6. Make the sequence safe to retry after a crash between any two steps.

There is no cross-implementation transaction covering this transfer. Keep the old item if the new write or verification fails. For long-lived tokens, define which source wins if both values exist, and coordinate that policy with helpers and older app versions. Apple's TN3137 distinguishes the two implementations and their access models. Apple TN3137

What can still go wrong

Service or account drift. A case change or renamed bundle-derived service can create a different identity. Centralize the constants used by every caller.

Extension mismatch. The containing app's private item does not automatically become an extension's item. Configure the intended shared group on both signed executables, then test each process.

Daemon mismatch. Moving the same wrapper into a system launch daemon changes its execution context. Review a file-based design appropriate to that daemon instead. The app user's Data Protection Keychain is unavailable there. Apple Keychain pitfalls

Library ambiguity. A library uses its host process's privileges. A test runner, GUI app, and command-line helper may have different capabilities.

An access group change. Changing the default group order can change where new items are added. Use an explicit group when sharing is part of the contract.

Main-thread stalls. Keychain work can wait on system services or interaction. Serialize mutable credential workflows away from UI work and marshal results back to the UI. An update can race with another process's delete even when one app serializes its own calls.

Test the signed app and its helpers

  • Add, read, update, delete, then confirm a read returns item-not-found.
  • Add twice and verify duplicate handling without destroying the existing value.
  • Relaunch and confirm the same service/account still reads.
  • Deliberately omit the flag in a native Mac fixture and confirm which implementation each call addresses.
  • Test locked-session and canceled-authentication paths without converting them into “no saved password.”
  • Exercise the actual extension or helper, including a mismatched group fixture.
  • Interrupt migration after add and before legacy deletion. Verify retry preserves the usable secret.
  • Inspect the shipped entitlements with codesign and confirm logs contain no credential material.

For credentials temporarily copied by the user, see clipboard expiry. Continue with security-scoped file access and release signing checks.

References

Expanded from Ehsan's original Keychain post.

Authoritative References