Sources/OrgApp/CryptPassphrases.swift

9945f06859a5feee9b6af3496e944cb6b395715b
orgstar/Sources/OrgApp/CryptPassphrases.swift

132 lines · 6402 bytes

  1import Foundation
  2import LocalAuthentication
  3import OrgDocument
  4import Security
  5
  6/// Passphrases for encrypted entries and files, kept in the Keychain by file path when asked.
  7/// Items are readable only on this device while it's unlocked, and only after Touch ID, Face
  8/// ID or the device's password (`.userPresence`); one authentication covers the reads that
  9/// follow for a while. Items earlier versions stored without that move over at their first read.
 10public enum CryptPassphrases {
 11    static let service = "sh.krz.orgstar.crypt.v2"
 12    /// Where earlier versions kept passphrases, readable without authentication.
 13    static let legacyService = "sh.krz.orgstar.crypt"
 14
 15    /// The authentication reads share.
 16    nonisolated(unsafe) static let context: LAContext = {
 17        let context = LAContext()
 18        context.touchIDAuthenticationAllowableReuseDuration = LATouchIDAuthenticationMaximumAllowableReuseDuration
 19        return context
 20    }()
 21
 22    static func query(_ path: String, service: String = service) -> [String: Any] {
 23        var query: [String: Any] = [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service, kSecAttrAccount as String: path]
 24        if service == Self.service { query[kSecUseDataProtectionKeychain as String] = true }
 25        return query
 26    }
 27
 28    /// The new item for `passphrase`: this device only, unlocked, after user presence.
 29    static func newItem(_ passphrase: String, for path: String) -> [String: Any]? {
 30        guard let access = SecAccessControlCreateWithFlags(nil, kSecAttrAccessibleWhenUnlockedThisDeviceOnly, .userPresence, nil) else { return nil }
 31        var item = query(path)
 32        item[kSecValueData as String] = Data(passphrase.utf8)
 33        item[kSecAttrAccessControl as String] = access
 34        item[kSecAttrLabel as String] = "orgstar: passphrase for " + (path as NSString).lastPathComponent
 35        return item
 36    }
 37
 38    public static func store(_ passphrase: String, for path: String) {
 39        forget(path)
 40        guard let item = newItem(passphrase, for: path) else { return }
 41        if SecItemAdd(item as CFDictionary, nil) == errSecMissingEntitlement {
 42            // A build without a Keychain entitlement (development) keeps the old kind of item.
 43            var legacy = query(path, service: legacyService)
 44            legacy[kSecValueData as String] = Data(passphrase.utf8)
 45            legacy[kSecAttrLabel as String] = item[kSecAttrLabel as String]
 46            SecItemAdd(legacy as CFDictionary, nil)
 47        }
 48    }
 49
 50    public static func forget(_ path: String) {
 51        SecItemDelete(query(path) as CFDictionary)
 52        SecItemDelete(query(path, service: legacyService) as CFDictionary)
 53    }
 54
 55    /// Whether an item exists, without asking for authentication.
 56    static func exists(_ query: [String: Any]) -> Bool {
 57        var q = query
 58        let quiet = LAContext()
 59        quiet.interactionNotAllowed = true
 60        q[kSecUseAuthenticationContext as String] = quiet
 61        q[kSecReturnAttributes as String] = true
 62        let status = SecItemCopyMatching(q as CFDictionary, nil)
 63        return status == errSecSuccess || status == errSecInteractionNotAllowed
 64    }
 65
 66    public static func hasStored(_ path: String) -> Bool {
 67        exists(query(path)) || exists(query(path, service: legacyService))
 68    }
 69
 70    /// The stored passphrase, once the person has proved who they are; nil otherwise.
 71    public static func stored(for path: String) async -> String? {
 72        let reason = "unlock the passphrase for " + (path as NSString).lastPathComponent
 73        if exists(query(path)) {
 74            var q = query(path)
 75            q[kSecReturnData as String] = true
 76            let context = Self.context
 77            context.localizedReason = reason
 78            q[kSecUseAuthenticationContext as String] = context
 79            let request = q
 80            // The read waits for Touch ID or the password, off the main thread.
 81            return await Task.detached { () -> String? in
 82                var result: AnyObject?
 83                guard SecItemCopyMatching(request as CFDictionary, &result) == errSecSuccess, let data = result as? Data else { return nil }
 84                return String(decoding: data, as: UTF8.self)
 85            }.value
 86        }
 87        guard exists(query(path, service: legacyService)) else { return nil }
 88        guard (try? await context.evaluatePolicy(.deviceOwnerAuthentication, localizedReason: reason)) == true else { return nil }
 89        var q = query(path, service: legacyService)
 90        q[kSecReturnData as String] = true
 91        var result: AnyObject?
 92        guard SecItemCopyMatching(q as CFDictionary, &result) == errSecSuccess, let data = result as? Data else { return nil }
 93        let passphrase = String(decoding: data, as: UTF8.self)
 94        // Moved to the protected kind of item; kept as it was where that can't be made.
 95        if let item = newItem(passphrase, for: path), SecItemAdd(item as CFDictionary, nil) == errSecSuccess {
 96            SecItemDelete(query(path, service: legacyService) as CFDictionary)
 97        }
 98        return passphrase
 99    }
100}
101
102extension CryptHold {
103    /// What the held file's notice says.
104    public func notice(for path: String) -> String {
105        let name = (path as NSString).lastPathComponent
106        return switch self {
107        case .entries(1): String(localized: "1 tagged entry isn't encrypted. Changes to \(name) aren't saved until it is.")
108        case .entries(let count): String(localized: "\(count) tagged entries aren't encrypted. Changes to \(name) aren't saved until they are.")
109        case .file: String(localized: "\(name) isn't saved until it has a passphrase.")
110        }
111    }
112}
113
114extension CryptHold: LocalizedError {
115    public var errorDescription: String? {
116        switch self {
117        case .entries(1): String(localized: "1 tagged entry isn't encrypted")
118        case .entries(let count): String(localized: "\(count) tagged entries aren't encrypted")
119        case .file: String(localized: "The file has no passphrase yet")
120        }
121    }
122}
123
124extension CryptReadError: LocalizedError {
125    public var errorDescription: String? {
126        switch self {
127        case .locked: String(localized: "The file is encrypted, and its passphrase isn't known")
128        case .wrongPassphrase: String(localized: "Wrong passphrase")
129        case .failed(let reason): reason
130        }
131    }
132}
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