Skip to main content
coreydaley.dev

A secrets app with zero vendor cryptography

The fastest way to make a secrets app less trustworthy is to write your own encryption for it.

Secret Store is a Mac app for the secrets that don’t fit a password manager’s login form: API keys, recovery codes, connection strings, private notes. The core of it went in this week, and its first rule is that I, the vendor, write no cryptography at all. Apple’s iCloud Keychain already encrypts items end to end and syncs them between your devices. Secret Store puts values into it and reads them back. It doesn’t wrap them, re-encrypt them, or derive keys over them.

That sounds like the easy option. Most of the work turned out to be in the keychain flags, one entitlement string I can never replace, and the fact that a “secret” is really two keychain items that can fall out of step.

What “zero vendor cryptography” means

There is no Secret Store crypto code to audit. The app stores each value exactly as it was typed, JSON-encoded, with no extra layer, and the end-to-end guarantee belongs entirely to Apple. The repo’s CLAUDE.md, the file both the coding agents and I work from, lists that as an invariant.

So there is no app password, no key file, and no server. If you trust iCloud Keychain with your Safari passwords, you’re trusting the same thing here. If you don’t, Secret Store can’t change that, and I’d rather say so than bolt a second layer on top.

A rule like that drifts quietly, so it’s also a CI check. A small script greps the Swift sources for imports of CryptoKit, CommonCrypto, CryptoTokenKit, OpenSSL, libsodium, and SwiftCrypto, and fails if it finds any. It’s a tripwire, not a proof: it would miss a dependency doing crypto internally. But it catches the obvious drift. The only security-related frameworks the app imports are Security, for the SecItem calls, and LocalAuthentication, for the Touch ID unlock.

Two keychain items per secret

Each secret is stored as two generic-password items that share the same account, the secret’s UUID:

  • a …meta service item holding the JSON-encoded name, notes, modification date, and version;
  • a …val service item holding the JSON-encoded value.

Listing the secrets only reads the meta items. The value is read on demand when you reveal or copy it.

The metadata goes in kSecValueData too, not in keychain attributes. Apple’s keychain protects an item’s secret data with a different key than its attributes, so keeping the name and notes in the data puts them under the same protection as the value. The only identifying attribute left is a UUID.

The flags that have to be right

Every query in KeychainSecretStore is built around the same handful of keys. Here is the base dictionary for a write:

let base: [CFString: Any] = [
    kSecClass:                      kSecClassGenericPassword,
    kSecAttrService:                service,
    kSecAttrAccount:                id.uuidString,
    kSecAttrSynchronizable:         true,
    kSecUseDataProtectionKeychain:  true,
    kSecAttrAccessGroup:            Self.accessGroup,
    kSecAttrAccessible:             kSecAttrAccessibleWhenUnlocked,
]

kSecUseDataProtectionKeychain: true has to be on every SecItem* call. Without it, macOS uses the older file-based keychain, and a sandboxed app gets -34018 (errSecMissingEntitlement) back at runtime. The Data Protection keychain is the iOS-style one, and it’s the one iCloud Keychain sync works with.

kSecAttrSynchronizable is true on writes and kSecAttrSynchronizableAny on reads and deletes. Writes need true so the item syncs at all. Reads and deletes need Any because, if you leave the key out, a query matches only items that don’t sync. Get either one wrong and nothing fails. Sync just doesn’t happen, or a delete misses the synced copy.

The access group is pinned forever

The app’s entitlement lists one keychain access group:

<key>keychain-access-groups</key>
<array>
    <string>$(AppIdentifierPrefix)com.coreydaley.secretstore</string>
</array>

Xcode expands $(AppIdentifierPrefix) to my team prefix at build time, and every item Secret Store writes carries the resulting team-prefixed access group.

Once the app ships, that string can never be replaced. Every synced item, on every device of every user, is bound to it, and the app can only see items in the groups its entitlement lists. Swap the value and every stored secret is orphaned: still in the user’s keychain, but unreachable by the app that put it there. An entitlement can list more than one group, so adding a second one later isn’t ruled out, but the original has to stay. CLAUDE.md says to treat it like a database primary key, and the entitlements file carries a comment saying the same in capitals.

