Modern Apps git

xtool.git

Public
git clone https://git.maproj.org/xtool.git
main ▾

xtool.git / Sources / XToolSupport / AppStoreConnect.swift

AppStoreConnect.swift485 lines · 20.8 KiBRaw
1import Foundation
2#if canImport(FoundationNetworking)
3import FoundationNetworking
4#endif
5import Crypto
6import XKit
7import XUtils
8import Subprocess
9import XCLIUtils
10
11/// Resolves the App Store Connect API key used by `xtool dist` and by
12/// app-store distribution signing.
13///
14/// Precedence: `XTOOL_ASC_KEY_ID` + `XTOOL_ASC_ISSUER_ID` +
15/// `XTOOL_ASC_KEY_PATH` (the env contract used by the Modern-Apps release
16/// pipeline), then the key saved by `xtool auth`.
17func resolveASCKey() throws -> ASCKey {
18 let env = ProcessInfo.processInfo.environment
19 if let id = env["XTOOL_ASC_KEY_ID"], let issuer = env["XTOOL_ASC_ISSUER_ID"],
20 let path = env["XTOOL_ASC_KEY_PATH"] {
21 let pem = try String(contentsOfFile: path, encoding: .utf8)
22 return ASCKey(id: id, issuerID: issuer, pem: pem)
23 }
24 if let token = try AuthToken.savedIfPresent(), case .appStoreConnect(let asc) = token {
25 return ASCKey(id: asc.id, issuerID: asc.issuerID, pem: asc.pem)
26 }
27 throw Console.Error("""
28 No App Store Connect API key available. Either set XTOOL_ASC_KEY_ID, \
29 XTOOL_ASC_ISSUER_ID and XTOOL_ASC_KEY_PATH, or log in with `xtool auth`.
30 """)
31}
32
33/// Minimal JSON value used to talk to App Store Connect without depending
34/// on the generated OpenAPI types (which only cover provisioning).
35enum ASCJSON: Sendable {
36 case object([String: ASCJSON])
37 case array([ASCJSON])
38 case string(String)
39 case number(Double)
40 case bool(Bool)
41 case null
42
43 init(parsing data: Data) throws {
44 let raw = try JSONSerialization.jsonObject(with: data)
45 self = try ASCJSON(raw: raw)
46 }
47
48 init(raw: Any) throws {
49 switch raw {
50 case let dict as [String: Any]:
51 self = .object(try dict.mapValues { try ASCJSON(raw: $0) })
52 case let array as [Any]:
53 self = .array(try array.map { try ASCJSON(raw: $0) })
54 case let string as String:
55 self = .string(string)
56 case let number as NSNumber:
57 // JSONSerialization turns booleans into NSNumber too; the
58 // objCType distinguishes them (char-backed for booleans).
59 if String(cString: number.objCType) == "c" {
60 self = .bool(number.boolValue)
61 } else {
62 self = .number(number.doubleValue)
63 }
64 case is NSNull:
65 self = .null
66 default:
67 throw Console.Error("Unexpected JSON value: \(type(of: raw))")
68 }
69 }
70
71 func serialize() throws -> Data {
72 try JSONSerialization.data(withJSONObject: rawObject, options: [.sortedKeys])
73 }
74
75 var rawObject: Any {
76 switch self {
77 case .object(let dict): dict.mapValues { $0.rawObject }
78 case .array(let array): array.map { $0.rawObject }
79 case .string(let string): string
80 case .number(let number): number
81 case .bool(let bool): bool
82 case .null: NSNull()
83 }
84 }
85
86 subscript(key: String) -> ASCJSON? {
87 guard case .object(let dict) = self else { return nil }
88 return dict[key]
89 }
90
91 var stringValue: String? {
92 guard case .string(let string) = self else { return nil }
93 return string
94 }
95
96 var boolValue: Bool? {
97 guard case .bool(let bool) = self else { return nil }
98 return bool
99 }
100
101 var arrayValue: [ASCJSON]? {
102 guard case .array(let array) = self else { return nil }
103 return array
104 }
105
106 var objectValue: [String: ASCJSON]? {
107 guard case .object(let dict) = self else { return nil }
108 return dict
109 }
110}
111
112/// Thin App Store Connect REST client (build uploads + review submission).
113///
114/// The base URL can be overridden with `XTOOL_ASC_BASE_URL`, which the tests
115/// use to run against a local stub server.
116struct AppStoreConnectClient: Sendable {
117 var key: ASCKey
118 var baseURL: URL
119
120 init(key: ASCKey) {
121 self.key = key
122 let override = ProcessInfo.processInfo.environment["XTOOL_ASC_BASE_URL"]
123 self.baseURL = URL(string: override ?? "https://api.appstoreconnect.apple.com")!
124 }
125
126 func request(
127 method: String,
128 path: String,
129 query: [String: String] = [:],
130 body: ASCJSON? = nil
131 ) async throws -> ASCJSON {
132 var components = URLComponents(url: baseURL.appendingPathComponent(path), resolvingAgainstBaseURL: false)!
133 if !query.isEmpty {
134 components.queryItems = query.map { URLQueryItem(name: $0.key, value: $0.value) }.sorted { $0.name < $1.name }
135 }
136 var request = URLRequest(url: components.url!)
137 request.httpMethod = method
138 request.setValue("Bearer \(try await key.makeJWT())", forHTTPHeaderField: "Authorization")
139 if let body {
140 request.httpBody = try body.serialize()
141 request.setValue("application/json", forHTTPHeaderField: "Content-Type")
142 }
143 let (data, response) = try await URLSession.shared.data(for: request)
144 guard let http = response as? HTTPURLResponse else {
145 throw Console.Error("App Store Connect: no HTTP response for \(method) \(path)")
146 }
147 guard (200..<300).contains(http.statusCode) else {
148 throw Console.Error(
149 "App Store Connect \(method) \(path) failed: HTTP \(http.statusCode)\n"
150 + String(decoding: data, as: UTF8.self)
151 )
152 }
153 if data.isEmpty { return .object([:]) }
154 return try ASCJSON(parsing: data)
155 }
156
157 // MARK: - Build upload
158
159 struct IPAMetadata: Sendable {
160 var bundleID: String
161 var version: String
162 var buildNumber: String
163 }
164
165 /// Reads CFBundleIdentifier / CFBundleShortVersionString / CFBundleVersion
166 /// from the `.app` inside an `.ipa` (via `unzip`, available on builders).
167 static func ipaMetadata(at ipa: URL) async throws -> IPAMetadata {
168 let listing = try await Subprocess.run(
169 .name("unzip"),
170 arguments: ["-Z1", ipa.path],
171 output: .string(limit: .max)
172 ).checkSuccess().standardOutput
173
174 guard let plistPath = listing.split(separator: "\n").map(String.init)
175 .first(where: { $0.hasPrefix("Payload/") && $0.hasSuffix(".app/Info.plist") }) else {
176 throw Console.Error("No Payload/*.app/Info.plist found in '\(ipa.path)'")
177 }
178 let plistData = try await Subprocess.run(
179 .name("unzip"),
180 arguments: ["-p", ipa.path, plistPath],
181 output: .data(limit: .max)
182 ).checkSuccess().standardOutput
183
184 let plist = try PropertyListSerialization.propertyList(from: plistData, format: nil)
185 guard let dict = plist as? [String: Any],
186 let bundleID = dict["CFBundleIdentifier"] as? String,
187 let version = dict["CFBundleShortVersionString"] as? String,
188 let buildNumber = dict["CFBundleVersion"] as? String else {
189 throw Console.Error("Info.plist in '\(ipa.path)' is missing bundle id / version keys")
190 }
191 return IPAMetadata(bundleID: bundleID, version: version, buildNumber: buildNumber)
192 }
193
194 struct Checksums: Sendable {
195 var md5: String
196 var sha256: String
197 }
198
199 static func checksums(of file: URL) throws -> Checksums {
200 let handle = try FileHandle(forReadingFrom: file)
201 defer { try? handle.close() }
202 var md5 = Insecure.MD5()
203 var sha256 = SHA256()
204 while let chunk = try handle.read(upToCount: 1 << 20), !chunk.isEmpty {
205 md5.update(data: chunk)
206 sha256.update(data: chunk)
207 }
208 func hex(_ digest: some Sequence<UInt8>) -> String {
209 digest.map { String(format: "%02x", $0) }.joined()
210 }
211 return Checksums(md5: hex(md5.finalize()), sha256: hex(sha256.finalize()))
212 }
213
214 struct UploadResult: Sendable {
215 var buildID: String
216 var state: String
217 }
218
219 /// Uploads an `.ipa` using the App Store Connect build-uploads API:
220 /// create buildUpload -> create buildUploadFile -> PUT each signed chunk
221 /// -> mark both uploaded. Returns the resulting build id when Apple has
222 /// linked one, otherwise the build-upload id.
223 func uploadIPA(at ipa: URL) async throws -> UploadResult {
224 let metadata = try await Self.ipaMetadata(at: ipa)
225 let fileSize = try FileManager.default.attributesOfItem(atPath: ipa.path)[.size] as? Int ?? 0
226
227 guard let appID = try await findAppID(bundleID: metadata.bundleID) else {
228 throw Console.Error("No App Store Connect app found for bundle id '\(metadata.bundleID)'")
229 }
230
231 let upload = try await request(method: "POST", path: "/v1/buildUploads", body: .object([
232 "data": .object([
233 "type": .string("buildUploads"),
234 "attributes": .object([
235 "cfBundleShortVersionString": .string(metadata.version),
236 "cfBundleVersion": .string(metadata.buildNumber),
237 "platform": .string("IOS"),
238 ]),
239 "relationships": .object([
240 "app": .object(["data": .object(["type": .string("apps"), "id": .string(appID)])])
241 ]),
242 ]),
243 ]))
244 guard let uploadID = upload["data"]?["id"]?.stringValue else {
245 throw Console.Error("buildUploads create returned no id: \(upload)")
246 }
247
248 let file = try await request(method: "POST", path: "/v1/buildUploadFiles", body: .object([
249 "data": .object([
250 "type": .string("buildUploadFiles"),
251 "attributes": .object([
252 "assetType": .string("ASSET"),
253 "fileName": .string(ipa.lastPathComponent),
254 "fileSize": .number(Double(fileSize)),
255 "uti": .string("com.apple.ipa"),
256 ]),
257 "relationships": .object([
258 "buildUpload": .object(["data": .object(["type": .string("buildUploads"), "id": .string(uploadID)])])
259 ]),
260 ]),
261 ]))
262 guard let fileID = file["data"]?["id"]?.stringValue,
263 let operations = file["data"]?["attributes"]?["uploadOperations"]?.arrayValue else {
264 throw Console.Error("buildUploadFiles create returned no upload operations: \(file)")
265 }
266
267 let data = try Data(contentsOf: ipa)
268 for operation in operations {
269 _ = try await uploadChunk(operation: operation, data: data)
270 }
271
272 _ = try await request(method: "PATCH", path: "/v1/buildUploadFiles/\(fileID)", body: .object([
273 "data": .object([
274 "type": .string("buildUploadFiles"),
275 "id": .string(fileID),
276 "attributes": .object([
277 "uploaded": .bool(true),
278 ]),
279 ]),
280 ]))
281 // Marking the file uploaded starts processing; buildUploads itself
282 // does not support UPDATE, so read back its state instead.
283 let finished = try await request(method: "GET", path: "/v1/buildUploads/\(uploadID)")
284
285 let state = finished["data"]?["attributes"]?["state"]?["state"]?.stringValue
286 ?? upload["data"]?["attributes"]?["state"]?["state"]?.stringValue ?? "UNKNOWN"
287 // Apple links a Build once processing starts; surface it when present.
288 let linkedBuild = finished["data"]?["relationships"]?["build"]?["data"]?["id"]?.stringValue
289 ?? finished["included"]?.arrayValue?
290 .first { $0["type"]?.stringValue == "builds" }?["id"]?.stringValue
291 return UploadResult(buildID: linkedBuild ?? uploadID, state: state)
292 }
293
294 /// Uploads one chunk; returns the chunk's MD5 hex digest.
295 private func uploadChunk(operation: ASCJSON, data: Data) async throws -> String {
296 guard let urlString = operation["url"]?.stringValue, let url = URL(string: urlString),
297 let method = operation["method"]?.stringValue,
298 let offsetJSON = operation["offset"], let lengthJSON = operation["length"],
299 case .number(let offset) = offsetJSON, case .number(let length) = lengthJSON else {
300 throw Console.Error("Malformed upload operation: \(operation)")
301 }
302 let chunk = data.subdata(in: Int(offset)..<Int(offset + length))
303 let digest = Insecure.MD5.hash(data: chunk).map { String(format: "%02x", $0) }.joined()
304 var request = URLRequest(url: url)
305 request.httpMethod = method
306 for header in operation["requestHeaders"]?.arrayValue ?? [] {
307 if let name = header["name"]?.stringValue, let value = header["value"]?.stringValue {
308 request.setValue(value, forHTTPHeaderField: name)
309 }
310 }
311 request.httpBody = chunk
312 let (_, response) = try await URLSession.shared.data(for: request)
313 guard let http = response as? HTTPURLResponse, (200..<300).contains(http.statusCode) else {
314 throw Console.Error("Chunk upload failed: \(String(describing: response))")
315 }
316 return digest
317 }
318
319 // MARK: - Review submission
320
321 func findAppID(bundleID: String) async throws -> String? {
322 let response = try await request(
323 method: "GET", path: "/v1/apps",
324 query: ["filter[bundleId]": bundleID, "fields[apps]": "bundleId"]
325 )
326 return response["data"]?.arrayValue?
327 .first { $0["attributes"]?["bundleId"]?.stringValue == bundleID }?["id"]?.stringValue
328 }
329
330 struct SubmissionResult: Sendable {
331 var submissionID: String
332 var state: String
333 }
334
335 /// Ensures an App Store version exists with the given `whatsNew`, attaches
336 /// the uploaded build, and submits it for review.
337 func submitForReview(
338 bundleID: String,
339 version: String,
340 buildNumber: String,
341 whatsNew: String,
342 locale: String
343 ) async throws -> SubmissionResult {
344 guard let appID = try await findAppID(bundleID: bundleID) else {
345 throw Console.Error("No App Store Connect app found for bundle id '\(bundleID)'")
346 }
347
348 let versionID = try await ensureVersion(appID: appID, version: version)
349 try await upsertWhatsNew(versionID: versionID, whatsNew: whatsNew, locale: locale)
350
351 guard let buildID = try await findBuild(appID: appID, buildNumber: buildNumber, version: version) else {
352 throw Console.Error("No processed build '\(buildNumber)' (\(version)) found for app \(appID) yet")
353 }
354 try await ensureEncryptionDeclaration(buildID: buildID)
355 _ = try await request(method: "PATCH", path: "/v1/appStoreVersions/\(versionID)/relationships/build", body: .object([
356 "data": .object(["type": .string("builds"), "id": .string(buildID)]),
357 ]))
358
359 // Reuse an open submission from a previous attempt when one exists.
360 let submissionID: String
361 let openSubmissions = try await request(
362 method: "GET", path: "/v1/apps/\(appID)/reviewSubmissions",
363 query: ["filter[state]": "READY_FOR_REVIEW", "fields[reviewSubmissions]": "state,platform"]
364 )
365 if let existing = openSubmissions["data"]?.arrayValue?.first?["id"]?.stringValue {
366 submissionID = existing
367 } else {
368 let submission = try await request(method: "POST", path: "/v1/reviewSubmissions", body: .object([
369 "data": .object([
370 "type": .string("reviewSubmissions"),
371 "attributes": .object(["platform": .string("IOS")]),
372 "relationships": .object([
373 "app": .object(["data": .object(["type": .string("apps"), "id": .string(appID)])])
374 ]),
375 ]),
376 ]))
377 guard let id = submission["data"]?["id"]?.stringValue else {
378 throw Console.Error("reviewSubmissions create returned no id: \(submission)")
379 }
380 submissionID = id
381 }
382 _ = try await request(method: "POST", path: "/v1/reviewSubmissionItems", body: .object([
383 "data": .object([
384 "type": .string("reviewSubmissionItems"),
385 "relationships": .object([
386 "reviewSubmission": .object(["data": .object(["type": .string("reviewSubmissions"), "id": .string(submissionID)])]),
387 "appStoreVersion": .object(["data": .object(["type": .string("appStoreVersions"), "id": .string(versionID)])]),
388 ]),
389 ]),
390 ]))
391 let submitted = try await request(method: "PATCH", path: "/v1/reviewSubmissions/\(submissionID)", body: .object([
392 "data": .object([
393 "type": .string("reviewSubmissions"),
394 "id": .string(submissionID),
395 "attributes": .object(["submitted": .bool(true)]),
396 ]),
397 ]))
398 let state = submitted["data"]?["attributes"]?["state"]?.stringValue ?? "SUBMITTED"
399 return SubmissionResult(submissionID: submissionID, state: state)
400 }
401
402 private func ensureVersion(appID: String, version: String) async throws -> String {
403 let existing = try await request(
404 method: "GET", path: "/v1/apps/\(appID)/appStoreVersions",
405 query: ["filter[versionString]": version, "filter[platform]": "IOS", "fields[appStoreVersions]": "versionString"]
406 )
407 if let id = existing["data"]?.arrayValue?
408 .first(where: { $0["attributes"]?["versionString"]?.stringValue == version })?["id"]?.stringValue {
409 return id
410 }
411 let created = try await request(method: "POST", path: "/v1/appStoreVersions", body: .object([
412 "data": .object([
413 "type": .string("appStoreVersions"),
414 "attributes": .object(["platform": .string("IOS"), "versionString": .string(version)]),
415 "relationships": .object([
416 "app": .object(["data": .object(["type": .string("apps"), "id": .string(appID)])])
417 ]),
418 ]),
419 ]))
420 guard let id = created["data"]?["id"]?.stringValue else {
421 throw Console.Error("appStoreVersions create returned no id: \(created)")
422 }
423 return id
424 }
425
426 private func upsertWhatsNew(versionID: String, whatsNew: String, locale: String) async throws {
427 let existing = try await request(
428 method: "GET", path: "/v1/appStoreVersions/\(versionID)/appStoreVersionLocalizations",
429 query: ["fields[appStoreVersionLocalizations]": "locale,whatsNew"]
430 )
431 if let locID = existing["data"]?.arrayValue?
432 .first(where: { $0["attributes"]?["locale"]?.stringValue == locale })?["id"]?.stringValue {
433 _ = try await request(method: "PATCH", path: "/v1/appStoreVersionLocalizations/\(locID)", body: .object([
434 "data": .object([
435 "type": .string("appStoreVersionLocalizations"),
436 "id": .string(locID),
437 "attributes": .object(["whatsNew": .string(whatsNew)]),
438 ]),
439 ]))
440 } else {
441 _ = try await request(method: "POST", path: "/v1/appStoreVersionLocalizations", body: .object([
442 "data": .object([
443 "type": .string("appStoreVersionLocalizations"),
444 "attributes": .object(["locale": .string(locale), "whatsNew": .string(whatsNew)]),
445 "relationships": .object([
446 "appStoreVersion": .object(["data": .object(["type": .string("appStoreVersions"), "id": .string(versionID)])])
447 ]),
448 ]),
449 ]))
450 }
451 }
452
453 /// App Store review requires an export-compliance answer on the build.
454 /// Declares `usesNonExemptEncryption=false` (standard exempt crypto)
455 /// when the build has no declaration yet.
456 private func ensureEncryptionDeclaration(buildID: String) async throws {
457 let build = try await request(
458 method: "GET", path: "/v1/builds/\(buildID)",
459 query: ["fields[builds]": "usesNonExemptEncryption"]
460 )
461 guard build["data"]?["attributes"]?["usesNonExemptEncryption"]?.boolValue == nil else { return }
462 _ = try await request(method: "PATCH", path: "/v1/builds/\(buildID)", body: .object([
463 "data": .object([
464 "type": .string("builds"),
465 "id": .string(buildID),
466 "attributes": .object(["usesNonExemptEncryption": .bool(false)]),
467 ]),
468 ]))
469 }
470
471 private func findBuild(appID: String, buildNumber: String, version: String) async throws -> String? {
472 let response = try await request(
473 method: "GET", path: "/v1/builds",
474 query: [
475 "filter[app]": appID,
476 "filter[version]": buildNumber,
477 "sort": "-uploadedDate",
478 "limit": "20",
479 "fields[builds]": "version,uploadedDate,processingState",
480 ]
481 )
482 return response["data"]?.arrayValue?
483 .first { $0["attributes"]?["version"]?.stringValue == buildNumber }?["id"]?.stringValue
484 }
485}