-
Notifications
You must be signed in to change notification settings - Fork 111
/
device_code.go
270 lines (247 loc) · 8.61 KB
/
device_code.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
package auth
import (
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
"github.com/rilldata/rill/admin"
"github.com/rilldata/rill/admin/database"
"github.com/rilldata/rill/admin/pkg/urlutil"
"github.com/rilldata/rill/cli/pkg/deviceauth"
)
const deviceCodeGrantType = "urn:ietf:params:oauth:grant-type:device_code"
// DeviceCodeResponse encapsulates the response for obtaining a device code.
type DeviceCodeResponse struct {
DeviceCode string `json:"device_code"`
UserCode string `json:"user_code"`
VerificationURI string `json:"verification_uri"`
VerificationCompleteURI string `json:"verification_uri_complete"`
ExpiresIn int `json:"expires_in"`
PollingInterval int `json:"interval"`
}
// TokenRequest encapsulates the request for obtaining an access token.
type TokenRequest struct {
GrantType string `json:"grant_type"`
DeviceCode string `json:"device_code"`
ClientID string `json:"client_id"`
}
// handleDeviceCodeRequest creates a 24 digit random device code and 8 digit user code and returns that
// to the client. The device code is used to poll for an access token, and the user code is displayed
// to the user and is used to authorize the device. The device code and user code are stored in the
// server's device code store.
func (a *Authenticator) handleDeviceCodeRequest(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "expected a POST request", http.StatusBadRequest)
return
}
body, err := io.ReadAll(r.Body)
if err != nil {
internalServerError(w, fmt.Errorf("failed to read request body: %w", err))
return
}
bodyStr := string(body)
values, err := url.ParseQuery(bodyStr)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
clientID := values.Get("client_id")
if clientID == "" {
http.Error(w, "client_id is required", http.StatusBadRequest)
return
}
scopes := strings.Split(values.Get("scope"), " ")
if len(scopes) == 0 {
http.Error(w, "scope is required", http.StatusBadRequest)
return
}
if len(scopes) > 1 || scopes[0] != "full_account" {
http.Error(w, "invalid scope", http.StatusBadRequest)
return
}
authCode, err := a.admin.IssueDeviceAuthCode(r.Context(), clientID)
if err != nil {
internalServerError(w, fmt.Errorf("failed to issue auth code: %w", err))
return
}
verificationURI, err := url.JoinPath(a.opts.FrontendURL, "/-/auth/device")
if err != nil {
internalServerError(w, fmt.Errorf("failed to create verification uri: %w", err))
return
}
qry := map[string]string{"user_code": authCode.UserCode}
if values.Get("redirect") != "" {
qry["redirect"] = values.Get("redirect")
}
verificationCompleteURI, err := urlutil.WithQuery(verificationURI, qry)
if err != nil {
internalServerError(w, fmt.Errorf("failed to create verification uri: %w", err))
return
}
resp := DeviceCodeResponse{
DeviceCode: authCode.DeviceCode,
UserCode: authCode.UserCode,
VerificationURI: verificationURI,
VerificationCompleteURI: verificationCompleteURI,
ExpiresIn: int(admin.DeviceAuthCodeTTL.Seconds()),
PollingInterval: 5,
}
respBytes, err := json.Marshal(resp)
if err != nil {
internalServerError(w, fmt.Errorf("failed to marshal response, %w", err))
return
}
w.Header().Set("Content-Type", "application/json")
_, err = w.Write(respBytes)
if err != nil {
internalServerError(w, fmt.Errorf("failed to write response, %w", err))
return
}
}
// handleUserCodeConfirmation handles the user code confirmation page. The user code is displayed
// to the user and they are asked to confirm that they want to authorize the device. If the user
// confirms, the device code is marked as approved in the server's device code store.
func (a *Authenticator) handleUserCodeConfirmation(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "expected a POST request", http.StatusBadRequest)
return
}
userCode := r.URL.Query().Get("user_code")
if userCode == "" {
http.Error(w, "user_code is required", http.StatusBadRequest)
return
}
confirmation := r.URL.Query().Get("code_confirmed")
if confirmation == "" {
http.Error(w, "no code confirmation", http.StatusBadRequest)
return
}
claims := GetClaims(r.Context())
if claims == nil {
internalServerError(w, fmt.Errorf("did not find any claims, %w", errors.New("server error")))
return
}
if claims.OwnerType() != OwnerTypeUser {
http.Error(w, "only users can confirm device codes", http.StatusBadRequest)
return
}
userID := claims.OwnerID()
authCode, err := a.admin.DB.FindPendingDeviceAuthCodeByUserCode(r.Context(), userCode)
if err != nil {
if errors.Is(err, database.ErrNotFound) {
http.Error(w, fmt.Sprintf("no such user code: %s found", userCode), http.StatusBadRequest)
return
}
internalServerError(w, fmt.Errorf("failed to get auth code for userCode: %s, %w", userCode, err))
return
}
// Update user code with user id and approval
authCode.UserID = &userID
if confirmation != "true" {
authCode.ApprovalState = database.DeviceAuthCodeStateRejected
} else {
authCode.ApprovalState = database.DeviceAuthCodeStateApproved
}
err = a.admin.DB.UpdateDeviceAuthCode(r.Context(), authCode.ID, userID, authCode.ApprovalState)
if err != nil {
internalServerError(w, fmt.Errorf("failed to update auth code for userCode: %s, %w", userCode, err))
}
}
// getAccessToken verifies the device code and returns an access token if the request is approved
func (a *Authenticator) getAccessToken(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "expected a POST request", http.StatusBadRequest)
return
}
body, err := io.ReadAll(r.Body)
if err != nil {
internalServerError(w, fmt.Errorf("failed to read request body: %w", err))
return
}
bodyStr := string(body)
values, err := url.ParseQuery(bodyStr)
if err != nil {
internalServerError(w, fmt.Errorf("failed to parse query: %w", err))
return
}
deviceCode := values.Get("device_code")
if deviceCode == "" {
http.Error(w, "device_code is required", http.StatusBadRequest)
return
}
grantType := values.Get("grant_type")
if grantType != deviceCodeGrantType {
http.Error(w, "invalid grant_type", http.StatusBadRequest)
return
}
authCode, err := a.admin.DB.FindDeviceAuthCodeByDeviceCode(r.Context(), deviceCode)
if err != nil {
if errors.Is(err, database.ErrNotFound) {
http.Error(w, fmt.Sprintf("no such device code: %s found", deviceCode), http.StatusBadRequest)
return
}
internalServerError(w, fmt.Errorf("failed to get auth code for deviceCode: %s, %w", deviceCode, err))
return
}
clientID := values.Get("client_id")
if clientID != authCode.ClientID {
http.Error(w, "invalid client_id", http.StatusBadRequest)
return
}
if authCode.Expiry.Before(time.Now()) {
http.Error(w, "expired_token", http.StatusUnauthorized)
return
}
if authCode.ApprovalState == database.DeviceAuthCodeStateRejected {
err = a.admin.DB.DeleteDeviceAuthCode(r.Context(), deviceCode)
if err != nil {
internalServerError(w, fmt.Errorf("failed to clean up rejected code: %s, %w", deviceCode, err))
return
}
http.Error(w, "rejected", http.StatusUnauthorized)
return
}
if authCode.ApprovalState == database.DeviceAuthCodeStatePending {
http.Error(w, "authorization_pending", http.StatusUnauthorized)
return
}
if authCode.ApprovalState != database.DeviceAuthCodeStateApproved || authCode.UserID == nil {
internalServerError(w, fmt.Errorf("inconsistent state, %w", errors.New("server error")))
return
}
// TODO handle too many requests
authToken, err := a.admin.IssueUserAuthToken(r.Context(), *authCode.UserID, authCode.ClientID, "")
if err != nil {
internalServerError(w, fmt.Errorf("failed to issue access token, %w", err))
return
}
err = a.admin.DB.DeleteDeviceAuthCode(r.Context(), deviceCode)
if err != nil {
internalServerError(w, fmt.Errorf("failed to clean up approved code: %s, %w", deviceCode, err))
return
}
resp := deviceauth.OAuthTokenResponse{
AccessToken: authToken.Token().String(),
TokenType: "Bearer",
ExpiresIn: time.UnixMilli(0).Unix(), // never expires
UserID: *authCode.UserID,
}
respBytes, err := json.Marshal(resp)
if err != nil {
internalServerError(w, fmt.Errorf("failed to marshal response, %w", err))
return
}
w.Header().Set("Content-Type", "application/json")
_, err = w.Write(respBytes)
if err != nil {
internalServerError(w, fmt.Errorf("failed to write response, %w", err))
return
}
}
func internalServerError(w http.ResponseWriter, err error) {
http.Error(w, err.Error(), http.StatusInternalServerError)
}