Sources/OrgDocument/Crypt.swift
257 lines · 11150 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}
11
12/// Why an encrypted file can't be read.
13public enum CryptReadError: Error, Equatable, Sendable {
14 /// Its passphrase isn't known.
15 case locked
16 case wrongPassphrase
17 case failed(String)
18}
19
20/// What the session knows about encrypted text, by file: the passphrases unlocked while the
21/// file is open, and for entries org-crypt encrypts on save (`org-crypt-use-before-save-magic`)
22/// the messages and the text each holds. Through `CryptFileSystem`, buffers keep the
23/// decrypted text while the file holds messages.
24public final class CryptVault: @unchecked Sendable {
25 private let lock = NSLock()
26 private var entries = false
27 private var entryTag = "crypt"
28 private var passphrases: [String: String] = [:]
29 /// By file: messages for entry texts by checksum, to give an unchanged entry its message again.
30 private var reuse: [String: [String: String]] = [:]
31 /// By file: the text of each message this session wrote, to read the file back as the buffer has it.
32 private var revealed: [String: [String: String]] = [:]
33 /// By file: whether the encrypted file was armored when read.
34 private var armored: [String: Bool] = [:]
35 private var onWrite: ((String) -> Void)?
36
37 public init() {}
38
39 private func locked<T>(_ body: () throws -> T) rethrows -> T {
40 lock.lock()
41 defer { lock.unlock() }
42 return try body()
43 }
44
45 private static func key(_ path: String) -> String { URL(fileURLWithPath: path).standardizedFileURL.path }
46
47 /// Whether `path` is a whole encrypted file, as EasyPG's `epa-file` opens `.gpg` files.
48 public static func isEncryptedFile(_ path: String) -> Bool { path.hasSuffix(".gpg") }
49
50 /// `org-crypt-use-before-save-magic`.
51 public var encryptsTaggedEntries: Bool {
52 get { locked { entries } }
53 set { locked { entries = newValue } }
54 }
55
56 /// `org-crypt-tag-matcher`.
57 public var tag: String {
58 get { locked { entryTag } }
59 set { locked { entryTag = newValue } }
60 }
61
62 /// Called with a file's path each time it was written.
63 public var written: ((String) -> Void)? {
64 get { locked { onWrite } }
65 set { locked { onWrite = newValue } }
66 }
67
68 public func passphrase(for path: String) -> String? {
69 locked { passphrases[Self.key(path)] }
70 }
71
72 /// `passphrase` encrypts and decrypts `path` until it's forgotten. Messages kept for reuse
73 /// under another passphrase are dropped.
74 public func unlock(_ passphrase: String, for path: String) {
75 let key = Self.key(path)
76 locked {
77 if passphrases[key] != passphrase { reuse[key] = nil }
78 passphrases[key] = passphrase
79 }
80 }
81
82 /// Drops the passphrase of `path`; the next save that needs it is held.
83 public func forgetPassphrase(for path: String) {
84 let key = Self.key(path)
85 locked {
86 passphrases[key] = nil
87 reuse[key] = nil
88 }
89 }
90
91 /// Drops everything kept for `path`, as when its buffer closes.
92 public func close(_ path: String) {
93 let key = Self.key(path)
94 locked {
95 passphrases[key] = nil
96 reuse[key] = nil
97 revealed[key] = nil
98 armored[key] = nil
99 }
100 }
101
102 /// The entry of `path` holding `plaintext` was decrypted from `message`: while it stays
103 /// so, saving writes `message` back unchanged.
104 public func remember(message: String, plaintext: String, for path: String) {
105 let key = Self.key(path)
106 locked { reuse[key, default: [:]][OrgCrypt.checksum(plaintext)] = message }
107 }
108
109 /// What keeps `text`, the buffer of `path`, from being written: tagged entries without a
110 /// known passphrase, or an encrypted file without one. Nil when it can be written.
111 public func hold(_ text: String, for path: String) -> CryptHold? {
112 let (passphrase, entries, tag) = locked { (passphrases[Self.key(path)], self.entries, entryTag) }
113 guard passphrase == nil else { return nil }
114 if Self.isEncryptedFile(path) { return .file }
115 guard entries else { return nil }
116 let count = OrgCrypt.unencrypted(text, tag: tag).count
117 return count > 0 ? .entries(count) : nil
118 }
119
120 /// Whether `text`, the buffer of `path`, holds anything that isn't on disk as it shows:
121 /// an encrypted file, or entries decrypted that saving encrypts. Such a buffer is left out
122 /// of what other views read and keep (`DocumentSession.openTexts`).
123 public func isPrivate(_ text: String, for path: String) -> Bool {
124 if Self.isEncryptedFile(path) { return true }
125 let (entries, tag) = locked { (self.entries, entryTag) }
126 return entries && !OrgCrypt.unencrypted(text, tag: tag).isEmpty
127 }
128
129 // MARK: - Reading and writing
130
131 /// The text of messages this session wrote for `path`.
132 public func revealedMessages(for path: String) -> [String: String] {
133 locked { revealed[Self.key(path)] ?? [:] }
134 }
135
136 /// `bytes` from disk as the buffer of `path` has them: the file decrypted, and the
137 /// messages this session wrote (`messages`, by default those known now) back to their text.
138 public func plain(_ bytes: [UInt8], for path: String, messages: [String: String]? = nil) throws -> [UInt8] {
139 var bytes = bytes
140 if Self.isEncryptedFile(path) { bytes = try decryptFile(bytes, for: path) }
141 let known = messages ?? revealedMessages(for: path)
142 guard !known.isEmpty, var text = Self.text(bytes), text.contains("-----BEGIN PGP MESSAGE-----") else { return bytes }
143 for (message, plaintext) in known where text.contains(message) {
144 text = text.replacingOccurrences(of: message, with: plaintext)
145 }
146 return Array(text.utf8)
147 }
148
149 /// `bytes`, the buffer of `path`, as the file holds them: tagged entries encrypted, then
150 /// the file encrypted, and the messages written for entries. Throws `CryptHold` when a
151 /// passphrase is needed and not known.
152 public func cipher(_ bytes: [UInt8], for path: String) throws -> (bytes: [UInt8], messages: [(message: String, plaintext: String)]) {
153 let key = Self.key(path)
154 let (passphrase, entries, tag, known) = locked { (passphrases[key], self.entries, entryTag, reuse[key] ?? [:]) }
155 var bytes = bytes
156 var messages: [(String, String)] = []
157 if entries, let text = Self.text(bytes), text.contains(tag) {
158 if let passphrase {
159 let sealed = try OrgCrypt.seal(text, passphrase: passphrase, tag: tag, reuse: { known[$0] })
160 bytes = Array(sealed.text.utf8)
161 messages = sealed.messages
162 } else {
163 let count = OrgCrypt.unencrypted(text, tag: tag).count
164 if count > 0 { throw CryptHold.entries(count) }
165 }
166 }
167 if Self.isEncryptedFile(path) {
168 guard let passphrase else { throw CryptHold.file }
169 let message = try OpenPGP.encryptedMessage(Data(bytes), passphrase: passphrase)
170 bytes = locked { armored[key] ?? false } ? Array(OpenPGP.armor(message).utf8) : [UInt8](message)
171 }
172 return (bytes, messages)
173 }
174
175 /// The messages in a file `cipher` gave were written: reading it back gives their text.
176 public func didWrite(_ messages: [(message: String, plaintext: String)], to path: String) {
177 let key = Self.key(path)
178 let callback = locked {
179 for (message, plaintext) in messages { revealed[key, default: [:]][message] = plaintext }
180 return onWrite
181 }
182 callback?(path)
183 }
184
185 /// Whether `passphrase` opens the encrypted file `bytes`; an empty file takes any.
186 public static func opens(_ bytes: [UInt8], passphrase: String) -> Bool {
187 bytes.isEmpty || (try? OpenPGP.decryptFile(Data(bytes), passphrase: passphrase)) != nil
188 }
189
190 private func decryptFile(_ bytes: [UInt8], for path: String) throws -> [UInt8] {
191 // New File makes an empty file: it has no passphrase until it's first saved.
192 guard !bytes.isEmpty else { return [] }
193 let key = Self.key(path)
194 guard let passphrase = locked({ passphrases[key] }) else { throw CryptReadError.locked }
195 let data = Data(bytes)
196 do {
197 let plain = try OpenPGP.decryptFile(data, passphrase: passphrase)
198 locked { armored[key] = OpenPGP.isArmored(data) }
199 return [UInt8](plain)
200 } catch let failure as OpenPGP.Failure {
201 throw failure == OpenPGP.wrongPassphrase ? CryptReadError.wrongPassphrase : CryptReadError.failed(failure.description)
202 }
203 }
204
205 /// `bytes` as text when they are UTF-8 exactly, a BOM included.
206 private static func text(_ bytes: [UInt8]) -> String? {
207 let text = String(decoding: bytes, as: UTF8.self)
208 return text.utf8.elementsEqual(bytes) ? text : nil
209 }
210}
211
212/// Files read and written through a `CryptVault`: what the buffer holds decrypted goes to
213/// disk encrypted, and comes back as the buffer has it.
214public struct CryptFileSystem: FileSystem {
215 public let base: FileSystem
216 public let vault: CryptVault
217
218 public init(base: FileSystem, vault: CryptVault) {
219 self.base = base
220 self.vault = vault
221 }
222
223 public func read(_ url: URL) throws -> [UInt8]? {
224 try base.read(url).map { try vault.plain($0, for: url.path) }
225 }
226
227 public func replace(_ url: URL, with bytes: [UInt8]) throws -> [UInt8]? {
228 let known = vault.revealedMessages(for: url.path)
229 let (encrypted, messages) = try vault.cipher(bytes, for: url.path)
230 let replaced = try base.replace(url, with: encrypted)
231 vault.didWrite(messages, to: url.path)
232 // The version replaced, as it read before this write's messages were known.
233 return replaced.map { (try? vault.plain($0, for: url.path, messages: known)) ?? $0 }
234 }
235}
236
237/// Recovery versions and snapshots through a `CryptVault`: kept encrypted as the file is, or
238/// not kept when that needs a passphrase that isn't known.
239public struct CryptRecoveryStore: RecoveryStore {
240 public let base: RecoveryStore
241 public let vault: CryptVault
242
243 public init(base: RecoveryStore, vault: CryptVault) {
244 self.base = base
245 self.vault = vault
246 }
247
248 public func keep(_ bytes: [UInt8], for url: URL, label: String) throws {
249 guard let encrypted = try? vault.cipher(bytes, for: url.path).bytes else { return }
250 try base.keep(encrypted, for: url, label: label)
251 }
252
253 public func keepSnapshot(_ bytes: [UInt8], for url: URL) throws {
254 guard let encrypted = try? vault.cipher(bytes, for: url.path).bytes else { return }
255 try base.keepSnapshot(encrypted, for: url)
256 }
257}