Sources/OrgApp/CryptPassphrases.swift

251e90e5c944e5c48aa1a5f50547f575049a9f5d
orgstar/Sources/OrgApp/CryptPassphrases.swift

399 lines · 18126 bytes

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