forked from snapcore/snapd
/
store.go
2440 lines (2094 loc) · 65.7 KB
/
store.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
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
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// -*- Mode: Go; indent-tabs-mode: t -*-
/*
* Copyright (C) 2014-2018 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
// Package store has support to use the Ubuntu Store for querying and downloading of snaps, and the related services.
package store
import (
"bytes"
"crypto"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"os/exec"
"path"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
"github.com/juju/ratelimit"
"golang.org/x/net/context"
"golang.org/x/net/context/ctxhttp"
"gopkg.in/retry.v1"
"github.com/snapcore/snapd/arch"
"github.com/snapcore/snapd/asserts"
"github.com/snapcore/snapd/client"
"github.com/snapcore/snapd/dirs"
"github.com/snapcore/snapd/httputil"
"github.com/snapcore/snapd/i18n"
"github.com/snapcore/snapd/jsonutil"
"github.com/snapcore/snapd/logger"
"github.com/snapcore/snapd/osutil"
"github.com/snapcore/snapd/overlord/auth"
"github.com/snapcore/snapd/progress"
"github.com/snapcore/snapd/release"
"github.com/snapcore/snapd/snap"
)
// TODO: better/shorter names are probably in order once fewer legacy places are using this
const (
// halJsonContentType is the default accept value for store requests
halJsonContentType = "application/hal+json"
// jsonContentType is for store enpoints that don't support HAL
jsonContentType = "application/json"
// UbuntuCoreWireProtocol is the protocol level we support when
// communicating with the store. History:
// - "1": client supports squashfs snaps
UbuntuCoreWireProtocol = "1"
)
type RefreshOptions struct {
// RefreshManaged indicates to the store that the refresh is
// managed via snapd-control.
RefreshManaged bool
PrivacyKey string
}
// the LimitTime should be slightly more than 3 times of our http.Client
// Timeout value
var defaultRetryStrategy = retry.LimitCount(5, retry.LimitTime(38*time.Second,
retry.Exponential{
Initial: 300 * time.Millisecond,
Factor: 2.5,
},
))
var connCheckStrategy = retry.LimitCount(3, retry.LimitTime(38*time.Second,
retry.Exponential{
Initial: 900 * time.Millisecond,
Factor: 1.3,
},
))
// Config represents the configuration to access the snap store
type Config struct {
// Store API base URLs. The assertions url is only separate because it can
// be overridden by its own env var.
StoreBaseURL *url.URL
AssertionsBaseURL *url.URL
// StoreID is the store id used if we can't get one through the AuthContext.
StoreID string
Architecture string
Series string
DetailFields []string
InfoFields []string
DeltaFormat string
// CacheDownloads is the number of downloads that should be cached
CacheDownloads int
// Proxy returns the HTTP proxy to use when talking to the store
Proxy func(*http.Request) (*url.URL, error)
}
// setBaseURL updates the store API's base URL in the Config. Must not be used
// to change active config.
func (cfg *Config) setBaseURL(u *url.URL) error {
storeBaseURI, err := storeURL(u)
if err != nil {
return err
}
assertsBaseURI, err := assertsURL()
if err != nil {
return err
}
cfg.StoreBaseURL = storeBaseURI
cfg.AssertionsBaseURL = assertsBaseURI
return nil
}
// Store represents the ubuntu snap store
type Store struct {
cfg *Config
architecture string
series string
noCDN bool
fallbackStoreID string
detailFields []string
infoFields []string
deltaFormat string
// reused http client
client *http.Client
authContext auth.AuthContext
mu sync.Mutex
suggestedCurrency string
cacher downloadCache
proxy func(*http.Request) (*url.URL, error)
}
func respToError(resp *http.Response, msg string) error {
tpl := "cannot %s: got unexpected HTTP status code %d via %s to %q"
if oops := resp.Header.Get("X-Oops-Id"); oops != "" {
tpl += " [%s]"
return fmt.Errorf(tpl, msg, resp.StatusCode, resp.Request.Method, resp.Request.URL, oops)
}
return fmt.Errorf(tpl, msg, resp.StatusCode, resp.Request.Method, resp.Request.URL)
}
// Deltas enabled by default on classic, but allow opting in or out on both classic and core.
func useDeltas() bool {
// only xdelta3 is supported for now, so check the binary exists here
// TODO: have a per-format checker instead
if _, err := getXdelta3Cmd(); err != nil {
return false
}
return osutil.GetenvBool("SNAPD_USE_DELTAS_EXPERIMENTAL", true)
}
func useStaging() bool {
return osutil.GetenvBool("SNAPPY_USE_STAGING_STORE")
}
// endpointURL clones a base URL and updates it with optional path and query.
func endpointURL(base *url.URL, path string, query url.Values) *url.URL {
u := *base
if path != "" {
u.Path = strings.TrimSuffix(u.Path, "/") + "/" + strings.TrimPrefix(path, "/")
u.RawQuery = ""
}
if len(query) != 0 {
u.RawQuery = query.Encode()
}
return &u
}
// apiURL returns the system default base API URL.
func apiURL() *url.URL {
s := "https://api.snapcraft.io/"
if useStaging() {
s = "https://api.staging.snapcraft.io/"
}
u, _ := url.Parse(s)
return u
}
// storeURL returns the base store URL, derived from either the given API URL
// or an env var override.
func storeURL(api *url.URL) (*url.URL, error) {
var override string
var overrideName string
// XXX: time to drop FORCE_CPI support
// XXX: Deprecated but present for backward-compatibility: this used
// to be "Click Package Index". Remove this once people have got
// used to SNAPPY_FORCE_API_URL instead.
if s := os.Getenv("SNAPPY_FORCE_CPI_URL"); s != "" && strings.HasSuffix(s, "api/v1/") {
overrideName = "SNAPPY_FORCE_CPI_URL"
override = strings.TrimSuffix(s, "api/v1/")
} else if s := os.Getenv("SNAPPY_FORCE_API_URL"); s != "" {
overrideName = "SNAPPY_FORCE_API_URL"
override = s
}
if override != "" {
u, err := url.Parse(override)
if err != nil {
return nil, fmt.Errorf("invalid %s: %s", overrideName, err)
}
return u, nil
}
return api, nil
}
func assertsURL() (*url.URL, error) {
if s := os.Getenv("SNAPPY_FORCE_SAS_URL"); s != "" {
u, err := url.Parse(s)
if err != nil {
return nil, fmt.Errorf("invalid SNAPPY_FORCE_SAS_URL: %s", err)
}
return u, nil
}
// nil means fallback to store base url
return nil, nil
}
func authLocation() string {
if useStaging() {
return "login.staging.ubuntu.com"
}
return "login.ubuntu.com"
}
func authURL() string {
if u := os.Getenv("SNAPPY_FORCE_SSO_URL"); u != "" {
return u
}
return "https://" + authLocation() + "/api/v2"
}
var defaultStoreDeveloperURL = "https://dashboard.snapcraft.io/"
func storeDeveloperURL() string {
if useStaging() {
return "https://dashboard.staging.snapcraft.io/"
}
return defaultStoreDeveloperURL
}
var defaultConfig = Config{}
// DefaultConfig returns a copy of the default configuration ready to be adapted.
func DefaultConfig() *Config {
cfg := defaultConfig
return &cfg
}
func init() {
storeBaseURI, err := storeURL(apiURL())
if err != nil {
panic(err)
}
if storeBaseURI.RawQuery != "" {
panic("store API URL may not contain query string")
}
err = defaultConfig.setBaseURL(storeBaseURI)
if err != nil {
panic(err)
}
defaultConfig.DetailFields = jsonutil.StructFields((*snapDetails)(nil), "snap_yaml_raw")
defaultConfig.InfoFields = jsonutil.StructFields((*storeSnap)(nil), "snap-yaml")
}
type searchResults struct {
Payload struct {
Packages []*snapDetails `json:"clickindex:package"`
} `json:"_embedded"`
}
type sectionResults struct {
Payload struct {
Sections []struct{ Name string } `json:"clickindex:sections"`
} `json:"_embedded"`
}
// The default delta format if not configured.
var defaultSupportedDeltaFormat = "xdelta3"
// New creates a new Store with the given access configuration and for given the store id.
func New(cfg *Config, authContext auth.AuthContext) *Store {
if cfg == nil {
cfg = &defaultConfig
}
detailFields := cfg.DetailFields
if detailFields == nil {
detailFields = defaultConfig.DetailFields
}
infoFields := cfg.InfoFields
if infoFields == nil {
infoFields = defaultConfig.InfoFields
}
architecture := cfg.Architecture
if cfg.Architecture == "" {
architecture = arch.UbuntuArchitecture()
}
series := cfg.Series
if cfg.Series == "" {
series = release.Series
}
deltaFormat := cfg.DeltaFormat
if deltaFormat == "" {
deltaFormat = defaultSupportedDeltaFormat
}
store := &Store{
cfg: cfg,
series: series,
architecture: architecture,
noCDN: osutil.GetenvBool("SNAPPY_STORE_NO_CDN"),
fallbackStoreID: cfg.StoreID,
detailFields: detailFields,
infoFields: infoFields,
authContext: authContext,
deltaFormat: deltaFormat,
proxy: cfg.Proxy,
client: httputil.NewHTTPClient(&httputil.ClientOptions{
Timeout: 10 * time.Second,
MayLogBody: true,
Proxy: cfg.Proxy,
}),
}
store.SetCacheDownloads(cfg.CacheDownloads)
return store
}
// API endpoint paths
const (
// see https://wiki.ubuntu.com/AppStore/Interfaces/ClickPackageIndex
// XXX: Repeating "api/" here is cumbersome, but the next generation
// of store APIs will probably drop that prefix (since it now
// duplicates the hostname), and we may want to switch to v2 APIs
// one at a time; so it's better to consider that as part of
// individual endpoint paths.
searchEndpPath = "api/v1/snaps/search"
ordersEndpPath = "api/v1/snaps/purchases/orders"
buyEndpPath = "api/v1/snaps/purchases/buy"
customersMeEndpPath = "api/v1/snaps/purchases/customers/me"
sectionsEndpPath = "api/v1/snaps/sections"
commandsEndpPath = "api/v1/snaps/names"
// v2
snapActionEndpPath = "v2/snaps/refresh"
snapInfoEndpPath = "v2/snaps/info"
deviceNonceEndpPath = "api/v1/snaps/auth/nonces"
deviceSessionEndpPath = "api/v1/snaps/auth/sessions"
assertionsPath = "api/v1/snaps/assertions"
)
func (s *Store) defaultSnapQuery() url.Values {
q := url.Values{}
if len(s.detailFields) != 0 {
q.Set("fields", strings.Join(s.detailFields, ","))
}
return q
}
func (s *Store) baseURL(defaultURL *url.URL) *url.URL {
u := defaultURL
if s.authContext != nil {
var err error
_, u, err = s.authContext.ProxyStoreParams(defaultURL)
if err != nil {
logger.Debugf("cannot get proxy store parameters from state: %v", err)
}
}
if u != nil {
return u
}
return defaultURL
}
func (s *Store) endpointURL(p string, query url.Values) *url.URL {
return endpointURL(s.baseURL(s.cfg.StoreBaseURL), p, query)
}
func (s *Store) assertionsEndpointURL(p string, query url.Values) *url.URL {
defBaseURL := s.cfg.StoreBaseURL
// can be overridden separately!
if s.cfg.AssertionsBaseURL != nil {
defBaseURL = s.cfg.AssertionsBaseURL
}
return endpointURL(s.baseURL(defBaseURL), path.Join(assertionsPath, p), query)
}
// LoginUser logs user in the store and returns the authentication macaroons.
func (s *Store) LoginUser(username, password, otp string) (string, string, error) {
macaroon, err := requestStoreMacaroon(s.client)
if err != nil {
return "", "", err
}
deserializedMacaroon, err := auth.MacaroonDeserialize(macaroon)
if err != nil {
return "", "", err
}
// get SSO 3rd party caveat, and request discharge
loginCaveat, err := loginCaveatID(deserializedMacaroon)
if err != nil {
return "", "", err
}
discharge, err := dischargeAuthCaveat(s.client, loginCaveat, username, password, otp)
if err != nil {
return "", "", err
}
return macaroon, discharge, nil
}
// authAvailable returns true if there is a user and/or device session setup
func (s *Store) authAvailable(user *auth.UserState) (bool, error) {
if user.HasStoreAuth() {
return true, nil
} else {
var device *auth.DeviceState
var err error
if s.authContext != nil {
device, err = s.authContext.Device()
if err != nil {
return false, err
}
}
return device != nil && device.SessionMacaroon != "", nil
}
}
// authenticateUser will add the store expected Macaroon Authorization header for user
func authenticateUser(r *http.Request, user *auth.UserState) {
var buf bytes.Buffer
fmt.Fprintf(&buf, `Macaroon root="%s"`, user.StoreMacaroon)
// deserialize root macaroon (we need its signature to do the discharge binding)
root, err := auth.MacaroonDeserialize(user.StoreMacaroon)
if err != nil {
logger.Debugf("cannot deserialize root macaroon: %v", err)
return
}
for _, d := range user.StoreDischarges {
// prepare discharge for request
discharge, err := auth.MacaroonDeserialize(d)
if err != nil {
logger.Debugf("cannot deserialize discharge macaroon: %v", err)
return
}
discharge.Bind(root.Signature())
serializedDischarge, err := auth.MacaroonSerialize(discharge)
if err != nil {
logger.Debugf("cannot re-serialize discharge macaroon: %v", err)
return
}
fmt.Fprintf(&buf, `, discharge="%s"`, serializedDischarge)
}
r.Header.Set("Authorization", buf.String())
}
// refreshDischarges will request refreshed discharge macaroons for the user
func refreshDischarges(httpClient *http.Client, user *auth.UserState) ([]string, error) {
newDischarges := make([]string, len(user.StoreDischarges))
for i, d := range user.StoreDischarges {
discharge, err := auth.MacaroonDeserialize(d)
if err != nil {
return nil, err
}
if discharge.Location() != UbuntuoneLocation {
newDischarges[i] = d
continue
}
refreshedDischarge, err := refreshDischargeMacaroon(httpClient, d)
if err != nil {
return nil, err
}
newDischarges[i] = refreshedDischarge
}
return newDischarges, nil
}
// refreshUser will refresh user discharge macaroon and update state
func (s *Store) refreshUser(user *auth.UserState) error {
if s.authContext == nil {
return fmt.Errorf("user credentials need to be refreshed but update in place only supported in snapd")
}
newDischarges, err := refreshDischarges(s.client, user)
if err != nil {
return err
}
curUser, err := s.authContext.UpdateUserAuth(user, newDischarges)
if err != nil {
return err
}
// update in place
*user = *curUser
return nil
}
// refreshDeviceSession will set or refresh the device session in the state
func (s *Store) refreshDeviceSession(device *auth.DeviceState) error {
if s.authContext == nil {
return fmt.Errorf("internal error: no authContext")
}
nonce, err := requestStoreDeviceNonce(s.client, s.endpointURL(deviceNonceEndpPath, nil).String())
if err != nil {
return err
}
devSessReqParams, err := s.authContext.DeviceSessionRequestParams(nonce)
if err != nil {
return err
}
session, err := requestDeviceSession(s.client, s.endpointURL(deviceSessionEndpPath, nil).String(), devSessReqParams, device.SessionMacaroon)
if err != nil {
return err
}
curDevice, err := s.authContext.UpdateDeviceAuth(device, session)
if err != nil {
return err
}
// update in place
*device = *curDevice
return nil
}
// authenticateDevice will add the store expected Macaroon X-Device-Authorization header for device
func authenticateDevice(r *http.Request, device *auth.DeviceState, apiLevel apiLevel) {
if device.SessionMacaroon != "" {
r.Header.Set(hdrSnapDeviceAuthorization[apiLevel], fmt.Sprintf(`Macaroon root="%s"`, device.SessionMacaroon))
}
}
func (s *Store) setStoreID(r *http.Request, apiLevel apiLevel) (customStore bool) {
storeID := s.fallbackStoreID
if s.authContext != nil {
cand, err := s.authContext.StoreID(storeID)
if err != nil {
logger.Debugf("cannot get store ID from state: %v", err)
} else {
storeID = cand
}
}
if storeID != "" {
r.Header.Set(hdrSnapDeviceStore[apiLevel], storeID)
return true
}
return false
}
type apiLevel int
const (
apiV1Endps apiLevel = 0 // api/v1 endpoints
apiV2Endps apiLevel = 1 // v2 endpoints
)
var (
hdrSnapDeviceAuthorization = []string{"X-Device-Authorization", "Snap-Device-Authorization"}
hdrSnapDeviceStore = []string{"X-Ubuntu-Store", "Snap-Device-Store"}
hdrSnapDeviceSeries = []string{"X-Ubuntu-Series", "Snap-Device-Series"}
hdrSnapDeviceArchitecture = []string{"X-Ubuntu-Architecture", "Snap-Device-Architecture"}
hdrSnapClassic = []string{"X-Ubuntu-Classic", "Snap-Classic"}
)
type deviceAuthNeed int
const (
deviceAuthPreferred deviceAuthNeed = iota
deviceAuthCustomStoreOnly
)
// requestOptions specifies parameters for store requests.
type requestOptions struct {
Method string
URL *url.URL
Accept string
ContentType string
APILevel apiLevel
ExtraHeaders map[string]string
Data []byte
// DeviceAuthNeed indicates the level of need to supply device
// authorization for this request, can be:
// - deviceAuthPreferred: should be provided if available
// - deviceAuthCustomStoreOnly: should be provided only in case
// of a custom store
DeviceAuthNeed deviceAuthNeed
}
func (r *requestOptions) addHeader(k, v string) {
if r.ExtraHeaders == nil {
r.ExtraHeaders = make(map[string]string)
}
r.ExtraHeaders[k] = v
}
func cancelled(ctx context.Context) bool {
select {
case <-ctx.Done():
return true
default:
return false
}
}
var expectedCatalogPreamble = []interface{}{
json.Delim('{'),
"_embedded",
json.Delim('{'),
"clickindex:package",
json.Delim('['),
}
type alias struct {
Name string `json:"name"`
}
type catalogItem struct {
Name string `json:"package_name"`
Version string `json:"version"`
Summary string `json:"summary"`
Aliases []alias `json:"aliases"`
Apps []string `json:"apps"`
}
type SnapAdder interface {
AddSnap(snapName, version, summary string, commands []string) error
}
func decodeCatalog(resp *http.Response, names io.Writer, db SnapAdder) error {
const what = "decode new commands catalog"
if resp.StatusCode != 200 {
return respToError(resp, what)
}
dec := json.NewDecoder(resp.Body)
for _, expectedToken := range expectedCatalogPreamble {
token, err := dec.Token()
if err != nil {
return err
}
if token != expectedToken {
return fmt.Errorf(what+": bad catalog preamble: expected %#v, got %#v", expectedToken, token)
}
}
for dec.More() {
var v catalogItem
if err := dec.Decode(&v); err != nil {
return fmt.Errorf(what+": %v", err)
}
if v.Name == "" {
continue
}
fmt.Fprintln(names, v.Name)
if len(v.Apps) == 0 {
continue
}
commands := make([]string, 0, len(v.Aliases)+len(v.Apps))
for _, alias := range v.Aliases {
commands = append(commands, alias.Name)
}
for _, app := range v.Apps {
commands = append(commands, snap.JoinSnapApp(v.Name, app))
}
if err := db.AddSnap(v.Name, v.Version, v.Summary, commands); err != nil {
return err
}
}
return nil
}
func decodeJSONBody(resp *http.Response, success interface{}, failure interface{}) error {
ok := (resp.StatusCode == 200 || resp.StatusCode == 201)
// always decode on success; decode failures only if body is not empty
if !ok && resp.ContentLength == 0 {
return nil
}
result := success
if !ok {
result = failure
}
if result != nil {
return json.NewDecoder(resp.Body).Decode(result)
}
return nil
}
// retryRequestDecodeJSON calls retryRequest and decodes the response into either success or failure.
func (s *Store) retryRequestDecodeJSON(ctx context.Context, reqOptions *requestOptions, user *auth.UserState, success interface{}, failure interface{}) (resp *http.Response, err error) {
return httputil.RetryRequest(reqOptions.URL.String(), func() (*http.Response, error) {
return s.doRequest(ctx, s.client, reqOptions, user)
}, func(resp *http.Response) error {
return decodeJSONBody(resp, success, failure)
}, defaultRetryStrategy)
}
// doRequest does an authenticated request to the store handling a potential macaroon refresh required if needed
func (s *Store) doRequest(ctx context.Context, client *http.Client, reqOptions *requestOptions, user *auth.UserState) (*http.Response, error) {
authRefreshes := 0
for {
req, err := s.newRequest(reqOptions, user)
if err != nil {
return nil, err
}
var resp *http.Response
if ctx != nil {
resp, err = ctxhttp.Do(ctx, client, req)
} else {
resp, err = client.Do(req)
}
if err != nil {
return nil, err
}
wwwAuth := resp.Header.Get("WWW-Authenticate")
if resp.StatusCode == 401 && authRefreshes < 4 {
// 4 tries: 2 tries for each in case both user
// and device need refreshing
var refreshNeed authRefreshNeed
if user != nil && strings.Contains(wwwAuth, "needs_refresh=1") {
// refresh user
refreshNeed.user = true
}
if strings.Contains(wwwAuth, "refresh_device_session=1") {
// refresh device session
refreshNeed.device = true
}
if refreshNeed.needed() {
err := s.refreshAuth(user, refreshNeed)
if err != nil {
return nil, err
}
// close previous response and retry
resp.Body.Close()
authRefreshes++
continue
}
}
return resp, err
}
}
type authRefreshNeed struct {
device bool
user bool
}
func (rn *authRefreshNeed) needed() bool {
return rn.device || rn.user
}
func (s *Store) refreshAuth(user *auth.UserState, need authRefreshNeed) error {
if need.user {
// refresh user
err := s.refreshUser(user)
if err != nil {
return err
}
}
if need.device {
// refresh device session
if s.authContext == nil {
return fmt.Errorf("internal error: no authContext")
}
device, err := s.authContext.Device()
if err != nil {
return err
}
err = s.refreshDeviceSession(device)
if err != nil {
return err
}
}
return nil
}
// build a new http.Request with headers for the store
func (s *Store) newRequest(reqOptions *requestOptions, user *auth.UserState) (*http.Request, error) {
var body io.Reader
if reqOptions.Data != nil {
body = bytes.NewBuffer(reqOptions.Data)
}
req, err := http.NewRequest(reqOptions.Method, reqOptions.URL.String(), body)
if err != nil {
return nil, err
}
customStore := s.setStoreID(req, reqOptions.APILevel)
if s.authContext != nil && (customStore || reqOptions.DeviceAuthNeed != deviceAuthCustomStoreOnly) {
device, err := s.authContext.Device()
if err != nil {
return nil, err
}
// we don't have a session yet but have a serial, try
// to get a session
if device.SessionMacaroon == "" && device.Serial != "" {
err = s.refreshDeviceSession(device)
if err == auth.ErrNoSerial {
// missing serial assertion, log and continue without device authentication
logger.Debugf("cannot set device session: %v", err)
}
if err != nil && err != auth.ErrNoSerial {
return nil, err
}
}
authenticateDevice(req, device, reqOptions.APILevel)
}
// only set user authentication if user logged in to the store
if user.HasStoreAuth() {
authenticateUser(req, user)
}
req.Header.Set("User-Agent", httputil.UserAgent())
req.Header.Set("Accept", reqOptions.Accept)
req.Header.Set(hdrSnapDeviceArchitecture[reqOptions.APILevel], s.architecture)
req.Header.Set(hdrSnapDeviceSeries[reqOptions.APILevel], s.series)
req.Header.Set(hdrSnapClassic[reqOptions.APILevel], strconv.FormatBool(release.OnClassic))
if reqOptions.APILevel == apiV1Endps {
req.Header.Set("X-Ubuntu-Wire-Protocol", UbuntuCoreWireProtocol)
}
if reqOptions.ContentType != "" {
req.Header.Set("Content-Type", reqOptions.ContentType)
}
for header, value := range reqOptions.ExtraHeaders {
req.Header.Set(header, value)
}
return req, nil
}
func (s *Store) cdnHeader() (string, error) {
if s.noCDN {
return "none", nil
}
if s.authContext == nil {
return "", nil
}
// set Snap-CDN from cloud instance information
// if available
// TODO: do we want a more complex retry strategy
// where we first to send this header and if the
// operation fails that way to even get the connection
// then we retry without sending this?
cloudInfo, err := s.authContext.CloudInfo()
if err != nil {
return "", err
}
if cloudInfo != nil {
cdnParams := []string{fmt.Sprintf("cloud-name=%q", cloudInfo.Name)}
if cloudInfo.Region != "" {
cdnParams = append(cdnParams, fmt.Sprintf("region=%q", cloudInfo.Region))
}
if cloudInfo.AvailabilityZone != "" {
cdnParams = append(cdnParams, fmt.Sprintf("availability-zone=%q", cloudInfo.AvailabilityZone))
}
return strings.Join(cdnParams, " "), nil
}
return "", nil
}
func (s *Store) extractSuggestedCurrency(resp *http.Response) {
suggestedCurrency := resp.Header.Get("X-Suggested-Currency")
if suggestedCurrency != "" {
s.mu.Lock()
s.suggestedCurrency = suggestedCurrency
s.mu.Unlock()
}
}
// ordersResult encapsulates the order data sent to us from the software center agent.
//
// {
// "orders": [
// {
// "snap_id": "abcd1234efgh5678ijkl9012",
// "currency": "USD",
// "amount": "2.99",
// "state": "Complete",
// "refundable_until": null,
// "purchase_date": "2016-09-20T15:00:00+00:00"
// },
// {
// "snap_id": "abcd1234efgh5678ijkl9012",
// "currency": null,
// "amount": null,
// "state": "Complete",
// "refundable_until": null,
// "purchase_date": "2016-09-20T15:00:00+00:00"
// }
// ]
// }
type ordersResult struct {
Orders []*order `json:"orders"`
}
type order struct {
SnapID string `json:"snap_id"`
Currency string `json:"currency"`
Amount string `json:"amount"`
State string `json:"state"`
RefundableUntil string `json:"refundable_until"`
PurchaseDate string `json:"purchase_date"`
}
// decorateOrders sets the MustBuy property of each snap in the given list according to the user's known orders.
func (s *Store) decorateOrders(snaps []*snap.Info, user *auth.UserState) error {
// Mark every non-free snap as must buy until we know better.
hasPriced := false
for _, info := range snaps {
if info.Paid {
info.MustBuy = true
hasPriced = true
}
}
if user == nil {
return nil
}
if !hasPriced {
return nil
}
var err error
reqOptions := &requestOptions{
Method: "GET",
URL: s.endpointURL(ordersEndpPath, nil),
Accept: jsonContentType,
}