forked from Tinder/sign-here
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathiTunesConnectService.swift
539 lines (519 loc) · 21.8 KB
/
iTunesConnectService.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
//
// iTunesConnectService.swift
// Services
//
// Created by Maxwell Elliott on 04/05/23.
//
import CoreLibrary
import Foundation
import PathKit
/// @mockable
internal protocol iTunesConnectService {
func fetchActiveCertificates(
jsonWebToken: String,
opensslPath: String,
privateKeyPath: String,
certificateType: String
) throws -> [DownloadCertificateResponse.DownloadCertificateResponseData]
func createCertificate(
jsonWebToken: String,
csr: Path,
certificateType: String
) throws -> CreateCertificateResponse
func determineBundleIdITCId(
jsonWebToken: String,
bundleIdentifier: String,
bundleIdentifierName: String?,
platform: String
) throws -> String
func fetchITCDeviceIDs(jsonWebToken: String) throws -> Set<String>
func createProfile(
jsonWebToken: String,
bundleId: String,
certificateId: String,
deviceIDs: Set<String>,
profileType: String,
profileName: String?
) throws -> CreateProfileResponse
func deleteProvisioningProfile(
jsonWebToken: String,
id: String
) throws
func fetchProvisioningProfile(
jsonWebToken: String,
name: String
) throws -> [ProfileResponseData]
}
internal class iTunesConnectServiceImp: iTunesConnectService {
enum Error: Swift.Error, CustomStringConvertible {
case invalidURL(string: String)
case unableToCreateURL(urlComponents: URLComponents)
case unableToDetermineITCIdForBundleId(bundleIdentifier: String, platform: String)
case unableToDetermineModulusForCertificate(output: ShellOutput)
case unableToDetermineModulusForPrivateKey(privateKeyPath: String, output: ShellOutput)
case unableToBase64DecodeCertificate(displayName: String)
case unableToDeleteProvisioningProfile(id: String, responseData: Data)
case unableToDecodeResponse(responseData: Data, decodingError: DecodingError)
var description: String {
switch self {
case let .invalidURL(string: string):
return """
[iTunesConnectServiceImp] Invalid url
- url string: \(string)
"""
case let .unableToCreateURL(urlComponents: urlComponents):
return """
[iTunesConnectServiceImp] Unable to create url for itunes connect request from url components: \(urlComponents.description)
"""
case let .unableToDetermineITCIdForBundleId(bundleIdentifier: bundleIdentifier, platform: platform):
return """
[iTunesConnectServiceImp] Unable to determine iTunesConnect API ID for bundle identifier
- Bundle Identifier: \(bundleIdentifier)
- Platform: \(platform)
"""
case let .unableToDetermineModulusForCertificate(output: output):
return """
[iTunesConnectServiceImp] Unable to determine modulus for certificate
- Output: \(output.outputString)
- Error: \(output.errorString)
"""
case let .unableToDetermineModulusForPrivateKey(privateKeyPath: privateKeyPath, output: output):
return """
[iTunesConnectServiceImp] Unable to determine modulus for private key
- Private Key: \(privateKeyPath)
- Output: \(output.outputString)
- Error: \(output.errorString)
"""
case let .unableToBase64DecodeCertificate(displayName: displayName):
return """
[iTunesConnectServiceImp] Unable to base 64 decode certificate
- Certificate display name: \(displayName)
"""
case let .unableToDeleteProvisioningProfile(id: id, responseData: responseData):
return """
[iTunesConnectServiceImp] Unable to delete provisioning profile
- id: \(id)
- Response: \(String(data: responseData, encoding: .utf8) ?? "unknown")
"""
case let .unableToDecodeResponse(responseData: responseData, decodingError: decodingError):
return """
[iTunesConnectServiceImp] Unable to decode response
- Decoding Error: \(decodingError)
- Response: \(String(data: responseData, encoding: .utf8) ?? "unknown")
"""
}
}
}
private enum Constants {
static let applicationJSONHeaderValue: String = "application/json"
static let contentTypeHeaderName: String = "Content-Type"
static let httpsScheme: String = "https"
static let itcHost: String = "api.appstoreconnect.apple.com"
}
private let network: Network
private let files: Files
private let shell: Shell
private let clock: Clock
init(
network: Network,
files: Files,
shell: Shell,
clock: Clock
) {
self.network = network
self.files = files
self.shell = shell
self.clock = clock
}
func fetchActiveCertificates(
jsonWebToken: String,
opensslPath: String,
privateKeyPath: String,
certificateType: String
) throws -> [DownloadCertificateResponse.DownloadCertificateResponseData] {
let currentDate: Date = clock.now()
var urlComponents: URLComponents = .init()
urlComponents.scheme = Constants.httpsScheme
urlComponents.host = Constants.itcHost
urlComponents.path = "/v1/certificates"
urlComponents.queryItems = [
.init(name: "filter[certificateType]", value: certificateType),
.init(name: "limit", value: "200")
]
guard let url: URL = urlComponents.url
else {
throw Error.unableToCreateURL(urlComponents: urlComponents)
}
var certificatesData: [DownloadCertificateResponse.DownloadCertificateResponseData] = []
var request: URLRequest = .init(url: url)
request.setValue("Bearer \(jsonWebToken)", forHTTPHeaderField: "Authorization")
let jsonDecoder: JSONDecoder = createITCApiJSONDecoder()
let data: Data = try network.execute(request: request)
do {
var response: DownloadCertificateResponse = try jsonDecoder.decode(
DownloadCertificateResponse.self,
from: data
)
certificatesData = response.data
while let next: String = response.links.next,
let nextURL: URL = .init(string: next) {
response = try performPagedRequest(
url: nextURL,
jsonWebToken: jsonWebToken
)
certificatesData.append(contentsOf: response.data)
}
guard !certificatesData.isEmpty
else {
return []
}
} catch let decodingError as DecodingError {
throw Error.unableToDecodeResponse(responseData: data, decodingError: decodingError)
}
let privateKeyModulus: String = try determinePrivateKeyModulus(opensslPath: opensslPath, privateKeyPath: privateKeyPath)
return try certificatesData
.filter { certificateData in
certificateData.attributes.expirationDate > currentDate
}
.filter { certificateData in
try certificateMatchesPrivateKey(
certificateData: certificateData,
privateKeyModulus: privateKeyModulus,
opensslPath: opensslPath
)
}
}
func createCertificate(
jsonWebToken: String,
csr: Path,
certificateType: String
) throws -> CreateCertificateResponse {
let urlString: String = "https://api.appstoreconnect.apple.com/v1/certificates"
guard let url: URL = .init(string: urlString)
else {
throw Error.invalidURL(string: urlString)
}
var request: URLRequest = .init(url: url)
request.setValue("Bearer \(jsonWebToken)", forHTTPHeaderField: "Authorization")
request.httpBody = try JSONEncoder().encode(
CreateCertificateRequest(
data: .init(
attributes: .init(
certificateType: certificateType,
csrContent: try files.read(csr)
),
type: "certificates"
)
)
)
request.setValue(Constants.applicationJSONHeaderValue, forHTTPHeaderField: "Accept")
request.setValue(Constants.applicationJSONHeaderValue, forHTTPHeaderField: Constants.contentTypeHeaderName)
request.httpMethod = "POST"
let data: Data = try network.execute(request: request)
do {
return try createITCApiJSONDecoder().decode(
CreateCertificateResponse.self,
from: data
)
} catch let decodingError as DecodingError {
throw Error.unableToDecodeResponse(responseData: data, decodingError: decodingError)
}
}
func determineBundleIdITCId(
jsonWebToken: String,
bundleIdentifier: String,
bundleIdentifierName: String?,
platform: String
) throws -> String {
var urlComponents: URLComponents = .init()
urlComponents.scheme = Constants.httpsScheme
urlComponents.host = Constants.itcHost
urlComponents.path = "/v1/bundleIds"
urlComponents.queryItems = [
.init(name: "filter[identifier]", value: bundleIdentifier),
.init(name: "filter[platform]", value: "IOS"),
.init(name: "limit", value: "200")
]
guard let url: URL = urlComponents.url
else {
throw Error.unableToCreateURL(urlComponents: urlComponents)
}
var request: URLRequest = .init(url: url)
request.setValue("Bearer \(jsonWebToken)", forHTTPHeaderField: "Authorization")
request.setValue(Constants.applicationJSONHeaderValue, forHTTPHeaderField: "Accept")
request.setValue(Constants.applicationJSONHeaderValue, forHTTPHeaderField: Constants.contentTypeHeaderName)
request.httpMethod = "GET"
let data: Data = try network.execute(request: request)
return try makeFirstITCIdForBundleId(
data: data,
bundleIdentifier: bundleIdentifier,
bundleIdentifierName: bundleIdentifierName,
platform: platform
)
}
private func makeFirstITCIdForBundleId(
data: Data,
bundleIdentifier: String,
bundleIdentifierName: String?,
platform: String
) throws -> String {
do {
let listBundleIDsResponse: ListBundleIDsResponse = try createITCApiJSONDecoder().decode(ListBundleIDsResponse.self, from: data)
guard let bundleIdITCId: String = listBundleIDsResponse.data.compactMap({ bundleData in
guard bundleData.attributes.identifier == bundleIdentifier
else {
return nil
}
if let bundleIdentifierName: String = bundleIdentifierName {
guard bundleIdentifierName == bundleData.attributes.name
else {
return nil
}
}
return bundleData.id
}).first
else {
throw Error.unableToDetermineITCIdForBundleId(
bundleIdentifier: bundleIdentifier,
platform: platform
)
}
return bundleIdITCId
} catch let decodingError as DecodingError {
throw Error.unableToDecodeResponse(responseData: data, decodingError: decodingError)
}
}
func fetchITCDeviceIDs(jsonWebToken: String) throws -> Set<String> {
var urlComponents: URLComponents = .init()
urlComponents.scheme = Constants.httpsScheme
urlComponents.host = Constants.itcHost
urlComponents.path = "/v1/devices"
urlComponents.queryItems = [
.init(name: "filter[status]", value: "ENABLED"),
.init(name: "filter[platform]", value: "IOS"),
.init(name: "limit", value: "200")
]
guard let url: URL = urlComponents.url
else {
throw Error.unableToCreateURL(urlComponents: urlComponents)
}
var request: URLRequest = .init(url: url)
request.setValue("Bearer \(jsonWebToken)", forHTTPHeaderField: "Authorization")
request.setValue(Constants.applicationJSONHeaderValue, forHTTPHeaderField: "Accept")
request.setValue(Constants.applicationJSONHeaderValue, forHTTPHeaderField: Constants.contentTypeHeaderName)
request.httpMethod = "GET"
let jsonDecoder: JSONDecoder = createITCApiJSONDecoder()
let data: Data = try network.execute(request: request)
do {
var response: ListDevicesResponse = try jsonDecoder.decode(
ListDevicesResponse.self,
from: data
)
var deviceData: [ListDevicesResponse.Device] = response.data
while let next: String = response.links.next,
let nextURL: URL = .init(string: next) {
response = try performPagedRequest(url: nextURL, jsonWebToken: jsonWebToken)
deviceData.append(contentsOf: response.data)
}
return .init(deviceData.map { device in
device.id
})
} catch let decodingError as DecodingError {
throw Error.unableToDecodeResponse(responseData: data, decodingError: decodingError)
}
}
private func performPagedRequest<T: Decodable>(url: URL, jsonWebToken: String) throws -> T {
var pagedRequest: URLRequest = .init(url: url)
pagedRequest.setValue("Bearer \(jsonWebToken)", forHTTPHeaderField: "Authorization")
let jsonDecoder: JSONDecoder = createITCApiJSONDecoder()
let data: Data = try network.execute(request: pagedRequest)
do {
return try jsonDecoder.decode(
T.self,
from: data
)
} catch let decodingError as DecodingError {
throw Error.unableToDecodeResponse(responseData: data, decodingError: decodingError)
}
}
func createProfile(
jsonWebToken: String,
bundleId: String,
certificateId: String,
deviceIDs: Set<String>,
profileType: String,
profileName: String? = nil
) throws -> CreateProfileResponse {
let urlString: String = "https://api.appstoreconnect.apple.com/v1/profiles"
guard let url: URL = .init(string: urlString)
else {
throw Error.invalidURL(string: urlString)
}
var request: URLRequest = .init(url: url)
request.setValue(Constants.applicationJSONHeaderValue, forHTTPHeaderField: "Accept")
request.setValue(Constants.applicationJSONHeaderValue, forHTTPHeaderField: Constants.contentTypeHeaderName)
request.setValue("Bearer \(jsonWebToken)", forHTTPHeaderField: "Authorization")
request.httpMethod = "POST"
let profileName = profileName ?? "\(certificateId)_\(profileType)_\(clock.now().timeIntervalSince1970)"
var devices: CreateProfileRequest.CreateProfileRequestData.Relationships.Devices? = nil
// ME: App Store profiles cannot use UDIDs
if ProfileType(rawValue: profileType).usesDevices {
devices = .init(
data: deviceIDs.sorted().map {
CreateProfileRequest.CreateProfileRequestData.Relationships.Devices.DevicesData(
id: $0,
type: "devices"
)
}
)
}
request.httpBody = try JSONEncoder().encode(CreateProfileRequest(
data: .init(
attributes: .init(
name: profileName,
profileType: profileType
),
relationships: .init(
bundleId: .init(
data: .init(
id: bundleId,
type: "bundleIds"
)
),
certificates: .init(
data: [
.init(
id: certificateId,
type: "certificates"
)
]
),
devices: devices
),
type: "profiles"
)
))
let jsonDecoder: JSONDecoder = createITCApiJSONDecoder()
let data: Data = try network.execute(request: request)
do {
return try jsonDecoder.decode(
CreateProfileResponse.self,
from: data
)
} catch let decodingError as DecodingError {
throw Error.unableToDecodeResponse(responseData: data, decodingError: decodingError)
}
}
func deleteProvisioningProfile(
jsonWebToken: String,
id: String
) throws {
var urlComponents: URLComponents = .init()
urlComponents.scheme = Constants.httpsScheme
urlComponents.host = Constants.itcHost
urlComponents.path = "/v1/profiles/\(id)"
guard let url: URL = urlComponents.url
else {
throw Error.unableToCreateURL(urlComponents: urlComponents)
}
var request: URLRequest = .init(url: url)
request.setValue("Bearer \(jsonWebToken)", forHTTPHeaderField: "Authorization")
request.setValue(Constants.applicationJSONHeaderValue, forHTTPHeaderField: "Accept")
request.setValue(Constants.applicationJSONHeaderValue, forHTTPHeaderField: Constants.contentTypeHeaderName)
request.httpMethod = "DELETE"
let tuple: (data: Data, _, statusCode: Int) = try network.executeWithStatusCode(request: request)
guard tuple.statusCode == 204
else {
throw Error.unableToDeleteProvisioningProfile(id: id, responseData: tuple.data)
}
}
func fetchProvisioningProfile(
jsonWebToken: String,
name: String
) throws -> [ProfileResponseData] {
var urlComponents: URLComponents = .init()
urlComponents.scheme = Constants.httpsScheme
urlComponents.host = Constants.itcHost
urlComponents.path = "/v1/profiles"
urlComponents.queryItems = [
.init(name: "filter[name]", value: name),
.init(name: "include", value: "devices")
]
guard let url: URL = urlComponents.url
else {
throw Error.unableToCreateURL(urlComponents: urlComponents)
}
var request: URLRequest = .init(url: url)
request.setValue("Bearer \(jsonWebToken)", forHTTPHeaderField: "Authorization")
request.setValue(Constants.applicationJSONHeaderValue, forHTTPHeaderField: "Accept")
request.setValue(Constants.applicationJSONHeaderValue, forHTTPHeaderField: Constants.contentTypeHeaderName)
request.httpMethod = "GET"
let jsonDecoder: JSONDecoder = createITCApiJSONDecoder()
let data: Data = try network.execute(request: request)
do {
return try jsonDecoder.decode(
GetProfilesResponse.self,
from: data
).data
} catch let decodingError as DecodingError {
throw Error.unableToDecodeResponse(responseData: data, decodingError: decodingError)
}
}
private func createITCApiJSONDecoder() -> JSONDecoder {
let jsonDecoder: JSONDecoder = .init()
let dateFormatter: DateFormatter = .init()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"
jsonDecoder.dateDecodingStrategy = .formatted(dateFormatter)
return jsonDecoder
}
private func certificateMatchesPrivateKey(
certificateData: DownloadCertificateResponse.DownloadCertificateResponseData,
privateKeyModulus: String,
opensslPath: String
) throws -> Bool {
let temporaryCerPath: Path = try files.uniqueTemporaryPath() + "validate_private_key.cer"
guard let data: Data = .init(base64Encoded: certificateData.attributes.certificateContent)
else {
throw Error.unableToBase64DecodeCertificate(displayName: certificateData.attributes.displayName)
}
try files.write(data, to: temporaryCerPath)
defer {
try? files.delete(temporaryCerPath)
}
let output: ShellOutput = shell.execute([
opensslPath,
"x509",
"-inform",
"der",
"-noout",
"-modulus",
"-in",
temporaryCerPath.string
])
guard output.isSuccessful
else {
throw Error.unableToDetermineModulusForCertificate(
output: output
)
}
return output.outputString.trimmingCharacters(in: .newlines) == privateKeyModulus
}
private func determinePrivateKeyModulus(opensslPath: String, privateKeyPath: String) throws -> String {
let output: ShellOutput = shell.execute([
opensslPath,
"rsa",
"-noout",
"-modulus",
"-in",
privateKeyPath
])
guard output.isSuccessful
else {
throw Error.unableToDetermineModulusForPrivateKey(
privateKeyPath: privateKeyPath,
output: output
)
}
return output.outputString.trimmingCharacters(in: .newlines)
}
}