-
Notifications
You must be signed in to change notification settings - Fork 43
/
export.go
279 lines (239 loc) · 9.65 KB
/
export.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
package codesign
import (
"errors"
"fmt"
"io/ioutil"
"os"
"path"
"path/filepath"
"github.com/bitrise-io/codesigndoc/bitriseio"
"github.com/bitrise-io/codesigndoc/bitriseio/bitrise"
"github.com/bitrise-io/codesigndoc/models"
"github.com/bitrise-io/codesigndoc/osxkeychain"
"github.com/bitrise-io/codesigndoc/utility"
"github.com/bitrise-io/go-utils/log"
"github.com/bitrise-io/go-xcode/certificateutil"
"github.com/bitrise-io/go-xcode/profileutil"
"github.com/bitrise-io/goinp/goinp"
)
// UploadConfig contains configuration to automatically upload artifacts to bitrise.io.
type UploadConfig struct {
PersonalAccessToken string
AppSlug string
}
// WriteFilesConfig controls writing artifacts as files.
type WriteFilesConfig struct {
WriteFiles WriteFilesLevel
AbsOutputDirPath string
}
// WriteFilesLevel describes if codesigning files should be written to the output directory.
type WriteFilesLevel int
const (
// Invalid represents an invalid value.
Invalid WriteFilesLevel = iota
// WriteFilesAlways writes build logs and codesigning files always.
WriteFilesAlways
// WriteFilesFallback writes artifacts when upload was not chosen or failed.
WriteFilesFallback
// WriteFilesDisabled does not write any files.
WriteFilesDisabled
)
// ExportReport describes the output of codesigning files export.
type ExportReport struct {
CertificatesUploaded bool
ProvisioningProfilesUploaded bool
CodesignFilesWritten bool
}
// ExportCodesigningFiles exports certificates from the Keychain and provisioning profiles from their directory.
func ExportCodesigningFiles(certificatesRequired []certificateutil.CertificateInfoModel, profilesRequired []profileutil.ProvisioningProfileInfoModel, askForPassword bool) (models.Certificates, []models.ProvisioningProfile, error) {
certificates, err := exportIdentities(certificatesRequired, askForPassword)
if err != nil {
return models.Certificates{}, nil, err
}
profiles, err := exportProvisioningProfiles(profilesRequired)
if err != nil {
return models.Certificates{}, nil, err
}
return certificates, profiles, nil
}
// UploadAndWriteCodesignFiles exports then uploads codesign files to bitrise.io and saves them to output folder.
func UploadAndWriteCodesignFiles(certificates models.Certificates, provisioningProfiles []models.ProvisioningProfile, writeFilesConfig WriteFilesConfig, uploadConfig UploadConfig) (ExportReport, error) {
var client *bitrise.Client
// both or none CLI flags are required
if uploadConfig.PersonalAccessToken != "" && uploadConfig.AppSlug != "" {
// Upload automatically if token is provided as CLI parameter, do not export to filesystem.
// Used to upload artifacts as part of another CLI tool
var err error
client, err = bitrise.NewClient(uploadConfig.PersonalAccessToken)
if err != nil {
return ExportReport{}, err
}
client.SetSelectedAppSlug(uploadConfig.AppSlug)
}
if client == nil {
uploadConfirmMsg := "Do you want to upload the provisioning profiles and certificates to Bitrise?"
if len(provisioningProfiles) == 0 {
uploadConfirmMsg = "Do you want to upload the certificates to Bitrise?"
}
fmt.Println()
shouldUpload, err := goinp.AskForBoolFromReader(uploadConfirmMsg, os.Stdin)
if err != nil {
return ExportReport{}, err
}
if shouldUpload {
if client, err = bitriseio.GetInteractiveConfigClient(); err != nil {
return ExportReport{}, err
}
}
}
var filesWritten bool
if writeFilesConfig.WriteFiles == WriteFilesAlways ||
writeFilesConfig.WriteFiles == WriteFilesFallback && client == nil {
if err := writeFiles(certificates, provisioningProfiles, writeFilesConfig); err != nil {
return ExportReport{}, err
}
filesWritten = true
}
if client == nil {
return ExportReport{
CertificatesUploaded: len(certificates.Info) == 0,
ProvisioningProfilesUploaded: len(provisioningProfiles) == 0,
CodesignFilesWritten: filesWritten,
}, nil
}
certificatesUploaded, profilesUploaded, err := bitriseio.UploadCodesigningFiles(client, certificates, provisioningProfiles)
return ExportReport{
CertificatesUploaded: certificatesUploaded,
ProvisioningProfilesUploaded: profilesUploaded,
CodesignFilesWritten: filesWritten,
}, err
}
func writeFiles(identities models.Certificates, provisioningProfiles []models.ProvisioningProfile, writeFilesConfig WriteFilesConfig) error {
if err := os.MkdirAll(writeFilesConfig.AbsOutputDirPath, 0700); err != nil {
return fmt.Errorf("failed to create output directory for codesigning files, error: %s", err)
}
entries, err := ioutil.ReadDir(writeFilesConfig.AbsOutputDirPath)
if err != nil && err != os.ErrNotExist {
return fmt.Errorf("failed to check output directory contents, error: %s", err)
}
containsArtifacts := false
for _, entry := range entries {
if !entry.IsDir() && (path.Ext(entry.Name()) != ".log") {
containsArtifacts = true
break
}
}
if containsArtifacts {
fmt.Println()
log.Warnf("Export output directory exists and is not empty.")
}
if err := writeIdentities(identities.Content, writeFilesConfig.AbsOutputDirPath); err != nil {
return err
}
if err := writeProvisioningProfiles(provisioningProfiles, writeFilesConfig.AbsOutputDirPath); err != nil {
return err
}
return nil
}
// exportIdentities exports the given certificates merged in a single .p12 file.
func exportIdentities(certificates []certificateutil.CertificateInfoModel, isAskForPassword bool) (models.Certificates, error) {
if len(certificates) == 0 {
return models.Certificates{}, nil
}
fmt.Println()
fmt.Println()
log.Infof("Required Identities/Certificates (%d)", len(certificates))
for _, certificate := range certificates {
log.Printf("- %s", certificate.CommonName)
}
fmt.Println()
log.Infof("Exporting the Identities (Certificates):")
var identitiesWithKeychainRefs []osxkeychain.IdentityWithRefModel
defer osxkeychain.ReleaseIdentityWithRefList(identitiesWithKeychainRefs)
for _, certificate := range certificates {
log.Printf("searching for Identity: %s", certificate.CommonName)
identityRef, err := osxkeychain.FindAndValidateIdentity(certificate.CommonName)
if err != nil {
return models.Certificates{}, fmt.Errorf("failed to export, error: %s", err)
}
if identityRef == nil {
return models.Certificates{}, errors.New("identity not found in the keychain, or it was invalid (expired)")
}
identitiesWithKeychainRefs = append(identitiesWithKeychainRefs, *identityRef)
}
identityKeychainRefs := osxkeychain.CreateEmptyCFTypeRefSlice()
for _, aIdentityWithRefItm := range identitiesWithKeychainRefs {
fmt.Println("exporting Identity:", aIdentityWithRefItm.Label)
identityKeychainRefs = append(identityKeychainRefs, aIdentityWithRefItm.KeychainRef)
}
fmt.Println()
if isAskForPassword {
log.Infof("Exporting from Keychain")
log.Warnf(" You'll be asked to provide a Passphrase for the .p12 file!")
} else {
log.Warnf("Exporting from Keychain using empty Passphrase...")
log.Printf("This means that if you want to import the file the passphrase at import should be left empty,")
log.Printf("you don't have to type in anything, just leave the passphrase input empty.")
}
fmt.Println()
log.Warnf("You'll most likely see popups one for each Identity from Keychain,")
log.Warnf("you will have to accept (Allow) those to be able to export the Identities!")
fmt.Println()
identities, err := osxkeychain.ExportFromKeychain(identityKeychainRefs, isAskForPassword)
if err != nil {
return models.Certificates{}, fmt.Errorf("failed to export from Keychain: %s", err)
}
return models.Certificates{
Info: certificates,
Content: identities,
}, nil
}
// writeIdentities writes identities to a file path.
func writeIdentities(identities []byte, absExportOutputDirPath string) error {
return ioutil.WriteFile(filepath.Join(absExportOutputDirPath, "Identities.p12"), identities, 0600)
}
// exportProvisioningProfiles returns provisioning profiles.
func exportProvisioningProfiles(profiles []profileutil.ProvisioningProfileInfoModel) ([]models.ProvisioningProfile, error) {
if len(profiles) == 0 {
return nil, nil
}
log.Infof("Required Provisioning Profiles (%d)", len(profiles))
for _, profile := range profiles {
log.Printf("- %s (UUID: %s)", profile.Name, profile.UUID)
}
fmt.Println()
log.Infof("Exporting Provisioning Profiles...")
var exportedProfiles []models.ProvisioningProfile
for _, profile := range profiles {
log.Printf("searching for required Provisioning Profile: %s (UUID: %s)", profile.Name, profile.UUID)
provisioningProfile, pth, err := profileutil.FindProvisioningProfile(profile.UUID)
if err != nil {
return nil, fmt.Errorf("failed to find Provisioning Profile: %s", err)
}
log.Printf("file found at: %s", pth)
exportedProfile, err := profileutil.NewProvisioningProfileInfo(*provisioningProfile)
if err != nil {
return nil, fmt.Errorf("failed to parse exported profile, error: %s", err)
}
contents, err := ioutil.ReadFile(pth)
if err != nil {
return nil, fmt.Errorf("could not read provisioning profile file, error: %s", err)
}
exportedProfiles = append(exportedProfiles, models.ProvisioningProfile{
Info: exportedProfile,
Content: contents,
})
}
return exportedProfiles, nil
}
// writeProvisioningProfiles writes provisioning profiles to the filesystem.
func writeProvisioningProfiles(profiles []models.ProvisioningProfile, absExportOutputDirPath string) error {
for _, profile := range profiles {
exportFileName := utility.ProfileExportFileNameNoPath(profile.Info)
exportPth := filepath.Join(absExportOutputDirPath, exportFileName)
if err := ioutil.WriteFile(exportPth, profile.Content, 0600); err != nil {
return fmt.Errorf("failed to write file, error: %s", err)
}
}
return nil
}