Tests/OrgAppTests/CryptReviewTests.swift
382 lines · 20275 bytes
1import Foundation
2import OrgCore
3import OrgDocument
4import Testing
5@testable import OrgApp
6
7/// What an encrypted entry or file must not leak, nor lose, past the save path.
8@MainActor
9struct CryptReviewTests {
10 static let secret = "Account 12345"
11 static let file = "* 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", "* Plain\nOpen text.\n* Last\n")
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 func replace(with text: String) throws {
29 let buffer = StateBuffer(session.document!)
30 session.attach(buffer)
31 try buffer.update { try $0.apply([TextEdit(range: 0..<($0.text as NSString).length, replacement: text)], baseRevision: $0.revision) }
32 session.bufferChanged()
33 }
34
35 func type(_ text: String, at offset: Int) throws {
36 let buffer = StateBuffer(session.document!)
37 session.attach(buffer)
38 try buffer.update { try $0.apply([TextEdit(range: offset..<offset, replacement: text)], baseRevision: $0.revision) }
39 session.bufferChanged()
40 }
41
42 func read(_ url: URL) -> String { (try? String(contentsOf: url, encoding: .utf8)) ?? "" }
43 var disk: String { read(file) }
44
45 var recoveryFiles: [String] {
46 let files = FileManager.default.enumerator(at: recoveryFolder, includingPropertiesForKeys: nil)?.compactMap { $0 as? URL } ?? []
47 return files.compactMap { try? Data(contentsOf: $0) }.map { String(decoding: $0, as: UTF8.self) }
48 }
49
50 func offset(of needle: String) -> Int { (session.document!.text as NSString).range(of: needle).location }
51
52 // 1
53 @Test func turningTheSettingOffKeepsSealingOpenFiles() throws {
54 session.open(file.path)
55 session.cryptUsed("pw", for: file.path)
56 try replace(with: Self.file)
57 #expect(session.save())
58 #expect(!disk.contains(Self.secret))
59 session.encryptsTaggedEntries = false
60 try type("x", at: 0)
61 #expect(session.save())
62 #expect(!disk.contains(Self.secret))
63 #expect(session.openTexts[file.path] == nil)
64 // A file opened after it was turned off is as before.
65 let other = try notes.write("b.org", Self.file)
66 session.open(other.path)
67 try type("y", at: 0)
68 #expect(session.save())
69 #expect(read(other).contains(Self.secret))
70 }
71
72 // 2
73 @Test func useDiskVersionOnAHeldFileKeepsTheEdits() throws {
74 session.open(file.path)
75 try replace(with: Self.file)
76 #expect(!session.save())
77 session.useDiskVersion()
78 #expect(session.document?.text == Self.file)
79 #expect(session.lastError?.contains("Encrypt…") == true)
80 #expect(session.restore(text: "* Plain\n")?.contains("Encrypt…") == true)
81 #expect(session.document?.text == Self.file)
82 #expect(recoveryFiles.isEmpty && disk == "* Plain\nOpen text.\n* Last\n")
83 }
84
85 // 3a
86 @Test func archivingAChildOfATaggedEntryEncryptsItFirst() throws {
87 let text = "* Parent :crypt:\nparent text\n** SECRETTITLE child\nchild secret\n* Other :crypt:\nother secret\n* Last\n"
88 try notes.write("a.org", text)
89 session.open(file.path)
90 let child = (text as NSString).range(of: "** SECRETTITLE").location
91 let archive = notes.url.appendingPathComponent("a.org_archive")
92 // A heading inside an encrypted entry isn't moved on its own, passphrase or not.
93 #expect(session.archive(from: (file.path, child))?.contains("inside an encrypted entry") == true)
94 session.cryptUsed("pw", for: file.path)
95 #expect(session.archive(from: (file.path, child))?.contains("inside an encrypted entry") == true)
96 let target = RefileTarget(label: "b.org", path: try notes.write("b.org", "* B\n").path, start: nil, title: "", level: 0, contentHash: "")
97 #expect(session.refile(to: target, from: (file.path, child))?.contains("inside an encrypted entry") == true)
98 #expect(!FileManager.default.fileExists(atPath: archive.path) && !read(notes.url.appendingPathComponent("b.org")).contains("SECRETTITLE"))
99 // A tagged entry is encrypted where it is, then archived.
100 let other = (session.document!.text as NSString).range(of: "* Other").location
101 #expect(session.archive(from: (file.path, other)) == "Archived to a.org_archive")
102 #expect(!read(archive).contains("other secret") && read(archive).contains("-----BEGIN PGP MESSAGE-----"))
103 #expect(session.save())
104 #expect(!disk.contains("child secret") && !disk.contains("SECRETTITLE"))
105 }
106
107 // Third review, A and B
108 @Test func shareSubtreeOfAHeadingInsideAnEncryptedEntry() throws {
109 let text = "* Parent :crypt:\nparent text\n** SECRETTITLE child\nchild secret\n* Last\n"
110 try notes.write("a.org", text)
111 session.open(file.path)
112 session.cryptUsed("pw", for: file.path)
113 let child = (text as NSString).range(of: "** SECRETTITLE").location
114 let share = try #require(session.subtreeShare(file.path, at: child))
115 #expect(share.fileName == "Encrypted entry.org")
116 #expect(!share.text.contains("SECRETTITLE") && !share.text.contains("child secret") && share.text.hasPrefix("* Encrypted entry :crypt:\n"))
117 let opened = try OrgCrypt.decryptInPlace(share.text, at: 0, passphrase: "pw")
118 #expect(opened.contains("** SECRETTITLE child\nchild secret\n"))
119 // Capture under that heading, into the file closed, isn't written.
120 session.kill(file.path)
121 let template = CaptureTemplate(key: "s", name: "Secret", target: .headline(file: file.path, headline: "SECRETTITLE child"), template: "* %?")
122 if case .success = session.capture("** Captured\n", template: template, root: nil) { Issue.record("captured into plaintext") }
123 #expect(disk == text)
124 }
125
126 @Test func shareSubtreeRefusesWhatCantBeEncrypted() throws {
127 let text = "* A :crypt:\na secret\n* B :crypt:\nb secret\n* End\n"
128 var both = try #require(try OrgCrypt.encrypt(text, at: 0, passphrase: "one"))
129 both = try #require(try OrgCrypt.encrypt(both, at: (both as NSString).range(of: "* B").location, passphrase: "two"))
130 try notes.write("a.org", both)
131 session.open(file.path)
132 session.cryptUsed("one", for: file.path)
133 try type("typed below b\n", at: offset(of: "* End"))
134 let b = offset(of: "* B")
135 #expect(session.refusesSubtreeShare(file.path, at: b)?.contains("public key") == true)
136 #expect(session.subtreeShare(file.path, at: b) == nil)
137 }
138
139 // Third review, C
140 @Test func hiddenClockTasksNeedTheirTitle() throws {
141 let hidden = ClockTask(path: "/x", title: "Real", ordinal: 1, id: nil).hiding("Encrypted entry")
142 #expect(hidden.title == "Encrypted entry" && hidden.titleHash != nil)
143 #expect(hidden.locate(in: "* A\n* Real\n") == 4)
144 #expect(hidden.locate(in: "* New\n* A\n* Real\n") == 10)
145 #expect(hidden.locate(in: "* A\n* Renamed\n") == nil)
146 #expect(hidden.refreshed(in: "* New\n* A\n* Real\n")?.title == "Encrypted entry")
147 }
148
149 // Third review, D2
150 @Test func keepMineHoldsWhenTheDiskVersionCantBeKept() throws {
151 session.open(file.path)
152 try type("x", at: 0)
153 try notes.write("a.org", "* Plain\n* Theirs :crypt:\ntheir secret\n")
154 session.keepMine()
155 #expect(session.held[file.path] == .entries(1) && session.lastError == nil)
156 #expect(disk.contains("their secret") && recoveryFiles.isEmpty)
157 }
158
159 // Third review, 3
160 @Test func aCancelledOpenEndsItsAuthentication() throws {
161 let path = notes.url.appendingPathComponent("d.org.gpg")
162 try OpenPGP.encryptedMessage(Data("* D\n".utf8), passphrase: "pw").write(to: path)
163 session.open(path.path)
164 let context = CryptPassphrases.context(for: path.path)
165 session.cancelUnlock()
166 #expect(CryptPassphrases.context(for: path.path) !== context)
167 CryptPassphrases.endSession(for: path.path)
168 #expect(!CryptPassphrases.protectsItems)
169 }
170
171 // 3b
172 @Test func encryptedFilesArchiveToEncryptedFilesAndRefileOnlyThere() throws {
173 let path = notes.url.appendingPathComponent("diary.org.gpg")
174 try OpenPGP.encryptedMessage(Data("* Monday\nDear diary.\n* Tuesday\nMore.\n".utf8), passphrase: "pw").write(to: path)
175 session.open(path.path)
176 #expect(session.unlock("pw", for: path.path) == nil)
177 let target = RefileTarget(label: "a.org", path: file.path, start: nil, title: "", level: 0, contentHash: "")
178 #expect(session.refile(to: target, from: (path.path, 0))?.contains("isn't") == true)
179 #expect(!disk.contains("Dear diary"))
180 #expect(session.archive(from: (path.path, 0)) == "Archived to diary_archive.org.gpg")
181 let archive = notes.url.appendingPathComponent("diary_archive.org.gpg")
182 #expect(!FileManager.default.fileExists(atPath: notes.url.appendingPathComponent("diary.org.gpg_archive").path))
183 let bytes = try Data(contentsOf: archive)
184 #expect(bytes.range(of: Data("Dear diary".utf8)) == nil)
185 #expect(String(decoding: try OpenPGP.decryptFile(bytes, passphrase: "pw"), as: UTF8.self).contains("Dear diary."))
186 // Capture into an encrypted file that isn't open writes nothing.
187 session.kill(path.path)
188 let template = CaptureTemplate(key: "d", name: "Diary", target: .file(path.path), template: "* %?")
189 if case .success = session.capture("* Captured secret\n", template: template, root: nil) { Issue.record("captured into a locked file") }
190 #expect(try Data(contentsOf: path).range(of: Data("Captured".utf8)) == nil)
191 }
192
193 // 5
194 @Test func textBelowAMessageIsHeldThenSealedWithIt() throws {
195 let encrypted = try #require(try OrgCrypt.encrypt(Self.file, at: (Self.file as NSString).range(of: "* Bank").location, passphrase: "pw"))
196 try notes.write("a.org", encrypted)
197 session.open(file.path)
198 try type("typed below\n", at: offset(of: "* Last"))
199 #expect(!session.save())
200 #expect(session.held[file.path] == .entries(1))
201 #expect(!disk.contains("typed below"))
202 #expect(session.unlock("pw", for: file.path) == nil)
203 #expect(!disk.contains("typed below"))
204 let bank = (disk as NSString).range(of: "* Bank").location
205 #expect(try OrgCrypt.decrypt(disk, at: bank, passphrase: "pw").plaintext == Self.secret + "\ntyped below\n")
206 }
207
208 // 7
209 @Test func exportsLeaveOutWhatIsEncryptedOnDisk() throws {
210 session.open(file.path)
211 session.cryptUsed("pw", for: file.path)
212 try replace(with: Self.file)
213 #expect(session.save())
214 #expect(session.exportLeavesOut(file.path))
215 #expect(session.exportText(of: file.path) == disk)
216 #expect(session.exportText(of: file.path)?.contains(Self.secret) == false)
217 let gpg = notes.url.appendingPathComponent("d.org.gpg")
218 try OpenPGP.encryptedMessage(Data("* D\nsecret\n".utf8), passphrase: "pw").write(to: gpg)
219 session.open(gpg.path)
220 #expect(session.unlock("pw", for: gpg.path) == nil)
221 #expect(session.exportText(of: gpg.path) == nil && session.exportLeavesOut(gpg.path))
222 // Nor is either copied for Emacs.
223 #expect(session.refusesEmacsCopy(gpg.path) != nil && session.refusesEmacsCopy(file.path) != nil)
224 let plain = try notes.write("c.org", "* C\n")
225 session.open(plain.path)
226 #expect(session.exportText(of: plain.path) == "* C\n" && session.refusesEmacsCopy(plain.path) == nil)
227 }
228
229 // 8
230 @Test func clockingInDoesntKeepEncryptedTitles() throws {
231 let text = "* Bank :crypt:\nintro\n** Secret task\nbody\n* Open task\n"
232 try notes.write("a.org", text)
233 session.open(file.path)
234 session.cryptUsed("pw", for: file.path)
235 let clock = ClockModel(file: notes.url.appendingPathComponent("clock.json"))
236 _ = clock.clockIn(session, path: file.path, at: (text as NSString).range(of: "** Secret").location)
237 #expect(clock.running?.heading == "Encrypted entry")
238 #expect(clock.history.allSatisfy { $0.title != "Secret task" })
239 #expect(!read(notes.url.appendingPathComponent("clock.json")).contains("Secret task"))
240 #expect(session.shareableTitle("Bank", path: file.path, heading: 0) == "Bank")
241 #expect(session.shareableTitle("Monday", path: "/x/d.org.gpg", heading: 0) == "Encrypted entry")
242 _ = clock.clockOut(session)
243 #expect(session.save())
244 #expect(!disk.contains("Secret task") && !disk.contains("intro"))
245 }
246
247 // Second review, 2
248 @Test func clockHistoryKeepsNoEncryptedTitle() throws {
249 let text = "* Bank :crypt:\nintro\n** Secret task\n:PROPERTIES:\n:ID: s-1\n:END:\nbody\n** Hidden no id\nmore\n* Open task\n"
250 try notes.write("a.org", text)
251 session.open(file.path)
252 session.cryptUsed("pw", for: file.path)
253 let clockFile = notes.url.appendingPathComponent("clock.json")
254 let clock = ClockModel(file: clockFile)
255 _ = clock.clockIn(session, path: file.path, at: (text as NSString).range(of: "** Secret").location)
256 _ = clock.clockIn(session, path: file.path, at: (session.document!.text as NSString).range(of: "** Hidden").location)
257 _ = clock.clockIn(session, path: file.path, at: (session.document!.text as NSString).range(of: "* Open").location)
258 #expect(!read(clockFile).contains("Secret task") && !read(clockFile).contains("Hidden no id"))
259 #expect(clock.history.map(\.title) == ["Open task", "Encrypted entry", "Encrypted entry"])
260 }
261
262 // Second review, 3
263 @Test func eachFileHasItsOwnAuthentication() throws {
264 let a = CryptPassphrases.context(for: "/x/a.org"), b = CryptPassphrases.context(for: "/x/b.org")
265 #expect(a !== b && CryptPassphrases.context(for: "/x/a.org") === a)
266 #expect(a.touchIDAuthenticationAllowableReuseDuration == 0)
267 CryptPassphrases.endSession(for: "/x/a.org")
268 #expect(CryptPassphrases.context(for: "/x/a.org") !== a)
269 }
270
271 // Second review, 4a
272 @Test func anEntryThePassphraseCantEncryptHoldsTheFile() throws {
273 let text = "* A :crypt:\na secret\n* B :crypt:\nb secret\n* End\n"
274 var both = try #require(try OrgCrypt.encrypt(text, at: 0, passphrase: "one"))
275 both = try #require(try OrgCrypt.encrypt(both, at: (both as NSString).range(of: "* B").location, passphrase: "two"))
276 try notes.write("a.org", both)
277 session.open(file.path)
278 #expect(session.unlock("one", for: file.path) == nil)
279 try type("typed below b\n", at: offset(of: "* End"))
280 #expect(!session.save())
281 guard case .blocked(let reason)? = session.held[file.path] else { Issue.record("\(String(describing: session.held[file.path]))"); return }
282 #expect(reason.contains("public key") && session.lastError == nil)
283 #expect(OrgCrypt.Failure("x").localizedDescription == "x")
284 #expect(!disk.contains("typed below b"))
285 }
286
287 // Second review, 4b
288 @Test func plaintextEntriesOnDiskHoldTheFileUntilThePassphrase() throws {
289 session.open(file.path)
290 try type("x", at: 0)
291 // Written elsewhere, with no file event.
292 try notes.write("a.org", "* Plain\nOpen text.\n* Last\n* Theirs :crypt:\ntheir secret\n")
293 #expect(!session.save())
294 #expect(session.held[file.path] == .entries(1) && session.lastError == nil)
295 #expect(session.unlock("pw", for: file.path) == nil)
296 #expect(!session.isDirty && !disk.contains("their secret") && session.document?.text.contains("their secret") == true)
297 #expect(recoveryFiles.allSatisfy { !$0.contains("their secret") })
298 }
299
300 // Second review, 6
301 @Test func anEncryptedFileSavesWithOneKey() throws {
302 let path = notes.url.appendingPathComponent("d.org.gpg")
303 try OpenPGP.encryptedMessage(Data("* D\nbody\n".utf8), passphrase: "pw").write(to: path)
304 session.open(path.path)
305 #expect(session.unlock("pw", for: path.path) == nil)
306 try type("x", at: 0)
307 #expect(session.save())
308 let clock = ContinuousClock()
309 var took: [Duration] = []
310 for n in 0..<3 {
311 try type("\(n)", at: 0)
312 took.append(clock.measure { _ = session.save() })
313 }
314 print("Autosave of an .org.gpg file: \(took)")
315 #expect(try OpenPGP.decryptFile(Data(contentsOf: path), passphrase: "pw") == Data("210x* D\nbody\n".utf8))
316 }
317
318 // MR 490 hooks
319 @Test func handoffAndShareSubtreeKeepWhatIsEncrypted() throws {
320 let text = "* Bank :crypt:\nintro\n** Secret child\nbody\n* Open\n"
321 try notes.write("a.org", text)
322 session.open(file.path)
323 let child = (text as NSString).range(of: "** Secret").location
324 // Without the passphrase, the subtree isn't shared.
325 #expect(session.handoffPlace(file.path, roots: [notes.url.path]) == nil)
326 #expect(session.refusesSubtreeShare(file.path, at: child)?.contains("Encrypt…") == true)
327 #expect(session.subtreeShare(file.path, at: child) == nil)
328 session.cryptUsed("pw", for: file.path)
329 let share = try #require(session.subtreeShare(file.path, at: child))
330 #expect(!share.text.contains("body") && share.text.contains("-----BEGIN PGP MESSAGE-----"))
331 #expect(session.document?.text == text)
332 let bank = try #require(session.subtreeShare(file.path, at: 0))
333 #expect(!bank.text.contains("intro") && !bank.text.contains("Secret child"))
334 // An open file without tagged entries is advertised as before.
335 let plain = try notes.write("b.org", "* Plain\n")
336 session.open(plain.path)
337 #expect(session.handoffPlace(plain.path, roots: [notes.url.path]) != nil)
338 // An encrypted file's entries aren't shared.
339 let gpg = notes.url.appendingPathComponent("d.org.gpg")
340 try OpenPGP.encryptedMessage(Data("* D\nsecret\n".utf8), passphrase: "pw").write(to: gpg)
341 session.open(gpg.path)
342 #expect(session.unlock("pw", for: gpg.path) == nil)
343 #expect(session.refusesSubtreeShare(gpg.path, at: 0) != nil && session.subtreeShare(gpg.path, at: 0) == nil)
344 }
345
346 // 9
347 @Test func unchangedEntriesKeepTheirMessageAcrossSaves() throws {
348 session.open(file.path)
349 session.cryptUsed("pw", for: file.path)
350 try replace(with: Self.file)
351 #expect(session.save())
352 let message = try #require(OrgCrypt.firstMessage(disk))
353 for n in 0..<5 {
354 try type("\(n)", at: 0)
355 #expect(session.save())
356 #expect(disk.contains(message))
357 }
358 #expect(session.crypt.revealedMessages(for: file.path).count == 1)
359 }
360
361 // 10
362 @Test func entriesEncryptedToAPublicKeyDontBlockThePassphrase() throws {
363 // A public-key session packet (tag 1) where a message's packets start.
364 let publicKey = OpenPGP.armor(Data([0xC1, 0x02, 0x03, 0x00]))
365 try notes.write("a.org", "* Pub :crypt:\n" + publicKey + "* Plain\n")
366 session.open(file.path)
367 try type("* New :crypt:\nnew secret\n", at: (session.document!.text as NSString).length)
368 #expect(!session.save())
369 #expect(session.unlock("pw", for: file.path) == nil)
370 #expect(!disk.contains("new secret"))
371 #expect(disk.contains(publicKey))
372 }
373
374 // 6
375 @Test func keychainItemsAreThisDeviceOnlyAfterUserPresence() throws {
376 let item = try #require(CryptPassphrases.newItem("pw", for: "/x/a.org"))
377 #expect(item[kSecAttrAccessControl as String] != nil)
378 #expect(item[kSecUseDataProtectionKeychain as String] as? Bool == true)
379 #expect(item[kSecAttrService as String] as? String == "sh.krz.orgstar.crypt.v2")
380 #expect(item[kSecAttrAccessible as String] == nil)
381 }
382}