-
Notifications
You must be signed in to change notification settings - Fork 601
/
Copy pathauth.go
383 lines (322 loc) · 10.3 KB
/
auth.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
// -*- Mode: Go; indent-tabs-mode: t -*-
/*
* Copyright (C) 2014-2016 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
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"gopkg.in/macaroon.v1"
"gopkg.in/retry.v1"
)
var (
myappsAPIBase = myappsURL()
// MyAppsMacaroonACLAPI points to MyApps endpoint to get a ACL macaroon
MyAppsMacaroonACLAPI = myappsAPIBase + "dev/api/acl/"
// MyAppsDeviceNonceAPI points to MyApps endpoint to get a nonce
MyAppsDeviceNonceAPI = myappsAPIBase + "identity/api/v1/nonces"
// MyAppsDeviceSessionAPI points to MyApps endpoint to get a device session
MyAppsDeviceSessionAPI = myappsAPIBase + "identity/api/v1/sessions"
ubuntuoneAPIBase = authURL()
// UbuntuoneLocation is the Ubuntuone location as defined in the store macaroon
UbuntuoneLocation = authLocation()
// UbuntuoneDischargeAPI points to SSO endpoint to discharge a macaroon
UbuntuoneDischargeAPI = ubuntuoneAPIBase + "/tokens/discharge"
// UbuntuoneRefreshDischargeAPI points to SSO endpoint to refresh a discharge macaroon
UbuntuoneRefreshDischargeAPI = ubuntuoneAPIBase + "/tokens/refresh"
)
type ssoMsg struct {
Code string `json:"code"`
Message string `json:"message"`
Extra map[string][]string `json:"extra"`
}
// returns true if the http status code is in the "success" range (2xx)
func httpStatusCodeSuccess(httpStatusCode int) bool {
return httpStatusCode/100 == 2
}
// returns true if the http status code is in the "client-error" range (4xx)
func httpStatusCodeClientError(httpStatusCode int) bool {
return httpStatusCode/100 == 4
}
// loginCaveatID returns the 3rd party caveat from the macaroon to be discharged by Ubuntuone
func loginCaveatID(m *macaroon.Macaroon) (string, error) {
caveatID := ""
for _, caveat := range m.Caveats() {
if caveat.Location == UbuntuoneLocation {
caveatID = caveat.Id
break
}
}
if caveatID == "" {
return "", fmt.Errorf("missing login caveat")
}
return caveatID, nil
}
// requestStoreMacaroon requests a macaroon for accessing package data from the ubuntu store.
func requestStoreMacaroon() (string, error) {
const errorPrefix = "cannot get snap access permission from store: "
data := map[string]interface{}{
"permissions": []string{"package_access", "package_purchase"},
}
var err error
macaroonJSONData, err := json.Marshal(data)
if err != nil {
return "", fmt.Errorf(errorPrefix+"%v", err)
}
var responseData struct {
Macaroon string `json:"macaroon"`
}
for attempt := retry.Start(defaultRetryStrategy, nil); attempt.Next(); {
req, err := http.NewRequest("POST", MyAppsMacaroonACLAPI, bytes.NewReader(macaroonJSONData))
if err != nil {
return "", fmt.Errorf(errorPrefix+"%v", err)
}
req.Header.Set("User-Agent", userAgent)
req.Header.Set("Accept", "application/json")
req.Header.Set("Content-Type", "application/json")
resp, err := httpClient.Do(req)
if err != nil {
if shouldRetryError(attempt, err) {
continue
}
break
}
if shouldRetryHttpResponse(attempt, resp) {
resp.Body.Close()
continue
}
defer resp.Body.Close()
// check return code, error on anything !200
if resp.StatusCode != 200 {
return "", fmt.Errorf(errorPrefix+"store server returned status %d", resp.StatusCode)
}
dec := json.NewDecoder(resp.Body)
if err = dec.Decode(&responseData); err != nil {
if shouldRetryError(attempt, err) {
continue
} // else we will error-out and break the retry loop below
}
break
}
if err != nil {
return "", fmt.Errorf(errorPrefix+"%v", err)
}
if responseData.Macaroon == "" {
return "", fmt.Errorf(errorPrefix + "empty macaroon returned")
}
return responseData.Macaroon, nil
}
func requestDischargeMacaroon(endpoint string, data map[string]string) (string, error) {
const errorPrefix = "cannot authenticate to snap store: "
var err error
dischargeJSONData, err := json.Marshal(data)
if err != nil {
return "", fmt.Errorf(errorPrefix+"%v", err)
}
var responseData struct {
Macaroon string `json:"discharge_macaroon"`
}
for attempt := retry.Start(defaultRetryStrategy, nil); attempt.Next(); {
req, err := http.NewRequest("POST", endpoint, bytes.NewReader(dischargeJSONData))
if err != nil {
return "", fmt.Errorf(errorPrefix+"%v", err)
}
req.Header.Set("User-Agent", userAgent)
req.Header.Set("Accept", "application/json")
req.Header.Set("Content-Type", "application/json")
resp, err := httpClient.Do(req)
if err != nil {
if shouldRetryError(attempt, err) {
continue
}
break
}
if shouldRetryHttpResponse(attempt, resp) {
resp.Body.Close()
continue
}
defer resp.Body.Close()
// check return code, error on 4xx and anything !200
switch {
case httpStatusCodeClientError(resp.StatusCode):
// get error details
var msg ssoMsg
dec := json.NewDecoder(resp.Body)
if err = dec.Decode(&msg); err != nil {
if shouldRetryError(attempt, err) {
continue
}
return "", fmt.Errorf(errorPrefix+"%v", err)
}
switch msg.Code {
case "TWOFACTOR_REQUIRED":
return "", ErrAuthenticationNeeds2fa
case "TWOFACTOR_FAILURE":
return "", Err2faFailed
case "INVALID_DATA":
return "", ErrInvalidAuthData(msg.Extra)
}
if msg.Message != "" {
return "", fmt.Errorf(errorPrefix+"%v", msg.Message)
}
fallthrough
case !httpStatusCodeSuccess(resp.StatusCode):
return "", fmt.Errorf(errorPrefix+"server returned status %d", resp.StatusCode)
}
dec := json.NewDecoder(resp.Body)
if err = dec.Decode(&responseData); err != nil {
if shouldRetryError(attempt, err) {
continue
} // else we will error-out and break the retry loop below
}
break
}
if err != nil {
return "", fmt.Errorf(errorPrefix+"%v", err)
}
if responseData.Macaroon == "" {
return "", fmt.Errorf(errorPrefix + "empty macaroon returned")
}
return responseData.Macaroon, nil
}
// dischargeAuthCaveat returns a macaroon with the store auth caveat discharged.
func dischargeAuthCaveat(caveat, username, password, otp string) (string, error) {
data := map[string]string{
"email": username,
"password": password,
"caveat_id": caveat,
}
if otp != "" {
data["otp"] = otp
}
return requestDischargeMacaroon(UbuntuoneDischargeAPI, data)
}
// refreshDischargeMacaroon returns a soft-refreshed discharge macaroon.
func refreshDischargeMacaroon(discharge string) (string, error) {
data := map[string]string{
"discharge_macaroon": discharge,
}
return requestDischargeMacaroon(UbuntuoneRefreshDischargeAPI, data)
}
// requestStoreDeviceNonce requests a nonce for device authentication against the store.
func requestStoreDeviceNonce() (string, error) {
const errorPrefix = "cannot get nonce from store: "
var responseData struct {
Nonce string `json:"nonce"`
}
var err error
for attempt := retry.Start(defaultRetryStrategy, nil); attempt.Next(); {
req, err := http.NewRequest("POST", MyAppsDeviceNonceAPI, nil)
if err != nil {
return "", fmt.Errorf(errorPrefix+"%v", err)
}
req.Header.Set("User-Agent", userAgent)
req.Header.Set("Accept", "application/json")
resp, err := httpClient.Do(req)
if err != nil {
if shouldRetryError(attempt, err) {
continue
}
break
}
if shouldRetryHttpResponse(attempt, resp) {
resp.Body.Close()
continue
}
defer resp.Body.Close()
// check return code, error on anything !200
if resp.StatusCode != 200 {
return "", fmt.Errorf(errorPrefix+"store server returned status %d", resp.StatusCode)
}
dec := json.NewDecoder(resp.Body)
if err = dec.Decode(&responseData); err != nil {
if shouldRetryError(attempt, err) {
continue
} // else we will error-out and break the retry loop below
}
break
}
if err != nil {
return "", fmt.Errorf(errorPrefix+"%v", err)
}
if responseData.Nonce == "" {
return "", fmt.Errorf(errorPrefix + "empty nonce returned")
}
return responseData.Nonce, nil
}
// requestDeviceSession requests a device session macaroon from the store.
func requestDeviceSession(serialAssertion, sessionRequest, previousSession string) (string, error) {
const errorPrefix = "cannot get device session from store: "
data := map[string]string{
"serial-assertion": serialAssertion,
"device-session-request": sessionRequest,
}
var err error
deviceJSONData, err := json.Marshal(data)
if err != nil {
return "", fmt.Errorf(errorPrefix+"%v", err)
}
var responseData struct {
Macaroon string `json:"macaroon"`
}
for attempt := retry.Start(defaultRetryStrategy, nil); attempt.Next(); {
req, err := http.NewRequest("POST", MyAppsDeviceSessionAPI, bytes.NewReader(deviceJSONData))
if err != nil {
return "", fmt.Errorf(errorPrefix+"%v", err)
}
req.Header.Set("User-Agent", userAgent)
req.Header.Set("Accept", "application/json")
req.Header.Set("Content-Type", "application/json")
if previousSession != "" {
req.Header.Set("X-Device-Authorization", fmt.Sprintf(`Macaroon root="%s"`, previousSession))
}
resp, err := httpClient.Do(req)
if err != nil {
if shouldRetryError(attempt, err) {
continue
}
break
}
if shouldRetryHttpResponse(attempt, resp) {
resp.Body.Close()
continue
}
defer resp.Body.Close()
// check return code, error on anything !200
if resp.StatusCode != 200 {
body, _ := ioutil.ReadAll(io.LimitReader(resp.Body, 1e6)) // do our best to read the body
return "", fmt.Errorf(errorPrefix+"store server returned status %d and body %q", resp.StatusCode, body)
}
dec := json.NewDecoder(resp.Body)
if err = dec.Decode(&responseData); err != nil {
if shouldRetryError(attempt, err) {
continue
} // else we will error-out and break the retry loop below
}
break
}
if err != nil {
return "", fmt.Errorf(errorPrefix+"%v", err)
}
if responseData.Macaroon == "" {
return "", fmt.Errorf(errorPrefix + "empty session returned")
}
return responseData.Macaroon, nil
}