xtool.git
Publicgit clone https://git.maproj.org/xtool.gitxtool.git / Sources / XToolSupport / DistributionSigning.swift
DistributionSigning.swift180 lines · 8.0 KiBRaw
| 1 | import Foundation |
| 2 | import DeveloperAPI |
| 3 | import Dependencies |
| 4 | import XKit |
| 5 | import XCLIUtils |
| 6 | import Subprocess |
| 7 | |
| 8 | /// App Store distribution signing for `xtool dev build --distribution app-store`. |
| 9 | /// |
| 10 | /// Inputs come from the release-pipeline env contract: |
| 11 | /// `XTOOL_DIST_P12_PATH` + `XTOOL_DIST_P12_PASSWORD` (a pre-made Apple |
| 12 | /// Distribution identity) and the App Store Connect API key (see |
| 13 | /// `resolveASCKey()`). The distribution certificate is extracted from the |
| 14 | /// P12 with `openssl`, an `IOS_APP_STORE` provisioning profile for the app's |
| 15 | /// bundle id is fetched (or created) via the ASC API, embedded, and the app |
| 16 | /// is signed with that identity and the profile's entitlements. |
| 17 | enum DistributionSigning { |
| 18 | struct Identity { |
| 19 | var certificate: Certificate |
| 20 | var privateKey: PrivateKey |
| 21 | /// Files holding decrypted key material; deleted after signing. |
| 22 | var tempDir: URL |
| 23 | } |
| 24 | |
| 25 | static func resolveIdentity() async throws -> Identity { |
| 26 | let env = ProcessInfo.processInfo.environment |
| 27 | guard let p12Path = env["XTOOL_DIST_P12_PATH"], let password = env["XTOOL_DIST_P12_PASSWORD"] else { |
| 28 | throw Console.Error(""" |
| 29 | --distribution app-store requires XTOOL_DIST_P12_PATH and \ |
| 30 | XTOOL_DIST_P12_PASSWORD (an Apple Distribution .p12). |
| 31 | """) |
| 32 | } |
| 33 | return try await extractIdentity(p12Path: p12Path, password: password) |
| 34 | } |
| 35 | |
| 36 | /// Extracts (cert DER, key PEM) from a PKCS12 using the `openssl` CLI. |
| 37 | /// `openssl` is present on Linux builders and macOS; parsing PKCS12 in |
| 38 | ///-process would need an OpenSSL binding xtool does not have. |
| 39 | static func extractIdentity(p12Path: String, password: String) async throws -> Identity { |
| 40 | let tempDir = FileManager.default.temporaryDirectory |
| 41 | .appendingPathComponent("xtool-dist-\(UUID().uuidString)", isDirectory: true) |
| 42 | try FileManager.default.createDirectory(at: tempDir, withIntermediateDirectories: true) |
| 43 | try FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: tempDir.path) |
| 44 | |
| 45 | func runOpenSSL(_ arguments: [String]) async throws { |
| 46 | try await Subprocess.run( |
| 47 | .name("openssl"), |
| 48 | arguments: .init(arguments), |
| 49 | output: .discarded, |
| 50 | error: .discarded |
| 51 | ).checkSuccess() |
| 52 | } |
| 53 | |
| 54 | let certPEM = tempDir.appendingPathComponent("cert.pem") |
| 55 | let keyPEM = tempDir.appendingPathComponent("key.pem") |
| 56 | let certDER = tempDir.appendingPathComponent("cert.der") |
| 57 | |
| 58 | // OpenSSL 3 may need -legacy for PKCS12 files made by older tooling. |
| 59 | func extract(_ base: [String]) async throws { |
| 60 | do { |
| 61 | try await runOpenSSL(base) |
| 62 | } catch { |
| 63 | try await runOpenSSL(base + ["-legacy"]) |
| 64 | } |
| 65 | } |
| 66 | try await extract([ |
| 67 | "pkcs12", "-in", p12Path, "-clcerts", "-nokeys", |
| 68 | "-out", certPEM.path, "-passin", "pass:\(password)", |
| 69 | ]) |
| 70 | try await extract([ |
| 71 | "pkcs12", "-in", p12Path, "-nocerts", "-nodes", |
| 72 | "-out", keyPEM.path, "-passin", "pass:\(password)", |
| 73 | ]) |
| 74 | try await runOpenSSL(["x509", "-in", certPEM.path, "-outform", "DER", "-out", certDER.path]) |
| 75 | try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: keyPEM.path) |
| 76 | |
| 77 | let certificate = try Certificate(data: Data(contentsOf: certDER)) |
| 78 | let privateKey = PrivateKey(data: try Data(contentsOf: keyPEM)) |
| 79 | return Identity(certificate: certificate, privateKey: privateKey, tempDir: tempDir) |
| 80 | } |
| 81 | |
| 82 | /// Signs `app` for App Store distribution in place. |
| 83 | static func signAppStore(_ app: URL) async throws { |
| 84 | let identity = try await resolveIdentity() |
| 85 | defer { try? FileManager.default.removeItem(at: identity.tempDir) } |
| 86 | |
| 87 | let infoURL = app.appendingPathComponent("Info.plist") |
| 88 | let infoData = try Data(contentsOf: infoURL) |
| 89 | guard let info = try PropertyListSerialization.propertyList(from: infoData, format: nil) as? [String: Any], |
| 90 | let bundleID = info["CFBundleIdentifier"] as? String else { |
| 91 | throw Console.Error("Could not read CFBundleIdentifier from '\(infoURL.path)'") |
| 92 | } |
| 93 | |
| 94 | let key = try resolveASCKey() |
| 95 | let client = DeveloperAPIClient(auth: .appStoreConnect(key)) |
| 96 | let profile = try await fetchOrCreateAppStoreProfile( |
| 97 | client: client, bundleID: bundleID, certificate: identity.certificate |
| 98 | ) |
| 99 | let digest = try profile.digest() |
| 100 | |
| 101 | let embedded = app.appendingPathComponent("embedded.mobileprovision") |
| 102 | try? FileManager.default.removeItem(at: embedded) |
| 103 | try profile.data().write(to: embedded) |
| 104 | |
| 105 | @Dependency(\.signer) var signer |
| 106 | let encoder = PropertyListEncoder() |
| 107 | encoder.outputFormat = .xml |
| 108 | try await signer.sign( |
| 109 | app: app, |
| 110 | identity: .real(identity.certificate, identity.privateKey), |
| 111 | entitlementMapping: [app: try encoder.encode(digest.entitlements)], |
| 112 | deep: true, |
| 113 | progress: { _ in } |
| 114 | ) |
| 115 | } |
| 116 | |
| 117 | private static func fetchOrCreateAppStoreProfile( |
| 118 | client: DeveloperAPIClient, |
| 119 | bundleID: String, |
| 120 | certificate: Certificate |
| 121 | ) async throws -> Mobileprovision { |
| 122 | let bundleIDs = try await client.bundleIdsGetCollection(query: .init( |
| 123 | filter_lbrack_identifier_rbrack_: [bundleID] |
| 124 | )).ok.body.json |
| 125 | guard let bundleResource = bundleIDs.data.first(where: { $0.attributes?.identifier == bundleID }) else { |
| 126 | throw Console.Error("No bundle id '\(bundleID)' registered in App Store Connect") |
| 127 | } |
| 128 | |
| 129 | // Find the ASC resource for the P12's certificate (matched by serial). |
| 130 | let certificates = try await DeveloperAPIPages { |
| 131 | try await client.certificatesGetCollection().ok.body.json |
| 132 | } next: { |
| 133 | $0.links.next |
| 134 | }.map(\.data).reduce(into: [], +=) |
| 135 | guard let certResource = certificates.first(where: { |
| 136 | $0.attributes?.serialNumber.map(certificate.hasSerialNumber) == true |
| 137 | }) else { |
| 138 | throw Console.Error("Distribution certificate from the P12 is not registered in App Store Connect") |
| 139 | } |
| 140 | |
| 141 | // Reuse an active app-store profile for this bundle id when one exists. |
| 142 | let profiles = try await DeveloperAPIPages { |
| 143 | try await client.profilesGetCollection().ok.body.json |
| 144 | } next: { |
| 145 | $0.links.next |
| 146 | }.map(\.data).reduce(into: [], +=) |
| 147 | for profile in profiles { |
| 148 | // The list response omits relationships unless included, so the |
| 149 | // deterministic name we create with is the reliable reuse key. |
| 150 | let isOurs = profile.attributes?.name == "xtool app-store \(bundleID)" |
| 151 | let matchesBundle = profile.relationships?.bundleId?.data?.id == bundleResource.id |
| 152 | guard profile.attributes?.profileType?.value1 == .iosAppStore, |
| 153 | profile.attributes?.profileState?.value1 == .active, |
| 154 | isOurs || matchesBundle, |
| 155 | let content = profile.attributes?.profileContent, |
| 156 | let data = Data(base64Encoded: content) else { continue } |
| 157 | return try Mobileprovision(data: data) |
| 158 | } |
| 159 | |
| 160 | let created = try await client.profilesCreateInstance(body: .json(.init( |
| 161 | data: .init( |
| 162 | _type: .profiles, |
| 163 | attributes: .init( |
| 164 | name: "xtool app-store \(bundleID)", |
| 165 | profileType: .init(.iosAppStore) |
| 166 | ), |
| 167 | relationships: .init( |
| 168 | bundleId: .init(data: .init(_type: .bundleIds, id: bundleResource.id)), |
| 169 | certificates: .init(data: [.init(_type: .certificates, id: certResource.id)]) |
| 170 | ) |
| 171 | ) |
| 172 | ))).created.body.json.data |
| 173 | |
| 174 | guard let content = created.attributes?.profileContent, |
| 175 | let data = Data(base64Encoded: content) else { |
| 176 | throw Console.Error("Created app-store profile had no profileContent") |
| 177 | } |
| 178 | return try Mobileprovision(data: data) |
| 179 | } |
| 180 | } |