forked from canonical/snapd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstore_asserts.go
248 lines (223 loc) · 7.42 KB
/
store_asserts.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
// -*- Mode: Go; indent-tabs-mode: t -*-
/*
* Copyright (C) 2014-2022 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 (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"path"
"strconv"
"github.com/snapcore/snapd/asserts"
"github.com/snapcore/snapd/httputil"
"github.com/snapcore/snapd/overlord/auth"
)
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)
}
type assertionSvcError struct {
// v1 error fields
// XXX: remove once switched to v2 API request.
Status int `json:"status"`
Type string `json:"type"`
Title string `json:"title"`
Detail string `json:"detail"`
// v2 error list - the only field included in v2 error response.
// XXX: there is an overlap with searchV2Results (and partially with
// errorListEntry), we could share the definition.
ErrorList []struct {
Code string `json:"code"`
Message string `json:"message"`
} `json:"error-list"`
}
func (e *assertionSvcError) isNotFound() bool {
return (len(e.ErrorList) > 0 && e.ErrorList[0].Code == "not-found" /* v2 error */) || e.Status == 404
}
func (e *assertionSvcError) toError() error {
// is it v2 error?
if len(e.ErrorList) > 0 {
return fmt.Errorf("assertion service error: %q", e.ErrorList[0].Message)
}
// v1 error
return fmt.Errorf("assertion service error: [%s] %q", e.Title, e.Detail)
}
func (s *Store) setMaxFormat(v url.Values, assertType *asserts.AssertionType) {
var maxFormat int
if s.cfg.AssertionMaxFormats == nil {
maxFormat = assertType.MaxSupportedFormat()
} else {
maxFormat = s.cfg.AssertionMaxFormats[assertType.Name]
}
v.Set("max-format", strconv.Itoa(maxFormat))
}
// Assertion retrieves the assertion for the given type and primary key.
func (s *Store) Assertion(assertType *asserts.AssertionType, primaryKey []string, user *auth.UserState) (asserts.Assertion, error) {
v := url.Values{}
s.setMaxFormat(v, assertType)
u := s.assertionsEndpointURL(path.Join(assertType.Name, path.Join(asserts.ReducePrimaryKey(assertType, primaryKey)...)), v)
var asrt asserts.Assertion
err := s.downloadAssertions(u, func(r io.Reader) error {
// decode assertion
dec := asserts.NewDecoder(r)
var e error
asrt, e = dec.Decode()
return e
}, func(svcErr *assertionSvcError) error {
// error-list indicates v2 error response.
if svcErr.isNotFound() {
// best-effort
headers, _ := asserts.HeadersFromPrimaryKey(assertType, primaryKey)
return &asserts.NotFoundError{
Type: assertType,
Headers: headers,
}
}
// default error
return nil
}, "fetch assertion", user)
if err != nil {
return nil, err
}
return asrt, nil
}
// SeqFormingAssertion retrieves the sequence-forming assertion for the given
// type (currently validation-set only). For sequence <= 0 we query for the
// latest sequence, otherwise the latest revision of the given sequence is
// requested.
func (s *Store) SeqFormingAssertion(assertType *asserts.AssertionType, sequenceKey []string, sequence int, user *auth.UserState) (asserts.Assertion, error) {
if !assertType.SequenceForming() {
return nil, fmt.Errorf("internal error: requested non sequence-forming assertion type %q", assertType.Name)
}
v := url.Values{}
s.setMaxFormat(v, assertType)
hasSequenceNumber := sequence > 0
if hasSequenceNumber {
// full primary key passed, query specific sequence number.
v.Set("sequence", fmt.Sprintf("%d", sequence))
} else {
// query for the latest sequence.
v.Set("sequence", "latest")
}
u := s.assertionsEndpointURL(path.Join(assertType.Name, path.Join(sequenceKey...)), v)
var asrt asserts.Assertion
err := s.downloadAssertions(u, func(r io.Reader) error {
// decode assertion
dec := asserts.NewDecoder(r)
var e error
asrt, e = dec.Decode()
return e
}, func(svcErr *assertionSvcError) error {
// error-list indicates v2 error response.
if svcErr.isNotFound() {
// XXX: this re-implements asserts.HeadersFromPrimaryKey() but is
// more relaxed about key length, making sequence optional. Should
// we make it a helper on its own in store for the not-found-error
// handling?
if len(sequenceKey) != len(assertType.PrimaryKey)-1 {
return fmt.Errorf("sequence key has wrong length for %q assertion", assertType.Name)
}
headers := make(map[string]string)
for i, keyVal := range sequenceKey {
name := assertType.PrimaryKey[i]
if keyVal == "" {
return fmt.Errorf("sequence key %q header cannot be empty", name)
}
headers[name] = keyVal
}
if hasSequenceNumber {
headers[assertType.PrimaryKey[len(assertType.PrimaryKey)-1]] = fmt.Sprintf("%d", sequence)
}
return &asserts.NotFoundError{
Type: assertType,
Headers: headers,
}
}
// default error
return nil
}, "fetch assertion", user)
if err != nil {
return nil, err
}
return asrt, nil
}
func (s *Store) downloadAssertions(u *url.URL, decodeBody func(io.Reader) error, handleSvcErr func(*assertionSvcError) error, what string, user *auth.UserState) error {
reqOptions := &requestOptions{
Method: "GET",
URL: u,
Accept: asserts.MediaType,
}
resp, err := httputil.RetryRequest(reqOptions.URL.String(), func() (*http.Response, error) {
return s.doRequest(context.TODO(), s.client, reqOptions, user)
}, func(resp *http.Response) error {
var e error
if resp.StatusCode == 200 {
e = decodeBody(resp.Body)
} else {
contentType := resp.Header.Get("Content-Type")
if contentType == jsonContentType || contentType == "application/problem+json" {
var svcErr assertionSvcError
dec := json.NewDecoder(resp.Body)
if e = dec.Decode(&svcErr); e != nil {
return fmt.Errorf("cannot decode assertion service error with HTTP status code %d: %v", resp.StatusCode, e)
}
if handleSvcErr != nil {
if e := handleSvcErr(&svcErr); e != nil {
return e
}
}
// default error handling
return svcErr.toError()
}
}
return e
}, defaultRetryStrategy)
if err != nil {
return err
}
if resp.StatusCode != 200 {
return respToError(resp, what)
}
return nil
}
// DownloadAssertions download the assertion streams at the given URLs
// and adds their assertions to the given asserts.Batch.
func (s *Store) DownloadAssertions(streamURLs []string, b *asserts.Batch, user *auth.UserState) error {
for _, ustr := range streamURLs {
u, err := url.Parse(ustr)
if err != nil {
return fmt.Errorf("invalid assertions stream URL: %v", err)
}
err = s.downloadAssertions(u, func(r io.Reader) error {
// decode stream
_, e := b.AddStream(r)
return e
}, nil, "download assertion stream", user)
if err != nil {
return err
}
}
return nil
}