import CryptoKit import Darwin import Foundation import Testing @testable import ParcelDev private final class UpdateFeedFixture { let root: URL let archive: URL let checksums: URL let source: URL let site: URL let destination: URL let repository: URL let marker: URL let startup: URL let key = Curve25519.Signing.PrivateKey() let originalArchive = Data("Signed feed archive fixture\n".utf8) var baseline = Data() var originalChecksums = Data() var calls = 0 var wrapper: URL? var publicKey: String { key.publicKey.rawRepresentation.base64EncodedString() } var signature: String { get throws { try key.signature(for: originalArchive).base64EncodedString() } } init() throws { root = try ReleaseTestSupport.temporary().appendingPathComponent("feed fixtures") archive = root.appendingPathComponent("download/update-1.2.3.dmg") checksums = root.appendingPathComponent("metadata/SHA256SUMS") source = root.appendingPathComponent("metadata/appcast.xml") site = root.appendingPathComponent("site") destination = site.appendingPathComponent("feeds/appcast.xml") repository = root.appendingPathComponent("repository") marker = root.appendingPathComponent("unexpected-startup") startup = root.appendingPathComponent("bash-env.sh") for directory in [archive.deletingLastPathComponent(), source.deletingLastPathComponent(), site, repository] { try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) } try originalArchive.write(to: archive) _ = try git(["init", "--initial-branch=main"]) for version in ["1.2.3", "1.2.4", "1.2.5"] { _ = try git(["commit", "--allow-empty", "-m", "Fixture " + version]) _ = try git(["tag", "v" + version]) } _ = try git(["update-ref", "refs/remotes/github/main", "HEAD"]) let generated = try ReleaseTestSupport.run( "update-metadata", [ "release", archive.path, signature, source.deletingLastPathComponent().path, ReleaseTestSupport.root.appendingPathComponent("Packaging/parcel.rb").path, ], environment: [ "PARCEL_VERSION": "1.2.3", "PARCEL_BUILD_NUMBER": "9", "PARCEL_DOWNLOAD_URL_PREFIX": url("1.2.3").components(separatedBy: "/").dropLast().joined( separator: "/"), ]) #expect(generated.status == 0, "\(generated.errorOutput)") baseline = try Data(contentsOf: source) originalChecksums = try Data(contentsOf: checksums) let item = try entry(XMLDocument(data: baseline)) #expect(LaunchFeed.text(item, "shortVersionString") == "1.2.3") #expect(LaunchFeed.text(item, "version") == "9") #expect( try String( contentsOf: source.deletingLastPathComponent().appendingPathComponent("parcel.rb"), encoding: .utf8 ).contains("version '1.2.3'")) try "touch '\(marker.path)'\n".write(to: startup, atomically: false, encoding: .utf8) let injected = archive.deletingLastPathComponent().appendingPathComponent("parcel-dev") try "#!/bin/sh\ntouch '\(marker.path)'\nexit 0\n".write(to: injected, atomically: false, encoding: .utf8) try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: injected.path) try "export PRODUCT_NAME=$(touch '\(marker.path)')\n".write( to: archive.deletingLastPathComponent().appendingPathComponent("product.env"), atomically: false, encoding: .utf8) } func clean() throws { try FileManager.default.removeItem(at: root.deletingLastPathComponent()) } func git(_ args: [String]) throws -> String { String( decoding: try DevProcess.checked( "/usr/bin/git", [ "-C", repository.path, "-c", "core.hooksPath=/dev/null", "-c", "user.name=Fixture", "-c", "user.email=fixture@example.invalid", ] + args), as: UTF8.self ).trimmingCharacters(in: .whitespacesAndNewlines) } func url(_ version: String) -> String { "https://example.invalid/example/product/releases/download/v\(version)/\(archive.lastPathComponent)" } func entry(_ document: XMLDocument) throws -> XMLElement { let channel = try LaunchFeed.channel(document) return try #require(channel.elements(forName: "item").first) } func write(version: String = "1.2.3", build: String = "9", attributes: [String: String] = [:]) throws { let document = try XMLDocument(data: baseline) let item = try entry(document) try #require(item.elements(forLocalName: "shortVersionString", uri: LaunchFeed.namespace).first).stringValue = version try #require(item.elements(forLocalName: "version", uri: LaunchFeed.namespace).first).stringValue = build let enclosure = try #require(item.elements(forName: "enclosure").first) enclosure.attribute(forName: "url")?.stringValue = url(version) for (name, value) in attributes { if name == "signature" { enclosure.attribute(forLocalName: "edSignature", uri: LaunchFeed.namespace)?.stringValue = value } else { enclosure.attribute(forName: name)?.stringValue = value } } try document.xmlData().write(to: source) } func invoke( error: String? = nil, version: String = "1.2.3", download: String? = nil, archive: URL? = nil, checksums: URL? = nil, key: String? = nil, relative: String = "feeds/appcast.xml", archiveArgument: String? = nil, checksumArgument: String? = nil ) throws -> String { let before = FileManager.default.fileExists(atPath: destination.path) ? try Data(contentsOf: destination) : nil let args = [ source.path, site.path, relative, version, download ?? url(version), archiveArgument ?? (archive ?? self.archive).path, checksumArgument ?? (checksums ?? self.checksums).path, key ?? publicKey, repository.path, ] var environment = ProcessInfo.processInfo.environment environment["BASH_ENV"] = startup.path environment["PRODUCT_DEFAULT_BRANCH"] = "main" environment["PARCEL_DEV_ROOT"] = ReleaseTestSupport.root.path environment["PARCEL_DEV_BINARY"] = try ReleaseTestSupport.binary let result: DevProcessResult if let wrapper { result = try DevProcess.run( "/bin/sh", [wrapper.path, "launch-feed"] + args, directory: ReleaseTestSupport.root, environment: environment) } else { result = try DevProcess.run( ReleaseTestSupport.binary, ["launch-feed"] + args, directory: archive?.deletingLastPathComponent() ?? self.archive.deletingLastPathComponent(), environment: environment) } if let error { #expect(result.status != 0, "Expected feed rejection") #expect(result.errorOutput.contains(error), "\(result.errorOutput)") #expect(!result.errorOutput.contains("Traceback")) let after = FileManager.default.fileExists(atPath: destination.path) ? try Data(contentsOf: destination) : nil #expect(before == after, "A rejected feed changed the published appcast") } else { #expect(result.status == 0, "\(result.errorOutput)") } let files = try #require(FileManager.default.enumerator(at: site, includingPropertiesForKeys: nil)) #expect(!files.compactMap { $0 as? URL }.contains { $0.lastPathComponent.hasPrefix(".appcast-") }) #expect( !FileManager.default.fileExists(atPath: marker.path), "Validation executed untrusted startup or downloaded config") calls += 1 return result.output } static func noncanonical(_ value: String) throws -> String { let alphabet = Array("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".utf8) var bytes = Array(value.utf8) let index = bytes.count - bytes.reversed().prefix(while: { $0 == 61 }).count - 1 let letter = try #require(alphabet.firstIndex(of: bytes[index])) bytes[index] = alphabet[letter + 1] let result = String(decoding: bytes, as: UTF8.self) #expect(Data(base64Encoded: result) == Data(base64Encoded: value)) return result } } @Suite struct UpdateFeedIntegrationTests { @Test func validatesCombinedFeedHistoryEvidenceAndRelocatedCallers() throws { let fixture = try UpdateFeedFixture() defer { #expect(throws: Never.self) { try fixture.clean() } } try fixture.write() for version in ["", "1.2", "letters", "1.2.3 bad", "1.2.3\n1.2.3", "1.2.3\t", "1.2.3\r"] { _ = try fixture.invoke(error: "Invalid version", version: version) } for version in ["1.2.3-beta.1", "1.2.3+build.42", "1.2.3-rc.1+build-42"] { _ = try fixture.invoke(error: "MAJOR.MINOR.PATCH", version: version) } for build in ["", "1.2", "-1", "letters", "123\n", "123\t", "123 "] { try fixture.write(build: build); _ = try fixture.invoke(error: "Invalid build number") } for build in ["0", "09"] { try fixture.write(build: build); _ = try fixture.invoke(error: "positive integers") } try fixture.write(version: "1.2.4") _ = try fixture.invoke(error: "selected release") let url = fixture.url("1.2.3") for invalid in [ url.replacingOccurrences(of: "https://", with: "http://"), url.replacingOccurrences(of: "https://", with: "https://user@"), url.replacingOccurrences(of: "https://", with: "https://@"), url + "?token=value", url + "#fragment", url.components(separatedBy: "/").dropLast().joined(separator: "/") + "/wrong.dmg", ] { try fixture.write(attributes: ["url": invalid]); _ = try fixture.invoke(error: "expected HTTPS download", download: invalid) } try fixture.write(attributes: ["url": "https://example.invalid/other/" + fixture.archive.lastPathComponent]) _ = try fixture.invoke(error: "length or URL") for length in ["0", String(fixture.originalArchive.count + 1), "invalid"] { try fixture.write(attributes: ["length": length]); _ = try fixture.invoke(error: "Appcast:") } try fixture.write() for key in [ "bad", Data(repeating: 0, count: 31).base64EncodedString(), try UpdateFeedFixture.noncanonical(fixture.publicKey), ] { _ = try fixture.invoke(error: "Appcast:", key: key) } for value in [ "bad", Data(repeating: 0, count: 63).base64EncodedString(), try UpdateFeedFixture.noncanonical(fixture.signature), ] { try fixture.write(attributes: ["signature": value]); _ = try fixture.invoke(error: "Appcast:") } try fixture.write(attributes: ["signature": Data(repeating: 0, count: 64).base64EncodedString()]) _ = try fixture.invoke(error: "signature does not match") try fixture.write() _ = try fixture.invoke( error: "signature does not match", key: Data(repeating: 0, count: 32).base64EncodedString()) let checksumCases = [ (String(repeating: "0", count: 64) + " " + fixture.archive.lastPathComponent + "\n", "SHA256SUMS"), (try UpdateCrypto.digest(fixture.archive) + " other.dmg\n", "SHA256SUMS"), ( String(decoding: fixture.originalChecksums + fixture.originalChecksums, as: UTF8.self), "invalid or duplicate" ), (String(repeating: "0", count: 64) + " ../escape.dmg\n", "invalid or duplicate"), ("invalid\n", "invalid or duplicate"), (String(repeating: "x", count: 100_001), "too large"), ] for (contents, error) in checksumCases { try Data(contents.utf8).write(to: fixture.checksums); _ = try fixture.invoke(error: error) } try fixture.originalChecksums.write(to: fixture.checksums) let links = fixture.root.appendingPathComponent("symlinks") try FileManager.default.createDirectory(at: links, withIntermediateDirectories: false) for path in [fixture.archive, fixture.checksums] { let link = links.appendingPathComponent(path.lastPathComponent) try FileManager.default.createSymbolicLink(at: link, withDestinationURL: path) _ = try fixture.invoke( error: "regular downloaded", archive: path == fixture.archive ? link : nil, checksums: path == fixture.checksums ? link : nil) } _ = try fixture.invoke( error: "regular downloaded", checksums: fixture.checksums.deletingLastPathComponent().appendingPathComponent("missing")) let fifo = fixture.checksums.deletingLastPathComponent().appendingPathComponent("fifo") #expect(mkfifo(fifo.path, 0o600) == 0) _ = try fixture.invoke(error: "regular downloaded", checksums: fifo) try Data().write(to: fixture.archive) try fixture.write(attributes: ["length": "0"]) _ = try fixture.invoke(error: "archive is empty") try fixture.originalArchive.write(to: fixture.archive) try fixture.write() #expect(!FileManager.default.fileExists(atPath: fixture.destination.path)) #expect(try fixture.invoke().contains("published")) let published = try Data(contentsOf: fixture.destination) #expect(try fixture.invoke().contains("already matches")) #expect(try Data(contentsOf: fixture.destination) == published) let altered = Data( String(decoding: fixture.originalArchive, as: UTF8.self).replacingOccurrences( of: "fixture", with: "tamper!" ).utf8) try altered.write(to: fixture.archive) _ = try fixture.invoke(error: "SHA256SUMS") try Data("\(UpdateCrypto.digest(fixture.archive)) \(fixture.archive.lastPathComponent)\n".utf8).write( to: fixture.checksums) _ = try fixture.invoke(error: "signature does not match") try fixture.originalArchive.write(to: fixture.archive) try fixture.originalChecksums.write(to: fixture.checksums) try fixture.write(version: "1.2.4", build: "10") #expect(try fixture.invoke(version: "1.2.4").contains("published")) let entries = try LaunchFeed.channel(LaunchFeed.parse(fixture.destination)).elements(forName: "item") #expect(entries.map { LaunchFeed.text($0, "version") } == ["10", "9"]) #expect(LaunchFeed.text(entries[1], "shortVersionString") == "1.2.3") #expect(try fixture.invoke(version: "1.2.4").contains("already matches")) try fixture.write(version: "1.2.4", build: "11") _ = try fixture.invoke(error: "different metadata", version: "1.2.4") for build in ["8", "10"] { try fixture.write(version: "1.2.5", build: build); _ = try fixture.invoke(error: "strictly greater", version: "1.2.5") } try fixture.write(version: "1.2.5", build: "00010") _ = try fixture.invoke(error: "positive integers", version: "1.2.5") try fixture.write(version: "1.2.5", build: "11") let previous = try Data(contentsOf: fixture.destination) let existing = try LaunchFeed.parse(fixture.destination) let first = try #require(LaunchFeed.channel(existing).elements(forName: "item").first) try #require(first.elements(forLocalName: "version", uri: LaunchFeed.namespace).first).stringValue = "1.0" try existing.xmlData().write(to: fixture.destination) _ = try fixture.invoke(error: "Invalid build number", version: "1.2.5") try previous.write(to: fixture.destination) for relative in ["../outside.xml", fixture.root.appendingPathComponent("absolute.xml").path] { _ = try fixture.invoke(error: "relative to the site repo", version: "1.2.5", relative: relative) } let outside = fixture.root.appendingPathComponent("outside") try FileManager.default.createDirectory(at: outside, withIntermediateDirectories: false) try FileManager.default.createSymbolicLink( at: fixture.site.appendingPathComponent("escape"), withDestinationURL: outside) _ = try fixture.invoke(error: "escapes the site repo", version: "1.2.5", relative: "escape/appcast.xml") #expect(!FileManager.default.fileExists(atPath: outside.appendingPathComponent("appcast.xml").path)) try FileManager.default.removeItem(at: fixture.destination) let other = fixture.site.appendingPathComponent("previous.xml") try previous.write(to: other) try FileManager.default.createSymbolicLink(at: fixture.destination, withDestinationURL: other) _ = try fixture.invoke(error: "replace a symlink", version: "1.2.5") #expect(try Data(contentsOf: other) == previous) try FileManager.default.removeItem(at: fixture.destination) try previous.write(to: fixture.destination) try Data("\(UpdateCrypto.digest(fixture.archive).uppercased()) *\(fixture.archive.lastPathComponent)\n".utf8) .write(to: fixture.checksums) #expect(try fixture.invoke(version: "1.2.5").contains("published")) let relocated = fixture.root.appendingPathComponent("project with spaces/Scripts") try FileManager.default.createDirectory(at: relocated, withIntermediateDirectories: true) for name in ["parcel-dev.sh", "version.sh"] { try FileManager.default.copyItem( at: ReleaseTestSupport.root.appendingPathComponent("Scripts/" + name), to: relocated.appendingPathComponent(name)) } fixture.wrapper = relocated.appendingPathComponent("parcel-dev.sh") func relativePath(_ path: URL) -> String { let base = ReleaseTestSupport.root.pathComponents let target = path.pathComponents let shared = zip(base, target).prefix(while: { pair in pair.0 == pair.1 }).count return (Array(repeating: "..", count: base.count - shared) + Array(target.dropFirst(shared))).joined( separator: "/") } #expect( try fixture.invoke( version: "1.2.5", archiveArgument: relativePath(fixture.archive), checksumArgument: relativePath(fixture.checksums) ).contains("already matches")) let resumed = try Data(contentsOf: fixture.destination) let crlf = try String(contentsOf: fixture.checksums, encoding: .utf8).replacingOccurrences( of: "\n", with: "\r\n") try Data(crlf.utf8).write(to: fixture.checksums) #expect(try fixture.invoke(version: "1.2.5").contains("already matches")) #expect(try Data(contentsOf: fixture.destination) == resumed) #expect(fixture.calls >= 67) } }