skip to content

With Keychain Services, how does a car-sharing app share its digital-key secret with its widget extension, and what breaks when the access group is wrong?

level: middleimportance: should knowfreq 35%

answer

  1. an extension is its own keychain client
  2. same entitlement on both targets
  3. keychain-access-groups with the Team ID prefix
  4. kSecAttrAccessGroup on the add and the query
  5. errSecMissingEntitlement versus errSecItemNotFound

basics

~20 s

Give the app and the widget extension the same Team ID-prefixed keychain-access-groups entry, and add and query the item with kSecAttrAccessGroup set to it. Otherwise the item lands in the app's private group and the widget gets errSecItemNotFound.

solid answer

~50 s

Every keychain item belongs to exactly one access group, and each app or extension can reach only the groups on its own list: its `keychain-access-groups` entries, then its app ID (Team ID plus bundle ID), then its App Groups. The first entry is the default group that `SecItemAdd` uses when no `kSecAttrAccessGroup` is given. A widget extension has its own app ID, so an item the app saved without a group is invisible to it. Enable Keychain Sharing on both targets with the same group, such as `ABCDE12345.com.example.carshare.shared`, and pass that string as `kSecAttrAccessGroup` when adding and querying. Naming a group the target is not entitled to, or the empty string, makes the add fail with `errSecMissingEntitlement` (-34018); querying such a group returns `errSecItemNotFound`. Items saved before sharing stay in the private group until migrated.

code

swift · 29 lines
swift
import Foundation
import Security

// Both targets list this group under Keychain Sharing; Xcode adds the Team ID prefix.
let sharedGroup = "ABCDE12345.com.example.carshare.shared"

func keyQuery() -> [String: Any] {
    [kSecClass as String: kSecClassGenericPassword,
     kSecAttrService as String: "com.example.carshare.car-key",
     kSecAttrAccount as String: "current-booking",
     kSecAttrAccessGroup as String: sharedGroup]
}

// In the app.
func storeDigitalKey(_ secret: Data) -> OSStatus {
    var attributes = keyQuery()
    attributes[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
    attributes[kSecValueData as String] = secret
    return SecItemAdd(attributes as CFDictionary, nil)
}

// In the widget extension.
func readDigitalKey() -> Data? {
    var query = keyQuery()
    query[kSecReturnData as String] = true
    var result: CFTypeRef?
    guard SecItemCopyMatching(query as CFDictionary, &result) == errSecSuccess else { return nil }
    return result as? Data
}

go deeper

for a junior

Recall that an extension is a separate keychain client and needs the same access group entitlement as the app to read a shared item.

for a middle

Explain how the group list is built, which entry is the default, and why the Team ID prefix and kSecAttrAccessGroup on both add and query matter.

for a senior

Diagnose a widget that reads nothing: missing entitlement on one target, an unprefixed string, items stranded in the private group, and plan the migration.

for a principal

Decide which secrets may be shared with extensions at all, whether a dedicated keychain group or the existing App Group carries them, and who reviews entitlement changes.

## How an access group decides who sees an item Every keychain item belongs to exactly **one access group**, recorded in its `kSecAttrAccessGroup` attribute. Every app and every app extension belongs to a list of groups, and it can read and write only items whose group is on that list. Sharing this way needs no permission from the user, and it works only between apps and extensions from the same development team. A widget is an app extension with its own bundle ID, so by default it is a separate keychain client: an item the main app adds without naming a group goes into the app's own group, where the widget cannot see it. ## The list of groups a target belongs to The system builds each target's list from its code-signed entitlements, in this order: 1. The strings in its **`keychain-access-groups`** entitlement, which Xcode's Keychain Sharing capability writes with the Team ID prefix. 2. Its **app ID**: Team ID plus bundle ID, for example `ABCDE12345.com.example.carshare.widget`. 3. The strings in its **App Groups** entitlement, such as `group.com.example.carshare`, which carry no Team ID prefix. The first entry is the **default access group**, used by `SecItemAdd` when the dictionary has no `kSecAttrAccessGroup`. A keychain access group can be the default because it comes first; an App Group never can, because the app ID always precedes it. | Group kind | Example | Can be the default | Also shares non-keychain data | |---|---|---|---| | Keychain access group | `ABCDE12345.com.example.carshare.shared` | Yes, when listed first | No | | App ID | `ABCDE12345.com.example.carshare` | Yes, when there are no keychain groups | No | | App Group | `group.com.example.carshare` | Never | Yes, such as a `UserDefaults` suite | ## Sharing the digital-key secret, step by step 1. Enable **Keychain Sharing** on the app target and on the widget extension target, and add the same group to both, such as `com.example.carshare.shared`. Xcode stores it with the Team ID in front. 2. When the app saves the secret, pass `kSecAttrAccessGroup` with the full prefixed string, so the item lands in the shared group rather than the default one. 3. In the widget, query with the same class, service, account and access group. 4. Choose an accessibility class for when the widget actually runs: if the extension can run while the phone is locked, an item with `kSecAttrAccessibleWhenUnlocked` answers its reads with `errSecInteractionNotAllowed`, so an after-first-unlock class fits better. ## What breaks when the group is wrong - **The item was added without a group.** It sits in the app's default group and the widget's query returns `errSecItemNotFound`. This is the most common cause. - **The group string in code lacks the Team ID prefix.** It matches no group the target belongs to, so the add fails with `errSecMissingEntitlement` (-34018) and a query finds nothing. - **Only one target has the entitlement.** The app's add succeeds; the widget is not a member of the group, so its query matches nothing. - **The empty string as the group.** Apple's documentation calls it always invalid; the add fails with `errSecMissingEntitlement`. - **The shared group is listed first by accident.** It becomes the app's default, so every item the app adds without a group is shared with the widget, which is more than intended. ## Moving items stored before sharing Items saved by an earlier release live in the app's private group. A first-launch migration in the new release reads the item, adds it with the shared `kSecAttrAccessGroup`, and deletes the private copy only after the add succeeds. Because the access group is part of a generic password's primary key, the two copies can coexist during the move without `errSecDuplicateItem`. A query without `kSecAttrAccessGroup` searches all of the app's groups and may return either copy in that window, so name the group in reads once the migration ships. ## Keychain access group or App Group - Use a **keychain access group** when only secrets need sharing; it keeps the sharing explicit and can serve as the default group. - Use the **App Group** the targets already have when they also share files or a `UserDefaults` suite; it works as a keychain access group too, but must always be named in `kSecAttrAccessGroup` because it is never the default.

  • If the app's keychain-access-groups entitlement lists the shared group first, what changes for items the app adds without kSecAttrAccessGroup?
    The first entry becomes the app's default access group, so those items land in the shared group and every target in it can read them. That is convenient for the widget but widens access for unrelated secrets. Name the group explicitly on every add, and keep the shared group off the top of the list unless sharing everything is intended.
  • Can a widget read the keychain through an App Group the targets already use for a UserDefaults suite?
    Yes. Since iOS 8 an App Group also acts as a keychain access group, so passing `group.com.example.carshare` as `kSecAttrAccessGroup` shares the item. It carries no Team ID prefix and can never be the default group, so every add and query must name it.

Access groups work like key-card zones in an office: each badge opens a list of zones, every locker sits in exactly one zone, and a new employee (the widget) cannot open a locker in your private office until both badges carry the shared zone.

  • Items an app stores are automatically visible to its own extensions.
  • kSecAttrAccessGroup can be set to any string; the keychain creates the group.
  • An App Group cannot be used to share keychain items.
  • Sharing an item with an extension requires asking the user for permission.
  • An item can belong to several access groups at once.