Sources/OrgDocument/Crypt.swift

8f2ce3e9aea5e545a257dab3e7600f258daab10b
orgstar/Sources/OrgDocument/Crypt.swift

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