Tests/OrgAppTests/CryptReviewTests.swift

1e2be994af63ee234fff2fe60543c62ca3f6905e
orgstar/Tests/OrgAppTests/CryptReviewTests.swift

284 lines · 14298 bytes

  1import Foundation
  2import OrgCore
  3import OrgDocument
  4import Testing
  5@testable import OrgApp
  6
  7/// What an encrypted entry or file must not leak, nor lose, past the save path.
  8@MainActor
  9struct CryptReviewTests {
 10    static let secret = "Account 12345"
 11    static let file = "* Plain\nOpen text.\n* Bank :crypt:\n\(secret)\n* Last\n"
 12
 13    let notes: Folder
 14    let file: URL
 15    let recoveryFolder: URL
 16    let session: DocumentSession
 17
 18    init() throws {
 19        notes = try Folder()
 20        file = try notes.write("a.org", "* Plain\nOpen text.\n* Last\n")
 21        recoveryFolder = notes.url.appendingPathComponent(".recovery")
 22        session = DocumentSession(recovery: FileRecoveryStore(directory: recoveryFolder))
 23        session.saveMode = .explicit
 24        session.encryptsTaggedEntries = true
 25        session.hasStoredPassphrase = { _ in false }
 26    }
 27
 28    func replace(with text: String) throws {
 29        let buffer = StateBuffer(session.document!)
 30        session.attach(buffer)
 31        try buffer.update { try $0.apply([TextEdit(range: 0..<($0.text as NSString).length, replacement: text)], baseRevision: $0.revision) }
 32        session.bufferChanged()
 33    }
 34
 35    func type(_ text: String, at offset: Int) throws {
 36        let buffer = StateBuffer(session.document!)
 37        session.attach(buffer)
 38        try buffer.update { try $0.apply([TextEdit(range: offset..<offset, replacement: text)], baseRevision: $0.revision) }
 39        session.bufferChanged()
 40    }
 41
 42    func read(_ url: URL) -> String { (try? String(contentsOf: url, encoding: .utf8)) ?? "" }
 43    var disk: String { read(file) }
 44
 45    var recoveryFiles: [String] {
 46        let files = FileManager.default.enumerator(at: recoveryFolder, includingPropertiesForKeys: nil)?.compactMap { $0 as? URL } ?? []
 47        return files.compactMap { try? Data(contentsOf: $0) }.map { String(decoding: $0, as: UTF8.self) }
 48    }
 49
 50    func offset(of needle: String) -> Int { (session.document!.text as NSString).range(of: needle).location }
 51
 52    // 1
 53    @Test func turningTheSettingOffKeepsSealingOpenFiles() throws {
 54        session.open(file.path)
 55        session.cryptUsed("pw", for: file.path)
 56        try replace(with: Self.file)
 57        #expect(session.save())
 58        #expect(!disk.contains(Self.secret))
 59        session.encryptsTaggedEntries = false
 60        try type("x", at: 0)
 61        #expect(session.save())
 62        #expect(!disk.contains(Self.secret))
 63        #expect(session.openTexts[file.path] == nil)
 64        // A file opened after it was turned off is as before.
 65        let other = try notes.write("b.org", Self.file)
 66        session.open(other.path)
 67        try type("y", at: 0)
 68        #expect(session.save())
 69        #expect(read(other).contains(Self.secret))
 70    }
 71
 72    // 2
 73    @Test func useDiskVersionOnAHeldFileKeepsTheEdits() throws {
 74        session.open(file.path)
 75        try replace(with: Self.file)
 76        #expect(!session.save())
 77        session.useDiskVersion()
 78        #expect(session.document?.text == Self.file)
 79        #expect(session.lastError?.contains("Encrypt…") == true)
 80        #expect(session.restore(text: "* Plain\n")?.contains("Encrypt…") == true)
 81        #expect(session.document?.text == Self.file)
 82        #expect(recoveryFiles.isEmpty && disk == "* Plain\nOpen text.\n* Last\n")
 83    }
 84
 85    // 3a
 86    @Test func archivingAChildOfATaggedEntryEncryptsItFirst() throws {
 87        let text = "* Parent :crypt:\nparent text\n** Child\nchild secret\n* Last\n"
 88        try notes.write("a.org", text)
 89        session.open(file.path)
 90        let child = (text as NSString).range(of: "** Child").location
 91        let archive = notes.url.appendingPathComponent("a.org_archive")
 92        #expect(session.archive(from: (file.path, child))?.contains("Encrypt…") == true)
 93        #expect(!FileManager.default.fileExists(atPath: archive.path))
 94        session.cryptUsed("pw", for: file.path)
 95        #expect(session.archive(from: (file.path, child)) == "Archived to a.org_archive")
 96        #expect(!read(archive).contains("child secret") && read(archive).contains("-----BEGIN PGP MESSAGE-----"))
 97        #expect(session.save())
 98        #expect(!disk.contains("child secret") && !disk.contains("parent text"))
 99    }
100
101    // 3b
102    @Test func encryptedFilesArchiveToEncryptedFilesAndRefileOnlyThere() throws {
103        let path = notes.url.appendingPathComponent("diary.org.gpg")
104        try OpenPGP.encryptedMessage(Data("* Monday\nDear diary.\n* Tuesday\nMore.\n".utf8), passphrase: "pw").write(to: path)
105        session.open(path.path)
106        #expect(session.unlock("pw", for: path.path) == nil)
107        let target = RefileTarget(label: "a.org", path: file.path, start: nil, title: "", level: 0, contentHash: "")
108        #expect(session.refile(to: target, from: (path.path, 0))?.contains("isn't") == true)
109        #expect(!disk.contains("Dear diary"))
110        #expect(session.archive(from: (path.path, 0)) == "Archived to diary_archive.org.gpg")
111        let archive = notes.url.appendingPathComponent("diary_archive.org.gpg")
112        #expect(!FileManager.default.fileExists(atPath: notes.url.appendingPathComponent("diary.org.gpg_archive").path))
113        let bytes = try Data(contentsOf: archive)
114        #expect(bytes.range(of: Data("Dear diary".utf8)) == nil)
115        #expect(String(decoding: try OpenPGP.decryptFile(bytes, passphrase: "pw"), as: UTF8.self).contains("Dear diary."))
116        // Capture into an encrypted file that isn't open writes nothing.
117        session.kill(path.path)
118        let template = CaptureTemplate(key: "d", name: "Diary", target: .file(path.path), template: "* %?")
119        if case .success = session.capture("* Captured secret\n", template: template, root: nil) { Issue.record("captured into a locked file") }
120        #expect(try Data(contentsOf: path).range(of: Data("Captured".utf8)) == nil)
121    }
122
123    // 5
124    @Test func textBelowAMessageIsHeldThenSealedWithIt() throws {
125        let encrypted = try #require(try OrgCrypt.encrypt(Self.file, at: (Self.file as NSString).range(of: "* Bank").location, passphrase: "pw"))
126        try notes.write("a.org", encrypted)
127        session.open(file.path)
128        try type("typed below\n", at: offset(of: "* Last"))
129        #expect(!session.save())
130        #expect(session.held[file.path] == .entries(1))
131        #expect(!disk.contains("typed below"))
132        #expect(session.unlock("pw", for: file.path) == nil)
133        #expect(!disk.contains("typed below"))
134        let bank = (disk as NSString).range(of: "* Bank").location
135        #expect(try OrgCrypt.decrypt(disk, at: bank, passphrase: "pw").plaintext == Self.secret + "\ntyped below\n")
136    }
137
138    // 7
139    @Test func exportsLeaveOutWhatIsEncryptedOnDisk() throws {
140        session.open(file.path)
141        session.cryptUsed("pw", for: file.path)
142        try replace(with: Self.file)
143        #expect(session.save())
144        #expect(session.exportLeavesOut(file.path))
145        #expect(session.exportText(of: file.path) == disk)
146        #expect(session.exportText(of: file.path)?.contains(Self.secret) == false)
147        let gpg = notes.url.appendingPathComponent("d.org.gpg")
148        try OpenPGP.encryptedMessage(Data("* D\nsecret\n".utf8), passphrase: "pw").write(to: gpg)
149        session.open(gpg.path)
150        #expect(session.unlock("pw", for: gpg.path) == nil)
151        #expect(session.exportText(of: gpg.path) == nil && session.exportLeavesOut(gpg.path))
152        // Nor is either copied for Emacs.
153        #expect(session.refusesEmacsCopy(gpg.path) != nil && session.refusesEmacsCopy(file.path) != nil)
154        let plain = try notes.write("c.org", "* C\n")
155        session.open(plain.path)
156        #expect(session.exportText(of: plain.path) == "* C\n" && session.refusesEmacsCopy(plain.path) == nil)
157    }
158
159    // 8
160    @Test func clockingInDoesntKeepEncryptedTitles() throws {
161        let text = "* Bank :crypt:\nintro\n** Secret task\nbody\n* Open task\n"
162        try notes.write("a.org", text)
163        session.open(file.path)
164        session.cryptUsed("pw", for: file.path)
165        let clock = ClockModel(file: notes.url.appendingPathComponent("clock.json"))
166        _ = clock.clockIn(session, path: file.path, at: (text as NSString).range(of: "** Secret").location)
167        #expect(clock.running?.heading == "Encrypted entry")
168        #expect(clock.history.allSatisfy { $0.title != "Secret task" })
169        #expect(!read(notes.url.appendingPathComponent("clock.json")).contains("Secret task"))
170        #expect(session.shareableTitle("Bank", path: file.path, heading: 0) == "Bank")
171        #expect(session.shareableTitle("Monday", path: "/x/d.org.gpg", heading: 0) == "Encrypted entry")
172        _ = clock.clockOut(session)
173        #expect(session.save())
174        #expect(!disk.contains("Secret task") && !disk.contains("intro"))
175    }
176
177    // Second review, 2
178    @Test func clockHistoryKeepsNoEncryptedTitle() throws {
179        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"
180        try notes.write("a.org", text)
181        session.open(file.path)
182        session.cryptUsed("pw", for: file.path)
183        let clockFile = notes.url.appendingPathComponent("clock.json")
184        let clock = ClockModel(file: clockFile)
185        _ = clock.clockIn(session, path: file.path, at: (text as NSString).range(of: "** Secret").location)
186        _ = clock.clockIn(session, path: file.path, at: (session.document!.text as NSString).range(of: "** Hidden").location)
187        _ = clock.clockIn(session, path: file.path, at: (session.document!.text as NSString).range(of: "* Open").location)
188        #expect(!read(clockFile).contains("Secret task") && !read(clockFile).contains("Hidden no id"))
189        #expect(clock.history.map(\.title) == ["Open task", "Encrypted entry", "Encrypted entry"])
190    }
191
192    // Second review, 3
193    @Test func eachFileHasItsOwnAuthentication() throws {
194        let a = CryptPassphrases.context(for: "/x/a.org"), b = CryptPassphrases.context(for: "/x/b.org")
195        #expect(a !== b && CryptPassphrases.context(for: "/x/a.org") === a)
196        #expect(a.touchIDAuthenticationAllowableReuseDuration == 0)
197        CryptPassphrases.endSession(for: "/x/a.org")
198        #expect(CryptPassphrases.context(for: "/x/a.org") !== a)
199    }
200
201    // Second review, 4a
202    @Test func anEntryThePassphraseCantEncryptHoldsTheFile() throws {
203        let text = "* A :crypt:\na secret\n* B :crypt:\nb secret\n* End\n"
204        var both = try #require(try OrgCrypt.encrypt(text, at: 0, passphrase: "one"))
205        both = try #require(try OrgCrypt.encrypt(both, at: (both as NSString).range(of: "* B").location, passphrase: "two"))
206        try notes.write("a.org", both)
207        session.open(file.path)
208        #expect(session.unlock("one", for: file.path) == nil)
209        try type("typed below b\n", at: offset(of: "* End"))
210        #expect(!session.save())
211        guard case .blocked(let reason)? = session.held[file.path] else { Issue.record("\(String(describing: session.held[file.path]))"); return }
212        #expect(reason.contains("public key") && session.lastError == nil)
213        #expect(OrgCrypt.Failure("x").localizedDescription == "x")
214        #expect(!disk.contains("typed below b"))
215    }
216
217    // Second review, 4b
218    @Test func plaintextEntriesOnDiskHoldTheFileUntilThePassphrase() throws {
219        session.open(file.path)
220        try type("x", at: 0)
221        // Written elsewhere, with no file event.
222        try notes.write("a.org", "* Plain\nOpen text.\n* Last\n* Theirs :crypt:\ntheir secret\n")
223        #expect(!session.save())
224        #expect(session.held[file.path] == .entries(1) && session.lastError == nil)
225        #expect(session.unlock("pw", for: file.path) == nil)
226        #expect(!session.isDirty && !disk.contains("their secret") && session.document?.text.contains("their secret") == true)
227        #expect(recoveryFiles.allSatisfy { !$0.contains("their secret") })
228    }
229
230    // Second review, 6
231    @Test func anEncryptedFileSavesWithOneKey() throws {
232        let path = notes.url.appendingPathComponent("d.org.gpg")
233        try OpenPGP.encryptedMessage(Data("* D\nbody\n".utf8), passphrase: "pw").write(to: path)
234        session.open(path.path)
235        #expect(session.unlock("pw", for: path.path) == nil)
236        try type("x", at: 0)
237        #expect(session.save())
238        let clock = ContinuousClock()
239        var took: [Duration] = []
240        for n in 0..<3 {
241            try type("\(n)", at: 0)
242            took.append(clock.measure { _ = session.save() })
243        }
244        print("Autosave of an .org.gpg file: \(took)")
245        #expect(try OpenPGP.decryptFile(Data(contentsOf: path), passphrase: "pw") == Data("210x* D\nbody\n".utf8))
246    }
247
248    // 9
249    @Test func unchangedEntriesKeepTheirMessageAcrossSaves() throws {
250        session.open(file.path)
251        session.cryptUsed("pw", for: file.path)
252        try replace(with: Self.file)
253        #expect(session.save())
254        let message = try #require(OrgCrypt.firstMessage(disk))
255        for n in 0..<5 {
256            try type("\(n)", at: 0)
257            #expect(session.save())
258            #expect(disk.contains(message))
259        }
260        #expect(session.crypt.revealedMessages(for: file.path).count == 1)
261    }
262
263    // 10
264    @Test func entriesEncryptedToAPublicKeyDontBlockThePassphrase() throws {
265        // A public-key session packet (tag 1) where a message's packets start.
266        let publicKey = OpenPGP.armor(Data([0xC1, 0x02, 0x03, 0x00]))
267        try notes.write("a.org", "* Pub :crypt:\n" + publicKey + "* Plain\n")
268        session.open(file.path)
269        try type("* New :crypt:\nnew secret\n", at: (session.document!.text as NSString).length)
270        #expect(!session.save())
271        #expect(session.unlock("pw", for: file.path) == nil)
272        #expect(!disk.contains("new secret"))
273        #expect(disk.contains(publicKey))
274    }
275
276    // 6
277    @Test func keychainItemsAreThisDeviceOnlyAfterUserPresence() throws {
278        let item = try #require(CryptPassphrases.newItem("pw", for: "/x/a.org"))
279        #expect(item[kSecAttrAccessControl as String] != nil)
280        #expect(item[kSecUseDataProtectionKeychain as String] as? Bool == true)
281        #expect(item[kSecAttrService as String] as? String == "sh.krz.orgstar.crypt.v2")
282        #expect(item[kSecAttrAccessible as String] == nil)
283    }
284}
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