Keep A Keychain Read Failure From Signing The User Out

Your app opens, asks the Keychain for its saved token, gets nil, and presents the sign-in screen. The person signs in again. Or they force-quit the app, reopen it, and discover they were signed in all along.

Before adding another login workaround, check what that nil means. Some wrappers return it for every unsuccessful Keychain operation. “No matching item” and “the item cannot be read right now” become indistinguishable.

Keep that distinction all the way to the restoration UI. A failed read should leave a recoverable failure, not become evidence that the credential has disappeared.

Download the complete example and checks.

A failed read can become a destructive reset

This is an old problem with current consequences. An answered Stack Overflow question describes people being sent to login after an unavailable credential read. Its older workaround discussion does not establish the cause of every modern failure.

Apple’s SecItem pitfalls guide establishes a particularly nasty case: data protection can prevent reading an item, while deleting that same item can still succeed. A read-error-to-delete-and-reset fallback can therefore destroy the credential it could not retrieve. The Keychain did its job; the fallback brought a shredder.

Christian Selig’s account of unavailable UserDefaults data illustrates the broader danger of treating inaccessible storage as empty storage. Here, we can use the Keychain’s actual return status instead of guessing from a missing value.

Preserve the read result

This example reads one non-synchronizing generic-password item containing a nonempty UTF-8 token. Use the same stable service and account strings as the code that wrote your item. A changed query can legitimately find nothing. Treat errSecItemNotFound as the result of this particular lookup. A single response cannot establish that the credential has been erased.

This sample assumes only one matching item across the access groups your app is entitled to use. Omitting kSecAttrAccessGroup searches those groups; it does not restrict the query to one default group. If your app shares Keychain items, include the exact access-group value used by the writer. Apple’s access-group troubleshooting guidance explains that query behavior.

The declarations below form one source file. They target iOS 17 or later and use Swift 6.1’s type-level nonisolated spelling so they also compile in projects whose default isolation is MainActor.

import Foundation
import LocalAuthentication
import Observation
import Security

nonisolated enum CredentialReadFailure: Error, Equatable {
    case securityStatus(OSStatus)
    case unexpectedResult
    case invalidTokenData
}

actor KeychainTokenReader {
    let service: String
    let account: String

    init(service: String, account: String) {
        self.service = service
        self.account = account
    }

    func read() throws(CredentialReadFailure) -> String? {
        let authentication = LAContext()
        authentication.interactionNotAllowed = true

        let query: [String: Any] = [
            kSecClass as String: kSecClassGenericPassword,
            kSecAttrService as String: service,
            kSecAttrAccount as String: account,
            kSecAttrSynchronizable as String: false,
            kSecUseDataProtectionKeychain as String: true,
            kSecUseAuthenticationContext as String: authentication,
            kSecMatchLimit as String: kSecMatchLimitOne,
            kSecReturnData as String: true
        ]
        var result: CFTypeRef?
        let status = SecItemCopyMatching(query as CFDictionary, &result)
        return try Self.interpret(status: status, result: result)
    }

    nonisolated static func interpret(
        status: OSStatus,
        result: CFTypeRef?
    ) throws(CredentialReadFailure) -> String? {
        switch status {
        case errSecItemNotFound:
            return nil
        case errSecSuccess:
            guard let data = result as? Data else {
                throw .unexpectedResult
            }
            guard let token = String(data: data, encoding: .utf8),
                  !token.isEmpty else {
                throw .invalidTokenData
            }
            return token
        default:
            throw .securityStatus(status)
        }
    }
}

There is exactly one path to nil: errSecItemNotFound. Permission, interaction, entitlement, and other errors retain their OSStatus. Unexpected result types and malformed stored bytes also remain failures. None of these paths deletes, overwrites, or “repairs” the item.

SecItemCopyMatching is synchronous. The reader owns the call inside its actor and returns only a sendable string to its caller; the query dictionary and authentication context stay inside that call. This does not make an in-progress Security call cancellable.

The LAContext.interactionNotAllowed setting makes this a noninteractive restoration attempt. If your existing item requires biometric or other user interaction, provide a separate deliberate authentication flow. Do not interpret this reader’s failure as proof that the device is locked, or turn a required prompt into an endless automatic retry.

Give restoration an unresolved state

A local token is a candidate for your existing authentication flow. It is not proof that the server still accepts it. Keep credential discovery separate from server validation and session revocation.

nonisolated enum CredentialState: Equatable {
    case unchecked
    case available(String)
    case missing
    case unavailable(CredentialReadFailure)
}

