Tests/OrgAppTests/CryptReviewTests.swift

b5aa2aefb2a4844c3369b8024a32c2f81a59bfd1
orgstar/Tests/OrgAppTests/CryptReviewTests.swift

528 lines · 28580 bytes

  1import CryptoKit
  2import Foundation
  3import OrgCore
  4import OrgDocument
  5import Testing
  6@testable import OrgApp
  7
  8/// What an encrypted entry or file must not leak, nor lose, past the save path.
  9@MainActor
 10struct CryptReviewTests {
 11    static let secret = "Account 12345"
 12    static let file = "* Plain\nOpen text.\n* Bank :crypt:\n\(secret)\n* Last\n"
 13
 14    let notes: Folder
 15    let file: URL
 16    let recoveryFolder: URL
 17    let session: DocumentSession
 18
 19    init() throws {
 20        notes = try Folder()
 21        file = try notes.write("a.org", "* Plain\nOpen text.\n* Last\n")
 22        recoveryFolder = notes.url.appendingPathComponent(".recovery")
 23        session = DocumentSession(recovery: FileRecoveryStore(directory: recoveryFolder))
 24        session.saveMode = .explicit
 25        session.encryptsTaggedEntries = true
 26        session.passphrases = FakeKeychain.passphrases(.undecided).passphrases
 27    }
 28
 29    func replace(with text: String) throws {
 30        let buffer = StateBuffer(session.document!)
 31        session.attach(buffer)
 32        try buffer.update { try $0.apply([TextEdit(range: 0..<($0.text as NSString).length, replacement: text)], baseRevision: $0.revision) }
 33        session.bufferChanged()
 34    }
 35
 36    func type(_ text: String, at offset: Int) throws {
 37        let buffer = StateBuffer(session.document!)
 38        session.attach(buffer)
 39        try buffer.update { try $0.apply([TextEdit(range: offset..<offset, replacement: text)], baseRevision: $0.revision) }
 40        session.bufferChanged()
 41    }
 42
 43    func read(_ url: URL) -> String { (try? String(contentsOf: url, encoding: .utf8)) ?? "" }
 44    var disk: String { read(file) }
 45
 46    var recoveryFiles: [String] {
 47        let files = FileManager.default.enumerator(at: recoveryFolder, includingPropertiesForKeys: nil)?.compactMap { $0 as? URL } ?? []
 48        return files.compactMap { try? Data(contentsOf: $0) }.map { String(decoding: $0, as: UTF8.self) }
 49    }
 50
 51    func offset(of needle: String) -> Int { (session.document!.text as NSString).range(of: needle).location }
 52
 53    // 1
 54    @Test func turningTheSettingOffKeepsSealingOpenFiles() throws {
 55        session.open(file.path)
 56        session.cryptUsed("pw", for: file.path)
 57        try replace(with: Self.file)
 58        #expect(session.save())
 59        #expect(!disk.contains(Self.secret))
 60        session.encryptsTaggedEntries = false
 61        try type("x", at: 0)
 62        #expect(session.save())
 63        #expect(!disk.contains(Self.secret))
 64        #expect(session.openTexts[file.path] == nil)
 65        // A file opened after it was turned off is as before.
 66        let other = try notes.write("b.org", Self.file)
 67        session.open(other.path)
 68        try type("y", at: 0)
 69        #expect(session.save())
 70        #expect(read(other).contains(Self.secret))
 71    }
 72
 73    // 2
 74    @Test func useDiskVersionOnAHeldFileKeepsTheEdits() throws {
 75        session.open(file.path)
 76        try replace(with: Self.file)
 77        #expect(!session.save())
 78        session.useDiskVersion()
 79        #expect(session.document?.text == Self.file)
 80        #expect(session.lastError?.contains("Encrypt…") == true)
 81        #expect(session.restore(text: "* Plain\n")?.contains("Encrypt…") == true)
 82        #expect(session.document?.text == Self.file)
 83        #expect(recoveryFiles.isEmpty && disk == "* Plain\nOpen text.\n* Last\n")
 84    }
 85
 86    // 3a
 87    @Test func archivingAChildOfATaggedEntryEncryptsItFirst() throws {
 88        let text = "* Parent :crypt:\nparent text\n** SECRETTITLE child\nchild secret\n* Other :crypt:\nother secret\n* Last\n"
 89        try notes.write("a.org", text)
 90        session.open(file.path)
 91        let child = (text as NSString).range(of: "** SECRETTITLE").location
 92        let archive = notes.url.appendingPathComponent("a.org_archive")
 93        // A heading inside an encrypted entry isn't moved on its own, passphrase or not.
 94        #expect(session.archive(from: (file.path, child))?.contains("inside an encrypted entry") == true)
 95        session.cryptUsed("pw", for: file.path)
 96        #expect(session.archive(from: (file.path, child))?.contains("inside an encrypted entry") == true)
 97        let target = RefileTarget(label: "b.org", path: try notes.write("b.org", "* B\n").path, start: nil, title: "", level: 0, contentHash: "")
 98        #expect(session.refile(to: target, from: (file.path, child))?.contains("inside an encrypted entry") == true)
 99        #expect(!FileManager.default.fileExists(atPath: archive.path) && !read(notes.url.appendingPathComponent("b.org")).contains("SECRETTITLE"))
100        // A tagged entry is encrypted where it is, then archived.
101        let other = (session.document!.text as NSString).range(of: "* Other").location
102        #expect(session.archive(from: (file.path, other)) == "Archived to a.org_archive")
103        #expect(!read(archive).contains("other secret") && read(archive).contains("-----BEGIN PGP MESSAGE-----"))
104        #expect(session.save())
105        #expect(!disk.contains("child secret") && !disk.contains("SECRETTITLE"))
106    }
107
108    // Third review, A and B
109    @Test func shareSubtreeOfAHeadingInsideAnEncryptedEntry() throws {
110        let text = "* Parent :crypt:\nparent text\n** SECRETTITLE child\nchild secret\n* Last\n"
111        try notes.write("a.org", text)
112        session.open(file.path)
113        session.cryptUsed("pw", for: file.path)
114        let child = (text as NSString).range(of: "** SECRETTITLE").location
115        let share = try #require(session.subtreeShare(file.path, at: child))
116        #expect(share.fileName == "Encrypted entry.org")
117        #expect(!share.text.contains("SECRETTITLE") && !share.text.contains("child secret") && share.text.hasPrefix("* Encrypted entry :crypt:\n"))
118        let opened = try OrgCrypt.decryptInPlace(share.text, at: 0, passphrase: "pw")
119        #expect(opened.contains("** SECRETTITLE child\nchild secret\n"))
120        // Capture under that heading, into the file closed, isn't written.
121        session.kill(file.path)
122        let template = CaptureTemplate(key: "s", name: "Secret", target: .headline(file: file.path, headline: "SECRETTITLE child"), template: "* %?")
123        if case .success = session.capture("** Captured\n", template: template, root: nil) { Issue.record("captured into plaintext") }
124        #expect(disk == text)
125    }
126
127    @Test func shareSubtreeRefusesWhatCantBeEncrypted() throws {
128        let text = "* A :crypt:\na secret\n* B :crypt:\nb secret\n* End\n"
129        var both = try #require(try OrgCrypt.encrypt(text, at: 0, passphrase: "one"))
130        both = try #require(try OrgCrypt.encrypt(both, at: (both as NSString).range(of: "* B").location, passphrase: "two"))
131        try notes.write("a.org", both)
132        session.open(file.path)
133        session.cryptUsed("one", for: file.path)
134        try type("typed below b\n", at: offset(of: "* End"))
135        let b = offset(of: "* B")
136        #expect(session.refusesSubtreeShare(file.path, at: b)?.contains("public key") == true)
137        #expect(session.subtreeShare(file.path, at: b) == nil)
138    }
139
140    // Final check, 1
141    @Test func closedFilesPutBackAVersionTheyCantKeep() throws {
142        let files = InjectingFileSystem()
143        let session = DocumentSession(fileSystem: files, recovery: FileRecoveryStore(directory: recoveryFolder))
144        session.encryptsTaggedEntries = true
145        session.passphrases = FakeKeychain.passphrases(.undecided).passphrases
146        let theirs = "* B\nb\n* Emacs :crypt:\nemacs secret\n* Work\nEMACSWORK\n"
147        let b = try notes.write("b.org", "* B\nb\n")
148        func check(_ message: String?, _ what: String) {
149            #expect(message?.contains("changed on disk") == true, "\(what): \(String(describing: message))")
150            #expect(read(b) == theirs, "\(what)")
151            #expect(recoveryFiles.allSatisfy { !$0.contains("emacs secret") }, "\(what)")
152            try? notes.write("b.org", "* B\nb\n")
153        }
154        // Replace in Files.
155        files.inject[b.path] = theirs
156        check(session.applyChanges([TextEdit(range: 4..<5, replacement: "c")], to: b.path, expecting: "* B\nb\n"), "replace")
157        // Agenda actions, the clock and capture run commands on the file.
158        files.inject[b.path] = theirs
159        if case .failed(let message) = session.perform(PrecomputedEdit(EditResult(baseRevision: 0, edits: [TextEdit(range: 4..<5, replacement: "c")])), path: b.path, at: 0, expect: nil) {
160            check(message, "perform")
161        } else {
162            Issue.record("perform succeeded")
163        }
164        // Refile into it, and a new heading under its heading.
165        try notes.write("a.org", "* Moved\nmoved text\n")
166        session.open(file.path)
167        files.inject[b.path] = theirs
168        let target = RefileTarget(label: "b.org", path: b.path, start: nil, title: "", level: 0, contentHash: "")
169        check(session.refile(to: target, from: (file.path, 0)), "refile")
170        #expect(disk == "* Moved\nmoved text\n")
171        files.inject[b.path] = theirs
172        if case .failure(.message(let message)) = session.createRefileChild(under: target, title: "New") { check(message, "child") } else { Issue.record("child added") }
173        // Archive into it.
174        try notes.write("a.org", "#+ARCHIVE: b.org::\n* Old\nold text\n")
175        session.kill(file.path)
176        session.open(file.path)
177        files.inject[b.path] = theirs
178        check(session.archive(from: (file.path, 19)), "archive")
179        // An open file merges it as before.
180        session.open(b.path)
181        let buffer = StateBuffer(session.document(of: b.path)!)
182        session.attach(buffer, for: b.path)
183        try buffer.update { try $0.apply([TextEdit(range: 0..<0, replacement: "x")], baseRevision: $0.revision) }
184        session.bufferChanged(b.path)
185        files.inject[b.path] = theirs
186        _ = session.save(b.path)
187        #expect(session.document(of: b.path)?.text.contains("EMACSWORK") == true)
188    }
189
190    @Test func aVersionWrittenAfterOursIsntOverwrittenByTheRestore() throws {
191        let files = InjectingFileSystem()
192        let session = DocumentSession(fileSystem: files, recovery: FileRecoveryStore(directory: recoveryFolder))
193        session.encryptsTaggedEntries = true
194        session.passphrases = FakeKeychain.passphrases(.undecided).passphrases
195        let b = try notes.write("b.org", "* B\nb\n")
196        files.inject[b.path] = "* B\nb\n* Emacs :crypt:\nemacs secret\n"
197        files.injectAfter[b.path] = "* B\nthird\n"
198        let message = session.applyChanges([TextEdit(range: 4..<5, replacement: "c")], to: b.path, expecting: "* B\nb\n")
199        #expect(message?.contains("changed on disk") == true)
200        #expect(read(b) == "* B\nthird\n")
201    }
202
203    // Final check, 2
204    @Test func sameFileMovesDontTakeAHeadingOutOfItsEntry() throws {
205        let text = "#+ARCHIVE: ::* Archive\n* Parent :crypt:\nparent text\n** SECRETTITLE child\nchild secret\n* Last\n"
206        try notes.write("a.org", text)
207        session.open(file.path)
208        session.cryptUsed("pw", for: file.path)
209        let child = (text as NSString).range(of: "** SECRETTITLE").location
210        let target = RefileTarget(label: "a.org", path: file.path, start: nil, title: "", level: 0, contentHash: "")
211        #expect(session.refile(to: target, from: (file.path, child))?.contains("inside an encrypted entry") == true)
212        #expect(session.archive(from: (file.path, child))?.contains("inside an encrypted entry") == true)
213        #expect(session.document?.text == text)
214        // An entry not inside one moves as before.
215        #expect(session.refile(to: target, from: (file.path, (text as NSString).range(of: "* Last").location)) != nil)
216    }
217
218    // Final check, 3
219    @Test func hiddenTitlesAreHashedWithAKey() throws {
220        ClockTask.titleKey = nil
221        let session = ClockTask(path: "/x", title: "Real", ordinal: 0, id: nil).hiding("Encrypted entry")
222        #expect(session.isSessionOnly && session.titleHash != OrgCrypt.checksum("Real"))
223        #expect(session.locate(in: "* Real\n") == 0)
224        let key = SymmetricKey(size: .bits256)
225        ClockTask.titleKey = key
226        defer { ClockTask.titleKey = nil }
227        let kept = ClockTask(path: "/x", title: "Real", ordinal: 0, id: nil).hiding("Encrypted entry")
228        #expect(!kept.isSessionOnly && kept.titleHash != OrgCrypt.checksum("Real") && kept.locate(in: "* Real\n") == 0)
229        // Hidden tasks that can be found only in this run aren't written to the clock's file.
230        ClockTask.titleKey = nil
231        let text = "* Bank :crypt:\nintro\n** Secret task\nbody\n"
232        try notes.write("a.org", text)
233        self.session.open(file.path)
234        self.session.cryptUsed("pw", for: file.path)
235        let clockFile = notes.url.appendingPathComponent("clock.json")
236        let clock = ClockModel(file: clockFile)
237        _ = clock.clockIn(self.session, path: file.path, at: (text as NSString).range(of: "** Secret").location)
238        _ = clock.clockOut(self.session)
239        #expect(clock.history.count == 1)
240        #expect(!read(clockFile).contains("s:"))
241    }
242
243    @Test func aRunWithoutTheKeyKeepsHiddenTasksHashedWithIt() throws {
244        let text = "* Bank :crypt:\nintro\n** Secret task\nbody\n* Plain\n"
245        try notes.write("a.org", text)
246        ClockTask.titleKey = SymmetricKey(size: .bits256)
247        let earlier = ClockTask(path: file.path, title: "Secret task", ordinal: 1, id: nil).hiding("Encrypted entry")
248        ClockTask.titleKey = nil
249        defer { ClockTask.titleKey = nil }
250        let clockFile = notes.url.appendingPathComponent("clock.json")
251        try JSONEncoder().encode(["history": [earlier]]).write(to: clockFile)
252        let clock = ClockModel(file: clockFile)
253        #expect(clock.history == [earlier])
254        session.open(file.path)
255        session.cryptUsed("pw", for: file.path)
256        _ = clock.clockIn(session, path: file.path, at: (text as NSString).range(of: "** Secret").location)
257        _ = clock.clockOut(session)
258        let now = try #require(session.document(of: file.path)?.text)
259        _ = clock.clockIn(session, path: file.path, at: (now as NSString).range(of: "* Plain").location)
260        _ = clock.clockOut(session)
261        // The earlier entry stays as it was; this run's hidden entry isn't written.
262        #expect(clock.history.count == 3 && clock.history.last == earlier)
263        let saved = read(clockFile)
264        #expect(saved.contains(try #require(earlier.titleHash)) && !saved.contains("s:"))
265        #expect(!saved.contains("Secret task"))
266    }
267
268    // Third review, C
269    @Test func hiddenClockTasksNeedTheirTitle() throws {
270        let hidden = ClockTask(path: "/x", title: "Real", ordinal: 1, id: nil).hiding("Encrypted entry")
271        #expect(hidden.title == "Encrypted entry" && hidden.titleHash != nil)
272        #expect(hidden.locate(in: "* A\n* Real\n") == 4)
273        #expect(hidden.locate(in: "* New\n* A\n* Real\n") == 10)
274        #expect(hidden.locate(in: "* A\n* Renamed\n") == nil)
275        #expect(hidden.refreshed(in: "* New\n* A\n* Real\n")?.title == "Encrypted entry")
276    }
277
278    // Third review, D2
279    @Test func keepMineHoldsWhenTheDiskVersionCantBeKept() throws {
280        session.open(file.path)
281        try type("x", at: 0)
282        try notes.write("a.org", "* Plain\n* Theirs :crypt:\ntheir secret\n")
283        session.keepMine()
284        #expect(session.held[file.path] == .entries(1) && session.lastError == nil)
285        #expect(disk.contains("their secret") && recoveryFiles.isEmpty)
286    }
287
288    // Third review, 3
289    @Test func aCancelledOpenEndsItsAuthentication() throws {
290        let path = notes.url.appendingPathComponent("d.org.gpg")
291        try OpenPGP.encryptedMessage(Data("* D\n".utf8), passphrase: "pw").write(to: path)
292        session.open(path.path)
293        let context = session.passphrases.context(for: path.path)
294        session.cancelUnlock()
295        #expect(session.passphrases.context(for: path.path) !== context)
296        session.passphrases.endSession(for: path.path)
297    }
298
299    // 3b
300    @Test func encryptedFilesArchiveToEncryptedFilesAndRefileOnlyThere() throws {
301        let path = notes.url.appendingPathComponent("diary.org.gpg")
302        try OpenPGP.encryptedMessage(Data("* Monday\nDear diary.\n* Tuesday\nMore.\n".utf8), passphrase: "pw").write(to: path)
303        session.open(path.path)
304        #expect(session.unlock("pw", for: path.path) == nil)
305        let target = RefileTarget(label: "a.org", path: file.path, start: nil, title: "", level: 0, contentHash: "")
306        #expect(session.refile(to: target, from: (path.path, 0))?.contains("isn't") == true)
307        #expect(!disk.contains("Dear diary"))
308        #expect(session.archive(from: (path.path, 0)) == "Archived to diary_archive.org.gpg")
309        let archive = notes.url.appendingPathComponent("diary_archive.org.gpg")
310        #expect(!FileManager.default.fileExists(atPath: notes.url.appendingPathComponent("diary.org.gpg_archive").path))
311        let bytes = try Data(contentsOf: archive)
312        #expect(bytes.range(of: Data("Dear diary".utf8)) == nil)
313        #expect(String(decoding: try OpenPGP.decryptFile(bytes, passphrase: "pw"), as: UTF8.self).contains("Dear diary."))
314        // Capture into an encrypted file that isn't open writes nothing.
315        session.kill(path.path)
316        let template = CaptureTemplate(key: "d", name: "Diary", target: .file(path.path), template: "* %?")
317        if case .success = session.capture("* Captured secret\n", template: template, root: nil) { Issue.record("captured into a locked file") }
318        #expect(try Data(contentsOf: path).range(of: Data("Captured".utf8)) == nil)
319    }
320
321    // 5
322    @Test func textBelowAMessageIsHeldThenSealedWithIt() throws {
323        let encrypted = try #require(try OrgCrypt.encrypt(Self.file, at: (Self.file as NSString).range(of: "* Bank").location, passphrase: "pw"))
324        try notes.write("a.org", encrypted)
325        session.open(file.path)
326        try type("typed below\n", at: offset(of: "* Last"))
327        #expect(!session.save())
328        #expect(session.held[file.path] == .entries(1))
329        #expect(!disk.contains("typed below"))
330        #expect(session.unlock("pw", for: file.path) == nil)
331        #expect(!disk.contains("typed below"))
332        let bank = (disk as NSString).range(of: "* Bank").location
333        #expect(try OrgCrypt.decrypt(disk, at: bank, passphrase: "pw").plaintext == Self.secret + "\ntyped below\n")
334    }
335
336    // 7
337    @Test func exportsLeaveOutWhatIsEncryptedOnDisk() throws {
338        session.open(file.path)
339        session.cryptUsed("pw", for: file.path)
340        try replace(with: Self.file)
341        #expect(session.save())
342        #expect(session.exportLeavesOut(file.path))
343        #expect(session.exportText(of: file.path) == disk)
344        #expect(session.exportText(of: file.path)?.contains(Self.secret) == false)
345        let gpg = notes.url.appendingPathComponent("d.org.gpg")
346        try OpenPGP.encryptedMessage(Data("* D\nsecret\n".utf8), passphrase: "pw").write(to: gpg)
347        session.open(gpg.path)
348        #expect(session.unlock("pw", for: gpg.path) == nil)
349        #expect(session.exportText(of: gpg.path) == nil && session.exportLeavesOut(gpg.path))
350        // Nor is either copied for Emacs.
351        #expect(session.refusesEmacsCopy(gpg.path) != nil && session.refusesEmacsCopy(file.path) != nil)
352        let plain = try notes.write("c.org", "* C\n")
353        session.open(plain.path)
354        #expect(session.exportText(of: plain.path) == "* C\n" && session.refusesEmacsCopy(plain.path) == nil)
355    }
356
357    // 8
358    @Test func clockingInDoesntKeepEncryptedTitles() throws {
359        let text = "* Bank :crypt:\nintro\n** Secret task\nbody\n* Open task\n"
360        try notes.write("a.org", text)
361        session.open(file.path)
362        session.cryptUsed("pw", for: file.path)
363        let clock = ClockModel(file: notes.url.appendingPathComponent("clock.json"))
364        _ = clock.clockIn(session, path: file.path, at: (text as NSString).range(of: "** Secret").location)
365        #expect(clock.running?.heading == "Encrypted entry")
366        #expect(clock.history.allSatisfy { $0.title != "Secret task" })
367        #expect(!read(notes.url.appendingPathComponent("clock.json")).contains("Secret task"))
368        #expect(session.shareableTitle("Bank", path: file.path, heading: 0) == "Bank")
369        #expect(session.shareableTitle("Monday", path: "/x/d.org.gpg", heading: 0) == "Encrypted entry")
370        _ = clock.clockOut(session)
371        #expect(session.save())
372        #expect(!disk.contains("Secret task") && !disk.contains("intro"))
373    }
374
375    // Second review, 2
376    @Test func clockHistoryKeepsNoEncryptedTitle() throws {
377        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"
378        try notes.write("a.org", text)
379        session.open(file.path)
380        session.cryptUsed("pw", for: file.path)
381        let clockFile = notes.url.appendingPathComponent("clock.json")
382        let clock = ClockModel(file: clockFile)
383        _ = clock.clockIn(session, path: file.path, at: (text as NSString).range(of: "** Secret").location)
384        _ = clock.clockIn(session, path: file.path, at: (session.document!.text as NSString).range(of: "** Hidden").location)
385        _ = clock.clockIn(session, path: file.path, at: (session.document!.text as NSString).range(of: "* Open").location)
386        #expect(!read(clockFile).contains("Secret task") && !read(clockFile).contains("Hidden no id"))
387        #expect(clock.history.map(\.title) == ["Open task", "Encrypted entry", "Encrypted entry"])
388    }
389
390    // Second review, 3
391    @Test func eachFileHasItsOwnAuthentication() throws {
392        let passphrases = session.passphrases
393        let a = passphrases.context(for: "/x/a.org"), b = passphrases.context(for: "/x/b.org")
394        #expect(a !== b && passphrases.context(for: "/x/a.org") === a)
395        #expect(a.touchIDAuthenticationAllowableReuseDuration == 0)
396        passphrases.endSession(for: "/x/a.org")
397        #expect(passphrases.context(for: "/x/a.org") !== a)
398    }
399
400    // Second review, 4a
401    @Test func anEntryThePassphraseCantEncryptHoldsTheFile() throws {
402        let text = "* A :crypt:\na secret\n* B :crypt:\nb secret\n* End\n"
403        var both = try #require(try OrgCrypt.encrypt(text, at: 0, passphrase: "one"))
404        both = try #require(try OrgCrypt.encrypt(both, at: (both as NSString).range(of: "* B").location, passphrase: "two"))
405        try notes.write("a.org", both)
406        session.open(file.path)
407        #expect(session.unlock("one", for: file.path) == nil)
408        try type("typed below b\n", at: offset(of: "* End"))
409        #expect(!session.save())
410        guard case .blocked(let reason)? = session.held[file.path] else { Issue.record("\(String(describing: session.held[file.path]))"); return }
411        #expect(reason.contains("public key") && session.lastError == nil)
412        #expect(OrgCrypt.Failure("x").localizedDescription == "x")
413        #expect(!disk.contains("typed below b"))
414    }
415
416    // Second review, 4b
417    @Test func plaintextEntriesOnDiskHoldTheFileUntilThePassphrase() throws {
418        session.open(file.path)
419        try type("x", at: 0)
420        // Written elsewhere, with no file event.
421        try notes.write("a.org", "* Plain\nOpen text.\n* Last\n* Theirs :crypt:\ntheir secret\n")
422        #expect(!session.save())
423        #expect(session.held[file.path] == .entries(1) && session.lastError == nil)
424        #expect(session.unlock("pw", for: file.path) == nil)
425        #expect(!session.isDirty && !disk.contains("their secret") && session.document?.text.contains("their secret") == true)
426        #expect(recoveryFiles.allSatisfy { !$0.contains("their secret") })
427    }
428
429    // Second review, 6
430    @Test func anEncryptedFileSavesWithOneKey() throws {
431        let path = notes.url.appendingPathComponent("d.org.gpg")
432        try OpenPGP.encryptedMessage(Data("* D\nbody\n".utf8), passphrase: "pw").write(to: path)
433        session.open(path.path)
434        #expect(session.unlock("pw", for: path.path) == nil)
435        try type("x", at: 0)
436        #expect(session.save())
437        let clock = ContinuousClock()
438        var took: [Duration] = []
439        for n in 0..<3 {
440            try type("\(n)", at: 0)
441            took.append(clock.measure { _ = session.save() })
442        }
443        print("Autosave of an .org.gpg file: \(took)")
444        #expect(try OpenPGP.decryptFile(Data(contentsOf: path), passphrase: "pw") == Data("210x* D\nbody\n".utf8))
445    }
446
447    // MR 490 hooks
448    @Test func handoffAndShareSubtreeKeepWhatIsEncrypted() throws {
449        let text = "* Bank :crypt:\nintro\n** Secret child\nbody\n* Open\n"
450        try notes.write("a.org", text)
451        session.open(file.path)
452        let child = (text as NSString).range(of: "** Secret").location
453        // Without the passphrase, the subtree isn't shared.
454        #expect(session.handoffPlace(file.path, roots: [notes.url.path]) == nil)
455        #expect(session.refusesSubtreeShare(file.path, at: child)?.contains("Encrypt…") == true)
456        #expect(session.subtreeShare(file.path, at: child) == nil)
457        session.cryptUsed("pw", for: file.path)
458        let share = try #require(session.subtreeShare(file.path, at: child))
459        #expect(!share.text.contains("body") && share.text.contains("-----BEGIN PGP MESSAGE-----"))
460        #expect(session.document?.text == text)
461        let bank = try #require(session.subtreeShare(file.path, at: 0))
462        #expect(!bank.text.contains("intro") && !bank.text.contains("Secret child"))
463        // An open file without tagged entries is advertised as before.
464        let plain = try notes.write("b.org", "* Plain\n")
465        session.open(plain.path)
466        #expect(session.handoffPlace(plain.path, roots: [notes.url.path]) != nil)
467        // An encrypted file's entries aren't shared.
468        let gpg = notes.url.appendingPathComponent("d.org.gpg")
469        try OpenPGP.encryptedMessage(Data("* D\nsecret\n".utf8), passphrase: "pw").write(to: gpg)
470        session.open(gpg.path)
471        #expect(session.unlock("pw", for: gpg.path) == nil)
472        #expect(session.refusesSubtreeShare(gpg.path, at: 0) != nil && session.subtreeShare(gpg.path, at: 0) == nil)
473    }
474
475    // 9
476    @Test func unchangedEntriesKeepTheirMessageAcrossSaves() throws {
477        session.open(file.path)
478        session.cryptUsed("pw", for: file.path)
479        try replace(with: Self.file)
480        #expect(session.save())
481        let message = try #require(OrgCrypt.firstMessage(disk))
482        for n in 0..<5 {
483            try type("\(n)", at: 0)
484            #expect(session.save())
485            #expect(disk.contains(message))
486        }
487        #expect(session.crypt.revealedMessages(for: file.path).count == 1)
488    }
489
490    // 10
491    @Test func entriesEncryptedToAPublicKeyDontBlockThePassphrase() throws {
492        // A public-key session packet (tag 1) where a message's packets start.
493        let publicKey = OpenPGP.armor(Data([0xC1, 0x02, 0x03, 0x00]))
494        try notes.write("a.org", "* Pub :crypt:\n" + publicKey + "* Plain\n")
495        session.open(file.path)
496        try type("* New :crypt:\nnew secret\n", at: (session.document!.text as NSString).length)
497        #expect(!session.save())
498        #expect(session.unlock("pw", for: file.path) == nil)
499        #expect(!disk.contains("new secret"))
500        #expect(disk.contains(publicKey))
501    }
502
503    // 6
504    @Test func keychainItemsAreThisDeviceOnlyAfterUserPresence() throws {
505        let item = try #require(SystemKeychain.newItem("pw", for: "/x/a.org"))
506        #expect(item[kSecAttrAccessControl as String] != nil)
507        #expect(item[kSecUseDataProtectionKeychain as String] as? Bool == true)
508        #expect(item[kSecAttrService as String] as? String == "sh.krz.orgstar.crypt.v2")
509        #expect(item[kSecAttrAccessible as String] == nil)
510    }
511}
512
513/// The disk, with another writer that puts `inject[path]` in place just before a replace, and
514/// a third that puts `injectAfter[path]` in place just after one.
515final class InjectingFileSystem: FileSystem, @unchecked Sendable {
516    let base = CoordinatedFileSystem(writesInPlaceWhenDenied: false)
517    var inject: [String: String] = [:]
518    var injectAfter: [String: String] = [:]
519
520    func read(_ url: URL) throws -> [UInt8]? { try base.read(url) }
521
522    func replace(_ url: URL, with bytes: [UInt8]) throws -> [UInt8]? {
523        if let text = inject.removeValue(forKey: url.path) { try Data(text.utf8).write(to: url) }
524        let replaced = try base.replace(url, with: bytes)
525        if let text = injectAfter.removeValue(forKey: url.path) { try Data(text.utf8).write(to: url) }
526        return replaced
527    }
528}
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