skip to content

With Keychain Services, why does SecItemAdd return errSecDuplicateItem when an app saves a refreshed token, and how should the save be written?

level: middleimportance: must knowfreq 60%

answer

  1. an item already exists
  2. composite primary key per class
  3. service, account, access group, synchronizable
  4. update first, add on not found
  5. accessibility is not part of the key

basics

~20 s

A generic password with the same kSecAttrService, kSecAttrAccount, access group and synchronizable flag already exists, so SecItemAdd refuses a second one. Write the save as SecItemUpdate with the new kSecValueData, calling SecItemAdd only when the update returns errSecItemNotFound.

solid answer

~40 s

Each keychain item class has a composite primary key. For `kSecClassGenericPassword` it is `kSecAttrService`, `kSecAttrAccount`, `kSecAttrAccessGroup` and `kSecAttrSynchronizable`; adding a second item with the same values fails with `errSecDuplicateItem` (-25299). A refresh token rotates on every refresh, so a save written as a bare `SecItemAdd` works once and collides ever after. Write it as update-or-add: call `SecItemUpdate(query, changes)`, where `query` holds only the identity and `changes` holds `kSecValueData`; on `errSecItemNotFound`, call `SecItemAdd` with the full attributes. Attributes outside the key, such as `kSecAttrAccessible` or `kSecAttrAccessControl`, do not make an item distinct, so adding the same service and account with a new accessibility class also returns `errSecDuplicateItem`. Delete-then-add works too, but leaves a moment with no token at all.

code

swift · 27 lines
swift
import Foundation
import Security

enum KeychainError: Error { case unhandled(OSStatus) }

