Tests/OrgAppTests/CryptReviewTests.swift
213 lines · 10389 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 // 9
178 @Test func unchangedEntriesKeepTheirMessageAcrossSaves() throws {
179 session.open(file.path)
180 session.cryptUsed("pw", for: file.path)
181 try replace(with: Self.file)
182 #expect(session.save())
183 let message = try #require(OrgCrypt.firstMessage(disk))
184 for n in 0..<5 {
185 try type("\(n)", at: 0)
186 #expect(session.save())
187 #expect(disk.contains(message))
188 }
189 #expect(session.crypt.revealedMessages(for: file.path).count == 1)
190 }
191
192 // 10
193 @Test func entriesEncryptedToAPublicKeyDontBlockThePassphrase() throws {
194 // A public-key session packet (tag 1) where a message's packets start.
195 let publicKey = OpenPGP.armor(Data([0xC1, 0x02, 0x03, 0x00]))
196 try notes.write("a.org", "* Pub :crypt:\n" + publicKey + "* Plain\n")
197 session.open(file.path)
198 try type("* New :crypt:\nnew secret\n", at: (session.document!.text as NSString).length)
199 #expect(!session.save())
200 #expect(session.unlock("pw", for: file.path) == nil)
201 #expect(!disk.contains("new secret"))
202 #expect(disk.contains(publicKey))
203 }
204
205 // 6
206 @Test func keychainItemsAreThisDeviceOnlyAfterUserPresence() throws {
207 let item = try #require(CryptPassphrases.newItem("pw", for: "/x/a.org"))
208 #expect(item[kSecAttrAccessControl as String] != nil)
209 #expect(item[kSecUseDataProtectionKeychain as String] as? Bool == true)
210 #expect(item[kSecAttrService as String] as? String == "sh.krz.orgstar.crypt.v2")
211 #expect(item[kSecAttrAccessible as String] == nil)
212 }
213}