Tests/OrgCoreTests/CryptFileTests.swift

29b770d6b2f9edcc6607ab4a46db6c659dd12c1d
orgstar/Tests/OrgCoreTests/CryptFileTests.swift

137 lines · 8727 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 unencryptedEntriesWithText() throws {
 33        #expect(OrgCrypt.unencrypted(OrgCryptTests.file).count == 2)
 34        let bank = (OrgCryptTests.file as NSString).range(of: "* TODO Bank").location
 35        let one = try #require(try OrgCrypt.encrypt(OrgCryptTests.file, at: bank, passphrase: "pw"))
 36        #expect(OrgCrypt.unencrypted(one).count == 1)
 37        #expect(OrgCrypt.firstMessage(one).map { OrgCrypt.opens($0, passphrase: "pw") } == true)
 38        #expect(OrgCrypt.firstMessage(one).map { OrgCrypt.opens($0, passphrase: "other") } == false)
 39        #expect(OrgCrypt.firstMessage(OrgCryptTests.file) == nil)
 40        #expect(OrgCrypt.unencrypted("* Empty :crypt:\n\n* B\n").isEmpty)
 41        #expect(OrgCrypt.unencrypted("#+FILETAGS: :crypt:\n* A\nsecret\n").count == 1)
 42    }
 43
 44    @Test func encryptedFilesRoundTrip() throws {
 45        let text = Data("* Diary\nDear diary, ünïcödé.\n".utf8)
 46        let binary = try OpenPGP.encryptedMessage(text, passphrase: "pw")
 47        #expect(!OpenPGP.isArmored(binary))
 48        #expect(try OpenPGP.decryptFile(binary, passphrase: "pw") == text)
 49        let armored = Data(try OpenPGP.encrypt(text, passphrase: "pw").utf8)
 50        #expect(OpenPGP.isArmored(armored))
 51        #expect(try OpenPGP.decryptFile(armored, passphrase: "pw") == text)
 52        #expect(throws: OpenPGP.wrongPassphrase) { try OpenPGP.decryptFile(binary, passphrase: "wrong") }
 53        #expect(throws: OpenPGP.Failure.self) { try OpenPGP.decryptFile(Data("* plain text\n".utf8), passphrase: "pw") }
 54    }
 55
 56    @Test(.enabled(if: gpg && oracle))
 57    func gpgReadsAndWritesEncryptedFiles() throws {
 58        let text = Data("* Diary\nDear diary, ünïcödé.\n".utf8)
 59        // `gpg --decrypt` reads orgstar's file, binary as orgstar writes it by default.
 60        let ours = try OpenPGP.encryptedMessage(text, passphrase: "pass phrase")
 61        #expect(try OpenPGPTests.gpg(["--passphrase", "pass phrase", "--decrypt"], input: ours) == text)
 62        // orgstar reads `gpg --symmetric`, binary and armored.
 63        let theirs = try OpenPGPTests.gpg(["--passphrase", "pass phrase", "--symmetric"], input: text)
 64        #expect(!OpenPGP.isArmored(theirs))
 65        #expect(try OpenPGP.decryptFile(theirs, passphrase: "pass phrase") == text)
 66        let armored = try OpenPGPTests.gpg(["--passphrase", "pass phrase", "--symmetric", "--armor"], input: text)
 67        #expect(try OpenPGP.decryptFile(armored, passphrase: "pass phrase") == text)
 68        #expect(throws: OpenPGP.Failure.self) { try OpenPGP.decryptFile(theirs, passphrase: "wrong") }
 69    }
 70
 71    /// Emacs with EasyPG (`epa-file`), symmetric, the passphrase given without asking, run on
 72    /// `file` in a fresh GnuPG home: `form` runs with `file` as the variable `file`.
 73    static func emacs(_ form: String, in folder: URL) throws -> String {
 74        let home = "/tmp/ogpg-\(UUID().uuidString.prefix(8))"
 75        try FileManager.default.createDirectory(atPath: home, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700])
 76        defer {
 77            let kill = Process()
 78            kill.executableURL = URL(fileURLWithPath: "/usr/bin/env")
 79            kill.arguments = ["gpgconf", "--homedir", home, "--kill", "gpg-agent"]
 80            try? kill.run()
 81            kill.waitUntilExit()
 82            try? FileManager.default.removeItem(atPath: home)
 83        }
 84        let elisp = """
 85        (progn
 86          (require 'org) (require 'epa-file) (epa-file-enable)
 87          (setq epg-pinentry-mode 'loopback epa-pinentry-mode 'loopback epa-file-select-keys 'silent epa-file-encrypt-to nil
 88                epg-gpg-program \(OrgCryptTests.lisp(OpenPGPTests.gpg!)) default-directory \(OrgCryptTests.lisp(folder.path + "/")))
 89          (cl-letf (((symbol-function 'epa-file-passphrase-callback-function) (lambda (&rest _) (copy-sequence "pw one")))
 90                    ((symbol-function 'epa-passphrase-callback-function) (lambda (&rest _) (copy-sequence "pw one"))))
 91            \(form)))
 92        """
 93        return try EmacsOracle.run(["-Q", "--batch", "--eval", elisp], environment: ["GNUPGHOME": home, "TZ": "UTC"])
 94    }
 95
 96    @Test(.enabled(if: emacs))
 97    func emacsOpensWhatOrgstarWritesAndTheReverse() throws {
 98        let folder = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-gpg-\(UUID().uuidString)")
 99        try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
100        defer { try? FileManager.default.removeItem(at: folder) }
101        let text = "* Diary :private:\nDear diary, ünïcödé.\n** Child\nMore.\n"
102        // orgstar's file, binary and armored, opened by `find-file` in Emacs.
103        for (name, data) in [("ours.org.gpg", try OpenPGP.encryptedMessage(Data(text.utf8), passphrase: "pw one")),
104                             ("armored.org.gpg", Data(try OpenPGP.encrypt(Data(text.utf8), passphrase: "pw one").utf8))] {
105            try data.write(to: folder.appendingPathComponent(name))
106            let log = try Self.emacs("""
107                (with-current-buffer (find-file-noselect \(OrgCryptTests.lisp(name)))
108                  (let ((coding-system-for-write 'utf-8-unix)) (write-region (point-min) (point-max) "out.txt")))
109                """, in: folder)
110            let read = try? String(contentsOf: folder.appendingPathComponent("out.txt"), encoding: .utf8)
111            #expect(read == text, "\(log)")
112            try? FileManager.default.removeItem(at: folder.appendingPathComponent("out.txt"))
113        }
114        // Emacs's file, saved through EasyPG, opened by orgstar.
115        let log = try Self.emacs("""
116            (with-current-buffer (find-file-noselect "theirs.org.gpg")
117              (insert \(OrgCryptTests.lisp(text)))
118              (let ((coding-system-for-write 'utf-8-unix)) (save-buffer)))
119            """, in: folder)
120        let theirs = try Data(contentsOf: folder.appendingPathComponent("theirs.org.gpg"))
121        #expect(theirs.range(of: Data("Dear diary".utf8)) == nil, "\(log)")
122        #expect(String(decoding: try OpenPGP.decryptFile(theirs, passphrase: "pw one"), as: UTF8.self) == text)
123        #expect(throws: OpenPGP.Failure.self) { try OpenPGP.decryptFile(theirs, passphrase: "wrong") }
124    }
125
126    @Test(.enabled(if: emacs))
127    func orgCryptKeepsAnUnchangedEntrysMessageAsOrgstarDoes() throws {
128        // Emacs: an entry decrypted and encrypted again, unchanged, gets its own message back.
129        // An entry with no text has none to carry the old message, and gets a new one.
130        let file = OrgCryptTests.file.replacingOccurrences(of: "* Empty :crypt:\n", with: "")
131        let (sealed, _) = try OrgCrypt.seal(file, passphrase: "pw one")
132        let again = try OrgCryptTests.emacs(sealed, "(org-decrypt-entries) (org-encrypt-entries)")
133        #expect(again == sealed)
134        // And reads what orgstar sealed.
135        #expect(try OrgCryptTests.emacs(sealed, "(org-decrypt-entries)") == file)
136    }
137}
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