func storeToken(_ token: Data) throws {
    let query: [String: Any] = [
        kSecClass as String: kSecClassGenericPassword,
        kSecAttrService as String: "com.example.carshare.auth",
        kSecAttrAccount as String: "refresh-token"
    ]
    let changes: [String: Any] = [kSecValueData as String: token]

    let status = SecItemUpdate(query as CFDictionary, changes as CFDictionary)
    switch status {
    case errSecSuccess:
        return
    case errSecItemNotFound:
        var attributes = query
        attributes[kSecValueData as String] = token
        attributes[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
        let addStatus = SecItemAdd(attributes as CFDictionary, nil)
        guard addStatus == errSecSuccess else { throw KeychainError.unhandled(addStatus) }
    default:
        throw KeychainError.unhandled(status)
    }
}

go deeper

for a junior

Recall that SecItemAdd fails with errSecDuplicateItem when the same service and account already exist, and that SecItemUpdate replaces the stored data.

for a middle

Explain the composite primary key of a generic password, why accessibility and access control sit outside it, and how update-or-add reacts to each status.

for a senior

Show the failure modes in production: tokens that silently stop rotating, duplicate items split across access groups or sync, and races between an app and its extension.

for a principal

Decide that no feature calls SecItemAdd directly; one wrapper owns identity keys, update-or-add and status mapping, and reviews reject hand-built keychain dictionaries.

## What errSecDuplicateItem says `SecItemAdd` returns **`errSecDuplicateItem`** (-25299) when the keychain already holds an item of the same class with the same **composite primary key**. The stored value plays no part: a token whose bytes changed on refresh is still a duplicate when its identifying attributes match. Because a refresh token rotates on every refresh, a save written as a bare `SecItemAdd` succeeds at sign-in and fails on every refresh after it, often silently, so the app keeps presenting the old token until the server rejects it and the member is signed out. ## The primary key of each class Apple's documentation lists the attributes that make two items distinct: | Item class | Primary key attributes | |---|---| | `kSecClassGenericPassword` | `kSecAttrService`, `kSecAttrAccount`, `kSecAttrAccessGroup`, `kSecAttrSynchronizable` | | `kSecClassInternetPassword` | `kSecAttrAccount`, `kSecAttrServer`, `kSecAttrProtocol`, `kSecAttrPort`, `kSecAttrPath`, `kSecAttrSecurityDomain`, `kSecAttrAuthenticationType`, plus access group and synchronizable | Everything else on a generic password, including `kSecAttrAccessible`, `kSecAttrAccessControl`, `kSecAttrLabel`, `kSecAttrDescription` and the creation date, is an attribute of the item but **not** part of its identity. ## Writing update-or-add Apple's guide on changing stored credentials recommends updating the existing item rather than adding a new one: 1. Build a **query** holding only identity: `kSecClass`, `kSecAttrService`, `kSecAttrAccount`, and `kSecAttrAccessGroup` if the item is shared. 2. Build a **changes** dictionary with what should change, normally `kSecValueData`. The header allows only real keychain attributes in this dictionary, so return keys and `kSecMatchLimit` stay out of it. 3. Call `SecItemUpdate(query, changes)`. On `errSecSuccess`, the save is done. 4. On `errSecItemNotFound`, merge the query with the data, add the accessibility class, and call `SecItemAdd`. 5. Treat any other status as a real failure and surface its code. The reverse order, adding first and updating on `errSecDuplicateItem`, works as well. Delete-then-add also works but opens a gap in which no token exists; a background read that lands in the gap concludes the member signed out. ## Traps around the pattern - **Accessibility is not identity.** Adding the same service and account with a new `kSecAttrAccessible` returns `errSecDuplicateItem`, and the old class stays until you change it with `SecItemUpdate` or delete and re-add. - **The access group is identity.** If one code path passes `kSecAttrAccessGroup` and another relies on the default group, the app can end up with two items, one per group, and a read without the group returns whichever it meets first. - **Synchronizable is identity.** An item added with `kSecAttrSynchronizable` set to true is distinct from a local item with the same service and account. A query without the key never sees synchronizable items; `kSecAttrSynchronizableAny` matches both. - **`SecItemUpdate` changes every match.** A query holding only `kSecClass` rewrites every generic password the app can reach, so qualify it with service and account. - **Two writers can race.** If the app and an extension both see `errSecItemNotFound` and both add, the second add returns `errSecDuplicateItem`; handle that by running the update again rather than reporting a failure. ## Reading the statuses a save can return | Status | Value | Meaning on a save | |---|---|---| | `errSecSuccess` | 0 | Stored | | `errSecItemNotFound` | -25300 | The update matched nothing: add instead | | `errSecDuplicateItem` | -25299 | The add collided: update instead | | `errSecMissingEntitlement` | -34018 | The access group named is not one the app belongs to | | `errSecParam` | -50 | A key or value in a dictionary is not valid | Keeping update-or-add inside one small wrapper type means every feature that stores a secret gets the same identity keys, the same explicit accessibility class and the same status handling. ## Testing the save The bug hides because the first save always works, so the tests must exercise the second one: - Save twice in a row and read back: the second value must win, with no `errSecDuplicateItem` swallowed on the way. - Save, change the accessibility class in code, save again, then read the item's attributes with `kSecReturnAttributes` to confirm which class it really carries. - Save from the app and from the extension with the same identity, and confirm a single item remains. - Sign out and confirm the delete leaves `errSecItemNotFound` behind, then sign in again and confirm the add path runs. Run keychain tests inside a host app on the Simulator or a device, so the test process carries the app's entitlements and access groups.

  • Can an app move an existing token to a new kSecAttrAccessible class by adding it again with that class?
    No. Accessibility is not part of a generic password's primary key, so the add returns `errSecDuplicateItem` and the old item keeps its old class. Change it with `SecItemUpdate`, passing the new `kSecAttrAccessible` in the attributes to update, or delete the item and add it again with the new class.
  • With update-or-add, what happens when the app and its widget extension save the same item at the same moment?
    Both updates can return `errSecItemNotFound`, both then call `SecItemAdd`, and the second add returns `errSecDuplicateItem`. Treat that status as a cue to run the update again instead of a failure, or route all writes for that item through one process.
  • Why might a query start returning the old token after the app begins saving it with kSecAttrSynchronizable set to true?
    Synchronizable is part of the primary key, so the new synced item and the old local item coexist with the same service and account. A query without `kSecAttrSynchronizable` sees only the local one. Query with `kSecAttrSynchronizableAny` to find both and delete the copy you no longer want.

A primary key is like a locker number at a gym: putting a new bag in locker 12 means swapping what is inside, not asking the front desk for a second locker 12, and repainting the door does not make it a different locker.

  • errSecDuplicateItem means the new token bytes equal the stored ones.
  • Adding the item again with a different kSecAttrAccessible creates a separate entry.
  • SecItemUpdate inserts the item when no match exists yet.
  • SecItemUpdate changes only the first item that matches the query.
  • Delete-then-add is always the safest way to replace a stored token.