It’s an odd kind of invariant, because nothing enforces it. The compiler won’t care, the tests will pass with a new group, and a fresh install will work. The only people who’d notice are existing users, all at once, after an update.

A 128 KB cap, on the encoded bytes

iCloud Keychain isn’t meant for large blobs, so values are capped at 128 KB. The comment next to the constant gives the reasoning: a conservative margin below a roughly 512 KB sync ceiling.

The detail that matters is what gets measured. The cap applies to the JSON-encoded SecretValue, which is exactly what goes into kSecValueData, not to the length of the Swift string:

public let maxSecretValueBytes: Int = 128 * 1024

public func validateSecretValueSize(
    _ value: SecretValue, encoder: JSONEncoder = JSONEncoder()
) throws {
    let encoded = try encoder.encode(value)
    if encoded.count > maxSecretValueBytes {
        throw SecretError.sizeExceeded(
            bytesEncoded: encoded.count, limit: maxSecretValueBytes)
    }
}

String length undercounts in three ways. Non-ASCII characters take more than one byte in UTF-8. JSONEncoder escapes quotes, backslashes, control characters, and (by default) forward slashes. And the encoded value also carries its UUID and the JSON punctuation.

create and updateValue both run the check before any SecItem call. The tests build a value whose encoding lands exactly on the limit and one that lands a single byte over, so the rule is pinned to the encoder’s real output.

When the two items disagree

Two keychain items can’t be written atomically. A crash between the two writes, or sync delivering one item before the other, leaves a secret half-present. So the store has to expect inconsistency rather than hope it won’t happen.

Sync shows up even in a plain write. Writes are an upsert: try SecItemUpdate, and if the item isn’t there, SecItemAdd. If the add comes back errSecDuplicateItem, that counts as success, because iCloud sync delivered the same item from another Mac in between. In that narrow race the synced copy stays and the local write is dropped.

Write order. The rule is to order the writes so the only possible half-state is the least harmful one. create writes the value item first, then the meta item. delete removes the meta item first, then the value. Either way, an interruption leaves a value with no metadata, which never appears in the list. The other half-state, metadata pointing at a value that isn’t there, would show up as a secret that fails when you open it. Local writes can’t produce it, but sync delivering a meta item ahead of its value still can.

Orphan scan. The scan lists the account IDs under both services, takes the symmetric difference, and labels each leftover as metaOnly or valueOnly. A value-only orphan matters more than it looks: it’s a secret value still in the keychain, and still syncing, after the user thinks it’s gone. The scan never deletes anything. It surfaces the orphans, and deleting them is a separate repair step the user confirms.

Fixed-point repair. Repair is idempotent. Scan, repair what it found, scan again, and the second scan comes back empty. The tests check this directly. An in-memory fake stores meta and value items separately, like the keychain does, and the tests use it to inject both failures: an interrupted create and an interrupted delete.

When two copies disagree

A different problem is two versions of the same secret’s metadata. Every edit bumps the meta’s version and stamps modifiedAt, and one rule decides between two copies:

public func resolving(against other: SecretMeta) -> SecretMeta {
    precondition(id == other.id, "Can only resolve metas with the same id")
    if version != other.version {
        return version > other.version ? self : other
    }
    if modifiedAt != other.modifiedAt {
        return modifiedAt > other.modifiedAt ? self : other
    }
    return self
}

Higher version wins. On a tie, the newer timestamp wins. On an exact tie, the receiver wins, which by convention is the current device’s copy. That last choice is arbitrary but deterministic, which is what you want from a tiebreak.

Right now only the version bump is wired into editing. The resolver is a pure function on SecretMeta, written and tested on its own, so every branch is covered without touching the keychain.

What I get, and what I give up

Handing encryption to Apple means I don’t have a vault format to design, a key to manage, or a server to run. Sync uses the same setup people already have for their passwords, and the help page lists the three things each Mac needs turned on.

What I give up is control. If Apple’s side has a bug, I can’t fix it, and Secret Store can’t go anywhere iCloud Keychain doesn’t. I also take on a short list of things that have to be exactly right forever: two flags on every call, one entitlement string, and the order of two writes.

A comment in capitals is my answer, but if your app’s security depends on a value that no test or compiler will ever check, how do you make sure the next person to touch it knows?

Related posts