|
| 1 | +package oauth2 |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "encoding/json" |
| 6 | + "fmt" |
| 7 | + "io" |
| 8 | + "net/http" |
| 9 | + "net/url" |
| 10 | + "strings" |
| 11 | + "time" |
| 12 | + |
| 13 | + "golang.org/x/oauth2/internal" |
| 14 | +) |
| 15 | + |
| 16 | +// https://datatracker.ietf.org/doc/html/rfc8628#section-3.5 |
| 17 | +const ( |
| 18 | + errAuthorizationPending = "authorization_pending" |
| 19 | + errSlowDown = "slow_down" |
| 20 | + errAccessDenied = "access_denied" |
| 21 | + errExpiredToken = "expired_token" |
| 22 | +) |
| 23 | + |
| 24 | +// DeviceAuthResponse describes a successful RFC 8628 Device Authorization Response |
| 25 | +// https://datatracker.ietf.org/doc/html/rfc8628#section-3.2 |
| 26 | +type DeviceAuthResponse struct { |
| 27 | + // DeviceCode |
| 28 | + DeviceCode string `json:"device_code"` |
| 29 | + // UserCode is the code the user should enter at the verification uri |
| 30 | + UserCode string `json:"user_code"` |
| 31 | + // VerificationURI is where user should enter the user code |
| 32 | + VerificationURI string `json:"verification_uri"` |
| 33 | + // VerificationURIComplete (if populated) includes the user code in the verification URI. This is typically shown to the user in non-textual form, such as a QR code. |
| 34 | + VerificationURIComplete string `json:"verification_uri_complete,omitempty"` |
| 35 | + // Expiry is when the device code and user code expire |
| 36 | + Expiry time.Time `json:"expires_in,omitempty"` |
| 37 | + // Interval is the duration in seconds that Poll should wait between requests |
| 38 | + Interval int64 `json:"interval,omitempty"` |
| 39 | +} |
| 40 | + |
| 41 | +func (d DeviceAuthResponse) MarshalJSON() ([]byte, error) { |
| 42 | + type Alias DeviceAuthResponse |
| 43 | + var expiresIn int64 |
| 44 | + if !d.Expiry.IsZero() { |
| 45 | + expiresIn = int64(time.Until(d.Expiry).Seconds()) |
| 46 | + } |
| 47 | + return json.Marshal(&struct { |
| 48 | + ExpiresIn int64 `json:"expires_in,omitempty"` |
| 49 | + *Alias |
| 50 | + }{ |
| 51 | + ExpiresIn: expiresIn, |
| 52 | + Alias: (*Alias)(&d), |
| 53 | + }) |
| 54 | + |
| 55 | +} |
| 56 | + |
| 57 | +func (c *DeviceAuthResponse) UnmarshalJSON(data []byte) error { |
| 58 | + type Alias DeviceAuthResponse |
| 59 | + aux := &struct { |
| 60 | + ExpiresIn int64 `json:"expires_in"` |
| 61 | + *Alias |
| 62 | + }{ |
| 63 | + Alias: (*Alias)(c), |
| 64 | + } |
| 65 | + if err := json.Unmarshal(data, &aux); err != nil { |
| 66 | + return err |
| 67 | + } |
| 68 | + if aux.ExpiresIn != 0 { |
| 69 | + c.Expiry = time.Now().UTC().Add(time.Second * time.Duration(aux.ExpiresIn)) |
| 70 | + } |
| 71 | + return nil |
| 72 | +} |
| 73 | + |
| 74 | +// DeviceAuth returns a device auth struct which contains a device code |
| 75 | +// and authorization information provided for users to enter on another device. |
| 76 | +func (c *Config) DeviceAuth(ctx context.Context, opts ...AuthCodeOption) (*DeviceAuthResponse, error) { |
| 77 | + // https://datatracker.ietf.org/doc/html/rfc8628#section-3.1 |
| 78 | + v := url.Values{ |
| 79 | + "client_id": {c.ClientID}, |
| 80 | + } |
| 81 | + if len(c.Scopes) > 0 { |
| 82 | + v.Set("scope", strings.Join(c.Scopes, " ")) |
| 83 | + } |
| 84 | + for _, opt := range opts { |
| 85 | + opt.setValue(v) |
| 86 | + } |
| 87 | + return retrieveDeviceAuth(ctx, c, v) |
| 88 | +} |
| 89 | + |
| 90 | +func retrieveDeviceAuth(ctx context.Context, c *Config, v url.Values) (*DeviceAuthResponse, error) { |
| 91 | + req, err := http.NewRequest("POST", c.Endpoint.DeviceAuthURL, strings.NewReader(v.Encode())) |
| 92 | + if err != nil { |
| 93 | + return nil, err |
| 94 | + } |
| 95 | + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| 96 | + req.Header.Set("Accept", "application/json") |
| 97 | + |
| 98 | + t := time.Now() |
| 99 | + r, err := internal.ContextClient(ctx).Do(req) |
| 100 | + if err != nil { |
| 101 | + return nil, err |
| 102 | + } |
| 103 | + |
| 104 | + body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20)) |
| 105 | + if err != nil { |
| 106 | + return nil, fmt.Errorf("oauth2: cannot auth device: %v", err) |
| 107 | + } |
| 108 | + if code := r.StatusCode; code < 200 || code > 299 { |
| 109 | + return nil, &RetrieveError{ |
| 110 | + Response: r, |
| 111 | + Body: body, |
| 112 | + } |
| 113 | + } |
| 114 | + |
| 115 | + da := &DeviceAuthResponse{} |
| 116 | + err = json.Unmarshal(body, &da) |
| 117 | + if err != nil { |
| 118 | + return nil, fmt.Errorf("unmarshal %s", err) |
| 119 | + } |
| 120 | + |
| 121 | + if !da.Expiry.IsZero() { |
| 122 | + // Make a small adjustment to account for time taken by the request |
| 123 | + da.Expiry = da.Expiry.Add(-time.Since(t)) |
| 124 | + } |
| 125 | + |
| 126 | + return da, nil |
| 127 | +} |
| 128 | + |
| 129 | +// DeviceAccessToken polls the server to exchange a device code for a token. |
| 130 | +func (c *Config) DeviceAccessToken(ctx context.Context, da *DeviceAuthResponse, opts ...AuthCodeOption) (*Token, error) { |
| 131 | + if !da.Expiry.IsZero() { |
| 132 | + var cancel context.CancelFunc |
| 133 | + ctx, cancel = context.WithDeadline(ctx, da.Expiry) |
| 134 | + defer cancel() |
| 135 | + } |
| 136 | + |
| 137 | + // https://datatracker.ietf.org/doc/html/rfc8628#section-3.4 |
| 138 | + v := url.Values{ |
| 139 | + "client_id": {c.ClientID}, |
| 140 | + "grant_type": {"urn:ietf:params:oauth:grant-type:device_code"}, |
| 141 | + "device_code": {da.DeviceCode}, |
| 142 | + } |
| 143 | + if len(c.Scopes) > 0 { |
| 144 | + v.Set("scope", strings.Join(c.Scopes, " ")) |
| 145 | + } |
| 146 | + for _, opt := range opts { |
| 147 | + opt.setValue(v) |
| 148 | + } |
| 149 | + |
| 150 | + // "If no value is provided, clients MUST use 5 as the default." |
| 151 | + // https://datatracker.ietf.org/doc/html/rfc8628#section-3.2 |
| 152 | + interval := da.Interval |
| 153 | + if interval == 0 { |
| 154 | + interval = 5 |
| 155 | + } |
| 156 | + |
| 157 | + ticker := time.NewTicker(time.Duration(interval) * time.Second) |
| 158 | + defer ticker.Stop() |
| 159 | + for { |
| 160 | + select { |
| 161 | + case <-ctx.Done(): |
| 162 | + return nil, ctx.Err() |
| 163 | + case <-ticker.C: |
| 164 | + tok, err := retrieveToken(ctx, c, v) |
| 165 | + if err == nil { |
| 166 | + return tok, nil |
| 167 | + } |
| 168 | + |
| 169 | + e, ok := err.(*RetrieveError) |
| 170 | + if !ok { |
| 171 | + return nil, err |
| 172 | + } |
| 173 | + switch e.ErrorCode { |
| 174 | + case errSlowDown: |
| 175 | + // https://datatracker.ietf.org/doc/html/rfc8628#section-3.5 |
| 176 | + // "the interval MUST be increased by 5 seconds for this and all subsequent requests" |
| 177 | + interval += 5 |
| 178 | + ticker.Reset(time.Duration(interval) * time.Second) |
| 179 | + case errAuthorizationPending: |
| 180 | + // Do nothing. |
| 181 | + case errAccessDenied, errExpiredToken: |
| 182 | + fallthrough |
| 183 | + default: |
| 184 | + return tok, err |
| 185 | + } |
| 186 | + } |
| 187 | + } |
| 188 | +} |
0 commit comments