Tests/OrgCoreTests/OpenPGPTests.swift

58f3b73e8ff337e5a15111fbb32c0d57cf2346da
orgstar/Tests/OrgCoreTests/OpenPGPTests.swift history · blame · raw

80 lines · 4045 bytes

5 symbols in this file
 1import Foundation
 2import Testing
 3@testable import OrgCore
 4
 5struct OpenPGPTests {
 6    static var gpg: String? {
 7        ["/opt/homebrew/bin/gpg", "/usr/local/bin/gpg", "/usr/bin/gpg"].first { FileManager.default.isExecutableFile(atPath: $0) }
 8    }
 9
10    /// gpg with its own short home (the agent's socket path has a length limit), the
11    /// passphrase given in loopback.
12    static func gpg(_ arguments: [String], input: Data) throws -> Data {
13        let home = "/tmp/ogpg-\(UUID().uuidString.prefix(8))"
14        try FileManager.default.createDirectory(atPath: home, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700])
15        defer {
16            let kill = Process()
17            kill.executableURL = URL(fileURLWithPath: "/usr/bin/env")
18            kill.arguments = ["gpgconf", "--homedir", home, "--kill", "gpg-agent"]
19            try? kill.run()
20            kill.waitUntilExit()
21            try? FileManager.default.removeItem(atPath: home)
22        }
23        let process = Process()
24        process.executableURL = URL(fileURLWithPath: gpg!)
25        process.arguments = ["--homedir", home, "--batch", "--yes", "--pinentry-mode", "loopback", "--quiet"] + arguments
26        let stdin = Pipe(), stdout = Pipe(), stderr = Pipe()
27        process.standardInput = stdin
28        process.standardOutput = stdout
29        process.standardError = stderr
30        try process.run()
31        stdin.fileHandleForWriting.write(input)
32        try stdin.fileHandleForWriting.close()
33        let out = stdout.fileHandleForReading.readDataToEndOfFile()
34        process.waitUntilExit()
35        guard process.terminationStatus == 0 else {
36            throw OpenPGP.Failure(String(decoding: stderr.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self))
37        }
38        return out
39    }
40
41    static let text = Data("Secret notes: ünïcödé, and\n** a sub-heading\n".utf8) + Data(repeating: 65, count: 3000)
42
43    static let variants: [[String]] = [
44        [],
45        ["--compress-algo", "none"],
46        ["--compress-algo", "zlib", "--cipher-algo", "AES128"],
47        ["--cipher-algo", "AES192", "--s2k-digest-algo", "SHA1"],
48        ["--s2k-mode", "1", "--s2k-digest-algo", "SHA512"],
49        ["--s2k-mode", "0", "--s2k-digest-algo", "SHA224"],
50        ["--s2k-count", "65011712"],
51        ["--force-mdc", "--compress-algo", "zip"],
52    ]
53
54    @Test(.enabled(if: gpg != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil), arguments: variants.indices)
55    func readsWhatGPGWrites(variant: Int) throws {
56        let armored = try Self.gpg(["--passphrase", "correct horse", "--symmetric", "--armor"] + Self.variants[variant], input: Self.text)
57        let message = try OpenPGP.dearmor(String(decoding: armored, as: UTF8.self))
58        #expect(try OpenPGP.decrypt(message, passphrase: "correct horse") == Self.text)
59        #expect(throws: OpenPGP.Failure.self) { try OpenPGP.decrypt(message, passphrase: "wrong") }
60    }
61
62    @Test(.enabled(if: gpg != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
63    func gpgReadsWhatWeWrite() throws {
64        for plain in [Self.text, Data(), Data("short\n".utf8), Data(repeating: 7, count: 70_000)] {
65            let armored = try OpenPGP.encrypt(plain, passphrase: "pass phrase")
66            #expect(armored.hasPrefix("-----BEGIN PGP MESSAGE-----\n\n") && armored.hasSuffix("-----END PGP MESSAGE-----\n"))
67            let back = try Self.gpg(["--passphrase", "pass phrase", "--decrypt"], input: Data(armored.utf8))
68            #expect(back == plain)
69            #expect(try OpenPGP.decrypt(OpenPGP.dearmor(armored), passphrase: "pass phrase") == plain)
70        }
71    }
72
73    @Test func armorChecksum() throws {
74        let armored = OpenPGP.armor(Data([1, 2, 3]))
75        #expect(try OpenPGP.dearmor(armored) == Data([1, 2, 3]))
76        let damaged = armored.replacingOccurrences(of: "AQID", with: "AQIE")
77        #expect(throws: OpenPGP.Failure.self) { try OpenPGP.dearmor(damaged) }
78        #expect(OpenPGP.crc24(Data()) == 0xB704CE)
79    }
80}