How do keychain access groups differ from app groups?

6.8.2 · L3 · Interview

Predict first

Which mechanism shares a login token between your app and its widget, safely?

// A: UserDefaults.standard
// B: a shared keychain access group
// C: a plain file in tmp
  • A
  • B
  • C

Mental model. An app group is a shared storage room. A keychain group is a safe in the bank: separate building, own key rules, and it keeps the contents even if you close your flat.

The keychain is a separate secure store, managed by a system service, not a folder. Items are tagged with an access group (kSecAttrAccessGroup). An app can read and write only items in the groups it is entitled to via the keychain-access-groups entitlement (its own team-prefixed bundle group by default, plus any shared groups you add). Apps from the same team that list the same group see the same items, which is how single sign-on between your own apps works. App groups and keychain groups are unrelated mechanisms: an app group shares files and defaults, a keychain group shares secrets.

Two details matter. Choose the accessibility class deliberately: kSecAttrAccessibleWhenUnlocked means the item is unreadable while the device is locked, so a background task or extension that runs then cannot get it; AfterFirstUnlock allows it after the first unlock since boot. And keychain items can survive deleting the app, unlike UserDefaults, which matters for “first run” logic and for clearing secrets on sign-out. The security section covers the API and threat model in depth.

The keychain is built for secrets and can be shared across entitled processes. Defaults and files are neither encrypted for this purpose nor shared by default.

Common traps

  • Using a “when unlocked” item from a background task. The read fails while the device is locked. Use an after-first-unlock class where appropriate.
  • Relying on keychain data disappearing on uninstall. It may remain; clear it explicitly on sign-out.

They might follow up with

  • Why does the team prefix matter? Access groups are scoped to the team, so a different developer’s app cannot read yours.
  • Can an extension read the app’s keychain item? Yes, if both list the same keychain access group in their entitlements.

Related questions

  • 6.8.1 What is an app group, and what can go wrong when an app and an extension share a database?
  • 6.1.3 What are entitlements, and what happens when they do not match the provisioning profile?
  • 2.5.8 What belongs in UserDefaults, and how do you design and test around it?

← What is an app group, and what can go wrong when an app and an…   Why is an app extension a separate process, and what does that mean… →