Commit 52d620b11e

52d620b11ecb28c3cd78962df6e07dbbe747bda1

parent: 251e90e5c9

Verified · cmc

cmc <hello@cleberg.net> · 2026-11-26 16:10 UTC

Save only passphrases that open the file; late answers change nothing

A typed passphrase is saved only when it opens every passphrase-encrypted
message in the file's text, so Encrypt beside an entry under another
passphrase, or an unlock that opened only the first message, keeps the saved
item. The "encrypted already" path saves nothing. answer(enable:) changes the
setting only while it is undecided. Turning off deletes by service. The shared
instance has no Keychain in a test process. The sheet's keep and answer logic
moved into CryptPassphrases.typed and answer(enable:passphrase:for:text:).

Ref #239

Layout: unified · split

Changed files (6)
Sources/OrgApp/CryptPassphrases.swift +61 −10 · view
@@ -1,6 +1,7 @@
1import CryptoKit 1import CryptoKit
2import Foundation 2import Foundation
3import LocalAuthentication 3import LocalAuthentication
4import OrgCore
4import OrgDocument 5import OrgDocument
5import Security 6import Security
6 7
@@ -14,6 +15,8 @@ public protocol PassphraseKeychain: AnyObject {
14 /// Saves `passphrase` for `path`. A message to show when it wasn't kept; nil otherwise. 15 /// 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 write(_ passphrase: String, for path: String) -> String?
16 func delete(_ path: String) 17 func delete(_ path: String)
18 /// Deletes every saved passphrase, whatever the listing finds.
19 func deleteAll()
17 /// The paths passphrases are saved for, without asking for authentication. 20 /// The paths passphrases are saved for, without asking for authentication.
18 func paths() -> [String] 21 func paths() -> [String]
19} 22}
@@ -26,7 +29,8 @@ public protocol PassphraseKeychain: AnyObject {
26@MainActor 29@MainActor
27@Observable 30@Observable
28public final class CryptPassphrases { 31public final class CryptPassphrases {
29 public static let shared = 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())
30 34
31 /// "Use Face ID to Decrypt", kept in user defaults on this device, not in `config.toml`. 35 /// "Use Face ID to Decrypt", kept in user defaults on this device, not in `config.toml`.
32 public enum Setting: String, Sendable { 36 public enum Setting: String, Sendable {
@@ -38,7 +42,7 @@ public final class CryptPassphrases {
38 /// Where earlier versions kept passphrases, readable without authentication. 42 /// Where earlier versions kept passphrases, readable without authentication.
39 nonisolated static let legacyService = "sh.krz.orgstar.crypt" 43 nonisolated static let legacyService = "sh.krz.orgstar.crypt"
40 44
41 @ObservationIgnored private let keychain: PassphraseKeychain 45 @ObservationIgnored let keychain: PassphraseKeychain
42 @ObservationIgnored private let defaults: UserDefaults 46 @ObservationIgnored private let defaults: UserDefaults
43 public private(set) var setting: Setting 47 public private(set) var setting: Setting
44 /// The question waits to be asked at launch: passphrases saved by an earlier version. 48 /// The question waits to be asked at launch: passphrases saved by an earlier version.
@@ -115,10 +119,36 @@ public final class CryptPassphrases {
115 /// Whether a typed passphrase waits for the question before it can be saved. 119 /// Whether a typed passphrase waits for the question before it can be saved.
116 public var asksFirst: Bool { setting == .undecided } 120 public var asksFirst: Bool { setting == .undecided }
117 121
118 /// The answer to the question: Enable turns the setting on, Not Now off. 122 /// The answer to the question: Enable turns the setting on, Not Now off. Nothing changes when
119 public func answer(enable: Bool) { 123 /// the setting was decided meanwhile (another window's question, or Settings).
120 set(enable ? .on : .off) 124 @discardableResult
125 public func answer(enable: Bool) -> Bool {
121 asking = false 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) }
122 } 152 }
123 153
124 /// Turns the setting on from Settings. 154 /// Turns the setting on from Settings.
@@ -130,7 +160,9 @@ public final class CryptPassphrases {
130 /// there are any. 160 /// there are any.
131 public func turnOff() { 161 public func turnOff() {
132 set(.off) 162 set(.off)
133 for path in keychain.paths() { forget(path) } 163 let paths = keychain.paths()
164 keychain.deleteAll()
165 for path in paths { endSession(for: path) }
134 refresh() 166 refresh()
135 } 167 }
136 168
@@ -163,11 +195,12 @@ public final class CryptPassphrases {
163 contexts.removeValue(forKey: path)?.invalidate() 195 contexts.removeValue(forKey: path)?.invalidate()
164 } 196 }
165 197
166 /// A passphrase typed for `path` that opened or encrypted it: saved while the setting is on. 198 /// A passphrase typed for `path` that opened or encrypted it, whose text is now `text`: saved
167 /// A message to show when it wasn't kept; nil otherwise. 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.
168 @discardableResult 201 @discardableResult
169 public func keep(_ passphrase: String, for path: String) -> String? { 202 public func keep(_ passphrase: String, for path: String, text: String) -> String? {
170 guard setting == .on else { return nil } 203 guard setting == .on, Self.opensAll(text, with: passphrase) else { return nil }
171 let note = keychain.write(passphrase, for: path) 204 let note = keychain.write(passphrase, for: path)
172 refresh() 205 refresh()
173 return note 206 return note
@@ -254,6 +287,13 @@ public final class SystemKeychain: PassphraseKeychain {
254 SecItemDelete(Self.query(path, service: CryptPassphrases.legacyService) as CFDictionary) 287 SecItemDelete(Self.query(path, service: CryptPassphrases.legacyService) as CFDictionary)
255 } 288 }
256 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 for _ in 0..<1000 where SecItemDelete(Self.query(nil, service: service) as CFDictionary) == errSecSuccess {}
294 }
295 }
296
257 /// `query` for attributes only, without asking for authentication. 297 /// `query` for attributes only, without asking for authentication.
258 nonisolated static func quiet(_ query: [String: Any]) -> [String: Any] { 298 nonisolated static func quiet(_ query: [String: Any]) -> [String: Any] {
259 var q = query 299 var q = query
@@ -317,6 +357,17 @@ public final class SystemKeychain: PassphraseKeychain {
317 } 357 }
318} 358}
319 359
360/// No Keychain: nothing is saved or found. For test processes.
361@MainActor
362final class NoKeychain: PassphraseKeychain {
363 func contains(_ path: String) -> Bool { false }
364 func read(_ path: String, context: LAContext) async -> String? { nil }
365 func write(_ passphrase: String, for path: String) -> String? { nil }
366 func delete(_ path: String) {}
367 func deleteAll() {}
368 func paths() -> [String] { [] }
369}
370
320/// The key clock history hashes encrypted headings' titles with, made once and kept in the 371/// 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. 372/// Keychain, on this device only, without asking for authentication.
322public enum ClockTitleKey { 373public enum ClockTitleKey {
Sources/OrgApp/CryptSheet.swift +25 −21 · view
@@ -68,9 +68,9 @@ public struct CryptSheet: View {
68 @State private var repeated = "" 68 @State private var repeated = ""
69 /// What the Keychain said when the passphrase was saved, shown with the result. 69 /// What the Keychain said when the passphrase was saved, shown with the result.
70 @State private var keychainNote: String? 70 @State private var keychainNote: String?
71 /// A typed passphrase that worked, waiting for the answer to whether to use Face ID, and 71 /// A typed passphrase that worked, the file's text with it, waiting for the answer to
72 /// what follows. 72 /// whether to use Face ID, and what follows.
73 @State private var question: (passphrase: String, then: () -> Void)? 73 @State private var question: (passphrase: String, text: String, then: () -> Void)?
74 @State private var problem: String? 74 @State private var problem: String?
75 /// The decrypted entry being edited, and the passphrase it came with. 75 /// The decrypted entry being edited, and the passphrase it came with.
76 @State private var editing: (original: String, passphrase: String)? 76 @State private var editing: (original: String, passphrase: String)?
@@ -132,23 +132,25 @@ public struct CryptSheet: View {
132 132
133 private var passphrases: CryptPassphrases { session?.passphrases ?? .shared } 133 private var passphrases: CryptPassphrases { session?.passphrases ?? .shared }
134 134
135 /// A typed passphrase worked: saved while the setting is on, after the question while it's 135 /// A typed passphrase worked, and the file's text is now `text`: saved while the setting is
136 /// undecided, then `then`. 136 /// on, after the question while it's undecided, then `then`. A nil `text` (nothing was
137 private func keep(_ passphrase: String, remembered: Bool, then: @escaping () -> Void) { 137 /// checked) saves nothing.
138 guard !remembered else { return then() } 138 private func keep(_ passphrase: String, remembered: Bool, text: String?, then: @escaping () -> Void) {
139 if passphrases.asksFirst { return question = (passphrase, then) } 139 guard !remembered, let text else { return then() }
140 keychainNote = passphrases.keep(passphrase, for: request.path) 140 if passphrases.typed(passphrase, for: request.path, text: text, note: &keychainNote) { return question = (passphrase, text, then) }
141 then() 141 then()
142 } 142 }
143 143
144 private func answer(enable: Bool) { 144 private func answer(enable: Bool) {
145 guard let question else { return } 145 guard let question else { return }
146 self.question = nil 146 self.question = nil
147 passphrases.answer(enable: enable) 147 keychainNote = passphrases.answer(enable: enable, passphrase: question.passphrase, for: request.path, text: question.text)
148 keychainNote = passphrases.keep(question.passphrase, for: request.path)
149 question.then() 148 question.then()
150 } 149 }
151 150
151 /// The open file's text, after a passphrase opened or saved it.
152 private var unlockedText: String { session?.document(of: request.path)?.text ?? "" }
153
152 private var title: String { 154 private var title: String {
153 switch request.mode { 155 switch request.mode {
154 case .encrypt: "Encrypt Entry" 156 case .encrypt: "Encrypt Entry"
@@ -195,9 +197,9 @@ public struct CryptSheet: View {
195 if request.unlocks { 197 if request.unlocks {
196 if let failure = session?.unlock(passphrase, for: request.path) { return problem = failure } 198 if let failure = session?.unlock(passphrase, for: request.path) { return problem = failure }
197 switch request.mode { 199 switch request.mode {
198 case .encryptOnSave: return finish(String(localized: "Tagged entries encrypted and saved"), passphrase: passphrase, remembered: remembered) 200 case .encryptOnSave: return finish(String(localized: "Tagged entries encrypted and saved"), passphrase: passphrase, remembered: remembered, text: unlockedText)
199 case .newFile: return finish(String(localized: "Saved encrypted"), passphrase: passphrase, remembered: remembered) 201 case .newFile: return finish(String(localized: "Saved encrypted"), passphrase: passphrase, remembered: remembered, text: unlockedText)
200 default: return finish(nil, passphrase: passphrase, remembered: remembered) 202 default: return finish(nil, passphrase: passphrase, remembered: remembered, text: unlockedText)
201 } 203 }
202 } 204 }
203 let current = text() 205 let current = text()
@@ -205,21 +207,21 @@ public struct CryptSheet: View {
205 switch request.mode { 207 switch request.mode {
206 case .encrypt: 208 case .encrypt:
207 guard let encrypted = try OrgCrypt.encrypt(current, at: request.offset, passphrase: passphrase) else { 209 guard let encrypted = try OrgCrypt.encrypt(current, at: request.offset, passphrase: passphrase) else {
208 return finish("The entry is encrypted already", passphrase: passphrase, remembered: remembered) 210 return finish("The entry is encrypted already", passphrase: passphrase, remembered: remembered, text: nil)
209 } 211 }
210 apply(encrypted) 212 apply(encrypted)
211 finish("Entry encrypted", passphrase: passphrase, remembered: remembered) 213 finish("Entry encrypted", passphrase: passphrase, remembered: remembered, text: encrypted)
212 case .encryptAll(let tag): 214 case .encryptAll(let tag):
213 let (encrypted, count) = try OrgCrypt.encryptAll(current, passphrase: passphrase, tag: tag) 215 let (encrypted, count) = try OrgCrypt.encryptAll(current, passphrase: passphrase, tag: tag)
214 if count > 0 { apply(encrypted) } 216 if count > 0 { apply(encrypted) }
215 finish("Encrypted \(count) \(count == 1 ? "entry" : "entries")", passphrase: passphrase, remembered: remembered) 217 finish("Encrypted \(count) \(count == 1 ? "entry" : "entries")", passphrase: passphrase, remembered: remembered, text: count > 0 ? encrypted : nil)
216 case .open: 218 case .open:
217 let plain = try OrgCrypt.decrypt(current, at: request.offset, passphrase: passphrase).plaintext 219 let plain = try OrgCrypt.decrypt(current, at: request.offset, passphrase: passphrase).plaintext
218 session?.cryptUsed(passphrase, for: request.path) 220 session?.cryptUsed(passphrase, for: request.path)
219 plaintext = plain 221 plaintext = plain
220 editing = (plain, passphrase) 222 editing = (plain, passphrase)
221 problem = nil 223 problem = nil
222 keep(passphrase, remembered: remembered) {} 224 keep(passphrase, remembered: remembered, text: current) {}
223 case .decryptInPlace: 225 case .decryptInPlace:
224 let message = OrgCrypt.encryptedRange(current, at: request.offset).map { (current as NSString).substring(with: NSRange($0)) } 226 let message = OrgCrypt.encryptedRange(current, at: request.offset).map { (current as NSString).substring(with: NSRange($0)) }
225 let decrypted = try OrgCrypt.decryptInPlace(current, at: request.offset, passphrase: passphrase) 227 let decrypted = try OrgCrypt.decryptInPlace(current, at: request.offset, passphrase: passphrase)
@@ -228,7 +230,7 @@ public struct CryptSheet: View {
228 session?.cryptDecrypted(message: message, plaintext: (decrypted as NSString).substring(with: NSRange(body)), for: request.path) 230 session?.cryptDecrypted(message: message, plaintext: (decrypted as NSString).substring(with: NSRange(body)), for: request.path)
229 } 231 }
230 apply(decrypted) 232 apply(decrypted)
231 finish("Entry decrypted", passphrase: passphrase, remembered: remembered) 233 finish("Entry decrypted", passphrase: passphrase, remembered: remembered, text: decrypted)
232 case .encryptOnSave, .openFile, .newFile: 234 case .encryptOnSave, .openFile, .newFile:
233 break 235 break
234 } 236 }
@@ -237,9 +239,11 @@ public struct CryptSheet: View {
237 } 239 }
238 } 240 }
239 241
240 private func finish(_ message: String?, passphrase: String, remembered: Bool) { 242 /// Closes with `message`; `text` is the file's text the passphrase was checked against, nil
243 /// when it wasn't.
244 private func finish(_ message: String?, passphrase: String, remembered: Bool, text: String?) {
241 if !request.unlocks { session?.cryptUsed(passphrase, for: request.path) } 245 if !request.unlocks { session?.cryptUsed(passphrase, for: request.path) }
242 keep(passphrase, remembered: remembered) { 246 keep(passphrase, remembered: remembered, text: text) {
243 let text = [message, keychainNote].compactMap { $0 }.joined(separator: " ") 247 let text = [message, keychainNote].compactMap { $0 }.joined(separator: " ")
244 done(text.isEmpty ? nil : text) 248 done(text.isEmpty ? nil : text)
245 } 249 }
Sources/OrgCore/Crypto/OrgCrypt.swift +17 · view
@@ -237,6 +237,23 @@ public enum OrgCrypt {
237 } 237 }
238 } 238 }
239 239
240 /// Every entry's message in `text` encrypted with a passphrase.
241 public static func messages(_ text: String) -> [String] {
242 let ns = text as NSString
243 var found: [String] = []
244 var search = NSRange(location: 0, length: ns.length)
245 while true {
246 let begin = ns.range(of: "-----BEGIN PGP MESSAGE-----", options: [], range: search)
247 guard begin.location != NSNotFound else { return found }
248 let lineStart = ns.lineRange(for: NSRange(location: begin.location, length: 0)).location
249 if let range = encryptedRange(text, at: lineStart), range.lowerBound == lineStart {
250 let message = ns.substring(with: NSRange(range))
251 if let data = try? OpenPGP.dearmor(message), OpenPGP.isSymmetric(data) { found.append(message) }
252 }
253 search = NSRange(location: NSMaxRange(begin), length: ns.length - NSMaxRange(begin))
254 }
255 }
256
240 /// Whether `passphrase` opens `message`. 257 /// Whether `passphrase` opens `message`.
241 public static func opens(_ message: String, passphrase: String) -> Bool { 258 public static func opens(_ message: String, passphrase: String) -> Bool {
242 (try? OpenPGP.decrypt(OpenPGP.dearmor(message), passphrase: passphrase)) != nil 259 (try? OpenPGP.decrypt(OpenPGP.dearmor(message), passphrase: passphrase)) != nil
Sources/Orgstar/OrgstarApp.swift +1 −1 · view
@@ -408,7 +408,7 @@ enum UnsavedChanges {
408 } else if let failure = session.unlock(passphrase, for: path) { 408 } else if let failure = session.unlock(passphrase, for: path) {
409 problem = failure 409 problem = failure
410 } else { 410 } else {
411 session.passphrases.keep(passphrase, for: path) 411 session.passphrases.keep(passphrase, for: path, text: session.document(of: path)?.text ?? "")
412 return !session.dirtyPaths.contains(path) 412 return !session.dirtyPaths.contains(path)
413 } 413 }
414 case .alertSecondButtonReturn: return true 414 case .alertSecondButtonReturn: return true
Tests/OrgAppTests/CryptPassphrasesTests.swift +118 −7 · view
@@ -45,9 +45,17 @@ final class FakeKeychain: PassphraseKeychain {
45 saved[path] = nil 45 saved[path] = nil
46 } 46 }
47 47
48 func deleteAll() {
49 calls.append("deleteAll")
50 saved = [:]
51 }
52
53 /// The listing finds nothing, as when the Keychain refuses it.
54 var listingFails = false
55
48 func paths() -> [String] { 56 func paths() -> [String] {
49 calls.append("paths") 57 calls.append("paths")
50 return Array(saved.keys) 58 return listingFails ? [] : Array(saved.keys)
51 } 59 }
52} 60}
53 61
@@ -99,7 +107,7 @@ struct CryptPassphrasesTests {
99 #expect(await passphrases.stored(for: file.path) == nil) 107 #expect(await passphrases.stored(for: file.path) == nil)
100 #expect(await passphrases.stored(for: gpg.path) == nil) 108 #expect(await passphrases.stored(for: gpg.path) == nil)
101 #expect(!passphrases.hasStored(file.path)) 109 #expect(!passphrases.hasStored(file.path))
102 #expect(passphrases.keep("typed", for: file.path) == nil) 110 #expect(passphrases.keep("typed", for: file.path, text: "") == nil)
103 #expect(session.unlock("pw", for: gpg.path) == nil) 111 #expect(session.unlock("pw", for: gpg.path) == nil)
104 #expect(session.isOpen(gpg.path)) 112 #expect(session.isOpen(gpg.path))
105 113
@@ -110,7 +118,7 @@ struct CryptPassphrasesTests {
110 @Test func onSavesATypedPassphraseAndReadsItThroughTheFilesAuthentication() async throws { 118 @Test func onSavesATypedPassphraseAndReadsItThroughTheFilesAuthentication() async throws {
111 let (keychain, passphrases) = FakeKeychain.passphrases(.on) 119 let (keychain, passphrases) = FakeKeychain.passphrases(.on)
112 #expect(!passphrases.asksFirst) 120 #expect(!passphrases.asksFirst)
113 #expect(passphrases.keep("pw", for: "/x/a.org") == nil) 121 #expect(passphrases.keep("pw", for: "/x/a.org", text: "") == nil)
114 #expect(keychain.saved == ["/x/a.org": "pw"]) 122 #expect(keychain.saved == ["/x/a.org": "pw"])
115 #expect(passphrases.savedPaths == ["/x/a.org"]) 123 #expect(passphrases.savedPaths == ["/x/a.org"])
116 #expect(passphrases.hasStored("/x/a.org")) 124 #expect(passphrases.hasStored("/x/a.org"))
@@ -151,11 +159,11 @@ struct CryptPassphrasesTests {
151 // Undecided: the first typed passphrase asks, and isn't saved before the answer. 159 // Undecided: the first typed passphrase asks, and isn't saved before the answer.
152 let (keychain, passphrases) = FakeKeychain.passphrases(.undecided, defaults: defaults) 160 let (keychain, passphrases) = FakeKeychain.passphrases(.undecided, defaults: defaults)
153 #expect(passphrases.setting == .undecided && passphrases.asksFirst) 161 #expect(passphrases.setting == .undecided && passphrases.asksFirst)
154 #expect(passphrases.keep("pw", for: "/x/a.org") == nil && keychain.saved.isEmpty) 162 #expect(passphrases.keep("pw", for: "/x/a.org", text: "") == nil && keychain.saved.isEmpty)
155 // Not Now turns it off, for good. 163 // Not Now turns it off, for good.
156 passphrases.answer(enable: false) 164 passphrases.answer(enable: false)
157 #expect(passphrases.setting == .off && !passphrases.asksFirst) 165 #expect(passphrases.setting == .off && !passphrases.asksFirst)
158 #expect(passphrases.keep("pw", for: "/x/a.org") == nil && keychain.saved.isEmpty) 166 #expect(passphrases.keep("pw", for: "/x/a.org", text: "") == nil && keychain.saved.isEmpty)
159 let later = CryptPassphrases(keychain: FakeKeychain(["/x/old.org": "pw"]), defaults: defaults) 167 let later = CryptPassphrases(keychain: FakeKeychain(["/x/old.org": "pw"]), defaults: defaults)
160 #expect(later.setting == .off && !later.asksFirst) 168 #expect(later.setting == .off && !later.asksFirst)
161 later.askIfSavedBefore() 169 later.askIfSavedBefore()
@@ -164,7 +172,7 @@ struct CryptPassphrasesTests {
164 let (enabled, enabling) = FakeKeychain.passphrases(.undecided) 172 let (enabled, enabling) = FakeKeychain.passphrases(.undecided)
165 enabling.answer(enable: true) 173 enabling.answer(enable: true)
166 #expect(enabling.setting == .on && !enabling.asksFirst) 174 #expect(enabling.setting == .on && !enabling.asksFirst)
167 enabling.keep("pw", for: "/x/a.org") 175 enabling.keep("pw", for: "/x/a.org", text: "")
168 #expect(enabled.saved == ["/x/a.org": "pw"]) 176 #expect(enabled.saved == ["/x/a.org": "pw"])
169 } 177 }
170 178
@@ -200,7 +208,7 @@ struct CryptPassphrasesTests {
200 passphrases.turnOff() 208 passphrases.turnOff()
201 #expect(passphrases.setting == .off) 209 #expect(passphrases.setting == .off)
202 #expect(keychain.saved.isEmpty && passphrases.savedPaths.isEmpty) 210 #expect(keychain.saved.isEmpty && passphrases.savedPaths.isEmpty)
203 #expect(Set(keychain.calls.filter { $0.hasPrefix("delete ") }) == ["delete /x/a.org", "delete /x/b.org.gpg"]) 211 #expect(keychain.calls.contains("deleteAll"))
204 #expect(passphrases.context(for: "/x/a.org") !== context) 212 #expect(passphrases.context(for: "/x/a.org") !== context)
205 // Forget in Settings removes one. 213 // Forget in Settings removes one.
206 let (one, forgetting) = FakeKeychain.passphrases(.on, saved: ["/x/a.org": "a", "/x/b.org": "b"]) 214 let (one, forgetting) = FakeKeychain.passphrases(.on, saved: ["/x/a.org": "a", "/x/b.org": "b"])
@@ -217,4 +225,107 @@ struct CryptPassphrasesTests {
217 passphrases.turnOff() 225 passphrases.turnOff()
218 #expect(defaults.string(forKey: "decryptWithBiometrics") == "off") 226 #expect(defaults.string(forKey: "decryptWithBiometrics") == "off")
219 } 227 }
228
229 // MARK: - Review of MR 494
230
231 /// Two entries, A encrypted with "pw" and B with "other".
232 static func twoPassphrases() throws -> String {
233 let text = "* A :crypt:\na\n* B :crypt:\nb\n"
234 let a = try #require(try OrgCrypt.encrypt(text, at: 0, passphrase: "pw"))
235 let b = (a as NSString).range(of: "* B").location
236 return try #require(try OrgCrypt.encrypt(a, at: b, passphrase: "other"))
237 }
238
239 /// 1: a passphrase is saved only when it opens every message in the file.
240 @Test func onlyAPassphraseThatOpensEveryMessageIsSaved() throws {
241 let mixed = try Self.twoPassphrases()
242 #expect(OrgCrypt.messages(mixed).count == 2)
243 let (keychain, passphrases) = FakeKeychain.passphrases(.on, saved: ["/x/a.org": "saved"])
244 // Encrypting an entry with "pw" beside one encrypted with "other": not saved, and the
245 // saved one stays.
246 #expect(passphrases.keep("pw", for: "/x/a.org", text: mixed) == nil)
247 #expect(keychain.saved == ["/x/a.org": "saved"])
248 #expect(!keychain.calls.contains { $0.hasPrefix("write ") })
249 // One that opens them all, or a file with no other message, is saved.
250 let one = try #require(try OrgCrypt.encrypt("* A :crypt:\na\n", at: 0, passphrase: "pw"))
251 passphrases.keep("pw", for: "/x/a.org", text: one)
252 #expect(keychain.saved == ["/x/a.org": "pw"])
253 passphrases.keep("new", for: "/x/b.org", text: "* Plain\n")
254 #expect(keychain.saved["/x/b.org"] == "new")
255 }
256
257 /// 1: the sheet's path, through the question, checks the same way.
258 @Test func theQuestionsAnswerSavesOnlyAPassphraseThatFits() throws {
259 let mixed = try Self.twoPassphrases()
260 let (keychain, passphrases) = FakeKeychain.passphrases(.undecided)
261 var note: String?
262 #expect(passphrases.typed("pw", for: "/x/a.org", text: mixed, note: &note))
263 #expect(passphrases.answer(enable: true, passphrase: "pw", for: "/x/a.org", text: mixed) == nil)
264 #expect(passphrases.setting == .on && keychain.saved.isEmpty)
265 #expect(!passphrases.typed("other", for: "/x/a.org", text: "* Plain\n", note: &note))
266 #expect(keychain.saved == ["/x/a.org": "other"])
267 }
268
269 /// 1: unlocking a file with a passphrase that opens its first message but not another.
270 @Test func unlockingWithAPassphraseThatOpensOnlySomeMessagesSavesNothing() async throws {
271 let mixed = try Self.twoPassphrases()
272 let file = try notes.write("a.org", mixed)
273 let (keychain, passphrases) = FakeKeychain.passphrases(.on, saved: [file.path: "saved"])
274 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".recovery")))
275 session.saveMode = .explicit
276 session.passphrases = passphrases
277 session.open(file.path)
278 #expect(session.unlock("pw", for: file.path) == nil)
279 passphrases.keep("pw", for: file.path, text: session.document(of: file.path)?.text ?? "")
280 #expect(keychain.saved == [file.path: "saved"])
281 }
282
283 /// 2: a question answered after the setting was decided elsewhere changes nothing.
284 @Test func aLateAnswerChangesNothing() {
285 // Two sheets asked; the first said Enable, the second Not Now.
286 let (keychain, passphrases) = FakeKeychain.passphrases(.undecided)
287 var note: String?
288 #expect(passphrases.typed("a", for: "/x/a.org", text: "", note: &note))
289 #expect(passphrases.typed("b", for: "/x/b.org", text: "", note: &note))
290 _ = passphrases.answer(enable: true, passphrase: "a", for: "/x/a.org", text: "")
291 _ = passphrases.answer(enable: false, passphrase: "b", for: "/x/b.org", text: "")
292 #expect(passphrases.setting == .on)
293 #expect(keychain.saved == ["/x/a.org": "a"])
294 // Settings turned it off while the question was open: Enable doesn't turn it on.
295 let (other, settings) = FakeKeychain.passphrases(.undecided)
296 #expect(settings.typed("a", for: "/x/a.org", text: "", note: &note))
297 settings.turnOff()
298 _ = settings.answer(enable: true, passphrase: "a", for: "/x/a.org", text: "")
299 #expect(settings.setting == .off && other.saved.isEmpty)
300 // The launch question too.
301 let (_, launch) = FakeKeychain.passphrases(.off)
302 launch.asking = true
303 #expect(!launch.answer(enable: true))
304 #expect(launch.setting == .off && !launch.asking)
305 }
306
307 /// 2: Not Now leaves earlier passphrases in place, unread, listed for Forget.
308 @Test func notNowKeepsEarlierPassphrasesListed() async {
309 let (keychain, passphrases) = FakeKeychain.passphrases(.undecided, saved: ["/x/old.org": "pw"])
310 passphrases.askIfSavedBefore()
311 passphrases.answer(enable: false)
312 #expect(keychain.saved == ["/x/old.org": "pw"])
313 #expect(await passphrases.stored(for: "/x/old.org") == nil)
314 passphrases.refresh()
315 #expect(passphrases.savedPaths == ["/x/old.org"])
316 }
317
318 /// 3: turning off deletes by service, so a listing that fails leaves nothing behind.
319 @Test func turningOffDeletesEverythingWhenTheListingFails() {
320 let (keychain, passphrases) = FakeKeychain.passphrases(.on, saved: ["/x/a.org": "a", "/x/b.org": "b"])
321 keychain.listingFails = true
322 passphrases.turnOff()
323 #expect(keychain.saved.isEmpty)
324 }
325
326 /// 4: the test process's sessions get no Keychain, whatever the setting in user defaults.
327 @Test func testSessionsDontReachTheKeychain() {
328 #expect(CryptPassphrases.shared.keychain is NoKeychain)
329 #expect(DocumentSession(recovery: FileRecoveryStore(directory: notes.url)).passphrases.keychain is NoKeychain)
330 }
220} 331}
docs/manual/guide/04-outlines.org +1 −1 · view
@@ -960,7 +960,7 @@ Messages are written with AES-256 and an iterated and salted SHA-256 key, which
960One setting decides whether passphrases are saved in the Keychain: Use Face ID to Decrypt on iPhone and iPad (Use Touch ID to Decrypt on the Mac and on an iPad with Touch ID). It is in Settings ▸ Encryption on the Mac and in the Settings tab on iOS. It is kept in the app's settings on the device, not in =config.toml=, so it isn't synced to other devices and can't be changed by editing a file. 960One setting decides whether passphrases are saved in the Keychain: Use Face ID to Decrypt on iPhone and iPad (Use Touch ID to Decrypt on the Mac and on an iPad with Touch ID). It is in Settings ▸ Encryption on the Mac and in the Settings tab on iOS. It is kept in the app's settings on the device, not in =config.toml=, so it isn't synced to other devices and can't be changed by editing a file.
961 961
962- Off :: No passphrase is saved in the Keychain or read from it. A passphrase is typed when it's needed: by the org-crypt commands, to open a =.org.gpg= file, and by Encrypt… for a held file. Once typed, it is kept in memory for that file until the file is closed. 962- Off :: No passphrase is saved in the Keychain or read from it. A passphrase is typed when it's needed: by the org-crypt commands, to open a =.org.gpg= file, and by Encrypt… for a held file. Once typed, it is kept in memory for that file until the file is closed.
963- On :: A passphrase typed for a file, once it has opened or encrypted the file, is saved in the Keychain for that file. From then on the commands, opening the file, Encrypt… and encrypting on save use it after Face ID, Touch ID or the device's passcode or password, without asking for the passphrase. 963- On :: A passphrase typed for a file, once it has opened or encrypted the file, is saved in the Keychain for that file, unless an encrypted entry in the file doesn't open with it (one encrypted with another passphrase); then the passphrase saved before, if any, is kept. From then on the commands, opening the file, Encrypt… and encrypting on save use it after Face ID, Touch ID or the device's passcode or password, without asking for the passphrase.
964 964
965Until you choose, the setting is undecided and works as Off. The first time you type a passphrase that works, orgstar explains that Face ID can then decrypt anything whose passphrase is saved in your Keychain, and asks whether to use it: Enable turns the setting on and saves that passphrase; Not Now turns it off. Either answer is kept, so the question isn't asked again; change it in Settings. If passphrases saved by an earlier version of orgstar are in the Keychain, the question is asked once at the first launch instead, and they aren't used unless you choose Enable. 965Until you choose, the setting is undecided and works as Off. The first time you type a passphrase that works, orgstar explains that Face ID can then decrypt anything whose passphrase is saved in your Keychain, and asks whether to use it: Enable turns the setting on and saves that passphrase; Not Now turns it off. Either answer is kept, so the question isn't asked again; change it in Settings. If passphrases saved by an earlier version of orgstar are in the Keychain, the question is asked once at the first launch instead, and they aren't used unless you choose Enable.
966 966
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