Modern Apps git

xtool.git

Public
git clone https://git.maproj.org/xtool.git
appstore-distribution ▾

xtool.git / Sources / XToolSupport / DistributionSigning.swift

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