Sources/OrgDocument/Crypt.swift

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