Tests/OrgAppTests/CryptReviewTests.swift

6e76718b67275264fce9c9041e50ec01592edace
orgstar/Tests/OrgAppTests/CryptReviewTests.swift

486 lines · 26075 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.hasStoredPassphrase = { _ in false }
 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.hasStoredPassphrase = { _ in false }
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    // Final check, 2
191    @Test func sameFileMovesDontTakeAHeadingOutOfItsEntry() throws {
192        let text = "#+ARCHIVE: ::* Archive\n* Parent :crypt:\nparent text\n** SECRETTITLE child\nchild secret\n* Last\n"
193        try notes.write("a.org", text)
194        session.open(file.path)
195        session.cryptUsed("pw", for: file.path)
196        let child = (text as NSString).range(of: "** SECRETTITLE").location
197        let target = RefileTarget(label: "a.org", path: file.path, start: nil, title: "", level: 0, contentHash: "")
198        #expect(session.refile(to: target, from: (file.path, child))?.contains("inside an encrypted entry") == true)
199        #expect(session.archive(from: (file.path, child))?.contains("inside an encrypted entry") == true)
200        #expect(session.document?.text == text)
201        // An entry not inside one moves as before.
202        #expect(session.refile(to: target, from: (file.path, (text as NSString).range(of: "* Last").location)) != nil)
203    }
204
205    // Final check, 3
206    @Test func hiddenTitlesAreHashedWithAKey() throws {
207        ClockTask.titleKey = nil
208        let session = ClockTask(path: "/x", title: "Real", ordinal: 0, id: nil).hiding("Encrypted entry")
209        #expect(session.isSessionOnly && session.titleHash != OrgCrypt.checksum("Real"))
210        #expect(session.locate(in: "* Real\n") == 0)
211        let key = SymmetricKey(size: .bits256)
212        ClockTask.titleKey = key
213        defer { ClockTask.titleKey = nil }
214        let kept = ClockTask(path: "/x", title: "Real", ordinal: 0, id: nil).hiding("Encrypted entry")
215        #expect(!kept.isSessionOnly && kept.titleHash != OrgCrypt.checksum("Real") && kept.locate(in: "* Real\n") == 0)
216        // Hidden tasks that can be found only in this run aren't written to the clock's file.
217        ClockTask.titleKey = nil
218        let text = "* Bank :crypt:\nintro\n** Secret task\nbody\n"
219        try notes.write("a.org", text)
220        self.session.open(file.path)
221        self.session.cryptUsed("pw", for: file.path)
222        let clockFile = notes.url.appendingPathComponent("clock.json")
223        let clock = ClockModel(file: clockFile)
224        _ = clock.clockIn(self.session, path: file.path, at: (text as NSString).range(of: "** Secret").location)
225        _ = clock.clockOut(self.session)
226        #expect(clock.history.count == 1)
227        #expect(!read(clockFile).contains("s:"))
228    }
229
230    // Third review, C
231    @Test func hiddenClockTasksNeedTheirTitle() throws {
232        let hidden = ClockTask(path: "/x", title: "Real", ordinal: 1, id: nil).hiding("Encrypted entry")
233        #expect(hidden.title == "Encrypted entry" && hidden.titleHash != nil)
234        #expect(hidden.locate(in: "* A\n* Real\n") == 4)
235        #expect(hidden.locate(in: "* New\n* A\n* Real\n") == 10)
236        #expect(hidden.locate(in: "* A\n* Renamed\n") == nil)
237        #expect(hidden.refreshed(in: "* New\n* A\n* Real\n")?.title == "Encrypted entry")
238    }
239
240    // Third review, D2
241    @Test func keepMineHoldsWhenTheDiskVersionCantBeKept() throws {
242        session.open(file.path)
243        try type("x", at: 0)
244        try notes.write("a.org", "* Plain\n* Theirs :crypt:\ntheir secret\n")
245        session.keepMine()
246        #expect(session.held[file.path] == .entries(1) && session.lastError == nil)
247        #expect(disk.contains("their secret") && recoveryFiles.isEmpty)
248    }
249
250    // Third review, 3
251    @Test func aCancelledOpenEndsItsAuthentication() throws {
252        let path = notes.url.appendingPathComponent("d.org.gpg")
253        try OpenPGP.encryptedMessage(Data("* D\n".utf8), passphrase: "pw").write(to: path)
254        session.open(path.path)
255        let context = CryptPassphrases.context(for: path.path)
256        session.cancelUnlock()
257        #expect(CryptPassphrases.context(for: path.path) !== context)
258        CryptPassphrases.endSession(for: path.path)
259        #expect(!CryptPassphrases.protectsItems)
260    }
261
262    // 3b
263    @Test func encryptedFilesArchiveToEncryptedFilesAndRefileOnlyThere() throws {
264        let path = notes.url.appendingPathComponent("diary.org.gpg")
265        try OpenPGP.encryptedMessage(Data("* Monday\nDear diary.\n* Tuesday\nMore.\n".utf8), passphrase: "pw").write(to: path)
266        session.open(path.path)
267        #expect(session.unlock("pw", for: path.path) == nil)
268        let target = RefileTarget(label: "a.org", path: file.path, start: nil, title: "", level: 0, contentHash: "")
269        #expect(session.refile(to: target, from: (path.path, 0))?.contains("isn't") == true)
270        #expect(!disk.contains("Dear diary"))
271        #expect(session.archive(from: (path.path, 0)) == "Archived to diary_archive.org.gpg")
272        let archive = notes.url.appendingPathComponent("diary_archive.org.gpg")
273        #expect(!FileManager.default.fileExists(atPath: notes.url.appendingPathComponent("diary.org.gpg_archive").path))
274        let bytes = try Data(contentsOf: archive)
275        #expect(bytes.range(of: Data("Dear diary".utf8)) == nil)
276        #expect(String(decoding: try OpenPGP.decryptFile(bytes, passphrase: "pw"), as: UTF8.self).contains("Dear diary."))
277        // Capture into an encrypted file that isn't open writes nothing.
278        session.kill(path.path)
279        let template = CaptureTemplate(key: "d", name: "Diary", target: .file(path.path), template: "* %?")
280        if case .success = session.capture("* Captured secret\n", template: template, root: nil) { Issue.record("captured into a locked file") }
281        #expect(try Data(contentsOf: path).range(of: Data("Captured".utf8)) == nil)
282    }
283
284    // 5
285    @Test func textBelowAMessageIsHeldThenSealedWithIt() throws {
286        let encrypted = try #require(try OrgCrypt.encrypt(Self.file, at: (Self.file as NSString).range(of: "* Bank").location, passphrase: "pw"))
287        try notes.write("a.org", encrypted)
288        session.open(file.path)
289        try type("typed below\n", at: offset(of: "* Last"))
290        #expect(!session.save())
291        #expect(session.held[file.path] == .entries(1))
292        #expect(!disk.contains("typed below"))
293        #expect(session.unlock("pw", for: file.path) == nil)
294        #expect(!disk.contains("typed below"))
295        let bank = (disk as NSString).range(of: "* Bank").location
296        #expect(try OrgCrypt.decrypt(disk, at: bank, passphrase: "pw").plaintext == Self.secret + "\ntyped below\n")
297    }
298
299    // 7
300    @Test func exportsLeaveOutWhatIsEncryptedOnDisk() throws {
301        session.open(file.path)
302        session.cryptUsed("pw", for: file.path)
303        try replace(with: Self.file)
304        #expect(session.save())
305        #expect(session.exportLeavesOut(file.path))
306        #expect(session.exportText(of: file.path) == disk)
307        #expect(session.exportText(of: file.path)?.contains(Self.secret) == false)
308        let gpg = notes.url.appendingPathComponent("d.org.gpg")
309        try OpenPGP.encryptedMessage(Data("* D\nsecret\n".utf8), passphrase: "pw").write(to: gpg)
310        session.open(gpg.path)
311        #expect(session.unlock("pw", for: gpg.path) == nil)
312        #expect(session.exportText(of: gpg.path) == nil && session.exportLeavesOut(gpg.path))
313        // Nor is either copied for Emacs.
314        #expect(session.refusesEmacsCopy(gpg.path) != nil && session.refusesEmacsCopy(file.path) != nil)
315        let plain = try notes.write("c.org", "* C\n")
316        session.open(plain.path)
317        #expect(session.exportText(of: plain.path) == "* C\n" && session.refusesEmacsCopy(plain.path) == nil)
318    }
319
320    // 8
321    @Test func clockingInDoesntKeepEncryptedTitles() throws {
322        let text = "* Bank :crypt:\nintro\n** Secret task\nbody\n* Open task\n"
323        try notes.write("a.org", text)
324        session.open(file.path)
325        session.cryptUsed("pw", for: file.path)
326        let clock = ClockModel(file: notes.url.appendingPathComponent("clock.json"))
327        _ = clock.clockIn(session, path: file.path, at: (text as NSString).range(of: "** Secret").location)
328        #expect(clock.running?.heading == "Encrypted entry")
329        #expect(clock.history.allSatisfy { $0.title != "Secret task" })
330        #expect(!read(notes.url.appendingPathComponent("clock.json")).contains("Secret task"))
331        #expect(session.shareableTitle("Bank", path: file.path, heading: 0) == "Bank")
332        #expect(session.shareableTitle("Monday", path: "/x/d.org.gpg", heading: 0) == "Encrypted entry")
333        _ = clock.clockOut(session)
334        #expect(session.save())
335        #expect(!disk.contains("Secret task") && !disk.contains("intro"))
336    }
337
338    // Second review, 2
339    @Test func clockHistoryKeepsNoEncryptedTitle() throws {
340        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"
341        try notes.write("a.org", text)
342        session.open(file.path)
343        session.cryptUsed("pw", for: file.path)
344        let clockFile = notes.url.appendingPathComponent("clock.json")
345        let clock = ClockModel(file: clockFile)
346        _ = clock.clockIn(session, path: file.path, at: (text as NSString).range(of: "** Secret").location)
347        _ = clock.clockIn(session, path: file.path, at: (session.document!.text as NSString).range(of: "** Hidden").location)
348        _ = clock.clockIn(session, path: file.path, at: (session.document!.text as NSString).range(of: "* Open").location)
349        #expect(!read(clockFile).contains("Secret task") && !read(clockFile).contains("Hidden no id"))
350        #expect(clock.history.map(\.title) == ["Open task", "Encrypted entry", "Encrypted entry"])
351    }
352
353    // Second review, 3
354    @Test func eachFileHasItsOwnAuthentication() throws {
355        let a = CryptPassphrases.context(for: "/x/a.org"), b = CryptPassphrases.context(for: "/x/b.org")
356        #expect(a !== b && CryptPassphrases.context(for: "/x/a.org") === a)
357        #expect(a.touchIDAuthenticationAllowableReuseDuration == 0)
358        CryptPassphrases.endSession(for: "/x/a.org")
359        #expect(CryptPassphrases.context(for: "/x/a.org") !== a)
360    }
361
362    // Second review, 4a
363    @Test func anEntryThePassphraseCantEncryptHoldsTheFile() throws {
364        let text = "* A :crypt:\na secret\n* B :crypt:\nb secret\n* End\n"
365        var both = try #require(try OrgCrypt.encrypt(text, at: 0, passphrase: "one"))
366        both = try #require(try OrgCrypt.encrypt(both, at: (both as NSString).range(of: "* B").location, passphrase: "two"))
367        try notes.write("a.org", both)
368        session.open(file.path)
369        #expect(session.unlock("one", for: file.path) == nil)
370        try type("typed below b\n", at: offset(of: "* End"))
371        #expect(!session.save())
372        guard case .blocked(let reason)? = session.held[file.path] else { Issue.record("\(String(describing: session.held[file.path]))"); return }
373        #expect(reason.contains("public key") && session.lastError == nil)
374        #expect(OrgCrypt.Failure("x").localizedDescription == "x")
375        #expect(!disk.contains("typed below b"))
376    }
377
378    // Second review, 4b
379    @Test func plaintextEntriesOnDiskHoldTheFileUntilThePassphrase() throws {
380        session.open(file.path)
381        try type("x", at: 0)
382        // Written elsewhere, with no file event.
383        try notes.write("a.org", "* Plain\nOpen text.\n* Last\n* Theirs :crypt:\ntheir secret\n")
384        #expect(!session.save())
385        #expect(session.held[file.path] == .entries(1) && session.lastError == nil)
386        #expect(session.unlock("pw", for: file.path) == nil)
387        #expect(!session.isDirty && !disk.contains("their secret") && session.document?.text.contains("their secret") == true)
388        #expect(recoveryFiles.allSatisfy { !$0.contains("their secret") })
389    }
390
391    // Second review, 6
392    @Test func anEncryptedFileSavesWithOneKey() throws {
393        let path = notes.url.appendingPathComponent("d.org.gpg")
394        try OpenPGP.encryptedMessage(Data("* D\nbody\n".utf8), passphrase: "pw").write(to: path)
395        session.open(path.path)
396        #expect(session.unlock("pw", for: path.path) == nil)
397        try type("x", at: 0)
398        #expect(session.save())
399        let clock = ContinuousClock()
400        var took: [Duration] = []
401        for n in 0..<3 {
402            try type("\(n)", at: 0)
403            took.append(clock.measure { _ = session.save() })
404        }
405        print("Autosave of an .org.gpg file: \(took)")
406        #expect(try OpenPGP.decryptFile(Data(contentsOf: path), passphrase: "pw") == Data("210x* D\nbody\n".utf8))
407    }
408
409    // MR 490 hooks
410    @Test func handoffAndShareSubtreeKeepWhatIsEncrypted() throws {
411        let text = "* Bank :crypt:\nintro\n** Secret child\nbody\n* Open\n"
412        try notes.write("a.org", text)
413        session.open(file.path)
414        let child = (text as NSString).range(of: "** Secret").location
415        // Without the passphrase, the subtree isn't shared.
416        #expect(session.handoffPlace(file.path, roots: [notes.url.path]) == nil)
417        #expect(session.refusesSubtreeShare(file.path, at: child)?.contains("Encrypt…") == true)
418        #expect(session.subtreeShare(file.path, at: child) == nil)
419        session.cryptUsed("pw", for: file.path)
420        let share = try #require(session.subtreeShare(file.path, at: child))
421        #expect(!share.text.contains("body") && share.text.contains("-----BEGIN PGP MESSAGE-----"))
422        #expect(session.document?.text == text)
423        let bank = try #require(session.subtreeShare(file.path, at: 0))
424        #expect(!bank.text.contains("intro") && !bank.text.contains("Secret child"))
425        // An open file without tagged entries is advertised as before.
426        let plain = try notes.write("b.org", "* Plain\n")
427        session.open(plain.path)
428        #expect(session.handoffPlace(plain.path, roots: [notes.url.path]) != nil)
429        // An encrypted file's entries aren't shared.
430        let gpg = notes.url.appendingPathComponent("d.org.gpg")
431        try OpenPGP.encryptedMessage(Data("* D\nsecret\n".utf8), passphrase: "pw").write(to: gpg)
432        session.open(gpg.path)
433        #expect(session.unlock("pw", for: gpg.path) == nil)
434        #expect(session.refusesSubtreeShare(gpg.path, at: 0) != nil && session.subtreeShare(gpg.path, at: 0) == nil)
435    }
436
437    // 9
438    @Test func unchangedEntriesKeepTheirMessageAcrossSaves() throws {
439        session.open(file.path)
440        session.cryptUsed("pw", for: file.path)
441        try replace(with: Self.file)
442        #expect(session.save())
443        let message = try #require(OrgCrypt.firstMessage(disk))
444        for n in 0..<5 {
445            try type("\(n)", at: 0)
446            #expect(session.save())
447            #expect(disk.contains(message))
448        }
449        #expect(session.crypt.revealedMessages(for: file.path).count == 1)
450    }
451
452    // 10
453    @Test func entriesEncryptedToAPublicKeyDontBlockThePassphrase() throws {
454        // A public-key session packet (tag 1) where a message's packets start.
455        let publicKey = OpenPGP.armor(Data([0xC1, 0x02, 0x03, 0x00]))
456        try notes.write("a.org", "* Pub :crypt:\n" + publicKey + "* Plain\n")
457        session.open(file.path)
458        try type("* New :crypt:\nnew secret\n", at: (session.document!.text as NSString).length)
459        #expect(!session.save())
460        #expect(session.unlock("pw", for: file.path) == nil)
461        #expect(!disk.contains("new secret"))
462        #expect(disk.contains(publicKey))
463    }
464
465    // 6
466    @Test func keychainItemsAreThisDeviceOnlyAfterUserPresence() throws {
467        let item = try #require(CryptPassphrases.newItem("pw", for: "/x/a.org"))
468        #expect(item[kSecAttrAccessControl as String] != nil)
469        #expect(item[kSecUseDataProtectionKeychain as String] as? Bool == true)
470        #expect(item[kSecAttrService as String] as? String == "sh.krz.orgstar.crypt.v2")
471        #expect(item[kSecAttrAccessible as String] == nil)
472    }
473}
474
475/// The disk, with another writer that puts `inject[path]` in place just before a replace.
476final class InjectingFileSystem: FileSystem, @unchecked Sendable {
477    let base = CoordinatedFileSystem(writesInPlaceWhenDenied: false)
478    var inject: [String: String] = [:]
479
480    func read(_ url: URL) throws -> [UInt8]? { try base.read(url) }
481
482    func replace(_ url: URL, with bytes: [UInt8]) throws -> [UInt8]? {
483        if let text = inject.removeValue(forKey: url.path) { try Data(text.utf8).write(to: url) }
484        return try base.replace(url, with: bytes)
485    }
486}
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