Sources/OrgDocument/Crypt.swift
344 lines · 15480 bytes
1import Foundation
2import OrgCore
3
4/// Why a file can't be written: what it would put on disk unencrypted.
5public enum CryptHold: Error, Equatable, Sendable {
6 /// This many crypt-tagged entries with text aren't encrypted, and their passphrase isn't known.
7 case entries(Int)
8 /// An encrypted file (`.org.gpg`) whose passphrase isn't known.
9 case file
10 /// Saving failed for a reason a passphrase can't fix, said here: an entry with text below
11 /// a message that the file's passphrase doesn't open.
12 case blocked(String)
13}
14
15/// Why an encrypted file can't be read.
16public enum CryptReadError: Error, Equatable, Sendable {
17 /// Its passphrase isn't known.
18 case locked
19 case wrongPassphrase
20 case failed(String)
21}
22
23/// What the session knows about encrypted text, by file: the passphrases unlocked while the
24/// file is open, and for entries org-crypt encrypts on save (`org-crypt-use-before-save-magic`)
25/// the messages and the text each holds. Through `CryptFileSystem`, buffers keep the
26/// decrypted text while the file holds messages.
27public final class CryptVault: @unchecked Sendable {
28 private let lock = NSLock()
29 private var entries = false
30 private var entryTag = "crypt"
31 private var passphrases: [String: String] = [:]
32 /// By file: messages for entry texts by checksum, to give an unchanged entry its message again.
33 private var reuse: [String: [String: String]] = [:]
34 /// By file: the text of each message this session wrote, to read the file back as the buffer has it.
35 private var revealed: [String: [String: String]] = [:]
36 /// By file: whether the encrypted file was armored when read.
37 private var armored: [String: Bool] = [:]
38 /// Files that seal tagged entries until they close, whatever the setting says now: those
39 /// it was on for, so that turning it off never writes what was encrypted in plaintext.
40 private var sealing: Set<String> = []
41 /// Files open in a buffer. Only they keep what the vault knows past a write.
42 private var open: Set<String> = []
43 /// By file: the bytes the last write replaced and the bytes it wrote, as on disk.
44 private var replacedBytes: [String: (replaced: [UInt8], written: [UInt8])] = [:]
45
46 /// The bytes the last write to `path` replaced and the bytes it wrote, as on disk; given once.
47 public func takeReplaced(for path: String) -> (replaced: [UInt8], written: [UInt8])? {
48 let key = Self.key(path)
49 return locked { replacedBytes.removeValue(forKey: key) }
50 }
51
52 func noteReplaced(_ bytes: [UInt8]?, written: [UInt8], for path: String) {
53 let key = Self.key(path)
54 locked { replacedBytes[key] = bytes.map { ($0, written) } }
55 }
56
57 /// By encrypted file: its bytes on disk and their text, last read or written.
58 private var lastFile: [String: (encrypted: [UInt8], plain: [UInt8])] = [:]
59
60 public init() {}
61
62 private func locked<T>(_ body: () throws -> T) rethrows -> T {
63 lock.lock()
64 defer { lock.unlock() }
65 return try body()
66 }
67
68 private static func key(_ path: String) -> String { URL(fileURLWithPath: path).standardizedFileURL.path }
69
70 /// Whether `path` is a whole encrypted file, as EasyPG's `epa-file` opens `.gpg` files.
71 public static func isEncryptedFile(_ path: String) -> Bool { path.hasSuffix(".gpg") }
72
73 /// `org-crypt-use-before-save-magic`.
74 public var encryptsTaggedEntries: Bool {
75 get { locked { entries } }
76 set { locked { entries = newValue } }
77 }
78
79 /// `org-crypt-tag-matcher`.
80 public var tag: String {
81 get { locked { entryTag } }
82 set { locked { entryTag = newValue } }
83 }
84
85 public func passphrase(for path: String) -> String? {
86 locked { passphrases[Self.key(path)] }
87 }
88
89 /// Whether saving `key` seals its tagged entries: the setting is on, or was while the
90 /// file was open. Call with the lock held.
91 private func seals(_ key: String) -> Bool {
92 if entries, open.contains(key) { sealing.insert(key) }
93 return entries || sealing.contains(key) || !(revealed[key]?.isEmpty ?? true)
94 }
95
96 /// Whether saving `path` encrypts its tagged entries.
97 public func sealsEntries(for path: String) -> Bool {
98 let key = Self.key(path)
99 return locked { seals(key) }
100 }
101
102 /// `passphrase` encrypts and decrypts `path` until it's forgotten. Messages kept for reuse
103 /// under another passphrase are dropped; those recorded before any passphrase was known
104 /// were opened with this one and are kept.
105 public func unlock(_ passphrase: String, for path: String) {
106 let key = Self.key(path)
107 locked {
108 if let known = passphrases[key], known != passphrase {
109 reuse[key] = nil
110 lastFile[key] = nil
111 }
112 passphrases[key] = passphrase
113 _ = seals(key)
114 }
115 }
116
117 /// Drops the passphrase of `path`; the next save that needs it is held.
118 public func forgetPassphrase(for path: String) {
119 let key = Self.key(path)
120 locked {
121 passphrases[key] = nil
122 reuse[key] = nil
123 }
124 }
125
126 private func dropIfClosed(_ key: String) {
127 locked {
128 guard !open.contains(key) else { return }
129 passphrases[key] = nil
130 reuse[key] = nil
131 revealed[key] = nil
132 armored[key] = nil
133 lastFile[key] = nil
134 sealing.remove(key)
135 }
136 }
137
138 /// Whether the vault keeps anything for `path`.
139 public func keepsAnything(for path: String) -> Bool {
140 let key = Self.key(path)
141 return locked { passphrases[key] != nil || !(revealed[key]?.isEmpty ?? true) || !(reuse[key]?.isEmpty ?? true) || lastFile[key] != nil || sealing.contains(key) }
142 }
143
144 /// `path` is open in a buffer.
145 public func opened(_ path: String) {
146 let key = Self.key(path)
147 locked { _ = open.insert(key) }
148 }
149
150 /// Drops everything kept for `path`, as when its buffer closes.
151 public func close(_ path: String) {
152 let key = Self.key(path)
153 locked {
154 open.remove(key)
155 passphrases[key] = nil
156 reuse[key] = nil
157 revealed[key] = nil
158 armored[key] = nil
159 sealing.remove(key)
160 lastFile[key] = nil
161 }
162 }
163
164 /// The entry of `path` holding `plaintext` was decrypted from `message`: while it stays
165 /// so, saving writes `message` back unchanged.
166 public func remember(message: String, plaintext: String, for path: String) {
167 let key = Self.key(path)
168 locked {
169 reuse[key, default: [:]][OrgCrypt.checksum(plaintext)] = message
170 _ = seals(key)
171 }
172 }
173
174 /// What keeps `text`, the buffer of `path`, from being written: tagged entries without a
175 /// known passphrase, or an encrypted file without one. Nil when it can be written.
176 public func hold(_ text: String, for path: String) -> CryptHold? {
177 let key = Self.key(path)
178 let (passphrase, entries, tag) = locked { (passphrases[key], seals(key), entryTag) }
179 guard passphrase == nil else { return nil }
180 if Self.isEncryptedFile(path) { return .file }
181 guard entries else { return nil }
182 let count = OrgCrypt.unencrypted(text, tag: tag).count
183 return count > 0 ? .entries(count) : nil
184 }
185
186 /// Whether `text`, the buffer of `path`, holds anything that isn't on disk as it shows:
187 /// an encrypted file, or entries decrypted that saving encrypts. Such a buffer is left out
188 /// of what other views read and keep (`DocumentSession.openTexts`).
189 public func isPrivate(_ text: String, for path: String) -> Bool {
190 if Self.isEncryptedFile(path) { return true }
191 let key = Self.key(path)
192 let (entries, tag, revealing) = locked { (seals(key), entryTag, !(revealed[key]?.isEmpty ?? true)) }
193 return revealing || (entries && !OrgCrypt.unencrypted(text, tag: tag).isEmpty)
194 }
195
196 // MARK: - Reading and writing
197
198 /// The text of messages this session wrote for `path`.
199 public func revealedMessages(for path: String) -> [String: String] {
200 locked { revealed[Self.key(path)] ?? [:] }
201 }
202
203 /// `bytes` from disk as the buffer of `path` has them: the file decrypted, and the
204 /// messages this session wrote (`messages`, by default those known now) back to their text.
205 public func plain(_ bytes: [UInt8], for path: String, messages: [String: String]? = nil) throws -> [UInt8] {
206 var bytes = bytes
207 if Self.isEncryptedFile(path) { bytes = try decryptFile(bytes, for: path) }
208 let known = messages ?? revealedMessages(for: path)
209 guard !known.isEmpty, var text = Self.text(bytes), text.contains("-----BEGIN PGP MESSAGE-----") else { return bytes }
210 for (message, plaintext) in known where text.contains(message) {
211 text = text.replacingOccurrences(of: message, with: plaintext)
212 }
213 return Array(text.utf8)
214 }
215
216 /// `bytes`, the buffer of `path`, as the file holds them: tagged entries encrypted, then
217 /// the file encrypted, and the messages written for entries. Throws `CryptHold` when a
218 /// passphrase is needed and not known.
219 public func cipher(_ bytes: [UInt8], for path: String) throws -> (bytes: [UInt8], messages: [(message: String, plaintext: String)], plain: [UInt8]?) {
220 let key = Self.key(path)
221 let (passphrase, entries, tag, known) = locked { (passphrases[key], seals(key), entryTag, reuse[key] ?? [:]) }
222 var bytes = bytes
223 var messages: [(String, String)] = []
224 if entries, let text = Self.text(bytes), text.contains(tag) {
225 if let passphrase {
226 let sealed = try OrgCrypt.seal(text, passphrase: passphrase, tag: tag, reuse: { known[$0] })
227 bytes = Array(sealed.text.utf8)
228 messages = sealed.messages
229 } else {
230 let count = OrgCrypt.unencrypted(text, tag: tag).count
231 if count > 0 { throw CryptHold.entries(count) }
232 }
233 }
234 if Self.isEncryptedFile(path) {
235 guard let passphrase else { throw CryptHold.file }
236 let plain = bytes
237 // The text the file holds already (a snapshot of it) is its bytes on disk, without
238 // another key's 65 MB of hashing.
239 if let last = locked({ lastFile[key] }), last.plain == plain { return (last.encrypted, messages, plain) }
240 let message = try OpenPGP.encryptedMessage(Data(bytes), passphrase: passphrase)
241 bytes = locked { armored[key] ?? false } ? Array(OpenPGP.armor(message).utf8) : [UInt8](message)
242 return (bytes, messages, plain)
243 }
244 return (bytes, messages, nil)
245 }
246
247 /// `cipher`'s result was written to `path`: reading it back gives the messages' text, and
248 /// an unchanged entry keeps its message at the next save. Messages no longer in the file
249 /// are forgotten.
250 public func didWrite(_ written: (bytes: [UInt8], messages: [(message: String, plaintext: String)], plain: [UInt8]?), to path: String) {
251 let key = Self.key(path)
252 locked {
253 // A file that isn't open keeps nothing (passphrase, messages, text) once the
254 // write's own reads are done.
255 if !open.contains(key) {
256 DispatchQueue.main.async { [weak self] in self?.dropIfClosed(key) }
257 }
258 revealed[key] = Dictionary(written.messages.map { ($0.message, $0.plaintext) }, uniquingKeysWith: { a, _ in a })
259 reuse[key] = Dictionary(written.messages.map { (OrgCrypt.checksum($0.plaintext), $0.message) }, uniquingKeysWith: { a, _ in a })
260 if let plain = written.plain { lastFile[key] = (written.bytes, plain) }
261 }
262 }
263
264 /// Whether `passphrase` opens the encrypted file `bytes`; an empty file takes any.
265 public static func opens(_ bytes: [UInt8], passphrase: String) -> Bool {
266 bytes.isEmpty || (try? OpenPGP.decryptFile(Data(bytes), passphrase: passphrase)) != nil
267 }
268
269 private func decryptFile(_ bytes: [UInt8], for path: String) throws -> [UInt8] {
270 // New File makes an empty file: it has no passphrase until it's first saved.
271 guard !bytes.isEmpty else { return [] }
272 let key = Self.key(path)
273 guard let passphrase = locked({ passphrases[key] }) else { throw CryptReadError.locked }
274 // Saving reads the file two or three times; each key costs 65 MB of hashing.
275 if let last = locked({ lastFile[key] }), last.encrypted == bytes { return last.plain }
276 let data = Data(bytes)
277 do {
278 let plain = [UInt8](try OpenPGP.decryptFile(data, passphrase: passphrase))
279 locked {
280 armored[key] = OpenPGP.isArmored(data)
281 lastFile[key] = (bytes, plain)
282 }
283 return plain
284 } catch let failure as OpenPGP.Failure {
285 throw failure == OpenPGP.wrongPassphrase ? CryptReadError.wrongPassphrase : CryptReadError.failed(failure.description)
286 }
287 }
288
289 /// `bytes` as text when they are UTF-8 exactly, a BOM included.
290 private static func text(_ bytes: [UInt8]) -> String? {
291 let text = String(decoding: bytes, as: UTF8.self)
292 return text.utf8.elementsEqual(bytes) ? text : nil
293 }
294}
295
296/// Files read and written through a `CryptVault`: what the buffer holds decrypted goes to
297/// disk encrypted, and comes back as the buffer has it.
298public struct CryptFileSystem: FileSystem {
299 public let base: FileSystem
300 public let vault: CryptVault
301
302 public init(base: FileSystem, vault: CryptVault) {
303 self.base = base
304 self.vault = vault
305 }
306
307 public func read(_ url: URL) throws -> [UInt8]? {
308 try base.read(url).map { try vault.plain($0, for: url.path) }
309 }
310
311 public func replace(_ url: URL, with bytes: [UInt8]) throws -> [UInt8]? {
312 let known = vault.revealedMessages(for: url.path)
313 let written = try vault.cipher(bytes, for: url.path)
314 let replaced = try base.replace(url, with: written.bytes)
315 vault.noteReplaced(replaced, written: written.bytes, for: url.path)
316 // The version replaced, as it read before this write's messages were known (and while
317 // the encrypted file's last bytes still decrypt from memory).
318 let previous = replaced.map { (try? vault.plain($0, for: url.path, messages: known)) ?? $0 }
319 vault.didWrite(written, to: url.path)
320 return previous
321 }
322}
323
324/// Recovery versions and snapshots through a `CryptVault`: kept encrypted as the file is. When
325/// that needs a passphrase that isn't known, `keep` throws `CryptHold`, so a caller that
326/// promises a copy stops; a snapshot is skipped.
327public struct CryptRecoveryStore: RecoveryStore {
328 public let base: RecoveryStore
329 public let vault: CryptVault
330
331 public init(base: RecoveryStore, vault: CryptVault) {
332 self.base = base
333 self.vault = vault
334 }
335
336 public func keep(_ bytes: [UInt8], for url: URL, label: String) throws {
337 try base.keep(try vault.cipher(bytes, for: url.path).bytes, for: url, label: label)
338 }
339
340 public func keepSnapshot(_ bytes: [UInt8], for url: URL) throws {
341 guard let encrypted = try? vault.cipher(bytes, for: url.path).bytes else { return }
342 try base.keepSnapshot(encrypted, for: url)
343 }
344}