Tests/OrgAppTests/CryptSaveTests.swift
300 lines · 14461 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.fileSaved = { 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 session.open(file.path)
102 try replace(with: Self.file)
103 #expect(!session.save())
104 #expect(session.held[file.path] == .entries(1))
105 #expect(disk == "* Plain\nOpen text.\n")
106 #expect(recoveryFiles.isEmpty)
107 #expect(session.isDirty)
108 // Nothing reads the held text from the session for the agenda or widgets.
109 #expect(session.openTexts[file.path] == nil)
110 // Keep Mine holds too.
111 session.keepMine()
112 #expect(disk == "* Plain\nOpen text.\n")
113 #expect(recoveryFiles.isEmpty)
114 // The passphrase, when given, encrypts and saves.
115 #expect(session.unlock("pw", for: file.path) == nil)
116 #expect(session.held.isEmpty)
117 #expect(!session.isDirty)
118 #expect(!disk.contains(Self.secret))
119 #expect(recoveryFiles.allSatisfy { !$0.contains(Self.secret) })
120 #expect(session.openTexts[file.path] == nil)
121 }
122
123 @Test func aHeldFileIsReleasedWhenTheEntryGoes() throws {
124 session.saveMode = .automatic
125 session.autosaveDelay = .seconds(60)
126 session.open(file.path)
127 try type("x", at: 0)
128 #expect(!session.save())
129 #expect(session.held[file.path] == .entries(1))
130 let text = session.document!.text as NSString
131 try replace(with: text.replacingOccurrences(of: " :crypt:", with: ""))
132 #expect(session.held.isEmpty)
133 }
134
135 @Test func aWrongPassphraseForTheFilesEntriesIsRefused() throws {
136 let encrypted = try #require(try OrgCrypt.encrypt(Self.file, at: (Self.file as NSString).range(of: "* Bank").location, passphrase: "pw"))
137 try notes.write("a.org", encrypted + "* New :crypt:\nNew secret\n")
138 session.open(file.path)
139 try type("x", at: 0)
140 #expect(!session.save())
141 #expect(session.held[file.path] == .entries(1))
142 #expect(session.unlock("other", for: file.path) == "Wrong passphrase")
143 #expect(session.isDirty && disk.hasPrefix(encrypted))
144 #expect(session.unlock("pw", for: file.path) == nil)
145 #expect(!disk.contains("New secret") && !session.isDirty)
146 }
147
148 @Test func blankTaggedEntriesDontHoldTheFile() throws {
149 try notes.write("a.org", "* Plain\n")
150 session.open(file.path)
151 try type("* Empty :crypt:\n", at: 8)
152 #expect(session.save())
153 #expect(disk == "* Plain\n* Empty :crypt:\n")
154 }
155
156 @Test func unchangedEncryptedEntriesStayByteForByte() throws {
157 let bank = (Self.file as NSString).range(of: "* Bank").location
158 let encrypted = try #require(try OrgCrypt.encrypt(Self.file, at: bank, passphrase: "pw"))
159 try notes.write("a.org", encrypted)
160 session.open(file.path)
161 // Decrypt Entry in File, as the passphrase sheet runs it.
162 let message = try #require(OrgCrypt.firstMessage(encrypted))
163 let decrypted = try OrgCrypt.decryptInPlace(encrypted, at: bank, passphrase: "pw")
164 session.cryptUsed("pw", for: file.path)
165 let body = try #require(OrgCrypt.bodyRange(decrypted, at: bank))
166 session.cryptDecrypted(message: message, plaintext: (decrypted as NSString).substring(with: NSRange(body)), for: file.path)
167 try replace(with: decrypted)
168 #expect(session.document?.text.contains(Self.secret) == true)
169 // Saving writes the entry's message as it was.
170 #expect(session.save())
171 #expect(disk == encrypted)
172 try type("More. ", at: offset(of: "Open text."))
173 #expect(session.save())
174 #expect(disk == (encrypted as NSString).replacingOccurrences(of: "Open text.", with: "More. Open text."))
175 #expect(disk.contains(message))
176 // A changed entry gets a new message.
177 try type("Changed. ", at: offset(of: Self.secret))
178 #expect(session.save())
179 #expect(!disk.contains(message) && !disk.contains("Changed."))
180 let saved = disk
181 #expect(try OrgCrypt.decrypt(saved, at: (saved as NSString).range(of: "* Bank").location, passphrase: "pw").plaintext == "Changed. \(Self.secret)\n")
182 // An entry left encrypted in the buffer stays as it is.
183 let other = try notes.write("b.org", encrypted)
184 session.open(other.path)
185 try type("x", at: 0)
186 #expect(session.save())
187 #expect((try String(contentsOf: other, encoding: .utf8)) == "x" + encrypted)
188 }
189
190 @Test func offWritesWhatTheBufferHas() throws {
191 session.encryptsTaggedEntries = false
192 try notes.write("a.org", "* Plain\n")
193 session.open(file.path)
194 try replace(with: Self.file)
195 #expect(session.save())
196 #expect(disk == Self.file)
197 #expect(session.openTexts[file.path] == Self.file)
198 }
199
200 @Test func aFileChangedOnDiskMergesWithTheDecryptedBuffer() throws {
201 try notes.write("a.org", "* Plain\nOpen text.\n")
202 session.open(file.path)
203 session.cryptUsed("pw", for: file.path)
204 try replace(with: Self.file)
205 #expect(session.save())
206 // Another program appends to the file; the buffer keeps its decrypted entry.
207 try notes.write("a.org", disk + "* From Emacs\n")
208 session.fileChanged(file.path)
209 #expect(session.document?.text == Self.file + "* From Emacs\n")
210 #expect(!session.isDirty)
211 try type("y", at: 0)
212 #expect(session.save())
213 #expect(!disk.contains(Self.secret) && disk.hasSuffix("* From Emacs\n"))
214 }
215
216 // MARK: - Encrypted files
217
218 static let gpgText = "* Diary\nDear diary, \(secret).\n"
219
220 @Test func encryptedFilesOpenWithThePassphraseAndSaveEncrypted() throws {
221 let message = try OpenPGP.encryptedMessage(Data(Self.gpgText.utf8), passphrase: "pw")
222 let path = notes.url.appendingPathComponent("diary.org.gpg")
223 try message.write(to: path)
224 var written: [String] = []
225 session.fileSaved = { written.append($0) }
226 session.open(path.path)
227 #expect(session.unlockRequest == path.path)
228 #expect(!session.isOpen(path.path))
229 #expect(session.unlock("wrong", for: path.path) == "Wrong passphrase")
230 #expect(try Data(contentsOf: path) == message)
231 #expect(session.unlock("pw", for: path.path) == nil)
232 #expect(session.unlockRequest == nil)
233 #expect(session.path == path.path && session.document?.text == Self.gpgText)
234 #expect(session.isOrg)
235 #expect(session.openTexts[path.path] == nil)
236 try type("x", at: 0)
237 #expect(session.save())
238 #expect(written == [path.path])
239 let disk = try Data(contentsOf: path)
240 #expect(!OpenPGP.isArmored(disk))
241 #expect(disk.range(of: Data(Self.secret.utf8)) == nil)
242 #expect(try OpenPGP.decryptFile(disk, passphrase: "pw") == Data(("x" + Self.gpgText).utf8))
243 // Recovery keeps the version replaced, encrypted, and shows it decrypted.
244 #expect(!recoveryFiles.isEmpty && recoveryFiles.allSatisfy { !$0.contains(Self.secret) })
245 let version = try #require(session.recoveryVersions().first)
246 #expect(session.recoveryText(version.url) == Self.gpgText)
247 // A passphrase forgotten while the file is open must be the file's when given again.
248 session.crypt.forgetPassphrase(for: path.path)
249 try type("y", at: 0)
250 #expect(!session.save())
251 #expect(session.held[path.path] == .file)
252 #expect(session.unlock("typo", for: path.path) == "Wrong passphrase")
253 #expect(session.unlock("pw", for: path.path) == nil && !session.isDirty)
254 #expect(try OpenPGP.decryptFile(Data(contentsOf: path), passphrase: "pw") == Data(("yx" + Self.gpgText).utf8))
255 // Closing forgets the passphrase.
256 session.kill(path.path)
257 session.open(path.path)
258 #expect(session.unlockRequest == path.path)
259 }
260
261 @Test func armoredFilesStayArmored() throws {
262 let armored = try OpenPGP.encrypt(Data(Self.gpgText.utf8), passphrase: "pw")
263 let path = try notes.write("diary.org.gpg", armored)
264 session.open(path.path)
265 #expect(session.unlock("pw", for: path.path) == nil)
266 try type("x", at: 0)
267 #expect(session.save())
268 let disk = try Data(contentsOf: path)
269 #expect(OpenPGP.isArmored(disk))
270 #expect(try OpenPGP.decryptFile(disk, passphrase: "pw") == Data(("x" + Self.gpgText).utf8))
271 }
272
273 @Test func aNewEncryptedFileWaitsForItsPassphrase() throws {
274 let path = try notes.write("new.org.gpg", "")
275 session.open(path.path)
276 #expect(session.unlockRequest == nil && session.path == path.path)
277 try type(Self.gpgText, at: 0)
278 #expect(!session.save())
279 #expect(session.held[path.path] == .file)
280 #expect(try Data(contentsOf: path).isEmpty)
281 #expect(recoveryFiles.isEmpty)
282 #expect(session.unlock("new", for: path.path) == nil)
283 #expect(!session.isDirty && session.held.isEmpty)
284 #expect(try OpenPGP.decryptFile(Data(contentsOf: path), passphrase: "new") == Data(Self.gpgText.utf8))
285 }
286
287 @Test func anEncryptedFileChangedOnDiskMergesInMemory() throws {
288 let path = notes.url.appendingPathComponent("diary.org.gpg")
289 try OpenPGP.encryptedMessage(Data(Self.gpgText.utf8), passphrase: "pw").write(to: path)
290 session.open(path.path)
291 #expect(session.unlock("pw", for: path.path) == nil)
292 try type("x", at: 0)
293 try OpenPGP.encryptedMessage(Data((Self.gpgText + "* Added elsewhere\n").utf8), passphrase: "pw").write(to: path)
294 session.fileChanged(path.path)
295 #expect(session.document?.text == "x" + Self.gpgText + "* Added elsewhere\n")
296 #expect(session.save())
297 #expect(try OpenPGP.decryptFile(Data(contentsOf: path), passphrase: "pw") == Data(("x" + Self.gpgText + "* Added elsewhere\n").utf8))
298 #expect(recoveryFiles.allSatisfy { !$0.contains(Self.secret) && !$0.contains("Added elsewhere") })
299 }
300}