-
Notifications
You must be signed in to change notification settings - Fork 12
/
profiles.go
510 lines (420 loc) · 16.4 KB
/
profiles.go
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
package autocodesign
import (
"errors"
"fmt"
"strings"
"time"
"github.com/bitrise-io/go-utils/log"
"github.com/bitrise-io/go-utils/retry"
"github.com/bitrise-io/go-utils/sliceutil"
"github.com/bitrise-io/go-xcode/profileutil"
"github.com/bitrise-io/go-xcode/v2/autocodesign/devportalclient/appstoreconnect"
"github.com/bitrise-io/go-xcode/xcodeproject/serialized"
)
func appIDName(bundleID string) string {
prefix := ""
if strings.HasSuffix(bundleID, ".*") {
prefix = "Wildcard "
}
r := strings.NewReplacer(".", " ", "_", " ", "-", " ", "*", " ")
return prefix + "Bitrise " + r.Replace(bundleID)
}
func ensureProfiles(profileClient DevPortalClient, distrType DistributionType,
certsByType map[appstoreconnect.CertificateType][]Certificate, app AppLayout,
devPortalDeviceIDs []string, minProfileDaysValid int) (*AppCodesignAssets, error) {
// Ensure Profiles
bundleIDByBundleIDIdentifer := map[string]*appstoreconnect.BundleID{}
containersByBundleID := map[string][]string{}
profileManager := profileManager{
client: profileClient,
bundleIDByBundleIDIdentifer: bundleIDByBundleIDIdentifer,
containersByBundleID: containersByBundleID,
}
fmt.Println()
log.Infof("Checking %s provisioning profiles", distrType)
certificate, err := SelectCertificate(certsByType, distrType)
if err != nil {
return nil, err
}
codesignAssets := AppCodesignAssets{
ArchivableTargetProfilesByBundleID: map[string]Profile{},
UITestTargetProfilesByBundleID: map[string]Profile{},
Certificate: certificate.CertificateInfo,
}
certType := CertificateTypeByDistribution[distrType]
certs := certsByType[certType]
var certIDs []string
for _, cert := range certs {
certIDs = append(certIDs, cert.ID)
}
platformProfileTypes, ok := PlatformToProfileTypeByDistribution[app.Platform]
if !ok {
return nil, fmt.Errorf("no profiles for platform: %s", app.Platform)
}
profileType := platformProfileTypes[distrType]
for bundleIDIdentifier, entitlements := range app.EntitlementsByArchivableTargetBundleID {
var profileDeviceIDs []string
if DistributionTypeRequiresDeviceList([]DistributionType{distrType}) {
profileDeviceIDs = devPortalDeviceIDs
}
profile, err := profileManager.ensureProfileWithRetry(profileType, bundleIDIdentifier, entitlements, certIDs, profileDeviceIDs, minProfileDaysValid)
if err != nil {
return nil, err
}
codesignAssets.ArchivableTargetProfilesByBundleID[bundleIDIdentifier] = *profile
}
if len(app.UITestTargetBundleIDs) > 0 && distrType == Development {
// Capabilities are not supported for UITest targets.
// Xcode managed signing uses Wildcard Provisioning Profiles for UITest target signing.
for _, bundleIDIdentifier := range app.UITestTargetBundleIDs {
wildcardBundleID, err := CreateWildcardBundleID(bundleIDIdentifier)
if err != nil {
return nil, fmt.Errorf("could not create wildcard bundle id: %s", err)
}
// Capabilities are not supported for UITest targets.
profile, err := profileManager.ensureProfileWithRetry(profileType, wildcardBundleID, nil, certIDs, devPortalDeviceIDs, minProfileDaysValid)
if err != nil {
return nil, err
}
codesignAssets.UITestTargetProfilesByBundleID[bundleIDIdentifier] = *profile
}
}
if len(profileManager.containersByBundleID) > 0 {
iCloudContainers := ""
for bundleID, containers := range containersByBundleID {
iCloudContainers = fmt.Sprintf("%s, containers:\n", bundleID)
for _, container := range containers {
iCloudContainers += fmt.Sprintf("- %s\n", container)
}
iCloudContainers += "\n"
}
return nil, &DetailedError{
ErrorMessage: "",
Title: "Unable to automatically assign iCloud containers to the following app IDs:",
Description: iCloudContainers,
Recommendation: "You have to manually add the listed containers to your app ID at: https://developer.apple.com/account/resources/identifiers/list.",
}
}
return &codesignAssets, nil
}
type profileManager struct {
client DevPortalClient
bundleIDByBundleIDIdentifer map[string]*appstoreconnect.BundleID
containersByBundleID map[string][]string
}
func (m profileManager) ensureBundleID(bundleIDIdentifier string, entitlements Entitlements) (*appstoreconnect.BundleID, error) {
fmt.Println()
log.Infof(" Searching for app ID for bundle ID: %s", bundleIDIdentifier)
bundleID, ok := m.bundleIDByBundleIDIdentifer[bundleIDIdentifier]
if !ok {
var err error
bundleID, err = m.client.FindBundleID(bundleIDIdentifier)
if err != nil {
return nil, fmt.Errorf("failed to find bundle ID: %w", err)
}
}
if bundleID == nil && isAppClip(entitlements) {
return nil, ErrAppClipAppID{}
}
if bundleID != nil {
log.Printf(" app ID found: %s", bundleID.Attributes.Name)
m.bundleIDByBundleIDIdentifer[bundleIDIdentifier] = bundleID
// Check if BundleID is sync with the project
err := m.client.CheckBundleIDEntitlements(*bundleID, entitlements)
if err != nil {
if mErr, ok := err.(NonmatchingProfileError); ok {
if isAppClip(entitlements) && hasSignInWithAppleEntitlement(entitlements) {
return nil, ErrAppClipAppIDWithAppleSigning{}
}
log.Warnf(" app ID capabilities invalid: %s", mErr.Reason)
log.Warnf(" app ID capabilities are not in sync with the project capabilities, synchronizing...")
if err := m.client.SyncBundleID(*bundleID, entitlements); err != nil {
return nil, fmt.Errorf("failed to update bundle ID capabilities: %w", err)
}
return bundleID, nil
}
return nil, fmt.Errorf("failed to validate bundle ID: %w", err)
}
log.Printf(" app ID capabilities are in sync with the project capabilities")
return bundleID, nil
}
// Create BundleID
log.Warnf(" app ID not found, generating...")
bundleID, err := m.client.CreateBundleID(bundleIDIdentifier, appIDName(bundleIDIdentifier))
if err != nil {
return nil, fmt.Errorf("failed to create bundle ID: %w", err)
}
containers, err := entitlements.ICloudContainers()
if err != nil {
return nil, fmt.Errorf("failed to get list of iCloud containers: %w", err)
}
if len(containers) > 0 {
m.containersByBundleID[bundleIDIdentifier] = containers
log.Errorf(" app ID created but couldn't add iCloud containers: %v", containers)
}
if err := m.client.SyncBundleID(*bundleID, entitlements); err != nil {
return nil, fmt.Errorf("failed to update bundle ID capabilities: %w", err)
}
m.bundleIDByBundleIDIdentifer[bundleIDIdentifier] = bundleID
return bundleID, nil
}
func (m profileManager) ensureProfileWithRetry(profileType appstoreconnect.ProfileType, bundleIDIdentifier string, entitlements Entitlements, certIDs, deviceIDs []string, minProfileDaysValid int) (*Profile, error) {
var profile *Profile
// Accessing the same Apple Developer Portal team can cause race conditions (parallel CI runs for example).
// Between the time of finding and downloading a profile, it could have been deleted for example.
if err := retry.Times(5).Wait(10 * time.Second).TryWithAbort(func(attempt uint) (error, bool) {
if attempt > 0 {
fmt.Println()
log.Printf(" Retrying profile preparation (attempt %d)", attempt)
}
var err error
profile, err = m.ensureProfile(profileType, bundleIDIdentifier, entitlements, certIDs, deviceIDs, minProfileDaysValid)
if err != nil {
if ok := errors.As(err, &ProfilesInconsistentError{}); ok {
log.Warnf(" %s", err)
return err, false
}
return err, true
}
return nil, false
}); err != nil {
return nil, err
}
return profile, nil
}
func (m profileManager) ensureProfile(profileType appstoreconnect.ProfileType, bundleIDIdentifier string, entitlements Entitlements, certIDs, deviceIDs []string, minProfileDaysValid int) (*Profile, error) {
fmt.Println()
log.Infof(" Checking bundle id: %s", bundleIDIdentifier)
log.Printf(" capabilities:")
for k, v := range entitlements {
log.Printf(" - %s: %v", k, v)
}
// Search for Bitrise managed Profile
name := profileName(profileType, bundleIDIdentifier)
profile, err := m.client.FindProfile(name, profileType)
if err != nil {
return nil, fmt.Errorf("failed to find profile: %w", err)
}
if profile == nil {
log.Warnf(" profile does not exist, generating...")
} else {
log.Printf(" Bitrise managed profile found: %s ID: %s UUID: %s Expiry: %s", profile.Attributes().Name, profile.ID(), profile.Attributes().UUID, time.Time(profile.Attributes().ExpirationDate))
if profile.Attributes().ProfileState == appstoreconnect.Active {
// Check if Bitrise managed Profile is sync with the project
err := checkProfile(m.client, profile, entitlements, deviceIDs, certIDs, minProfileDaysValid)
if err != nil {
if mErr, ok := err.(NonmatchingProfileError); ok {
log.Warnf(" the profile is not in sync with the project requirements (%s), regenerating ...", mErr.Reason)
} else {
return nil, fmt.Errorf("failed to check if profile is valid: %w", err)
}
} else { // Profile matches
log.Donef(" profile is in sync with the project requirements")
return &profile, nil
}
}
if profile.Attributes().ProfileState == appstoreconnect.Invalid {
// If the profile's bundle id gets modified, the profile turns in Invalid state.
log.Warnf(" the profile state is invalid, regenerating ...")
}
if err := m.client.DeleteProfile(profile.ID()); err != nil {
return nil, fmt.Errorf("failed to delete profile: %w", err)
}
}
// Search for BundleID
bundleID, err := m.ensureBundleID(bundleIDIdentifier, entitlements)
if err != nil {
return nil, fmt.Errorf("failed to ensure application identifier for %s: %w", bundleIDIdentifier, err)
}
// Create Bitrise managed Profile
fmt.Println()
log.Infof(" Creating profile for bundle id: %s", bundleID.Attributes.Name)
profile, err = m.client.CreateProfile(name, profileType, *bundleID, certIDs, deviceIDs)
if err != nil {
return nil, fmt.Errorf("failed to create profile: %w", err)
}
log.Donef(" profile created: %s", profile.Attributes().Name)
return &profile, nil
}
func isAppClip(entitlements Entitlements) bool {
for key := range entitlements {
if key == appstoreconnect.ParentApplicationIdentifierEntitlementKey {
return true
}
}
return false
}
func hasSignInWithAppleEntitlement(entitlements Entitlements) bool {
for key := range entitlements {
if key == appstoreconnect.SignInWithAppleEntitlementKey {
return true
}
}
return false
}
// DistributionTypeRequiresDeviceList returns true if the provided distribution method requires a provisioning profile with a device list.
func DistributionTypeRequiresDeviceList(distrTypes []DistributionType) bool {
for _, distrType := range distrTypes {
if distrType == Development || distrType == AdHoc {
return true
}
}
return false
}
// CreateWildcardBundleID creates a wildcard bundle identifier, by replacing the provided bundle id's last component with an asterisk (*).
func CreateWildcardBundleID(bundleID string) (string, error) {
idx := strings.LastIndex(bundleID, ".")
if idx == -1 {
return "", fmt.Errorf("invalid bundle id (%s): does not contain *", bundleID)
}
return bundleID[:idx] + ".*", nil
}
// profileName generates profile name with layout: Bitrise <platform> <distribution type> - (<bundle id>)
func profileName(profileType appstoreconnect.ProfileType, bundleID string) string {
platform, ok := ProfileTypeToPlatform[profileType]
if !ok {
panic(fmt.Sprintf("unknown profile type: %s", profileType))
}
distribution, ok := ProfileTypeToDistribution[profileType]
if !ok {
panic(fmt.Sprintf("unknown profile type: %s", profileType))
}
prefix := ""
if strings.HasSuffix(bundleID, ".*") {
// `*` char is not allowed in Profile name.
bundleID = strings.TrimSuffix(bundleID, ".*")
prefix = "Wildcard "
}
return fmt.Sprintf("%sBitrise %s %s - (%s)", prefix, platform, distribution, bundleID)
}
func checkProfileEntitlements(client DevPortalClient, prof Profile, appEntitlements Entitlements) error {
profileEnts, err := prof.Entitlements()
if err != nil {
return err
}
missingContainers, err := FindMissingContainers(appEntitlements, profileEnts)
if err != nil {
return fmt.Errorf("failed to check missing containers: %s", err)
}
if len(missingContainers) > 0 {
return NonmatchingProfileError{
Reason: fmt.Sprintf("project uses containers that are missing from the provisioning profile: %v", missingContainers),
}
}
bundleID, err := prof.BundleID()
if err != nil {
return err
}
return client.CheckBundleIDEntitlements(bundleID, appEntitlements)
}
// ParseRawProfileEntitlements ...
func ParseRawProfileEntitlements(profileContents []byte) (Entitlements, error) {
pkcs, err := profileutil.ProvisioningProfileFromContent(profileContents)
if err != nil {
return nil, fmt.Errorf("failed to parse pkcs7 from profile content: %s", err)
}
profile, err := profileutil.NewProvisioningProfileInfo(*pkcs)
if err != nil {
return nil, fmt.Errorf("failed to parse profile info from pkcs7 content: %s", err)
}
return Entitlements(profile.Entitlements), nil
}
// FindMissingContainers ...
func FindMissingContainers(projectEnts, profileEnts Entitlements) ([]string, error) {
projContainerIDs, err := serialized.Object(projectEnts).StringSlice(ICloudIdentifiersEntitlementKey)
if err != nil {
if serialized.IsKeyNotFoundError(err) {
return nil, nil // project has no container
}
return nil, err
}
// project has containers, so the profile should have at least the same
profContainerIDs, err := serialized.Object(profileEnts).StringSlice(ICloudIdentifiersEntitlementKey)
if err != nil {
if serialized.IsKeyNotFoundError(err) {
return projContainerIDs, nil
}
return nil, err
}
// project and profile also has containers, check if profile contains the containers the project need
var missing []string
for _, projContainerID := range projContainerIDs {
var found bool
for _, profContainerID := range profContainerIDs {
if projContainerID == profContainerID {
found = true
break
}
}
if !found {
missing = append(missing, projContainerID)
}
}
return missing, nil
}
func checkProfileCertificates(profileCertificateIDs []string, certificateIDs []string) error {
for _, id := range certificateIDs {
if !sliceutil.IsStringInSlice(id, profileCertificateIDs) {
return NonmatchingProfileError{
Reason: fmt.Sprintf("certificate with ID (%s) not included in the profile", id),
}
}
}
return nil
}
func checkProfileDevices(profileDeviceIDs []string, deviceIDs []string) error {
for _, id := range deviceIDs {
if !sliceutil.IsStringInSlice(id, profileDeviceIDs) {
return NonmatchingProfileError{
Reason: fmt.Sprintf("device with ID (%s) not included in the profile", id),
}
}
}
return nil
}
func isProfileExpired(prof Profile, minProfileDaysValid int) bool {
relativeExpiryTime := time.Now()
if minProfileDaysValid > 0 {
relativeExpiryTime = relativeExpiryTime.Add(time.Duration(minProfileDaysValid) * 24 * time.Hour)
}
return time.Time(prof.Attributes().ExpirationDate).Before(relativeExpiryTime)
}
func checkProfile(client DevPortalClient, prof Profile, entitlements Entitlements, deviceIDs, certificateIDs []string, minProfileDaysValid int) error {
if isProfileExpired(prof, minProfileDaysValid) {
return NonmatchingProfileError{
Reason: fmt.Sprintf("profile expired, or will expire in less then %d day(s)", minProfileDaysValid),
}
}
if err := checkProfileEntitlements(client, prof, entitlements); err != nil {
return err
}
profileCertificateIDs, err := prof.CertificateIDs()
if err != nil {
return err
}
if err := checkProfileCertificates(profileCertificateIDs, certificateIDs); err != nil {
return err
}
profileDeviceIDs, err := prof.DeviceIDs()
if err != nil {
return err
}
return checkProfileDevices(profileDeviceIDs, deviceIDs)
}
// SelectCertificate selects the first certificate with the given distribution type.
func SelectCertificate(certsByType map[appstoreconnect.CertificateType][]Certificate, distrType DistributionType) (*Certificate, error) {
certType := CertificateTypeByDistribution[distrType]
certs := certsByType[certType]
if len(certs) == 0 {
return nil, fmt.Errorf("no valid certificate provided for distribution type: %s", distrType)
}
if len(certs) > 1 {
log.Warnf("Multiple certificates provided for distribution type: %s", distrType)
for _, c := range certs {
log.Warnf("- %s", c.CertificateInfo.CommonName)
}
}
selectedCertificate := certs[0]
log.Warnf("Using certificate for %s distribution: %s", distrType, selectedCertificate.CertificateInfo.CommonName)
return &selectedCertificate, nil
}