SPB Git

Repository Public

SessionTokenStore.swift 5.3 KB 118 lines swift

1// SP Notes Core2// File: Sources/SPNotesAPI/SessionTokenStore.swift3// Description: Storage of the opaque session token: Keychain in the apps (this device only, never synced), memory in4//              tests. The token is never logged nor printed.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import Security1011/// Where the session token lives. The token is the only secret the apps keep: an opaque 43-character value issued by12/// the server after a passkey verification.13public protocol SessionTokenStore: Sendable {14    /// The stored token, or `nil` when signed out (or when the store cannot be read).15    func load() -> String?16    func save(_ token: String) throws17    func clear() throws18}1920/// A failed Keychain operation (`OSStatus`).21public struct KeychainError: Error, Equatable, Sendable, CustomStringConvertible {22    public var status: OSStatus23    public init(status: OSStatus) { self.status = status }24    public var description: String {25        let text = SecCopyErrorMessageString(status, nil) as String? ?? "unknown"26        return "Keychain error \(status): \(text)"27    }28}2930/// Session token kept as a generic password. The item is readable after the first unlock (background sync while the31/// device is locked), bound to this device (`ThisDeviceOnly`: not restored on another device) and never synchronised32/// with iCloud Keychain.33public struct KeychainTokenStore: SessionTokenStore {34    public let service: String35    public let account: String36    /// Keychain access group shared by an app and its extensions (share extension, widgets); `nil` = the app's own.37    public let accessGroup: String?38    /// Uses the data-protection keychain on macOS (the iOS-style keychain: required for access groups and for the39    /// accessibility class to be honoured). It needs a signed app with a keychain entitlement; unsigned command-line40    /// tools and unit tests must pass `false` and get the legacy file keychain. Ignored on iOS.41    public let useDataProtectionKeychain: Bool4243    /// - Parameters:44    ///   - service: `kSecAttrService`, e.g. `ai.spboucher.spnotes.session`.45    ///   - account: `kSecAttrAccount`; use the origin of the backend so that test servers never share a token with production.46    public init(service: String = "ai.spboucher.spnotes.session", account: String, accessGroup: String? = nil, useDataProtectionKeychain: Bool = true) {47        self.service = service48        self.account = account49        self.accessGroup = accessGroup50        self.useDataProtectionKeychain = useDataProtectionKeychain51    }5253    /// The store of one backend: the account is the origin.54    public init(configuration: APIConfiguration, service: String = "ai.spboucher.spnotes.session", accessGroup: String? = nil, useDataProtectionKeychain: Bool = true) {55        self.init(service: service, account: configuration.origin, accessGroup: accessGroup, useDataProtectionKeychain: useDataProtectionKeychain)56    }5758    private var baseQuery: [String: Any] {59        var q: [String: Any] = [60            kSecClass as String: kSecClassGenericPassword,61            kSecAttrService as String: service,62            kSecAttrAccount as String: account,63            kSecAttrSynchronizable as String: false,64        ]65        if let accessGroup { q[kSecAttrAccessGroup as String] = accessGroup }66        #if os(macOS)67        if useDataProtectionKeychain { q[kSecUseDataProtectionKeychain as String] = true }68        #endif69        return q70    }7172    public func load() -> String? {73        var q = baseQuery74        q[kSecReturnData as String] = true75        q[kSecMatchLimit as String] = kSecMatchLimitOne76        var out: CFTypeRef?77        guard SecItemCopyMatching(q as CFDictionary, &out) == errSecSuccess, let data = out as? Data else { return nil }78        let token = String(decoding: data, as: UTF8.self)79        return token.isEmpty ? nil : token80    }8182    public func save(_ token: String) throws {83        let attributes: [String: Any] = [84            kSecValueData as String: Data(token.utf8),85            kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly,86        ]87        var status = SecItemUpdate(baseQuery as CFDictionary, attributes as CFDictionary)88        if status == errSecItemNotFound {89            status = SecItemAdd(baseQuery.merging(attributes) { $1 } as CFDictionary, nil)90        }91        guard status == errSecSuccess else { throw KeychainError(status: status) }92    }9394    public func clear() throws {95        let status = SecItemDelete(baseQuery as CFDictionary)96        guard status == errSecSuccess || status == errSecItemNotFound else { throw KeychainError(status: status) }97    }98}99100/// In-memory store for unit tests, previews and the live integration tests.101public final class InMemoryTokenStore: SessionTokenStore, @unchecked Sendable {102    private let lock = NSLock()103    private var token: String?104    private var saves = 0105    private var clears = 0106107    public init(token: String? = nil) { self.token = token }108109    public func load() -> String? { lock.withLock { token } }110    public func save(_ token: String) { lock.withLock { self.token = token; saves += 1 } }111    public func clear() { lock.withLock { token = nil; clears += 1 } }112113    /// Number of `save` calls (tests).114    public var saveCount: Int { lock.withLock { saves } }115    /// Number of `clear` calls (tests).116    public var clearCount: Int { lock.withLock { clears } }117}118
Files main
Menu

Theme