Sources/OrgApp/CryptPassphrases.swift

8f2ce3e9aea5e545a257dab3e7600f258daab10b
orgstar/Sources/OrgApp/CryptPassphrases.swift

451 lines · 20804 bytes

  1import CryptoKit
  2import Foundation
  3import LocalAuthentication
  4import OrgCore
  5import OrgDocument
  6import Security
  7
  8/// Where passphrases are saved: the Keychain, or a stand-in in tests.
  9@MainActor
 10public protocol PassphraseKeychain: AnyObject {
 11    /// Whether a passphrase is saved for `path`, without asking for authentication.
 12    func contains(_ path: String) -> Bool
 13    /// The passphrase saved for `path`, once `context` has authenticated the person; nil otherwise.
 14    func read(_ path: String, context: LAContext) async -> String?
 15    /// Saves `passphrase` for `path`. A message to show when it wasn't kept; nil otherwise.
 16    func write(_ passphrase: String, for path: String) -> String?
 17    func delete(_ path: String)
 18    /// Deletes every saved passphrase, whatever the listing finds.
 19    func deleteAll()
 20    /// The paths passphrases are saved for, without asking for authentication.
 21    func paths() -> [String]
 22}
 23
 24/// Passphrases for encrypted entries and files, saved in the Keychain by file path while "Use
 25/// Face ID to Decrypt" is on. Off or undecided, the Keychain isn't read or written: a passphrase
 26/// is typed and kept in memory while its file is open. Items are readable only on this device
 27/// while it's unlocked, and only after Touch ID, Face ID or the device's password
 28/// (`.userPresence`), asked once per file while it's open.
 29@MainActor
 30@Observable
 31public final class CryptPassphrases {
 32    /// The app's passphrases. A test process, which has XCTest loaded, gets no Keychain.
 33    public static let shared = CryptPassphrases(keychain: NSClassFromString("XCTestCase") != nil ? NoKeychain() : SystemKeychain())
 34
 35    /// "Use Face ID to Decrypt", kept in user defaults on this device, not in `config.toml`.
 36    public enum Setting: String, Sendable {
 37        case undecided, on, off
 38    }
 39
 40    nonisolated static let settingKey = "decryptWithBiometrics"
 41    nonisolated static let service = "sh.krz.orgstar.crypt.v2"
 42    /// Where earlier versions kept passphrases, readable without authentication.
 43    nonisolated static let legacyService = "sh.krz.orgstar.crypt"
 44
 45    @ObservationIgnored let keychain: PassphraseKeychain
 46    @ObservationIgnored private let defaults: UserDefaults
 47    public private(set) var setting: Setting
 48    /// The question waits to be asked at launch: passphrases saved by an earlier version.
 49    public var asking = false
 50    /// The files with a saved passphrase, as Settings lists them.
 51    public private(set) var savedPaths: [String] = []
 52
 53    public init(keychain: PassphraseKeychain = SystemKeychain(), defaults: UserDefaults = .standard) {
 54        self.keychain = keychain
 55        self.defaults = defaults
 56        setting = defaults.string(forKey: Self.settingKey).flatMap(Setting.init) ?? .undecided
 57    }
 58
 59    private func set(_ setting: Setting) {
 60        self.setting = setting
 61        defaults.set(setting.rawValue, forKey: Self.settingKey)
 62    }
 63
 64    /// Whether this build can keep passphrases limited to this device: the Developer ID Mac app
 65    /// has no Keychain entitlement and keeps them in the login keychain.
 66    public static var protectsItems: Bool {
 67        #if os(macOS) && !APPSTORE
 68        false
 69        #else
 70        true
 71        #endif
 72    }
 73
 74    /// Said beside the setting where `protectsItems` is false.
 75    public static var caveat: String {
 76        String(localized: "This version of orgstar keeps remembered passphrases in your login keychain without limiting them to this Mac; Touch ID or your password is still asked before one is used.")
 77    }
 78
 79    /// Face ID, Touch ID or Optic ID, as this device has it; the Mac's is Touch ID.
 80    public static var biometryName: String {
 81        #if os(macOS)
 82        return "Touch ID"
 83        #else
 84        let context = LAContext()
 85        _ = context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil)
 86        return switch context.biometryType {
 87        case .touchID: "Touch ID"
 88        case .opticID: "Optic ID"
 89        default: "Face ID"
 90        }
 91        #endif
 92    }
 93
 94    /// The setting's name.
 95    public static var title: String { String(localized: "Use \(biometryName) to Decrypt") }
 96
 97    /// The question asked the first time a passphrase is typed, and at launch.
 98    public static var question: String { String(localized: "Use \(biometryName) to Decrypt?") }
 99
