Sources/OrgApp/CryptPassphrases.swift

3ae217cf9d3d7884e3e5238934298e929bcc5cc0
orgstar/Sources/OrgApp/CryptPassphrases.swift

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