@MainActor
@Observable
final class CredentialRestoration {
    private(set) var state = CredentialState.unchecked
    private(set) var isReading = false

    private let read: @Sendable () async throws(CredentialReadFailure) -> String?
    private var generation = UUID()

    init(
        read: @escaping @Sendable () async throws(CredentialReadFailure) -> String?
    ) {
        self.read = read
    }

    func restore() async {
        guard !isReading else { return }
        let ticket = generation
        isReading = true
        defer {
            if generation == ticket { isReading = false }
        }

        let next: CredentialState
        do {
            let token = try await read()
            next = token.map(CredentialState.available) ?? .missing
        } catch {
            next = .unavailable(error)
        }

        guard generation == ticket, !Task.isCancelled else { return }
        state = next
    }

    func invalidate() {
        generation = UUID()
        isReading = false
        state = .unchecked
    }
}

Create the model once for the restoration flow, using your existing item identifiers:

@MainActor
func makeCredentialRestoration(
    service: String,
    account: String
) -> CredentialRestoration {
    let reader = KeychainTokenReader(service: service, account: account)
    return CredentialRestoration { () async throws(CredentialReadFailure) -> String? in
        try await reader.read()
    }
}

Call await model.restore() from the task that owns restoration. While isReading is true, the previous outcome remains available for a small progress indicator. Calling restore() again while a read is in flight returns immediately. The first call still owns the result. If its view task is cancelled and a replacement task arrives during that read, the second call can return with the state still unchecked. Keep restoration owned by the session flow, or retry the unresolved read once isReading clears.

Handle the outcome explicitly:

StateUseful next action
uncheckedBegin restoration when the feature needs it.
availablePass the token to the existing authenticated-session flow.
missingA lookup reported no match. If it ran in the background or while locked, retry when the user returns before offering sign-in.
unavailableShow a concise recovery message and a contextual Retry. Preserve the stored item.

This distinction matters even for a reported no-match. Firebase Auth maintainers documented locked-device prewarming reads that returned errSecItemNotFound for an existing item. An automatic restoration attempt should never authorize deleting a credential or revoking a session. Let the next user-visible attempt guide the sign-in UI. Firebase Auth’s fix and report

For a foreground-only item, another attempt after the app becomes active or receives protectedDataDidBecomeAvailableNotification can be useful. Treat the event as a reason to retry, not as a guarantee that this particular query will now succeed. The read result still decides the outcome. An entitlement error needs a configuration fix, not a polling timer.

After the read returns, the model checks for cancellation before applying the result. Cancellation is cooperative. A request that arrives after that check cannot take back an applied result.

On sign-out or account change, call invalidate() before starting the replacement flow. That invalidates the ticket held by any in-flight read. Retire the old model and its retry triggers. The factory captures a particular service and account, so create a new model with the new identifiers when switching accounts. Your existing sign-out path still owns credential removal, server revocation and account-scoped cache invalidation.

Keep the protection you actually need

Choose an item’s accessibility when writing it according to the feature’s requirements. Apple’s accessibility guidance recommends the most restrictive suitable setting. A foreground-only token and a token required for legitimate background work may need different policies.

Changing every item to a more permissive setting is not the error-handling fix. On a passcode-protected device, AfterFirstUnlockThisDeviceOnly remains unavailable after a restart until the first unlock. Preserve status information under either policy.

Log an operation name and the numeric status when useful. Keep tokens, returned data, account identifiers, and complete query dictionaries out of logs. The private logging article covers that boundary.

Prove the failure policy separately from the lock state

The companion checks the exact article declarations with synthetic success, missing-item, interaction, entitlement, malformed-data, and unexpected-result responses. It also controls completion order to check cancellation and invalidation during restoration. A deliberately broken reader that maps every error to nil provides the negative control: it produces .missing for a credential-read failure.

Verification: the exact declarations compile with Xcode 27.2/Swift 6.4.2, including the iOS 17 deployment target, in both ordinary and MainActor default-isolation modes. Controlled checks pass on macOS 27.2; actual synthetic-item reads and malformed-byte preservation pass on iOS 27.2 Simulator in both modes. Injecting errSecInteractionNotAllowed proves how this code handles that status; it does not reproduce an actual locked iPhone. Test foreground/background launch, lock/unlock, restart before first unlock, and any biometric access-control policy on a device before claiming those lifecycle behaviors for your app. Simulator item reads likewise do not prove hardware data protection.