100    /// What the setting does, in the question and in Settings.
101    public static var explanation: String {
102        let name = biometryName
103        #if os(macOS)
104        return String(localized: "Passphrases you type for encrypted files and entries are saved in the Keychain, and \(name) or your password unlocks them. \(name) can then decrypt anything whose passphrase is saved in your Keychain. Otherwise a passphrase is typed when it's needed and kept only while its file is open.")
105        #else
106        return String(localized: "Passphrases you type for encrypted files and entries are saved in the Keychain, and \(name) or your passcode unlocks them. \(name) can then decrypt anything whose passphrase is saved in your Keychain. Otherwise a passphrase is typed when it's needed and kept only while its file is open.")
107        #endif
108    }
109
110    /// What turning the setting off removes, for its confirmation.
111    public static func removal(_ count: Int) -> String {
112        count == 1
113            ? String(localized: "The passphrase saved for 1 file is removed from the Keychain.")
114            : String(localized: "The passphrases saved for \(count) files are removed from the Keychain.")
115    }
116
117    // MARK: - The setting
118
119    /// Whether a typed passphrase waits for the question before it can be saved.
120    public var asksFirst: Bool { setting == .undecided }
121
122    /// The answer to the question: Enable turns the setting on, Not Now off. Nothing changes when
123    /// the setting was decided meanwhile (another window's question, or Settings).
124    @discardableResult
125    public func answer(enable: Bool) -> Bool {
126        asking = false
127        guard setting == .undecided else { return false }
128        set(enable ? .on : .off)
129        return true
130    }
131
132    /// A passphrase typed for `path` worked, and the file's text is now `text`: saved while the
133    /// setting is on, with the Keychain's message in `note`. True when the question must be
134    /// answered first, with `answer(enable:passphrase:for:text:)`.
135    public func typed(_ passphrase: String, for path: String, text: String, note: inout String?) -> Bool {
136        if asksFirst { return true }
137        note = keep(passphrase, for: path, text: text)
138        return false
139    }
140
141    /// The answer to the question asked for a typed passphrase: the passphrase is saved when the
142    /// answer turned the setting on. The Keychain's message; nil otherwise.
143    public func answer(enable: Bool, passphrase: String, for path: String, text: String) -> String? {
144        guard answer(enable: enable) else { return nil }
145        return keep(passphrase, for: path, text: text)
146    }
147
148    /// Whether `passphrase` opens every message in `text` encrypted with a passphrase, so that
149    /// saving it can't replace the one the file's other entries need.
150    nonisolated static func opensAll(_ text: String, with passphrase: String) -> Bool {
151        OrgCrypt.messages(text).allSatisfy { OrgCrypt.opens($0, passphrase: passphrase) }
152    }
153
154    /// Turns the setting on from Settings.
155    public func turnOn() {
156        set(.on)
157    }
158
159    /// Turns the setting off and removes every saved passphrase; Settings confirms first when
160    /// there are any.
161    public func turnOff() {
162        set(.off)
163        let paths = keychain.paths()
164        keychain.deleteAll()
165        for path in paths { endSession(for: path) }
166        refresh()
167    }
168
169    /// At launch: passphrases saved by an earlier version, while the setting is undecided, ask
170    /// the question.
171    public func askIfSavedBefore() {
172        guard setting == .undecided, !keychain.paths().isEmpty else { return }
173        asking = true
174    }
175
176    /// Reads the files with a saved passphrase again, for Settings.
177    public func refresh() {
178        savedPaths = keychain.paths().sorted()
179    }
180
181    // MARK: - Passphrases
182
183    /// One authentication per file while it's open; `endSession` ends it.
184    @ObservationIgnored private var contexts: [String: LAContext] = [:]
185
186    func context(for path: String) -> LAContext {
187        if let context = contexts[path] { return context }
188        let context = LAContext()
189        contexts[path] = context
190        return context
191    }
192
193    /// The file closed: its authentication no longer reads its passphrase.
194    public func endSession(for path: String) {
195        contexts.removeValue(forKey: path)?.invalidate()
196    }
197
198    /// A passphrase typed for `path` that opened or encrypted it, whose text is now `text`: saved
199    /// while the setting is on and it opens every message in `text`. A message to show when it
200    /// wasn't kept; nil otherwise.
201    @discardableResult
202    public func keep(_ passphrase: String, for path: String, text: String) -> String? {
203        guard setting == .on, Self.opensAll(text, with: passphrase) else { return nil }
204        let note = keychain.write(passphrase, for: path)
205        refresh()
206        return note
207    }
208
209    /// Forget Encryption Passphrase, or Forget in Settings: the saved passphrase is removed.
210    public func forget(_ path: String) {
211        endSession(for: path)
212        keychain.delete(path)
213        savedPaths.removeAll { $0 == path }
214    }
215
216    /// Whether a passphrase is saved for `path` and may be used, without asking for authentication.
217    public func hasStored(_ path: String) -> Bool {
218        setting == .on && keychain.contains(path)
219    }
220
221    /// The saved passphrase, once the person has proved who they are; nil otherwise, and always
222    /// while the setting isn't on.
223    public func stored(for path: String) async -> String? {
224        guard setting == .on, keychain.contains(path) else { return nil }
225        return await keychain.read(path, context: context(for: path))
226    }
227}
228
229/// The Keychain. New items are this device only, unlocked, after user presence. Items earlier
230/// versions saved without that move over at their first read. A build without a Keychain
231/// entitlement (the Developer ID Mac app) can't make such items and keeps the old kind.
232@MainActor
233public final class SystemKeychain: PassphraseKeychain {
234    public init() {}
235
236    /// A Keychain query handed to the thread that waits on it; nothing else uses it meanwhile.
237    struct Request: @unchecked Sendable {
238        let query: [String: Any]
239    }
240
241    nonisolated static func query(_ path: String?, service: String = CryptPassphrases.service) -> [String: Any] {
242        var query: [String: Any] = [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service]
243        if let path { query[kSecAttrAccount as String] = path }
244        if service == CryptPassphrases.service { query[kSecUseDataProtectionKeychain as String] = true }
245        return query
246    }
247
248    /// The new item for `passphrase`: this device only, unlocked, after user presence.
249    nonisolated static func newItem(_ passphrase: String, for path: String) -> [String: Any]? {
250        guard let access = SecAccessControlCreateWithFlags(nil, kSecAttrAccessibleWhenUnlockedThisDeviceOnly, .userPresence, nil) else { return nil }
251        var item = query(path)
252        item[kSecValueData as String] = Data(passphrase.utf8)
253        item[kSecAttrAccessControl as String] = access
254        item[kSecAttrLabel as String] = "orgstar: passphrase for " + (path as NSString).lastPathComponent
255        return item
256    }
257
258    /// Adds `item`, in place of one there already.
259    nonisolated static func add(_ item: [String: Any], replacing query: [String: Any]) -> OSStatus {
260        var status = SecItemAdd(item as CFDictionary, nil)
261        if status == errSecDuplicateItem {
262            SecItemDelete(query as CFDictionary)
263            status = SecItemAdd(item as CFDictionary, nil)
264        }
265        return status
266    }
267
268    public func write(_ passphrase: String, for path: String) -> String? {
269        let refused = String(localized: "The passphrase wasn't remembered: the Keychain refused it.")
270        guard let item = Self.newItem(passphrase, for: path) else { return refused }
271        let status = Self.add(item, replacing: Self.query(path))
272        if status == errSecSuccess {
273            SecItemDelete(Self.query(path, service: CryptPassphrases.legacyService) as CFDictionary)
274            return nil
275        }
276        guard status == errSecMissingEntitlement else { return refused }
277        var legacy = Self.query(path, service: CryptPassphrases.legacyService)
278        legacy[kSecValueData as String] = Data(passphrase.utf8)
279        legacy[kSecAttrLabel as String] = item[kSecAttrLabel as String]
280        guard Self.add(legacy, replacing: Self.query(path, service: CryptPassphrases.legacyService)) == errSecSuccess else { return refused }
281        SecItemDelete(Self.query(path) as CFDictionary)
282        return nil
283    }
284
285    public func delete(_ path: String) {
286        SecItemDelete(Self.query(path) as CFDictionary)
287        SecItemDelete(Self.query(path, service: CryptPassphrases.legacyService) as CFDictionary)
288    }
289
290    public func deleteAll() {
291        for service in [CryptPassphrases.service, CryptPassphrases.legacyService] {
292            // The file-based keychain may delete one match per call.
293            var count = 0
294            while count < 1000, SecItemDelete(Self.query(nil, service: service) as CFDictionary) == errSecSuccess { count += 1 }
295        }
296    }
297
298    /// `query` for attributes only, without asking for authentication.
299    nonisolated static func quiet(_ query: [String: Any]) -> [String: Any] {
300        var q = query
301        let quiet = LAContext()
302        quiet.interactionNotAllowed = true
303        q[kSecUseAuthenticationContext as String] = quiet
304        q[kSecReturnAttributes as String] = true
305        return q
306    }
307
308    /// Whether an item exists, without asking for authentication.
309    nonisolated static func exists(_ query: [String: Any]) -> Bool {
310        let status = SecItemCopyMatching(quiet(query) as CFDictionary, nil)
311        return status == errSecSuccess || status == errSecInteractionNotAllowed
312    }
313
314    public func contains(_ path: String) -> Bool {
315        Self.exists(Self.query(path)) || Self.exists(Self.query(path, service: CryptPassphrases.legacyService))
316    }
317
318    public func paths() -> [String] {
319        var paths: Set<String> = []
320        for service in [CryptPassphrases.service, CryptPassphrases.legacyService] {
321            var q = Self.quiet(Self.query(nil, service: service))
322            q[kSecMatchLimit as String] = kSecMatchLimitAll
323            var result: AnyObject?
324            guard SecItemCopyMatching(q as CFDictionary, &result) == errSecSuccess, let items = result as? [[String: Any]] else { continue }
325            for item in items { if let account = item[kSecAttrAccount as String] as? String { paths.insert(account) } }
326        }
327        return Array(paths)
328    }
329
330    public func read(_ path: String, context: LAContext) async -> String? {
331        let reason = "unlock the passphrase for " + (path as NSString).lastPathComponent
332        if Self.exists(Self.query(path)) {
333            var q = Self.query(path)
334            q[kSecReturnData as String] = true
335            context.localizedReason = reason
336            q[kSecUseAuthenticationContext as String] = context
337            let request = Request(query: q)
338            // The read waits for Touch ID or the password, off the main thread.
339            return await Task.detached { () -> String? in
340                var result: AnyObject?
341                guard SecItemCopyMatching(request.query as CFDictionary, &result) == errSecSuccess, let data = result as? Data else { return nil }
342                return String(decoding: data, as: UTF8.self)
343            }.value
344        }
345        let legacyQuery = Self.query(path, service: CryptPassphrases.legacyService)
346        guard Self.exists(legacyQuery) else { return nil }
347        guard (try? await context.evaluatePolicy(.deviceOwnerAuthentication, localizedReason: reason)) == true else { return nil }
348        var q = legacyQuery
349        q[kSecReturnData as String] = true
350        var result: AnyObject?
351        guard SecItemCopyMatching(q as CFDictionary, &result) == errSecSuccess, let data = result as? Data else { return nil }
352        let passphrase = String(decoding: data, as: UTF8.self)
353        // Moved to the protected kind of item; kept as it was where that can't be made.
354        if let item = Self.newItem(passphrase, for: path), Self.add(item, replacing: Self.query(path)) == errSecSuccess {
355            SecItemDelete(legacyQuery as CFDictionary)
356        }
357        return passphrase
358    }
359}
360
361/// No Keychain: nothing is saved or found. For test processes.
362@MainActor
363final class NoKeychain: PassphraseKeychain {
364    func contains(_ path: String) -> Bool { false }
365    func read(_ path: String, context: LAContext) async -> String? { nil }
366    func write(_ passphrase: String, for path: String) -> String? { nil }
367    func delete(_ path: String) {}
368    func deleteAll() {}
369    func paths() -> [String] { [] }
370}
371
372/// The key clock history hashes encrypted headings' titles with, made once and kept in the
373/// Keychain, on this device only, without asking for authentication.
374public enum ClockTitleKey {
375    static let service = "sh.krz.orgstar.clock-title-key"
376
377    static func query(dataProtection: Bool) -> [String: Any] {
378        var query: [String: Any] = [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service, kSecAttrAccount as String: "key"]
379        if dataProtection { query[kSecUseDataProtectionKeychain as String] = true }
380        return query
381    }
382
383    /// The key, made and kept the first time; nil when the Keychain keeps none.
384    public static func loadOrCreate() -> SymmetricKey? {
385        for dataProtection in [true, false] {
386            var q = query(dataProtection: dataProtection)
387            q[kSecReturnData as String] = true
388            var result: AnyObject?
389            if SecItemCopyMatching(q as CFDictionary, &result) == errSecSuccess, let data = result as? Data, data.count == 32 { return SymmetricKey(data: data) }
390        }
391        let key = SymmetricKey(size: .bits256)
392        let data = key.withUnsafeBytes { Data($0) }
393        for dataProtection in [true, false] {
394            var item = query(dataProtection: dataProtection)
395            item[kSecValueData as String] = data
396            item[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
397            item[kSecAttrLabel as String] = "orgstar: clock history key"
398            if SecItemAdd(item as CFDictionary, nil) == errSecSuccess { return key }
399        }
400        return nil
401    }
402}
403
404extension CryptHold {
405    /// Whether giving the passphrase lets the file be saved.
406    public var takesPassphrase: Bool {
407        if case .blocked = self { return false }
408        return true
409    }
410
411    /// What the held file's notice says.
412    public func notice(for path: String) -> String {
413        let name = (path as NSString).lastPathComponent
414        return switch self {
415        case .entries(1): String(localized: "1 tagged entry isn't encrypted. Changes to \(name) aren't saved until it is.")
416        case .entries(let count): String(localized: "\(count) tagged entries aren't encrypted. Changes to \(name) aren't saved until they are.")
417        case .file: String(localized: "\(name) isn't saved until it has a passphrase.")
418        case .blocked(let reason): reason + ". " + String(localized: "Changes to \(name) aren't saved until that's fixed.")
419        }
420    }
421}
422
423extension SaveError: LocalizedError {
424    public var errorDescription: String? {
425        switch self {
426        case .fileKeepsChanging: String(localized: "The file keeps changing on disk; nothing was saved.")
427        case .otherVersionRestored: String(localized: "The file changed on disk; nothing was changed.")
428        }
429    }
430}
431
432extension CryptHold: LocalizedError {
433    public var errorDescription: String? {
434        switch self {
435        case .entries(1): String(localized: "1 tagged entry isn't encrypted")
436        case .entries(let count): String(localized: "\(count) tagged entries aren't encrypted")
437        case .file: String(localized: "The file has no passphrase yet")
438        case .blocked(let reason): reason
439        }
440    }
441}
442
443extension CryptReadError: LocalizedError {
444    public var errorDescription: String? {
445        switch self {
446        case .locked: String(localized: "The file is encrypted, and its passphrase isn't known")
447        case .wrongPassphrase: String(localized: "Wrong passphrase")
448        case .failed(let reason): reason
449        }
450    }
451}
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form