Sources/OrgDocument/Crypt.swift

34f0b480a611c3278a48821f0233ba97462b13d1
orgstar/Sources/OrgDocument/Crypt.swift

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