-
Notifications
You must be signed in to change notification settings - Fork 16
/
appstore.go
400 lines (340 loc) · 10 KB
/
appstore.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
package appstore
import (
"bytes"
"crypto/sha256"
"encoding/json"
"errors"
"fmt"
"io"
"mime/multipart"
"net/http"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/saucelabs/saucectl/internal/multipartext"
"github.com/rs/zerolog/log"
"github.com/saucelabs/saucectl/internal/msg"
"github.com/saucelabs/saucectl/internal/requesth"
"github.com/saucelabs/saucectl/internal/storage"
)
// UploadResponse represents the response as is returned by the app store.
type UploadResponse struct {
Item Item `json:"item"`
}
// ListResponse represents the response as is returned by the app store.
type ListResponse struct {
Items []Item `json:"items"`
Links Links `json:"links"`
Page int `json:"page"`
PerPage int `json:"per_page"`
TotalItems int `json:"total_items"`
}
// errorResponse is a generic error response from the server.
type errorResponse struct {
Code int `json:"code"`
Title string `json:"title"`
Detail string `json:"detail"`
}
// Links represents the pagination information returned by the app store.
type Links struct {
Self string `json:"self"`
Prev string `json:"prev"`
Next string `json:"next"`
}
// Item represents the metadata about the uploaded file.
type Item struct {
ID string `json:"id"`
Name string `json:"name"`
Size int `json:"size"`
UploadTimestamp int64 `json:"upload_timestamp"`
}
// AppStore implements a remote file storage for storage.AppService.
// See https://wiki.saucelabs.com/display/DOCS/Application+Storage for more details.
type AppStore struct {
HTTPClient *http.Client
URL string
Username string
AccessKey string
}
// New returns an implementation for AppStore
func New(url, username, accessKey string, timeout time.Duration) *AppStore {
return &AppStore{
HTTPClient: &http.Client{Timeout: timeout},
URL: url,
Username: username,
AccessKey: accessKey,
}
}
// isMobileAppPackage determines if a file is a mobile app package.
func isMobileAppPackage(name string) bool {
return strings.HasSuffix(name, ".ipa") || strings.HasSuffix(name, ".apk") || strings.HasSuffix(name, ".aab")
}
// Download downloads a file with the given id. It's the caller's responsibility to close the reader.
func (s *AppStore) Download(id string) (io.ReadCloser, int64, error) {
req, err := requesth.New(http.MethodGet, fmt.Sprintf("%s/v1/storage/download/%s", s.URL, id), nil)
if err != nil {
return nil, 0, err
}
req.SetBasicAuth(s.Username, s.AccessKey)
resp, err := s.HTTPClient.Do(req)
if err != nil {
return nil, 0, err
}
switch resp.StatusCode {
case 200:
return resp.Body, resp.ContentLength, nil
case 401, 403:
return nil, 0, storage.ErrAccessDenied
case 404:
return nil, 0, storage.ErrFileNotFound
case 429:
return nil, 0, storage.ErrTooManyRequest
default:
return nil, 0, newServerError(resp)
}
}
// UploadStream uploads the contents of reader and stores them under the given filename.
func (s *AppStore) UploadStream(filename, description string, reader io.Reader) (storage.Item, error) {
multipartReader, contentType, err := multipartext.NewMultipartReader(filename, description, reader)
if err != nil {
return storage.Item{}, err
}
req, err := requesth.New(http.MethodPost, fmt.Sprintf("%s/v1/storage/upload", s.URL), multipartReader)
if err != nil {
return storage.Item{}, err
}
req.Header.Set("Content-Type", contentType)
req.SetBasicAuth(s.Username, s.AccessKey)
resp, err := s.HTTPClient.Do(req)
switch resp.StatusCode {
case 200, 201:
var ur UploadResponse
if err := json.NewDecoder(resp.Body).Decode(&ur); err != nil {
return storage.Item{}, err
}
return storage.Item{
ID: ur.Item.ID,
Name: ur.Item.Name,
Uploaded: time.Unix(ur.Item.UploadTimestamp, 0),
}, err
case 401, 403:
return storage.Item{}, storage.ErrAccessDenied
case 429:
return storage.Item{}, storage.ErrTooManyRequest
default:
return storage.Item{}, newServerError(resp)
}
}
// Upload uploads file to remote storage
//
// Deprecated: Use UploadStream.
func (s *AppStore) Upload(filename string, description string) (storage.Item, error) {
body, contentType, err := readFile(filename, description)
if err != nil {
return storage.Item{}, err
}
request, err := createRequest(fmt.Sprintf("%s/v1/storage/upload", s.URL), s.Username, s.AccessKey, body, contentType)
if err != nil {
return storage.Item{}, err
}
resp, err := s.HTTPClient.Do(request)
if err != nil {
if err.(*url.Error).Timeout() {
msg.LogUploadTimeout()
if !isMobileAppPackage(filename) {
msg.LogUploadTimeoutSuggestion()
}
return storage.Item{}, errors.New(msg.FailedToUpload)
}
return storage.Item{}, err
}
defer resp.Body.Close()
if resp.StatusCode != 201 {
b, err := io.ReadAll(resp.Body)
if err != nil {
return storage.Item{}, err
}
log.Error().Msgf("%s. Invalid response %d, body: %v", msg.FailedToUpload, resp.StatusCode, string(b))
return storage.Item{}, errors.New(msg.FailedToUpload)
}
var ur UploadResponse
if err := json.NewDecoder(resp.Body).Decode(&ur); err != nil {
return storage.Item{}, err
}
return storage.Item{ID: ur.Item.ID}, err
}
func readFile(fileName, description string) (*bytes.Buffer, string, error) {
file, err := os.Open(fileName)
if err != nil {
return nil, "", err
}
defer file.Close()
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
defer writer.Close()
part, err := writer.CreateFormFile("payload", filepath.Base(file.Name()))
if err != nil {
return nil, "", err
}
// FIXME This consumes quite a bit of memory (think of large mobile apps, node modules etc.).
_, err = io.Copy(part, file)
if err != nil {
return nil, "", err
}
if err := writer.WriteField("description", description); err != nil {
return nil, "", err
}
return body, writer.FormDataContentType(), nil
}
func createRequest(url, username, accesskey string, body io.Reader, contentType string) (*http.Request, error) {
req, err := requesth.New(http.MethodPost, url, body)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", contentType)
req.SetBasicAuth(username, accesskey)
return req, nil
}
// Find looks for a file having the same signature.
//
// Deprecated: Use List instead.
func (s *AppStore) Find(filename string) (storage.Item, error) {
if filename == "" {
return storage.Item{}, nil
}
hash, err := calculateBundleHash(filename)
if err != nil {
return storage.Item{}, err
}
log.Info().Msgf("Checksum: %s", hash)
queryString := fmt.Sprintf("?sha256=%s", hash)
request, err := createLocateRequest(fmt.Sprintf("%s/v1/storage/files", s.URL), s.Username, s.AccessKey, queryString)
if err != nil {
return storage.Item{}, err
}
lr, err := s.executeLocateRequest(request)
if err != nil {
return storage.Item{}, err
}
if lr.TotalItems == 0 {
return storage.Item{}, nil
}
return storage.Item{ID: lr.Items[0].ID}, nil
}
// List returns a list of items stored in the Sauce app storage that match the search criteria specified by opts.
func (s *AppStore) List(opts storage.ListOptions) (storage.List, error) {
uri, _ := url.Parse(s.URL)
uri.Path = "/v1/storage/files"
// Default MaxResults if not set or out of range.
if opts.MaxResults < 1 || opts.MaxResults > 100 {
opts.MaxResults = 100
}
query := uri.Query()
query.Set("per_page", strconv.Itoa(opts.MaxResults))
if opts.MaxResults == 1 {
query.Set("paginate", "no")
}
if opts.Q != "" {
query.Set("q", opts.Q)
}
if opts.Name != "" {
query.Set("name", opts.Name)
}
if opts.SHA256 != "" {
query.Set("sha256", opts.SHA256)
}
uri.RawQuery = query.Encode()
req, err := requesth.New(http.MethodGet, uri.String(), nil)
if err != nil {
return storage.List{}, err
}
req.SetBasicAuth(s.Username, s.AccessKey)
resp, err := s.HTTPClient.Do(req)
if err != nil {
return storage.List{}, err
}
defer resp.Body.Close()
switch resp.StatusCode {
case 200:
var listResp ListResponse
if err := json.NewDecoder(resp.Body).Decode(&listResp); err != nil {
return storage.List{}, err
}
var items []storage.Item
for _, v := range listResp.Items {
items = append(items, storage.Item{
ID: v.ID,
Name: v.Name,
Size: v.Size,
Uploaded: time.Unix(v.UploadTimestamp, 0),
})
}
return storage.List{
Items: items,
Truncated: listResp.TotalItems > len(items),
}, nil
case 401, 403:
return storage.List{}, storage.ErrAccessDenied
case 429:
return storage.List{}, storage.ErrTooManyRequest
default:
return storage.List{}, newServerError(resp)
}
}
func calculateBundleHash(filename string) (string, error) {
fs, err := os.Open(filename)
if err != nil {
return "", err
}
defer fs.Close()
hsh := sha256.New()
if _, err := io.Copy(hsh, fs); err != nil {
return "", err
}
hash := fmt.Sprintf("%x", hsh.Sum(nil))
return hash, nil
}
func createLocateRequest(url, username, accesskey string, queryString string) (*http.Request, error) {
req, err := requesth.New(http.MethodGet, fmt.Sprintf("%s%s&per_page=1", url, queryString), nil)
if err != nil {
return nil, err
}
req.SetBasicAuth(username, accesskey)
return req, nil
}
func (s *AppStore) executeLocateRequest(request *http.Request) (ListResponse, error) {
resp, err := s.HTTPClient.Do(request)
if err != nil {
return ListResponse{}, err
}
defer resp.Body.Close()
var lr ListResponse
if err := json.NewDecoder(resp.Body).Decode(&lr); err != nil {
return ListResponse{}, err
}
return lr, nil
}
// newServerError inspects server error responses, trying to gather as much information as possible, especially if the body
// conforms to the errorResponse format, and returns a storage.ServerError.
func newServerError(resp *http.Response) *storage.ServerError {
var errResp errorResponse
body, _ := io.ReadAll(resp.Body)
defer resp.Body.Close()
reader := bytes.NewReader(body)
err := json.NewDecoder(reader).Decode(&errResp)
if err != nil {
return &storage.ServerError{
Code: resp.StatusCode,
Title: resp.Status,
Msg: string(body),
}
}
return &storage.ServerError{
Code: errResp.Code,
Title: errResp.Title,
Msg: errResp.Detail,
}
}