Tests/OrgCoreTests/OrgCryptTests.swift

110 lines · 5790 bytes

  1import Foundation
  2import Testing
  3@testable import OrgCore
  4
  5struct OrgCryptTests {
  6    static let file = """
  7        #+TITLE: Secrets
  8        * Plain
  9        Open text.
 10        * TODO Bank :crypt:
 11        SCHEDULED: <2026-10-20 Tue>
 12        :PROPERTIES:
 13        :ID: bank
 14        :END:
 15        :LOGBOOK:
 16        CLOCK: [2026-10-01 Thu 09:00]--[2026-10-01 Thu 10:00] =>  1:00
 17        :END:
 18        Account 12345, ünïcödé.
 19        ** Child
 20        Child text.
 21
 22        * Diary :crypt:
 23        Dear diary.
 24        * Empty :crypt:
 25        * Last
 26        """ + "\n"
 27
 28    static func lisp(_ s: String) -> String {
 29        "\"" + s.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\""
 30    }
 31
 32    /// `form` run in Emacs on `text` in an Org buffer, with symmetric org-crypt and the
 33    /// passphrase given in loopback; the buffer's text afterwards.
 34    static func emacs(_ text: String, _ form: String) throws -> String {
 35        let home = "/tmp/ogpg-\(UUID().uuidString.prefix(8))"
 36        try FileManager.default.createDirectory(atPath: home, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700])
 37        defer {
 38            let kill = Process()
 39            kill.executableURL = URL(fileURLWithPath: "/usr/bin/env")
 40            kill.arguments = ["gpgconf", "--homedir", home, "--kill", "gpg-agent"]
 41            try? kill.run()
 42            kill.waitUntilExit()
 43            try? FileManager.default.removeItem(atPath: home)
 44        }
 45        let out = home + "/out.org"
 46        let elisp = """
 47        (progn
 48          (require 'org) (require 'org-crypt) (require 'epg)
 49          (setq org-crypt-key nil epg-pinentry-mode 'loopback org-crypt-disable-auto-save nil
 50                epg-gpg-program "/opt/homebrew/bin/gpg")
 51          (require 'epa)
 52          (cl-letf (((symbol-function 'epa-passphrase-callback-function) (lambda (&rest _) (copy-sequence "pw one")))
 53                    ((symbol-function 'epg-passphrase-callback-function) (lambda (&rest _) (copy-sequence "pw one"))))
 54            (with-temp-buffer
 55              (insert \(lisp(text)))
 56              (org-mode)
 57              \(form)
 58              (write-region (point-min) (point-max) \(lisp(out))))))
 59        """
 60        let log = try EmacsOracle.run(["-Q", "--batch", "--eval", elisp], environment: ["GNUPGHOME": home, "TZ": "UTC"])
 61        guard let result = try? String(contentsOfFile: out, encoding: .utf8) else { throw EmacsOracle.EvaluateError(log: log) }
 62        return result
 63    }
 64
 65    /// The text with each message's lines as one placeholder line.
 66    static func masked(_ s: String) -> String {
 67        s.replacing(#/(?s)-----BEGIN PGP MESSAGE-----.*?-----END PGP MESSAGE-----\n/#, with: "<MESSAGE>\n")
 68    }
 69
 70    static var gpg: Bool { FileManager.default.isExecutableFile(atPath: "/opt/homebrew/bin/gpg") }
 71
 72    @Test(.enabled(if: gpg && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
 73    func encryptsAndDecryptsAsOrg() throws {
 74        // Emacs encrypts every tagged entry; ours does the same around the same text.
 75        let theirs = try Self.emacs(Self.file, "(org-encrypt-entries)")
 76        let (ours, count) = try OrgCrypt.encryptAll(Self.file, passphrase: "pw one")
 77        #expect(count == 3)
 78        #expect(Self.masked(ours) == Self.masked(theirs), "ours:\n\(Self.masked(ours))\nemacs:\n\(Self.masked(theirs))")
 79        // Each side reads the other's.
 80        var back = theirs
 81        for heading in OrgCrypt.taggedHeadings(back).reversed() { back = try OrgCrypt.decryptInPlace(back, at: heading, passphrase: "pw one") }
 82        #expect(back == Self.file, "\(back.debugDescription)\n\(Self.file.debugDescription)")
 83        let decrypted = try Self.emacs(ours, "(org-decrypt-entries)")
 84        #expect(decrypted == Self.file, "\(decrypted)")
 85        let bank = (ours as NSString).range(of: "* TODO Bank").location
 86        #expect(try OrgCrypt.decrypt(ours, at: bank, passphrase: "pw one").plaintext == "Account 12345, ünïcödé.\n** Child\nChild text.\n")
 87        #expect(throws: OrgCrypt.Failure("Wrong passphrase")) { try OrgCrypt.decrypt(ours, at: bank, passphrase: "nope") }
 88        // Edited and encrypted again, Emacs reads it.
 89        let edited = try OrgCrypt.replacing(ours, at: bank, with: "New text.\n", passphrase: "pw one")
 90        let read = try Self.emacs(edited, "(goto-char (point-min)) (re-search-forward \"Bank\") (org-decrypt-entry)")
 91        #expect(read.contains("* TODO Bank :crypt:\nSCHEDULED: <2026-10-20 Tue>\n:PROPERTIES:\n:ID: bank\n:END:\n:LOGBOOK:\nCLOCK: [2026-10-01 Thu 09:00]--[2026-10-01 Thu 10:00] =>  1:00\n:END:\nNew text.\n\n* Diary"), "\(read)")
 92    }
 93
 94    @Test func regions() throws {
 95        let file = Self.file
 96        let bank = (file as NSString).range(of: "* TODO Bank").location
 97        let body = try #require(OrgCrypt.bodyRange(file, at: bank + 3))
 98        #expect((file as NSString).substring(with: NSRange(body)) == "Account 12345, ünïcödé.\n** Child\nChild text.\n")
 99        #expect(OrgCrypt.encryptedRange(file, at: bank) == nil)
100        // The child inherits the tag.
101        #expect(OrgCrypt.taggedHeadings(file).count == 4)
102        let encrypted = try #require(try OrgCrypt.encrypt(file, at: bank, passphrase: "x"))
103        #expect(try OrgCrypt.encrypt(encrypted, at: bank, passphrase: "x") == nil)
104        #expect(throws: OrgCrypt.Failure.self) { try OrgCrypt.encrypt("text\n", at: 0, passphrase: "x") }
105        // A decrypted heading above the entry's level goes below it.
106        let shallow = try OrgCrypt.replacing(encrypted, at: bank, with: "* Top\ntext\n", passphrase: "x")
107        let placed = try OrgCrypt.decryptInPlace(shallow, at: bank, passphrase: "x")
108        #expect(placed.contains(":END:\n** Top\ntext\n\n* Diary"), "\(placed)")
109    }
110}