Tests/OrgAppTests/CryptSaveTests.swift
316 lines · 15120 bytes
1import Foundation
2import OrgCore
3import OrgDocument
4import Testing
5@testable import OrgApp
6
7/// Saving with `org-crypt-use-before-save-magic`, and `.org.gpg` files: what reaches disk.
8@MainActor
9struct CryptSaveTests {
10 static let secret = "Account 12345"
11 static let file = "#+TITLE: Notes\n* Plain\nOpen text.\n* Bank :crypt:\n\(secret)\n* Last\n"
12
13 let notes: Folder
14 let file: URL
15 let recoveryFolder: URL
16 let session: DocumentSession
17
18 init() throws {
19 notes = try Folder()
20 file = try notes.write("a.org", Self.file)
21 recoveryFolder = notes.url.appendingPathComponent(".recovery")
22 session = DocumentSession(recovery: FileRecoveryStore(directory: recoveryFolder))
23 session.saveMode = .explicit
24 session.encryptsTaggedEntries = true
25 session.hasStoredPassphrase = { _ in false }
26 }
27
28 /// Types `text` at `offset` in the open file, as the editor would.
29 func type(_ text: String, at offset: Int) throws {
30 let buffer = StateBuffer(session.document!)
31 session.attach(buffer)
32 try buffer.update { try $0.apply([TextEdit(range: offset..<offset, replacement: text)], baseRevision: $0.revision) }
33 session.bufferChanged()
34 }
35
36 /// Puts `text` in place of the open file's text.
37 func replace(with text: String) throws {
38 let buffer = StateBuffer(session.document!)
39 session.attach(buffer)
40 try buffer.update { try $0.apply([TextEdit(range: 0..<($0.text as NSString).length, replacement: text)], baseRevision: $0.revision) }
41 session.bufferChanged()
42 }
43
44 var disk: String { (try? String(contentsOf: file, encoding: .utf8)) ?? "" }
45
46 /// Every file the recovery folder holds, as text.
47 var recoveryFiles: [String] {
48 let files = FileManager.default.enumerator(at: recoveryFolder, includingPropertiesForKeys: nil)?.compactMap { $0 as? URL } ?? []
49 return files.compactMap { try? Data(contentsOf: $0) }.map { String(decoding: $0, as: UTF8.self) }
50 }
51
52 func offset(of needle: String) -> Int {
53 (session.document!.text as NSString).range(of: needle).location
54 }
55
56 /// Waits for `condition`, as the Keychain's answer comes back on a task.
57 func wait(_ condition: () -> Bool) async throws {
58 for _ in 0..<200 where !condition() { try await Task.sleep(for: .milliseconds(10)) }
59 }
60
61 @Test func savesTaggedEntriesEncryptedWithTheRememberedPassphrase() async throws {
62 try notes.write("a.org", "* Bank :crypt:\nold\n* Last\n")
63 session.hasStoredPassphrase = { _ in true }
64 var asked = 0
65 session.storedPassphrase = { _ in asked += 1; return "pw" }
66 var written: [String] = []
67 session.fileWritten = { written.append($0) }
68 session.open(file.path)
69 try replace(with: Self.file)
70 #expect(!session.save())
71 try await wait { !session.isDirty }
72 #expect(session.held.isEmpty)
73 #expect(asked == 1)
74 #expect(written == [file.path])
75 // The buffer keeps the text; the file has a message in its place.
76 #expect(session.document?.text == Self.file)
77 #expect(!disk.contains(Self.secret) && !disk.contains("old"))
78 #expect(disk.contains("* Bank :crypt:\n-----BEGIN PGP MESSAGE-----\n"))
79 let bank = (disk as NSString).range(of: "* Bank").location
80 #expect(try OrgCrypt.decrypt(disk, at: bank, passphrase: "pw").plaintext == Self.secret + "\n")
81 // The version the save replaced went to recovery encrypted too.
82 #expect(!recoveryFiles.isEmpty)
83 #expect(recoveryFiles.allSatisfy { !$0.contains(Self.secret) && !$0.contains("old") })
84 // Later saves don't ask again.
85 try type("More. ", at: offset(of: "Open text."))
86 #expect(session.save())
87 #expect(asked == 1)
88 #expect(written.count == 2)
89 #expect(!disk.contains(Self.secret))
90 // The index reads the file from disk and keeps no text of the entry.
91 let workspace = try WorkspaceModel(directory: notes.url.appendingPathComponent(".index"))
92 try await workspace.addRoot(notes.url)
93 let database = try Data(contentsOf: notes.url.appendingPathComponent(".index/index.sqlite"))
94 #expect(database.range(of: Data(Self.secret.utf8)) == nil)
95 #expect(try workspace.search("12345").isEmpty)
96 #expect(try workspace.search("Open").map(\.title).contains("Plain"))
97 }
98
99 @Test func holdsTheWholeFileWithoutThePassphrase() throws {
100 try notes.write("a.org", "* Plain\nOpen text.\n")
101 var written: [String] = []
102 session.fileWritten = { written.append($0) }
103 session.open(file.path)
104 try replace(with: Self.file)
105 #expect(!session.save())
106 #expect(session.held[file.path] == .entries(1))
107 #expect(written.isEmpty)
108 #expect(disk == "* Plain\nOpen text.\n")
109 #expect(recoveryFiles.isEmpty)
110 #expect(session.isDirty)
111 // Nothing reads the held text from the session for the agenda or widgets.
112 #expect(session.openTexts[file.path] == nil)
113 // Keep Mine holds too.
114 session.keepMine()
115 #expect(disk == "* Plain\nOpen text.\n")
116 #expect(recoveryFiles.isEmpty)
117 // The passphrase, when given, encrypts and saves.
118 #expect(written.isEmpty)
119 #expect(session.unlock("pw", for: file.path) == nil)
120 #expect(session.held.isEmpty)
121 #expect(!session.isDirty)
122 #expect(written == [file.path])
123 #expect(!disk.contains(Self.secret))
124 #expect(recoveryFiles.allSatisfy { !$0.contains(Self.secret) })
125 #expect(session.openTexts[file.path] == nil)
126 }
127
128 @Test func restoringAVersionOfAHeldFileKeepsNoPlaintext() throws {
129 try notes.write("a.org", "* Plain\nOpen text.\n")
130 session.open(file.path)
131 try replace(with: Self.file)
132 #expect(!session.save())
133 #expect(session.restore(text: "* Plain\nOpen text.\n* Other\n") == nil)
134 #expect(recoveryFiles.isEmpty)
135 #expect(session.save())
136 #expect(recoveryFiles.allSatisfy { !$0.contains(Self.secret) })
137 }
138
139 @Test func aHeldFileIsReleasedWhenTheEntryGoes() throws {
140 session.saveMode = .automatic
141 session.autosaveDelay = .seconds(60)
142 session.open(file.path)
143 try type("x", at: 0)
144 #expect(!session.save())
145 #expect(session.held[file.path] == .entries(1))
146 let text = session.document!.text as NSString
147 try replace(with: text.replacingOccurrences(of: " :crypt:", with: ""))
148 #expect(session.held.isEmpty)
149 }
150
151 @Test func aWrongPassphraseForTheFilesEntriesIsRefused() throws {
152 let encrypted = try #require(try OrgCrypt.encrypt(Self.file, at: (Self.file as NSString).range(of: "* Bank").location, passphrase: "pw"))
153 try notes.write("a.org", encrypted + "* New :crypt:\nNew secret\n")
154 session.open(file.path)
155 try type("x", at: 0)
156 #expect(!session.save())
157 #expect(session.held[file.path] == .entries(1))
158 #expect(session.unlock("other", for: file.path) == "Wrong passphrase")
159 #expect(session.isDirty && disk.hasPrefix(encrypted))
160 #expect(session.unlock("pw", for: file.path) == nil)
161 #expect(!disk.contains("New secret") && !session.isDirty)
162 }
163
164 @Test func blankTaggedEntriesDontHoldTheFile() throws {
165 try notes.write("a.org", "* Plain\n")
166 session.open(file.path)
167 try type("* Empty :crypt:\n", at: 8)
168 #expect(session.save())
169 #expect(disk == "* Plain\n* Empty :crypt:\n")
170 }
171
172 @Test func unchangedEncryptedEntriesStayByteForByte() throws {
173 let bank = (Self.file as NSString).range(of: "* Bank").location
174 let encrypted = try #require(try OrgCrypt.encrypt(Self.file, at: bank, passphrase: "pw"))
175 try notes.write("a.org", encrypted)
176 session.open(file.path)
177 // Decrypt Entry in File, as the passphrase sheet runs it.
178 let message = try #require(OrgCrypt.firstMessage(encrypted))
179 let decrypted = try OrgCrypt.decryptInPlace(encrypted, at: bank, passphrase: "pw")
180 session.cryptUsed("pw", for: file.path)
181 let body = try #require(OrgCrypt.bodyRange(decrypted, at: bank))
182 session.cryptDecrypted(message: message, plaintext: (decrypted as NSString).substring(with: NSRange(body)), for: file.path)
183 try replace(with: decrypted)
184 #expect(session.document?.text.contains(Self.secret) == true)
185 // Saving writes the entry's message as it was.
186 #expect(session.save())
187 #expect(disk == encrypted)
188 try type("More. ", at: offset(of: "Open text."))
189 #expect(session.save())
190 #expect(disk == (encrypted as NSString).replacingOccurrences(of: "Open text.", with: "More. Open text."))
191 #expect(disk.contains(message))
192 // A changed entry gets a new message.
193 try type("Changed. ", at: offset(of: Self.secret))
194 #expect(session.save())
195 #expect(!disk.contains(message) && !disk.contains("Changed."))
196 let saved = disk
197 #expect(try OrgCrypt.decrypt(saved, at: (saved as NSString).range(of: "* Bank").location, passphrase: "pw").plaintext == "Changed. \(Self.secret)\n")
198 // An entry left encrypted in the buffer stays as it is.
199 let other = try notes.write("b.org", encrypted)
200 session.open(other.path)
201 try type("x", at: 0)
202 #expect(session.save())
203 #expect((try String(contentsOf: other, encoding: .utf8)) == "x" + encrypted)
204 }
205
206 @Test func offWritesWhatTheBufferHas() throws {
207 session.encryptsTaggedEntries = false
208 try notes.write("a.org", "* Plain\n")
209 session.open(file.path)
210 try replace(with: Self.file)
211 #expect(session.save())
212 #expect(disk == Self.file)
213 #expect(session.openTexts[file.path] == Self.file)
214 }
215
216 @Test func aFileChangedOnDiskMergesWithTheDecryptedBuffer() throws {
217 try notes.write("a.org", "* Plain\nOpen text.\n")
218 session.open(file.path)
219 session.cryptUsed("pw", for: file.path)
220 try replace(with: Self.file)
221 #expect(session.save())
222 // Another program appends to the file; the buffer keeps its decrypted entry.
223 try notes.write("a.org", disk + "* From Emacs\n")
224 session.fileChanged(file.path)
225 #expect(session.document?.text == Self.file + "* From Emacs\n")
226 #expect(!session.isDirty)
227 try type("y", at: 0)
228 #expect(session.save())
229 #expect(!disk.contains(Self.secret) && disk.hasSuffix("* From Emacs\n"))
230 }
231
232 // MARK: - Encrypted files
233
234 static let gpgText = "* Diary\nDear diary, \(secret).\n"
235
236 @Test func encryptedFilesOpenWithThePassphraseAndSaveEncrypted() throws {
237 let message = try OpenPGP.encryptedMessage(Data(Self.gpgText.utf8), passphrase: "pw")
238 let path = notes.url.appendingPathComponent("diary.org.gpg")
239 try message.write(to: path)
240 var written: [String] = []
241 session.fileWritten = { written.append($0) }
242 session.open(path.path)
243 #expect(session.unlockRequest == path.path)
244 #expect(!session.isOpen(path.path))
245 #expect(session.unlock("wrong", for: path.path) == "Wrong passphrase")
246 #expect(try Data(contentsOf: path) == message)
247 #expect(session.unlock("pw", for: path.path) == nil)
248 #expect(session.unlockRequest == nil)
249 #expect(session.path == path.path && session.document?.text == Self.gpgText)
250 #expect(session.isOrg)
251 #expect(session.openTexts[path.path] == nil)
252 try type("x", at: 0)
253 #expect(session.save())
254 #expect(written == [path.path])
255 let disk = try Data(contentsOf: path)
256 #expect(!OpenPGP.isArmored(disk))
257 #expect(disk.range(of: Data(Self.secret.utf8)) == nil)
258 #expect(try OpenPGP.decryptFile(disk, passphrase: "pw") == Data(("x" + Self.gpgText).utf8))
259 // Recovery keeps the version replaced, encrypted, and shows it decrypted.
260 #expect(!recoveryFiles.isEmpty && recoveryFiles.allSatisfy { !$0.contains(Self.secret) })
261 let version = try #require(session.recoveryVersions().first)
262 #expect(session.recoveryText(version.url) == Self.gpgText)
263 // A passphrase forgotten while the file is open must be the file's when given again.
264 session.crypt.forgetPassphrase(for: path.path)
265 try type("y", at: 0)
266 #expect(!session.save())
267 #expect(session.held[path.path] == .file)
268 #expect(session.unlock("typo", for: path.path) == "Wrong passphrase")
269 #expect(session.unlock("pw", for: path.path) == nil && !session.isDirty)
270 #expect(try OpenPGP.decryptFile(Data(contentsOf: path), passphrase: "pw") == Data(("yx" + Self.gpgText).utf8))
271 // Closing forgets the passphrase.
272 session.kill(path.path)
273 session.open(path.path)
274 #expect(session.unlockRequest == path.path)
275 }
276
277 @Test func armoredFilesStayArmored() throws {
278 let armored = try OpenPGP.encrypt(Data(Self.gpgText.utf8), passphrase: "pw")
279 let path = try notes.write("diary.org.gpg", armored)
280 session.open(path.path)
281 #expect(session.unlock("pw", for: path.path) == nil)
282 try type("x", at: 0)
283 #expect(session.save())
284 let disk = try Data(contentsOf: path)
285 #expect(OpenPGP.isArmored(disk))
286 #expect(try OpenPGP.decryptFile(disk, passphrase: "pw") == Data(("x" + Self.gpgText).utf8))
287 }
288
289 @Test func aNewEncryptedFileWaitsForItsPassphrase() throws {
290 let path = try notes.write("new.org.gpg", "")
291 session.open(path.path)
292 #expect(session.unlockRequest == nil && session.path == path.path)
293 try type(Self.gpgText, at: 0)
294 #expect(!session.save())
295 #expect(session.held[path.path] == .file)
296 #expect(try Data(contentsOf: path).isEmpty)
297 #expect(recoveryFiles.isEmpty)
298 #expect(session.unlock("new", for: path.path) == nil)
299 #expect(!session.isDirty && session.held.isEmpty)
300 #expect(try OpenPGP.decryptFile(Data(contentsOf: path), passphrase: "new") == Data(Self.gpgText.utf8))
301 }
302
303 @Test func anEncryptedFileChangedOnDiskMergesInMemory() throws {
304 let path = notes.url.appendingPathComponent("diary.org.gpg")
305 try OpenPGP.encryptedMessage(Data(Self.gpgText.utf8), passphrase: "pw").write(to: path)
306 session.open(path.path)
307 #expect(session.unlock("pw", for: path.path) == nil)
308 try type("x", at: 0)
309 try OpenPGP.encryptedMessage(Data((Self.gpgText + "* Added elsewhere\n").utf8), passphrase: "pw").write(to: path)
310 session.fileChanged(path.path)
311 #expect(session.document?.text == "x" + Self.gpgText + "* Added elsewhere\n")
312 #expect(session.save())
313 #expect(try OpenPGP.decryptFile(Data(contentsOf: path), passphrase: "pw") == Data(("x" + Self.gpgText + "* Added elsewhere\n").utf8))
314 #expect(recoveryFiles.allSatisfy { !$0.contains(Self.secret) && !$0.contains("Added elsewhere") })
315 }
316}