Tests/OrgAppTests/CryptSaveTests.swift

63ae15b64d76b8b7c4d413cf6a6c5434c50d402d
orgstar/Tests/OrgAppTests/CryptSaveTests.swift

363 lines · 18253 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.passphrases = FakeKeychain.passphrases(.undecided).passphrases
 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        let (keychain, passphrases) = FakeKeychain.passphrases(.on, saved: [file.path: "pw"])
 64        session.passphrases = passphrases
 65        var asked: Int { keychain.calls.filter { $0.hasPrefix("read ") }.count }
 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        // No copy of the buffer can be kept, so the version isn't restored.
134        #expect(session.restore(text: "* Plain\nOpen text.\n* Other\n")?.contains("Encrypt…") == true)
135        #expect(session.document?.text == Self.file)
136        #expect(recoveryFiles.isEmpty)
137        #expect(session.unlock("pw", for: file.path) == nil)
138        #expect(session.restore(text: "* Plain\nOpen text.\n* Other\n") == nil)
139        #expect(session.save())
140        #expect(recoveryFiles.allSatisfy { !$0.contains(Self.secret) })
141    }
142
143    @Test func replaceInFilesKeepsNoPlaintextAndIsHeld() throws {
144        try notes.write("a.org", "* Plain\nOpen text.\n")
145        session.open(file.path)
146        try replace(with: Self.file)
147        // The buffer has no editor: Replace in Files keeps a copy first, and can't keep one now.
148        let changed = (Self.file as NSString).replacingOccurrences(of: "Open text.", with: "Shut text.")
149        #expect(session.applyChanges(lineEdits(from: Self.file, to: changed), to: file.path, expecting: Self.file) == nil)
150        #expect(!session.save())
151        #expect(session.held[file.path] == .entries(1))
152        #expect(recoveryFiles.isEmpty)
153        #expect(disk == "* Plain\nOpen text.\n")
154        // With the passphrase, the copy is kept encrypted.
155        session.cryptUsed("pw", for: file.path)
156        #expect(session.applyChanges(lineEdits(from: changed, to: Self.file), to: file.path, expecting: changed) == nil)
157        #expect(session.save())
158        #expect(!recoveryFiles.isEmpty && recoveryFiles.allSatisfy { !$0.contains(Self.secret) })
159        #expect(!disk.contains(Self.secret))
160        // A file that isn't open, with an unencrypted tagged entry on disk, isn't written.
161        session.cryptUsed("other", for: "/nowhere")
162        let closed = try notes.write("b.org", Self.file)
163        let message = session.applyChanges(lineEdits(from: Self.file, to: changed), to: closed.path, expecting: Self.file)
164        #expect(message?.contains("1 tagged entry isn't encrypted") == true)
165        #expect((try String(contentsOf: closed, encoding: .utf8)) == Self.file)
166        #expect(recoveryFiles.allSatisfy { !$0.contains(Self.secret) })
167    }
168
169    @Test func aHeldFileIsReleasedWhenTheEntryGoes() throws {
170        session.saveMode = .automatic
171        session.autosaveDelay = .seconds(60)
172        session.open(file.path)
173        try type("x", at: 0)
174        #expect(!session.save())
175        #expect(session.held[file.path] == .entries(1))
176        let text = session.document!.text as NSString
177        try replace(with: text.replacingOccurrences(of: " :crypt:", with: ""))
178        #expect(session.held.isEmpty)
179    }
180
181    @Test func aWrongPassphraseForTheFilesEntriesIsRefused() throws {
182        let encrypted = try #require(try OrgCrypt.encrypt(Self.file, at: (Self.file as NSString).range(of: "* Bank").location, passphrase: "pw"))
183        try notes.write("a.org", encrypted + "* New :crypt:\nNew secret\n")
184        session.open(file.path)
185        try type("x", at: 0)
186        #expect(!session.save())
187        #expect(session.held[file.path] == .entries(1))
188        #expect(session.unlock("other", for: file.path) == "Wrong passphrase")
189        #expect(session.isDirty && disk.hasPrefix(encrypted))
190        #expect(session.unlock("pw", for: file.path) == nil)
191        #expect(!disk.contains("New secret") && !session.isDirty)
192    }
193
194    @Test func blankTaggedEntriesDontHoldTheFile() throws {
195        try notes.write("a.org", "* Plain\n")
196        session.open(file.path)
197        try type("* Empty :crypt:\n", at: 8)
198        #expect(session.save())
199        #expect(disk == "* Plain\n* Empty :crypt:\n")
200    }
201
202    @Test func unchangedEncryptedEntriesStayByteForByte() throws {
203        let bank = (Self.file as NSString).range(of: "* Bank").location
204        let encrypted = try #require(try OrgCrypt.encrypt(Self.file, at: bank, passphrase: "pw"))
205        try notes.write("a.org", encrypted)
206        session.open(file.path)
207        // Decrypt Entry in File, as the passphrase sheet runs it.
208        let message = try #require(OrgCrypt.firstMessage(encrypted))
209        let decrypted = try OrgCrypt.decryptInPlace(encrypted, at: bank, passphrase: "pw")
210        session.cryptUsed("pw", for: file.path)
211        let body = try #require(OrgCrypt.bodyRange(decrypted, at: bank))
212        session.cryptDecrypted(message: message, plaintext: (decrypted as NSString).substring(with: NSRange(body)), for: file.path)
213        try replace(with: decrypted)
214        #expect(session.document?.text.contains(Self.secret) == true)
215        // Saving writes the entry's message as it was.
216        #expect(session.save())
217        #expect(disk == encrypted)
218        try type("More. ", at: offset(of: "Open text."))
219        #expect(session.save())
220        #expect(disk == (encrypted as NSString).replacingOccurrences(of: "Open text.", with: "More. Open text."))
221        #expect(disk.contains(message))
222        // A changed entry gets a new message.
223        try type("Changed. ", at: offset(of: Self.secret))
224        #expect(session.save())
225        #expect(!disk.contains(message) && !disk.contains("Changed."))
226        let saved = disk
227        #expect(try OrgCrypt.decrypt(saved, at: (saved as NSString).range(of: "* Bank").location, passphrase: "pw").plaintext == "Changed. \(Self.secret)\n")
228        // An entry left encrypted in the buffer stays as it is.
229        let other = try notes.write("b.org", encrypted)
230        session.open(other.path)
231        try type("x", at: 0)
232        #expect(session.save())
233        #expect((try String(contentsOf: other, encoding: .utf8)) == "x" + encrypted)
234    }
235
236    @Test func decryptInFileKeepsTheMessageInTheSheetsOrder() throws {
237        let bank = (Self.file as NSString).range(of: "* Bank").location
238        let encrypted = try #require(try OrgCrypt.encrypt(Self.file, at: bank, passphrase: "pw"))
239        try notes.write("a.org", encrypted)
240        session.open(file.path)
241        // The passphrase sheet records the message before the passphrase is known to the session.
242        let message = try #require(OrgCrypt.firstMessage(encrypted))
243        let decrypted = try OrgCrypt.decryptInPlace(encrypted, at: bank, passphrase: "pw")
244        let body = try #require(OrgCrypt.bodyRange(decrypted, at: bank))
245        session.cryptDecrypted(message: message, plaintext: (decrypted as NSString).substring(with: NSRange(body)), for: file.path)
246        session.cryptUsed("pw", for: file.path)
247        try replace(with: decrypted)
248        try type("More. ", at: offset(of: "Open text."))
249        #expect(session.save())
250        #expect(disk == (encrypted as NSString).replacingOccurrences(of: "Open text.", with: "More. Open text."))
251    }
252
253    @Test func offWritesWhatTheBufferHas() throws {
254        session.encryptsTaggedEntries = false
255        try notes.write("a.org", "* Plain\n")
256        session.open(file.path)
257        try replace(with: Self.file)
258        #expect(session.save())
259        #expect(disk == Self.file)
260        #expect(session.openTexts[file.path] == Self.file)
261    }
262
263    @Test func aFileChangedOnDiskMergesWithTheDecryptedBuffer() throws {
264        try notes.write("a.org", "* Plain\nOpen text.\n")
265        session.open(file.path)
266        session.cryptUsed("pw", for: file.path)
267        try replace(with: Self.file)
268        #expect(session.save())
269        // Another program appends to the file; the buffer keeps its decrypted entry.
270        try notes.write("a.org", disk + "* From Emacs\n")
271        session.fileChanged(file.path)
272        #expect(session.document?.text == Self.file + "* From Emacs\n")
273        #expect(!session.isDirty)
274        try type("y", at: 0)
275        #expect(session.save())
276        #expect(!disk.contains(Self.secret) && disk.hasSuffix("* From Emacs\n"))
277    }
278
279    // MARK: - Encrypted files
280
281    static let gpgText = "* Diary\nDear diary, \(secret).\n"
282
283    @Test func encryptedFilesOpenWithThePassphraseAndSaveEncrypted() throws {
284        let message = try OpenPGP.encryptedMessage(Data(Self.gpgText.utf8), passphrase: "pw")
285        let path = notes.url.appendingPathComponent("diary.org.gpg")
286        try message.write(to: path)
287        var written: [String] = []
288        session.fileWritten = { written.append($0) }
289        session.open(path.path)
290        #expect(session.unlockRequest == path.path)
291        #expect(!session.isOpen(path.path))
292        #expect(session.unlock("wrong", for: path.path) == "Wrong passphrase")
293        #expect(try Data(contentsOf: path) == message)
294        #expect(session.unlock("pw", for: path.path) == nil)
295        #expect(session.unlockRequest == nil)
296        #expect(session.path == path.path && session.document?.text == Self.gpgText)
297        #expect(session.isOrg)
298        #expect(session.openTexts[path.path] == nil)
299        try type("x", at: 0)
300        #expect(session.save())
301        #expect(written == [path.path])
302        let disk = try Data(contentsOf: path)
303        #expect(!OpenPGP.isArmored(disk))
304        #expect(disk.range(of: Data(Self.secret.utf8)) == nil)
305        #expect(try OpenPGP.decryptFile(disk, passphrase: "pw") == Data(("x" + Self.gpgText).utf8))
306        // Recovery keeps the version replaced, encrypted, and shows it decrypted.
307        #expect(!recoveryFiles.isEmpty && recoveryFiles.allSatisfy { !$0.contains(Self.secret) })
308        let version = try #require(session.recoveryVersions().first)
309        #expect(session.recoveryText(version.url) == Self.gpgText)
310        // A passphrase forgotten while the file is open must be the file's when given again.
311        session.crypt.forgetPassphrase(for: path.path)
312        try type("y", at: 0)
313        #expect(!session.save())
314        #expect(session.held[path.path] == .file)
315        #expect(session.unlock("typo", for: path.path) == "Wrong passphrase")
316        #expect(session.unlock("pw", for: path.path) == nil && !session.isDirty)
317        #expect(try OpenPGP.decryptFile(Data(contentsOf: path), passphrase: "pw") == Data(("yx" + Self.gpgText).utf8))
318        // Closing forgets the passphrase.
319        session.kill(path.path)
320        session.open(path.path)
321        #expect(session.unlockRequest == path.path)
322    }
323
324    @Test func armoredFilesStayArmored() throws {
325        let armored = try OpenPGP.encrypt(Data(Self.gpgText.utf8), passphrase: "pw")
326        let path = try notes.write("diary.org.gpg", armored)
327        session.open(path.path)
328        #expect(session.unlock("pw", for: path.path) == nil)
329        try type("x", at: 0)
330        #expect(session.save())
331        let disk = try Data(contentsOf: path)
332        #expect(OpenPGP.isArmored(disk))
333        #expect(try OpenPGP.decryptFile(disk, passphrase: "pw") == Data(("x" + Self.gpgText).utf8))
334    }
335
336    @Test func aNewEncryptedFileWaitsForItsPassphrase() throws {
337        let path = try notes.write("new.org.gpg", "")
338        session.open(path.path)
339        #expect(session.unlockRequest == nil && session.path == path.path)
340        try type(Self.gpgText, at: 0)
341        #expect(!session.save())
342        #expect(session.held[path.path] == .file)
343        #expect(try Data(contentsOf: path).isEmpty)
344        #expect(recoveryFiles.isEmpty)
345        #expect(session.unlock("new", for: path.path) == nil)
346        #expect(!session.isDirty && session.held.isEmpty)
347        #expect(try OpenPGP.decryptFile(Data(contentsOf: path), passphrase: "new") == Data(Self.gpgText.utf8))
348    }
349
350    @Test func anEncryptedFileChangedOnDiskMergesInMemory() throws {
351        let path = notes.url.appendingPathComponent("diary.org.gpg")
352        try OpenPGP.encryptedMessage(Data(Self.gpgText.utf8), passphrase: "pw").write(to: path)
353        session.open(path.path)
354        #expect(session.unlock("pw", for: path.path) == nil)
355        try type("x", at: 0)
356        try OpenPGP.encryptedMessage(Data((Self.gpgText + "* Added elsewhere\n").utf8), passphrase: "pw").write(to: path)
357        session.fileChanged(path.path)
358        #expect(session.document?.text == "x" + Self.gpgText + "* Added elsewhere\n")
359        #expect(session.save())
360        #expect(try OpenPGP.decryptFile(Data(contentsOf: path), passphrase: "pw") == Data(("x" + Self.gpgText + "* Added elsewhere\n").utf8))
361        #expect(recoveryFiles.allSatisfy { !$0.contains(Self.secret) && !$0.contains("Added elsewhere") })
362    }
363}
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