Tests/OrgAppTests/CryptSaveTests.swift

60cc4d87d6d78c99bbe339580b8e42e59b0d3529
orgstar/Tests/OrgAppTests/CryptSaveTests.swift

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