Tests/OrgCoreTests/CryptFileTests.swift

m5-crypt
orgstar/Tests/OrgCoreTests/CryptFileTests.swift

163 lines · 10492 bytes

  1import Foundation
  2import Testing
  3@testable import OrgCore
  4
  5/// Encrypting tagged entries on save (`OrgCrypt.seal`) and whole encrypted files, against
  6/// gpg and Emacs's EasyPG.
  7struct CryptFileTests {
  8    static var oracle: Bool { ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil }
  9    static var gpg: Bool { OpenPGPTests.gpg != nil }
 10    static var emacs: Bool { gpg && oracle && EmacsOracle.isAvailable }
 11
 12    @Test func sealEncryptsTaggedEntriesFromTheTop() throws {
 13        let (sealed, messages) = try OrgCrypt.seal(OrgCryptTests.file, passphrase: "pw")
 14        // Bank's tagged child goes inside Bank's message; the empty entry gets one too.
 15        #expect(messages.map(\.plaintext) == ["Account 12345, ünïcödé.\n** Child\nChild text.\n", "Dear diary.\n", ""])
 16        let (all, count) = try OrgCrypt.encryptAll(OrgCryptTests.file, passphrase: "pw")
 17        #expect(count == 3)
 18        #expect(OrgCryptTests.masked(sealed) == OrgCryptTests.masked(all))
 19        for (message, plaintext) in messages {
 20            #expect(sealed.contains(message))
 21            #expect(try String(decoding: OpenPGP.decrypt(OpenPGP.dearmor(message), passphrase: "pw"), as: UTF8.self) == plaintext)
 22        }
 23        // Sealing again changes nothing: every entry is encrypted.
 24        #expect(try OrgCrypt.seal(sealed, passphrase: "pw").text == sealed)
 25        // Entries known by their text get their message back.
 26        let known = Dictionary(uniqueKeysWithValues: messages.map { (OrgCrypt.checksum($0.plaintext), $0.message) })
 27        #expect(try OrgCrypt.seal(OrgCryptTests.file, passphrase: "pw", reuse: { known[$0] }).text == sealed)
 28        // Without the tag, the text is as it was.
 29        #expect(try OrgCrypt.seal("* A\ntext\n", passphrase: "pw").text == "* A\ntext\n")
 30    }
 31
 32    @Test func newMessagesUseGnuPGsIterationCount() throws {
 33        let clock = ContinuousClock()
 34        var message = Data()
 35        let time = try clock.measure { message = try OpenPGP.encryptedMessage(Data("x".utf8), passphrase: "pw") }
 36        let first = try #require(try OpenPGP.packets(message).first)
 37        // Version 4, AES-256, iterated and salted SHA-256, 8 bytes of salt, coded count 0xFF.
 38        #expect(first.tag == 3 && Array(first.body.prefix(4)) == [4, 9, 3, 8] && first.body[12] == 0xFF)
 39        #expect(OpenPGP.isSymmetric(message))
 40        #expect(!OpenPGP.isSymmetric(Data([0xC1, 0x02, 0x03, 0x00])))
 41        let read = try clock.measure { _ = try OpenPGP.decrypt(message, passphrase: "pw") }
 42        print("S2K with coded count 0xFF: encrypt \(time), decrypt \(read)")
 43    }
 44
 45    @Test func textBelowAMessageIsSealedWithIt() throws {
 46        let bank = (OrgCryptTests.file as NSString).range(of: "* TODO Bank").location
 47        let one = try #require(try OrgCrypt.encrypt(OrgCryptTests.file, at: bank, passphrase: "pw"))
 48        let typed = one.replacingOccurrences(of: "\n* Diary", with: "\nTyped below.\n* Diary")
 49        #expect(OrgCrypt.unencrypted(typed).count == 2)
 50        let (sealed, messages) = try OrgCrypt.seal(typed, passphrase: "pw")
 51        #expect(!sealed.contains("Typed below."))
 52        #expect(try OrgCrypt.decrypt(sealed, at: bank, passphrase: "pw").plaintext == "Account 12345, ünïcödé.\n** Child\nChild text.\n\nTyped below.\n")
 53        // What reads back for the message is the text the entry had, message and all.
 54        #expect(messages.first?.plaintext.contains("-----BEGIN PGP MESSAGE-----") == true)
 55        #expect(throws: OrgCrypt.Failure.self) { try OrgCrypt.seal(typed, passphrase: "wrong") }
 56    }
 57
 58    @Test func unencryptedEntriesWithText() throws {
 59        #expect(OrgCrypt.unencrypted(OrgCryptTests.file).count == 2)
 60        let bank = (OrgCryptTests.file as NSString).range(of: "* TODO Bank").location
 61        let one = try #require(try OrgCrypt.encrypt(OrgCryptTests.file, at: bank, passphrase: "pw"))
 62        #expect(OrgCrypt.unencrypted(one).count == 1)
 63        #expect(OrgCrypt.firstMessage(one).map { OrgCrypt.opens($0, passphrase: "pw") } == true)
 64        #expect(OrgCrypt.firstMessage(one).map { OrgCrypt.opens($0, passphrase: "other") } == false)
 65        #expect(OrgCrypt.firstMessage(OrgCryptTests.file) == nil)
 66        #expect(OrgCrypt.unencrypted("* Empty :crypt:\n\n* B\n").isEmpty)
 67        #expect(OrgCrypt.unencrypted("#+FILETAGS: :crypt:\n* A\nsecret\n").count == 1)
 68    }
 69
 70    @Test func encryptedFilesRoundTrip() throws {
 71        let text = Data("* Diary\nDear diary, ünïcödé.\n".utf8)
 72        let binary = try OpenPGP.encryptedMessage(text, passphrase: "pw")
 73        #expect(!OpenPGP.isArmored(binary))
 74        #expect(try OpenPGP.decryptFile(binary, passphrase: "pw") == text)
 75        let armored = Data(try OpenPGP.encrypt(text, passphrase: "pw").utf8)
 76        #expect(OpenPGP.isArmored(armored))
 77        #expect(try OpenPGP.decryptFile(armored, passphrase: "pw") == text)
 78        #expect(throws: OpenPGP.wrongPassphrase) { try OpenPGP.decryptFile(binary, passphrase: "wrong") }
 79        #expect(throws: OpenPGP.Failure.self) { try OpenPGP.decryptFile(Data("* plain text\n".utf8), passphrase: "pw") }
 80    }
 81
 82    @Test(.enabled(if: gpg && oracle))
 83    func gpgReadsAndWritesEncryptedFiles() throws {
 84        let text = Data("* Diary\nDear diary, ünïcödé.\n".utf8)
 85        // `gpg --decrypt` reads orgstar's file, binary as orgstar writes it by default.
 86        let ours = try OpenPGP.encryptedMessage(text, passphrase: "pass phrase")
 87        #expect(try OpenPGPTests.gpg(["--passphrase", "pass phrase", "--decrypt"], input: ours) == text)
 88        // orgstar reads `gpg --symmetric`, binary and armored.
 89        let theirs = try OpenPGPTests.gpg(["--passphrase", "pass phrase", "--symmetric"], input: text)
 90        #expect(!OpenPGP.isArmored(theirs))
 91        #expect(try OpenPGP.decryptFile(theirs, passphrase: "pass phrase") == text)
 92        let armored = try OpenPGPTests.gpg(["--passphrase", "pass phrase", "--symmetric", "--armor"], input: text)
 93        #expect(try OpenPGP.decryptFile(armored, passphrase: "pass phrase") == text)
 94        #expect(throws: OpenPGP.Failure.self) { try OpenPGP.decryptFile(theirs, passphrase: "wrong") }
 95    }
 96
 97    /// Emacs with EasyPG (`epa-file`), symmetric, the passphrase given without asking, run on
 98    /// `file` in a fresh GnuPG home: `form` runs with `file` as the variable `file`.
 99    static func emacs(_ form: String, in folder: URL) throws -> String {
100        let home = "/tmp/ogpg-\(UUID().uuidString.prefix(8))"
101        try FileManager.default.createDirectory(atPath: home, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700])
102        defer {
103            let kill = Process()
104            kill.executableURL = URL(fileURLWithPath: "/usr/bin/env")
105            kill.arguments = ["gpgconf", "--homedir", home, "--kill", "gpg-agent"]
106            try? kill.run()
107            kill.waitUntilExit()
108            try? FileManager.default.removeItem(atPath: home)
109        }
110        let elisp = """
111        (progn
112          (require 'org) (require 'epa-file) (epa-file-enable)
113          (setq epg-pinentry-mode 'loopback epa-pinentry-mode 'loopback epa-file-select-keys 'silent epa-file-encrypt-to nil
114                epg-gpg-program \(OrgCryptTests.lisp(OpenPGPTests.gpg!)) default-directory \(OrgCryptTests.lisp(folder.path + "/")))
115          (cl-letf (((symbol-function 'epa-file-passphrase-callback-function) (lambda (&rest _) (copy-sequence "pw one")))
116                    ((symbol-function 'epa-passphrase-callback-function) (lambda (&rest _) (copy-sequence "pw one"))))
117            \(form)))
118        """
119        return try EmacsOracle.run(["-Q", "--batch", "--eval", elisp], environment: ["GNUPGHOME": home, "TZ": "UTC"])
120    }
121
122    @Test(.enabled(if: emacs))
123    func emacsOpensWhatOrgstarWritesAndTheReverse() throws {
124        let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-gpg-\(UUID().uuidString)")
125        try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
126        defer { try? FileManager.default.removeItem(at: folder) }
127        let text = "* Diary :private:\nDear diary, ünïcödé.\n** Child\nMore.\n"
128        // orgstar's file, binary and armored, opened by `find-file` in Emacs.
129        for (name, data) in [("ours.org.gpg", try OpenPGP.encryptedMessage(Data(text.utf8), passphrase: "pw one")),
130                             ("armored.org.gpg", Data(try OpenPGP.encrypt(Data(text.utf8), passphrase: "pw one").utf8))] {
131            try data.write(to: folder.appendingPathComponent(name))
132            let log = try Self.emacs("""
133                (with-current-buffer (find-file-noselect \(OrgCryptTests.lisp(name)))
134                  (let ((coding-system-for-write 'utf-8-unix)) (write-region (point-min) (point-max) "out.txt")))
135                """, in: folder)
136            let read = try? String(contentsOf: folder.appendingPathComponent("out.txt"), encoding: .utf8)
137            #expect(read == text, "\(log)")
138            try? FileManager.default.removeItem(at: folder.appendingPathComponent("out.txt"))
139        }
140        // Emacs's file, saved through EasyPG, opened by orgstar.
141        let log = try Self.emacs("""
142            (with-current-buffer (find-file-noselect "theirs.org.gpg")
143              (insert \(OrgCryptTests.lisp(text)))
144              (let ((coding-system-for-write 'utf-8-unix)) (save-buffer)))
145            """, in: folder)
146        let theirs = try Data(contentsOf: folder.appendingPathComponent("theirs.org.gpg"))
147        #expect(theirs.range(of: Data("Dear diary".utf8)) == nil, "\(log)")
148        #expect(String(decoding: try OpenPGP.decryptFile(theirs, passphrase: "pw one"), as: UTF8.self) == text)
149        #expect(throws: OpenPGP.Failure.self) { try OpenPGP.decryptFile(theirs, passphrase: "wrong") }
150    }
151
152    @Test(.enabled(if: emacs))
153    func orgCryptKeepsAnUnchangedEntrysMessageAsOrgstarDoes() throws {
154        // Emacs: an entry decrypted and encrypted again, unchanged, gets its own message back.
155        // An entry with no text has none to carry the old message, and gets a new one.
156        let file = OrgCryptTests.file.replacingOccurrences(of: "* Empty :crypt:\n", with: "")
157        let (sealed, _) = try OrgCrypt.seal(file, passphrase: "pw one")
158        let again = try OrgCryptTests.emacs(sealed, "(org-decrypt-entries) (org-encrypt-entries)")
159        #expect(again == sealed)
160        // And reads what orgstar sealed.
161        #expect(try OrgCryptTests.emacs(sealed, "(org-decrypt-entries)") == file)
162    }
163}
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