Modern Apps git

xtool.git

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

xtool.git / Sources / XToolSupport / AppStoreConnect.swift

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