-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
Copy pathapi_v2_auth.go
474 lines (437 loc) · 14.2 KB
/
api_v2_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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
// Copyright 2021 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package server
import (
"context"
"encoding/base64"
"net/http"
"github.com/cockroachdb/cockroach/pkg/security/username"
"github.com/cockroachdb/cockroach/pkg/server/serverpb"
"github.com/cockroachdb/cockroach/pkg/sql"
"github.com/cockroachdb/cockroach/pkg/sql/roleoption"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sessiondata"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/protoutil"
"github.com/cockroachdb/errors"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
)
// authenticationV2Server is a sub-server under apiV2Server that handles
// authentication-related endpoints, such as login and logout. The actual
// verification of sessions for regular endpoints happens in authenticationV2Mux,
// not here.
type authenticationV2Server struct {
ctx context.Context
sqlServer *SQLServer
authServer *authenticationServer
mux *http.ServeMux
basePath string
}
// newAuthenticationV2Server creates a new authenticationV2Server for the given
// outer Server, and base path.
func newAuthenticationV2Server(
ctx context.Context, s *Server, basePath string,
) *authenticationV2Server {
simpleMux := http.NewServeMux()
authServer := &authenticationV2Server{
sqlServer: s.sqlServer,
authServer: newAuthenticationServer(s.cfg.Config, s.sqlServer),
mux: simpleMux,
ctx: ctx,
basePath: basePath,
}
authServer.registerRoutes()
return authServer
}
func (a *authenticationV2Server) registerRoutes() {
a.bindEndpoint("login/", a.login)
a.bindEndpoint("logout/", a.logout)
}
func (a *authenticationV2Server) bindEndpoint(endpoint string, handler http.HandlerFunc) {
a.mux.HandleFunc(a.basePath+endpoint, handler)
}
// createSessionFor creates a login session for the given user.
//
// The caller is responsible to ensure the username has been normalized already.
func (a *authenticationV2Server) createSessionFor(
ctx context.Context, userName username.SQLUsername,
) (string, error) {
// Create a new database session, generating an ID and secret key.
id, secret, err := a.authServer.newAuthSession(ctx, userName)
if err != nil {
return "", apiInternalError(ctx, err)
}
// Generate and set a session for the response. Because HTTP cookies
// must be strings, the cookie value (a marshaled protobuf) is encoded in
// base64. We just piggyback on the v1 API SessionCookie here, however
// this won't be set as an HTTP cookie on the client side.
cookieValue := &serverpb.SessionCookie{
ID: id,
Secret: secret,
}
cookieValueBytes, err := protoutil.Marshal(cookieValue)
if err != nil {
return "", errors.Wrap(err, "session cookie could not be encoded")
}
value := base64.StdEncoding.EncodeToString(cookieValueBytes)
return value, nil
}
// swagger:model loginResponse
type loginResponse struct {
// Session string for a valid API session. Specify this in header for any API
// requests that require authentication.
Session string `json:"session"`
}
// swagger:operation POST /login/ login
//
// API Login
//
// Creates an API session for use with API endpoints that require
// authentication.
//
// ---
// parameters:
// - name: credentials
// schema:
// type: object
// properties:
// username:
// type: string
// password:
// type: string
// required:
// - username
// - password
// in: body
// description: Credentials for login
// required: true
// produces:
// - application/json
// - text/plain
// consumes:
// - application/x-www-form-urlencoded
// responses:
// "200":
// description: Login response.
// schema:
// "$ref": "#/definitions/loginResponse"
// "400":
// description: Bad request, if required parameters absent.
// type: string
// "401":
// description: Unauthorized, if credentials don't match.
// type: string
func (a *authenticationV2Server) login(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, "not found", http.StatusNotFound)
}
if err := r.ParseForm(); err != nil {
apiV2InternalError(r.Context(), err, w)
return
}
if r.Form.Get("username") == "" {
http.Error(w, "username not specified", http.StatusBadRequest)
return
}
// In CockroachDB SQL, unlike in PostgreSQL, usernames are
// case-insensitive. Therefore we need to normalize the username
// here, so that the normalized username is retained in the session
// table: the APIs extract the username from the session table
// without further normalization.
username, _ := username.MakeSQLUsernameFromUserInput(r.Form.Get("username"), username.PurposeValidation)
// Verify the provided username/password pair.
verified, expired, err := a.authServer.verifyPasswordDBConsole(a.ctx, username, r.Form.Get("password"))
if err != nil {
apiV2InternalError(r.Context(), err, w)
return
}
if expired {
http.Error(w, "the password has expired", http.StatusUnauthorized)
return
}
if !verified {
http.Error(w, "the provided credentials did not match any account on the server", http.StatusUnauthorized)
return
}
session, err := a.createSessionFor(a.ctx, username)
if err != nil {
apiV2InternalError(r.Context(), err, w)
return
}
writeJSONResponse(r.Context(), w, http.StatusOK, &loginResponse{Session: session})
}
// swagger:model logoutResponse
type logoutResponse struct {
// Indicates whether logout was successful.
LoggedOut bool `json:"logged_out"`
}
// swagger:operation POST /logout/ logout
//
// API Logout
//
// Logs out on a previously-created API session.
//
// ---
// produces:
// - application/json
// - text/plain
// security:
// - api_session: []
// responses:
// "200":
// description: Logout response.
// schema:
// "$ref": "#/definitions/logoutResponse"
// "400":
// description: Bad request, if API session not present in headers, or
// invalid session.
// type: string
func (a *authenticationV2Server) logout(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, "not found", http.StatusNotFound)
}
session := r.Header.Get(apiV2AuthHeader)
if session == "" {
http.Error(w, "invalid or unspecified session", http.StatusBadRequest)
return
}
var sessionCookie serverpb.SessionCookie
decoded, err := base64.StdEncoding.DecodeString(session)
if err != nil {
apiV2InternalError(r.Context(), err, w)
return
}
if err := protoutil.Unmarshal(decoded, &sessionCookie); err != nil {
apiV2InternalError(r.Context(), err, w)
return
}
// Revoke the session.
if n, err := a.sqlServer.internalExecutor.ExecEx(
a.ctx,
"revoke-auth-session",
nil, /* txn */
sessiondata.InternalExecutorOverride{User: username.RootUserName()},
`UPDATE system.web_sessions SET "revokedAt" = now() WHERE id = $1`,
sessionCookie.ID,
); err != nil {
apiV2InternalError(r.Context(), err, w)
return
} else if n == 0 {
err := status.Errorf(
codes.InvalidArgument,
"session with id %d nonexistent", sessionCookie.ID)
log.Infof(a.ctx, "%v", err)
http.Error(w, "invalid session", http.StatusBadRequest)
return
}
writeJSONResponse(r.Context(), w, http.StatusOK, &logoutResponse{LoggedOut: true})
}
func (a *authenticationV2Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
a.mux.ServeHTTP(w, r)
}
// authenticationV2Mux provides authentication checks for an arbitrary inner
// http.Handler. If the session cookie is not set, an HTTP 401 error is returned
// and the request isn't routed through to the inner handler. On success, the
// username is set on the request context for use in the inner handler.
type authenticationV2Mux struct {
s *authenticationV2Server
inner http.Handler
}
func newAuthenticationV2Mux(s *authenticationV2Server, inner http.Handler) *authenticationV2Mux {
return &authenticationV2Mux{
s: s,
inner: inner,
}
}
// apiV2UseCookieBasedAuth is a magic value of the auth header that
// tells us to look for the session in the cookie. This can be used by
// frontend code to maintain cookie-based auth while interacting with
// the API.
const apiV2UseCookieBasedAuth = "cookie"
// getSession decodes the cookie from the request, looks up the
// corresponding session, and returns the logged in user name. The
// session can be looked up either from a session cookie as used in the
// non-v2 API server, or via the session header. In order for us to pick
// up a session, the header must still be non-empty in the case of
// cookie-based auth. If there's an error, it returns an error value and
// also sends the error over http using w.
func (a *authenticationV2Mux) getSession(
w http.ResponseWriter, req *http.Request,
) (string, *serverpb.SessionCookie, error) {
// Validate the returned session header or cookie.
rawSession := req.Header.Get(apiV2AuthHeader)
if len(rawSession) == 0 {
err := errors.New("invalid session header")
http.Error(w, err.Error(), http.StatusUnauthorized)
return "", nil, err
}
possibleSessions := []string{}
if rawSession == apiV2UseCookieBasedAuth {
cookies := req.Cookies()
for _, c := range cookies {
if c.Name != SessionCookieName {
continue
}
possibleSessions = append(possibleSessions, c.Value)
}
} else {
possibleSessions = append(possibleSessions, rawSession)
}
sessionCookie := &serverpb.SessionCookie{}
var decoded []byte
var err error
for i := range possibleSessions {
decoded, err = base64.StdEncoding.DecodeString(possibleSessions[i])
if err != nil {
continue
}
err = protoutil.Unmarshal(decoded, sessionCookie)
if err != nil {
continue
}
// We've successfully decoded a session from cookie or header
break
}
if err != nil {
err := errors.New("invalid session header")
http.Error(w, err.Error(), http.StatusBadRequest)
return "", nil, err
}
valid, username, err := a.s.authServer.verifySession(req.Context(), sessionCookie)
if err != nil {
apiV2InternalError(req.Context(), err, w)
return "", nil, err
}
if !valid {
err := errors.New("the provided authentication session could not be validated")
http.Error(w, err.Error(), http.StatusUnauthorized)
return "", nil, err
}
return username, sessionCookie, nil
}
func (a *authenticationV2Mux) ServeHTTP(w http.ResponseWriter, req *http.Request) {
username, cookie, err := a.getSession(w, req)
if err == nil {
// Valid session found. Set the username in the request context, so
// child http.Handlers can access it.
ctx := req.Context()
ctx = context.WithValue(ctx, webSessionUserKey{}, username)
ctx = context.WithValue(ctx, webSessionIDKey{}, cookie.ID)
req = req.WithContext(ctx)
} else {
// getSession writes an error to w if err != nil.
return
}
a.inner.ServeHTTP(w, req)
}
type apiRole int
const (
regularRole apiRole = iota
adminRole
superUserRole
)
// roleAuthorizationMux enforces a role (eg. type of user, role option)
// for an arbitrary inner mux. Meant to be used under authenticationV2Mux. If
// the logged-in user is not at least of `role` type, and doesn't have
// the `option` roleoption, an HTTP 403 forbidden error is returned. Otherwise,
// the request is passed onto the inner http.Handler.
type roleAuthorizationMux struct {
ie *sql.InternalExecutor
role apiRole
option roleoption.Option
inner http.Handler
}
func (r *roleAuthorizationMux) getRoleForUser(
ctx context.Context, user username.SQLUsername,
) (apiRole, error) {
if user.IsRootUser() {
// Shortcut.
return superUserRole, nil
}
row, err := r.ie.QueryRowEx(
ctx, "check-is-admin", nil, /* txn */
sessiondata.InternalExecutorOverride{User: user},
"SELECT crdb_internal.is_admin()")
if err != nil {
return regularRole, err
}
if row == nil {
return regularRole, errors.AssertionFailedf("hasAdminRole: expected 1 row, got 0")
}
if len(row) != 1 {
return regularRole, errors.AssertionFailedf("hasAdminRole: expected 1 column, got %d", len(row))
}
dbDatum, ok := tree.AsDBool(row[0])
if !ok {
return regularRole, errors.AssertionFailedf("hasAdminRole: expected bool, got %T", row[0])
}
if dbDatum {
return adminRole, nil
}
return regularRole, nil
}
func (r *roleAuthorizationMux) hasRoleOption(
ctx context.Context, user username.SQLUsername, roleOption roleoption.Option,
) (bool, error) {
if user.IsRootUser() {
// Shortcut.
return true, nil
}
row, err := r.ie.QueryRowEx(
ctx, "check-role-option", nil, /* txn */
sessiondata.InternalExecutorOverride{User: user},
"SELECT crdb_internal.has_role_option($1)", roleOption.String())
if err != nil {
return false, err
}
if row == nil {
return false, errors.AssertionFailedf("hasRoleOption: expected 1 row, got 0")
}
if len(row) != 1 {
return false, errors.AssertionFailedf("hasRoleOption: expected 1 column, got %d", len(row))
}
dbDatum, ok := tree.AsDBool(row[0])
if !ok {
return false, errors.AssertionFailedf("hasRoleOption: expected bool, got %T", row[0])
}
return bool(dbDatum), nil
}
func (r *roleAuthorizationMux) ServeHTTP(w http.ResponseWriter, req *http.Request) {
// The username is set in authenticationV2Mux, and must correspond with a
// logged-in user.
username := username.MakeSQLUsernameFromPreNormalizedString(
req.Context().Value(webSessionUserKey{}).(string))
if role, err := r.getRoleForUser(req.Context(), username); err != nil || role < r.role {
if err != nil {
apiV2InternalError(req.Context(), err, w)
} else {
http.Error(w, "user not allowed to access this endpoint", http.StatusForbidden)
}
return
}
if r.option > 0 {
ok, err := r.hasRoleOption(req.Context(), username, r.option)
if err != nil {
apiV2InternalError(req.Context(), err, w)
return
} else if !ok {
http.Error(w, "user not allowed to access this endpoint", http.StatusForbidden)
return
}
}
r.inner.ServeHTTP(w, req)
}
// apiToOutgoingGatewayCtx converts an HTTP API (v1 or v2) context, to one that
// can issue outgoing RPC requests under the same logged-in user.
func apiToOutgoingGatewayCtx(ctx context.Context, r *http.Request) context.Context {
return metadata.NewOutgoingContext(ctx, forwardAuthenticationMetadata(ctx, r))
}