|
| 1 | +// Copyright 2023 Jetpack Technologies Inc and contributors. All rights reserved. |
| 2 | +// Use of this source code is governed by the license in the LICENSE file. |
| 3 | + |
| 4 | +package auth |
| 5 | + |
| 6 | +import ( |
| 7 | + "context" |
| 8 | + "encoding/json" |
| 9 | + "fmt" |
| 10 | + "io" |
| 11 | + "net/http" |
| 12 | + "net/url" |
| 13 | + "path/filepath" |
| 14 | + "strings" |
| 15 | + "time" |
| 16 | + |
| 17 | + "github.com/pkg/browser" |
| 18 | + "github.com/pkg/errors" |
| 19 | + "go.jetpack.io/devbox/internal/boxcli/usererr" |
| 20 | + "go.jetpack.io/devbox/internal/xdg" |
| 21 | +) |
| 22 | + |
| 23 | +const additionalSleepOnSlowDown = 1 |
| 24 | + |
| 25 | +type codeResponse struct { |
| 26 | + DeviceCode string `json:"device_code"` |
| 27 | + UserCode string `json:"user_code"` |
| 28 | + VerificationURI string `json:"verification_uri"` |
| 29 | + VerificationURIComplete string `json:"verification_uri_complete"` |
| 30 | + ExpiresIn int `json:"expires_in"` |
| 31 | + Interval int `json:"interval"` |
| 32 | +} |
| 33 | + |
| 34 | +type tokenSet struct { |
| 35 | + AccessToken string `json:"access_token"` |
| 36 | + RefreshToken string `json:"refresh_token"` |
| 37 | + IDToken string `json:"id_token"` |
| 38 | + TokenType string `json:"token_type"` |
| 39 | + ExpiresIn int `json:"expires_in"` |
| 40 | +} |
| 41 | + |
| 42 | +// used for both requestToken and refreshToken functions |
| 43 | +type requestTokenError struct { |
| 44 | + Error string `json:"error"` |
| 45 | + ErrorDescription string `json:"error_description"` |
| 46 | +} |
| 47 | + |
| 48 | +// showVerificationURL presents a device flow verification URL to the user, |
| 49 | +// either by printing it to stdout or opening a web browser. |
| 50 | +func (a *Authenticator) showVerificationURL(url string, w io.Writer) { |
| 51 | + err := browser.OpenURL(url) |
| 52 | + if err == nil { |
| 53 | + fmt.Fprintf(w, "Opening your browser to complete the login. "+ |
| 54 | + "If your browser didn't open, you can go to this URL "+ |
| 55 | + "and confirm your code manually:\n%s\n\n", url) |
| 56 | + return |
| 57 | + } |
| 58 | + fmt.Fprintf( |
| 59 | + w, |
| 60 | + "Please go to this URL to confirm this code and login: %s\n\n", url) |
| 61 | +} |
| 62 | + |
| 63 | +// requestDeviceCode requests a device code that the user can use to |
| 64 | +// authorize the device. |
| 65 | +func (a *Authenticator) requestDeviceCode() (*codeResponse, error) { |
| 66 | + reqURL := fmt.Sprintf("https://%s/oauth/device/code", a.Domain) |
| 67 | + payload := strings.NewReader(fmt.Sprintf( |
| 68 | + "client_id=%s&scope=%s&audience=%s", |
| 69 | + a.ClientID, |
| 70 | + url.QueryEscape(a.Scope), |
| 71 | + a.Audience, |
| 72 | + )) |
| 73 | + |
| 74 | + req, err := http.NewRequest(http.MethodPost, reqURL, payload) |
| 75 | + if err != nil { |
| 76 | + bytesPayload, _ := io.ReadAll(payload) |
| 77 | + return nil, errors.Wrapf( |
| 78 | + err, |
| 79 | + "failed to send request to URL: %s with payload: %s", |
| 80 | + reqURL, |
| 81 | + string(bytesPayload), |
| 82 | + ) |
| 83 | + } |
| 84 | + |
| 85 | + req.Header.Add("content-type", "application/x-www-form-urlencoded") |
| 86 | + |
| 87 | + res, err := http.DefaultClient.Do(req) |
| 88 | + if err != nil { |
| 89 | + return nil, errors.Wrap(err, "failed to send Request") |
| 90 | + } |
| 91 | + |
| 92 | + defer res.Body.Close() |
| 93 | + body, err := io.ReadAll(res.Body) |
| 94 | + if err != nil { |
| 95 | + return nil, errors.Wrap(err, "failed to read response body") |
| 96 | + } |
| 97 | + |
| 98 | + if res.StatusCode != http.StatusOK { |
| 99 | + return nil, errors.Errorf( |
| 100 | + "got status code: %d, with body %s", |
| 101 | + res.StatusCode, |
| 102 | + string(body), |
| 103 | + ) |
| 104 | + } |
| 105 | + |
| 106 | + response := codeResponse{} |
| 107 | + return &response, json.Unmarshal(body, &response) |
| 108 | +} |
| 109 | + |
| 110 | +// requestTokens polls the Auth0 API for tokens. |
| 111 | +func (a *Authenticator) requestTokens( |
| 112 | + ctx context.Context, |
| 113 | + codeResponse *codeResponse, |
| 114 | +) (*tokenSet, error) { |
| 115 | + |
| 116 | + timeToSleep := codeResponse.Interval |
| 117 | + ticker := time.NewTicker(time.Duration(timeToSleep) * time.Second) |
| 118 | + defer ticker.Stop() |
| 119 | + |
| 120 | + // numTries is a counter to guard against infinite looping. |
| 121 | + // In the normal course: |
| 122 | + // Status Code 200 OK: we early return within loop |
| 123 | + // Known Error scenarios: we continue looping and requesting Auth0 API. |
| 124 | + // These are not "errors" so much as "user hasn't yet completed |
| 125 | + // browser login flow" |
| 126 | + // Unknown Error scenarios: we early return within loop |
| 127 | + |
| 128 | + for numTries := 0; numTries < 100; numTries++ { |
| 129 | + select { |
| 130 | + case <-ctx.Done(): |
| 131 | + return nil, errors.WithStack(ctx.Err()) |
| 132 | + |
| 133 | + case <-ticker.C: |
| 134 | + res, err := a.tryRequestToken(codeResponse) |
| 135 | + if err != nil { |
| 136 | + return nil, errors.WithStack(err) |
| 137 | + } |
| 138 | + |
| 139 | + defer res.Body.Close() |
| 140 | + body, err := io.ReadAll(res.Body) |
| 141 | + if err != nil { |
| 142 | + return nil, errors.WithStack(err) |
| 143 | + } |
| 144 | + |
| 145 | + // Handle success |
| 146 | + if res.StatusCode == http.StatusOK { |
| 147 | + tokens := tokenSet{} |
| 148 | + return &tokens, json.Unmarshal(body, &tokens) |
| 149 | + } |
| 150 | + |
| 151 | + // Handle failure scenarios |
| 152 | + moreSleep, err := handleFailure(body, res.StatusCode) |
| 153 | + if err != nil { |
| 154 | + return nil, errors.WithStack(err) |
| 155 | + } |
| 156 | + timeToSleep += moreSleep |
| 157 | + ticker.Reset(time.Duration(timeToSleep) * time.Second) |
| 158 | + } |
| 159 | + } |
| 160 | + |
| 161 | + return nil, usererr.New("max number of tries exceeded") |
| 162 | +} |
| 163 | + |
| 164 | +func (a *Authenticator) doRefreshToken( |
| 165 | + refreshToken string, |
| 166 | +) (*tokenSet, error) { |
| 167 | + |
| 168 | + reqURL := fmt.Sprintf("https://%s/oauth/token", a.Domain) |
| 169 | + |
| 170 | + payload := fmt.Sprintf( |
| 171 | + "grant_type=refresh_token&client_id=%s&refresh_token=%s", |
| 172 | + a.ClientID, |
| 173 | + refreshToken, |
| 174 | + ) |
| 175 | + payloadReader := strings.NewReader(payload) |
| 176 | + |
| 177 | + req, err := http.NewRequest(http.MethodPost, reqURL, payloadReader) |
| 178 | + if err != nil { |
| 179 | + return nil, errors.Wrapf( |
| 180 | + err, |
| 181 | + "failed to create request to URL: %s, with payload: %s", |
| 182 | + reqURL, |
| 183 | + payload, |
| 184 | + ) |
| 185 | + } |
| 186 | + |
| 187 | + req.Header.Add("content-type", "application/x-www-form-urlencoded") |
| 188 | + |
| 189 | + res, err := http.DefaultClient.Do(req) |
| 190 | + if err != nil { |
| 191 | + return nil, errors.Wrapf( |
| 192 | + err, |
| 193 | + "failed POST request to reqURL: %s, payload: %s ", |
| 194 | + reqURL, |
| 195 | + payload, |
| 196 | + ) |
| 197 | + } |
| 198 | + |
| 199 | + defer res.Body.Close() |
| 200 | + body, err := io.ReadAll(res.Body) |
| 201 | + if err != nil { |
| 202 | + return nil, errors.Wrap(err, "failed to read response body") |
| 203 | + } |
| 204 | + |
| 205 | + if res.StatusCode == http.StatusOK { |
| 206 | + tokens := &tokenSet{} |
| 207 | + return tokens, json.Unmarshal(body, tokens) |
| 208 | + } |
| 209 | + |
| 210 | + tokenErrorBody := requestTokenError{} |
| 211 | + if err := json.Unmarshal(body, &tokenErrorBody); err != nil { |
| 212 | + return nil, errors.Wrapf( |
| 213 | + err, |
| 214 | + "unable to unmarshal requestTokenError from body %s", |
| 215 | + body, |
| 216 | + ) |
| 217 | + } |
| 218 | + return nil, errors.Errorf( |
| 219 | + "refreshing access token returned an error (%s) with description: %s", |
| 220 | + tokenErrorBody.Error, |
| 221 | + tokenErrorBody.ErrorDescription, |
| 222 | + ) |
| 223 | +} |
| 224 | + |
| 225 | +func (a *Authenticator) tryRequestToken( |
| 226 | + codeResponse *codeResponse, |
| 227 | +) (*http.Response, error) { |
| 228 | + reqURL := fmt.Sprintf("https://%s/oauth/token", a.Domain) |
| 229 | + |
| 230 | + grantType := "urn:ietf:params:oauth:grant-type:device_code" |
| 231 | + payload := strings.NewReader(fmt.Sprintf( |
| 232 | + "grant_type=%s&device_code=%s&client_id=%s", |
| 233 | + url.QueryEscape(grantType), |
| 234 | + codeResponse.DeviceCode, |
| 235 | + a.ClientID, |
| 236 | + )) |
| 237 | + |
| 238 | + req, err := http.NewRequest(http.MethodPost, reqURL, payload) |
| 239 | + if err != nil { |
| 240 | + return nil, errors.WithStack(err) |
| 241 | + } |
| 242 | + |
| 243 | + req.Header.Add("content-type", "application/x-www-form-urlencoded") |
| 244 | + |
| 245 | + return http.DefaultClient.Do(req) |
| 246 | +} |
| 247 | + |
| 248 | +// handleFailure handles the failure scenarios for requestTokens. |
| 249 | +func handleFailure(body []byte, code int) (int, error) { |
| 250 | + tokenErrorBody := requestTokenError{} |
| 251 | + if err := json.Unmarshal(body, &tokenErrorBody); err != nil { |
| 252 | + return 0, errors.WithStack(err) |
| 253 | + } |
| 254 | + |
| 255 | + if code == http.StatusTooManyRequests { |
| 256 | + if tokenErrorBody.Error != "slow_down" { |
| 257 | + return 0, errors.Errorf( |
| 258 | + "got status code: %d, response body: %s", |
| 259 | + code, |
| 260 | + body, |
| 261 | + ) |
| 262 | + } |
| 263 | + |
| 264 | + return additionalSleepOnSlowDown, nil |
| 265 | + |
| 266 | + } else if code == http.StatusForbidden { |
| 267 | + |
| 268 | + // this error is received when waiting for user to take action |
| 269 | + // when they are logging in via browser. Continue polling. |
| 270 | + if tokenErrorBody.Error != "authorization_pending" { |
| 271 | + return 0, errors.Errorf( |
| 272 | + "got status code: %d, response body: %s", |
| 273 | + code, |
| 274 | + body, |
| 275 | + ) |
| 276 | + } |
| 277 | + |
| 278 | + return 0, nil // No slowdown, just keep trying |
| 279 | + } |
| 280 | + // The user has not authorized the device quickly enough, so |
| 281 | + // the `device_code` has expired. Notify the user that the |
| 282 | + // flow has expired and prompt them to re-initiate the flow. |
| 283 | + // The "expired_token" is returned exactly once. After that, |
| 284 | + // the dreaded "invalid_grant" will be returned and device |
| 285 | + // must stop polling. |
| 286 | + if tokenErrorBody.Error == "expired_token" || tokenErrorBody.Error == "invalid_grant" { |
| 287 | + return 0, usererr.New( |
| 288 | + "The device code has expired. Please try `devbox auth login` again.") |
| 289 | + } |
| 290 | + |
| 291 | + // "access_denied" can be received for: |
| 292 | + // 1. user refused to authorize the device. |
| 293 | + // 2. Auth server denied the transaction. |
| 294 | + // 3. A configured Auth0 "rule" denied access |
| 295 | + if tokenErrorBody.Error == "access_denied" { |
| 296 | + return 0, usererr.New("Access was denied") |
| 297 | + } |
| 298 | + |
| 299 | + // Unknown error |
| 300 | + return 0, usererr.New("Unable to login") |
| 301 | +} |
| 302 | + |
| 303 | +func getAuthFilePath() string { |
| 304 | + return xdg.StateSubpath(filepath.FromSlash("devbox/auth.json")) |
| 305 | +} |
0 commit comments