Sources/OrgDocument/Crypt.swift

9945f06859a5feee9b6af3496e944cb6b395715b
orgstar/Sources/OrgDocument/Crypt.swift

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