Forward-port improvements to generate_appcast from main branch (overridable download URL prefixes, extracting archives to uniqued output directory names during generation, -h flag to print usage, support for specifying Ed25519 key as string on command line, much smarter args parsing, ability to override keychain used to find signing keys)

This commit is contained in:
Gwynne Raskind committed 2020-07-24 20:43:22 -05:00
1 parent 418068e902
commit 9422bf16ae
5 files changed
+250 -62

No files matched your search

+4
View File
@@ -466,6 +466,7 @@
F8761EB11ADC5068000C9034 /* SUCodeSigningVerifierTest.m in Sources */ = {isa = PBXBuildFile; fileRef = F8761EB01ADC5068000C9034 /* SUCodeSigningVerifierTest.m */; };
F8761EB31ADC50EB000C9034 /* SparkleTestCodeSignApp.zip in Resources */ = {isa = PBXBuildFile; fileRef = F8761EB21ADC50EB000C9034 /* SparkleTestCodeSignApp.zip */; };
FA30773D24CBC295007BA37D /* testlocalizedreleasenotesappcast.xml in Resources */ = {isa = PBXBuildFile; fileRef = FA30773C24CBC295007BA37D /* testlocalizedreleasenotesappcast.xml */; };
FA30773F24CBC3E9007BA37D /* URL+Hashing.swift in Sources */ = {isa = PBXBuildFile; fileRef = FA30773E24CBC3E9007BA37D /* URL+Hashing.swift */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
@@ -1375,6 +1376,7 @@
FA1941D00D94A70100DD942E /* ConfigCommon.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = ConfigCommon.xcconfig; sourceTree = "<group>"; };
FA1941D10D94A70100DD942E /* ConfigFramework.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = ConfigFramework.xcconfig; sourceTree = "<group>"; };
FA30773C24CBC295007BA37D /* testlocalizedreleasenotesappcast.xml */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xml; path = testlocalizedreleasenotesappcast.xml; sourceTree = "<group>"; };
FA30773E24CBC3E9007BA37D /* URL+Hashing.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "URL+Hashing.swift"; sourceTree = "<group>"; };
FA3AAF3B1050B273004B3130 /* ConfigUnitTest.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = ConfigUnitTest.xcconfig; sourceTree = "<group>"; };
FE5536F517A2C6A7007CB333 /* ko */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = ko; path = ko.lproj/Sparkle.strings; sourceTree = "<group>"; };
FE5536F617A2C6AB007CB333 /* sk */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = sk; path = sk.lproj/Sparkle.strings; sourceTree = "<group>"; };
@@ -2000,6 +2002,7 @@
7205C4401E13049400E370AE /* main.swift */,
7205C4491E1304CE00E370AE /* Signatures.swift */,
7205C44B1E1304CE00E370AE /* Unarchive.swift */,
FA30773E24CBC3E9007BA37D /* URL+Hashing.swift */,
);
path = generate_appcast;
sourceTree = "<group>";
@@ -3345,6 +3348,7 @@
7205C4411E13049400E370AE /* main.swift in Sources */,
7205C45F1E13066F00E370AE /* SUBinaryDeltaApply.m in Sources */,
7205C4621E1306A600E370AE /* SUBinaryDeltaCommon.m in Sources */,
FA30773F24CBC3E9007BA37D /* URL+Hashing.swift in Sources */,
7205C4611E13069000E370AE /* SUBinaryDeltaCreate.m in Sources */,
7205C45B1E13064C00E370AE /* SUBinaryDeltaUnarchiver.m in Sources */,
7205C45D1E13065F00E370AE /* SUConstants.m in Sources */,
+10 -2
View File
@@ -47,6 +47,7 @@ class ArchiveItem: CustomStringConvertible {
var dsaSignature: String?
var edSignature: String?
var downloadUrlPrefix: URL?
init(version: String, shortVersion: String?, feedURL: URL?, minimumSystemVersion: String?, publicEdKey: String?, supportsDSA: Bool, appPath: URL, archivePath: URL) throws {
self.version = version
@@ -95,6 +96,10 @@ class ArchiveItem: CustomStringConvertible {
var feedURL: URL?
if let feedURLStr = infoPlist["SUFeedURL"] as? String {
feedURL = URL(string: feedURLStr)
if feedURL?.pathExtension == "php" {
feedURL = feedURL!.deletingLastPathComponent()
feedURL = feedURL!.appendingPathComponent("appcast.xml")
}
}
try self.init(version: version,
@@ -122,8 +127,11 @@ class ArchiveItem: CustomStringConvertible {
guard let escapedFilename = self.archivePath.lastPathComponent.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else {
return nil
}
if let relative = self.feedURL {
return URL(string: escapedFilename, relativeTo: relative)
if let downloadUrlPrefix = self.downloadUrlPrefix {
// if a download url prefix was given use this one
return URL(string: escapedFilename, relativeTo: downloadUrlPrefix)
} else if let relativeFeedUrl = self.feedURL {
return URL(string: escapedFilename, relativeTo: relativeFeedUrl)
}
return URL(string: escapedFilename)
}
+54
View File
@@ -0,0 +1,54 @@
//
// URL+Hashing.swift
// generate_appcast
//
// Created by Nate Weaver on 2020-05-01.
// Copyright © 2020 Sparkle Project. All rights reserved.
//
import Foundation
import CommonCrypto
extension FileHandle {
/// Calculate the SHA-256 hash of the file referenced by the file handle.
///
/// - Returns: The SHA-256 hash of the file (as a hexadecimal string).
func sha256String() -> String {
// This uses CommonCrypto instead of CryptoKit so it can work on macOS < 10.15
var context = CC_SHA256_CTX()
CC_SHA256_Init(&context)
while true {
let data = self.readData(ofLength: 65_536)
guard data.count > 0 else { break }
_ = data.withUnsafeBytes {
CC_SHA256_Update(&context, $0.baseAddress, numericCast($0.count))
}
}
let hash = UnsafeMutableBufferPointer<UInt8>.allocate(capacity: Int(CC_SHA256_DIGEST_LENGTH))
CC_SHA256_Final(hash.baseAddress, &context)
return hash.reduce("") { $0 + String(format: "%02x", $1) }
}
}
extension URL {
/// Calculates the SHA-256 hash of the file referened by the URL.
///
/// - Returns: The SHA-256 hash of the file (as a hexadecimal string), or `nil` if
/// the URL doesn't point to a file.
func sha256String() -> String? {
guard self.isFileURL else { return nil }
guard let filehandle = try? FileHandle(forReadingFrom: self) else { return nil }
return filehandle.sha256String()
}
}
+7 -1
View File
@@ -58,7 +58,13 @@ func unarchiveUpdates(archivesSourceDir: URL, archivesDestDir: URL, verbose: Boo
var running = 0
for item in dir.filter({ !$0.hasPrefix(".") && !$0.hasSuffix(".delta") && !$0.hasSuffix(".xml") && !$0.hasSuffix(".html") }) {
let itemPath = archivesSourceDir.appendingPathComponent(item)
let archiveDestDir = archivesDestDir.appendingPathComponent(itemPath.lastPathComponent)
let archiveDestDir: URL
if let hash = itemPath.sha256String() {
archiveDestDir = archivesDestDir.appendingPathComponent(hash)
} else {
archiveDestDir = archivesDestDir.appendingPathComponent(itemPath.lastPathComponent)
}
var isDir: ObjCBool = false
if fileManager.fileExists(atPath: itemPath.path, isDirectory: &isDir) && isDir.boolValue {
+175 -59
View File
@@ -25,26 +25,176 @@ func printUsage() {
)
}
func loadPrivateKeys(_ privateDSAKey: SecKey?) -> PrivateKeys {
func printHelp() {
let command = URL(fileURLWithPath: CommandLine.arguments.first!).lastPathComponent
print(
"Usage: \(command) [OPTIONS] [ARCHIVES_FOLDER]\n",
"Options:\n",
"\t-f: provide the path to the private DSA key\n",
"\t-n: provide the name of the private DSA key. This option has to be used together with `-k`\n",
"\t-k: provide the name of the keychain. This option has to be used together with `-n`\n",
"\t-s: provide the path to the private EdDSA key\n",
"\t--download-url-prefix: provide a static url that will be used as prefix for the url from where updates will be downloaded\n"
)
}
func loadPrivateKeys(_ privateDSAKey: SecKey?, _ privateEdString: String?) -> PrivateKeys {
var privateEdKey: Data?
var publicEdKey: Data?
var item: CFTypeRef?
let res = SecItemCopyMatching([
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: "https://sparkle-project.org",
kSecAttrAccount as String: "ed25519",
kSecAttrProtocol as String: kSecAttrProtocolSSH,
kSecReturnData as String: kCFBooleanTrue,
] as CFDictionary, &item)
if res == errSecSuccess, let encoded = item as? Data, let keys = Data(base64Encoded: encoded) {
var keys: Data?
// private + public key is provided as argument
if let privateEdString = privateEdString {
if privateEdString.count == 128, let data = Data(base64Encoded: privateEdString) {
keys = data
} else {
print("Warning: Private key not found in the argument. Please provide a valid key.")
}
}
// get keys from kechain instead
else {
let res = SecItemCopyMatching([
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: "https://sparkle-project.org",
kSecAttrAccount as String: "ed25519",
kSecAttrProtocol as String: kSecAttrProtocolSSH,
kSecReturnData as String: kCFBooleanTrue,
] as CFDictionary, &item)
if res == errSecSuccess, let encoded = item as? Data, let data = Data(base64Encoded: encoded) {
keys = data
} else {
print("Warning: Private key not found in the Keychain (\(res)). Please run the generate_keys tool")
}
}
if let keys = keys {
privateEdKey = keys[0..<64]
publicEdKey = keys[64...]
} else {
print("Warning: Private key not found in the Keychain (\(res)). Please run the generate_keys tool")
}
return PrivateKeys(privateDSAKey: privateDSAKey, privateEdKey: privateEdKey, publicEdKey: publicEdKey)
}
func parseCommandLineOptions(argumentList: [String]) -> (privateDSAKey: SecKey?, privateEdString: String?, downloadUrlPrefix: URL?, archivesSourceDir: URL) {
// if the option `-h` is in the argument list print the help dialog
if argumentList.contains("-h") {
printHelp()
exit(1)
}
// make a mutable copy of the argument list
var arguments = argumentList
// remove the first element since this is the path to executable which we don't need
arguments.removeFirst()
// define the variables for the possible argument values
var privateDSAKey: SecKey?
var privateEdString: String?
var downloadUrlPrefix: URL?
var archivesSourceDir: URL
// check if the private dsa key option is present
if let privateDSAKeyOptionIndex = arguments.firstIndex(of: "-f") {
// check that when accessing the value of the option we don't get out of bounds
if privateDSAKeyOptionIndex + 1 >= arguments.count {
print("Too few arguments were given")
exit(1)
}
// get the private DSA key
let privateKeyUrl = URL(fileURLWithPath: arguments[privateDSAKeyOptionIndex + 1])
do {
privateDSAKey = try loadPrivateDSAKey(at: privateKeyUrl)
} catch {
print("Unable to load DSA private key from", privateKeyUrl.path, "\n", error)
exit(1)
}
// remove the already parsed arguments
arguments.remove(at: privateDSAKeyOptionIndex)
arguments.remove(at: privateDSAKeyOptionIndex + 1)
}
// check if the private dsa sould be loaded using the keyname and the name of the keychain
if let keyNameOptionIndex = arguments.firstIndex(of: "-n"), let keychainNameOptionIndex = arguments.firstIndex(of: "-k") {
// check that when accessing one of the values of the options we don't get out of bounds
if keyNameOptionIndex + 1 >= arguments.count || keychainNameOptionIndex + 1 >= arguments.count {
print("Too few arguments were given")
exit(1)
}
// get the keyname and the keychain url to load the private DSA key
let keyName: String = arguments[keyNameOptionIndex + 1]
let keychainUrl: URL = URL(fileURLWithPath: arguments[keychainNameOptionIndex + 1])
do {
privateDSAKey = try loadPrivateDSAKey(named: keyName, fromKeychainAt: keychainUrl)
} catch {
print("Unable to load DSA private key '\(keyName)' from keychain at", keychainUrl.path, "\n", error)
exit(1)
}
// remove the already parsed arguments
arguments.remove(at: keyNameOptionIndex + 1)
arguments.remove(at: keyNameOptionIndex)
arguments.remove(at: arguments.firstIndex(of: "-k")! + 1)
arguments.remove(at: keychainNameOptionIndex)
}
// check if the private EdDSA key string was given as an argument
if let privateEdDSAKeyOptionIndex = arguments.firstIndex(of: "-s") {
// check that when accessing the value of the option we don't get out of bounds
if privateEdDSAKeyOptionIndex + 1 >= arguments.count {
print("Too few arguments were given")
exit(1)
}
// get the private EdDSA key string
privateEdString = arguments[privateEdDSAKeyOptionIndex + 1]
// remove the already parsed argument
arguments.remove(at: privateEdDSAKeyOptionIndex + 1)
arguments.remove(at: privateEdDSAKeyOptionIndex)
}
// check if a prefix for the download url of the archives was given
if let downloadUrlPrefixOptionIndex = arguments.firstIndex(of: "--download-url-prefix") {
// check that when accessing the value of the option we don't get out of bounds
if downloadUrlPrefixOptionIndex + 1 >= arguments.count {
print("Too few arguments were given")
exit(1)
}
// get the download url prefix
downloadUrlPrefix = URL(string: arguments[downloadUrlPrefixOptionIndex + 1])
// remove the parsed argument
arguments.remove(at: downloadUrlPrefixOptionIndex + 1)
arguments.remove(at: downloadUrlPrefixOptionIndex)
}
// now that all command line options have been removed from the arguments array
// there should only be the path to the private DSA key (if provided) path to the archives dir left
if arguments.count == 2 {
// if there are two arguments left they are the private DSA key and the path to the archives directory (in this order)
// first get the private DSA key
let privateKeyUrl = URL(fileURLWithPath: arguments[0])
do {
privateDSAKey = try loadPrivateDSAKey(at: privateKeyUrl)
} catch {
print("Unable to load DSA private key from", privateKeyUrl.path, "\n", error)
exit(1)
}
// remove the parsed path to the DSA key
arguments.removeFirst()
}
// now only the archives source dir is left
archivesSourceDir = URL(fileURLWithPath: arguments[0], isDirectory: true)
return (privateDSAKey, privateEdString, downloadUrlPrefix, archivesSourceDir)
}
func main() {
let args = CommandLine.arguments
if args.count < 2 {
@@ -53,60 +203,26 @@ func main() {
}
var privateDSAKey: SecKey?
var privateEdString: String?
var downloadUrlPrefix: URL?
var archivesSourceDir: URL
// this was typical usage for DSA keys
if args.count == 3 || (args.count == 4 && args[1] == "-f") {
// private key specified by filename
let privateKeyURL = URL(fileURLWithPath: args.count == 3 ? args[1] : args[2])
(privateDSAKey, privateEdString, downloadUrlPrefix, archivesSourceDir) = parseCommandLineOptions(argumentList: args)
do {
privateDSAKey = try loadPrivateDSAKey(at: privateKeyURL)
} catch {
print("Unable to load DSA private key from", privateKeyURL.path, "\n", error)
exit(1)
}
}
// this is legacy for DSA keychain; probably very rarely used
else if args.count == 6 && (args[1] == "-n" || args[1] == "-k") {
// private key specified by keychain + key name
let keyName: String
let keychainURL: URL
if args[1] == "-n" {
if args[3] != "-k" {
printUsage()
exit(1)
}
keyName = args[2]
keychainURL = URL(fileURLWithPath: args[4])
} else {
if args[3] != "-n" {
printUsage()
exit(1)
}
keyName = args[4]
keychainURL = URL(fileURLWithPath: args[2])
}
do {
privateDSAKey = try loadPrivateDSAKey(named: keyName, fromKeychainAt: keychainURL)
} catch {
print("Unable to load DSA private key '\(keyName)' from keychain at", keychainURL.path, "\n", error)
exit(1)
}
} else if args.count != 2 {
printUsage()
exit(1)
}
let archivesSourceDir = URL(fileURLWithPath: args.last!, isDirectory: true)
let keys = loadPrivateKeys(privateDSAKey)
let keys = loadPrivateKeys(privateDSAKey, privateEdString)
do {
let allUpdates = try makeAppcast(archivesSourceDir: archivesSourceDir, keys: keys, verbose: verbose)
// if a download url prefix was provided set it for each archive item
if downloadUrlPrefix != nil {
for (_, archiveItems) in allUpdates {
for archiveItem in archiveItems {
archiveItem.downloadUrlPrefix = downloadUrlPrefix
}
}
}
for (appcastFile, updates) in allUpdates {
let appcastDestPath = URL(fileURLWithPath: appcastFile, relativeTo: archivesSourceDir)
try writeAppcast(appcastDestPath: appcastDestPath, updates: updates)