-
Notifications
You must be signed in to change notification settings - Fork 28
/
rest_auth.go
619 lines (527 loc) · 17.2 KB
/
rest_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
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
// Copyright 2015-Present Couchbase, Inc.
//
// Use of this software is governed by the Business Source License included
// in the file licenses/BSL-Couchbase.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/APL2.txt.
package cbft
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"github.com/blevesearch/bleve/v2"
"github.com/buger/jsonparser"
"github.com/couchbase/cbauth"
"github.com/couchbase/cbgt"
"github.com/couchbase/cbgt/rest"
log "github.com/couchbase/clog"
audit "github.com/couchbase/goutils/go-cbaudit"
)
// CBAuthWebCreds extra level-of-indirection allows for overrides and
// for more testability.
var CBAuthWebCreds = cbauth.AuthWebCreds
// CBAuthIsAllowed extra level-of-indirection allows for overrides and
// for more testability.
var CBAuthIsAllowed = func(creds cbauth.Creds, permission string) (
bool, error) {
return creds.IsAllowed(permission)
}
// CBAuthSendForbidden extra level-of-indirection allows for overrides
// and for more testability.
var CBAuthSendForbidden = func(w http.ResponseWriter, permission string) {
cbauth.SendForbidden(w, permission)
}
// CBAuthSendUnauthorized extra level-of-indirection allows for
// overrides and for more testability.
var CBAuthSendUnauthorized = func(w http.ResponseWriter) {
cbauth.SendUnauthorized(w)
}
// UrlWithAuth extra level-of-indirection allows for
// overrides and for more testability.
var UrlWithAuth = func(authType, urlStr string) (string, error) {
if authType == "cbauth" {
return cbgt.CBAuthURL(urlStr)
}
return urlStr, nil
}
// --------------------------------------------------
// Map of "method:path" => "perm". For example, "GET:/api/index" =>
// "cluster.bucket.fts!read".
var restPermsMap = map[string]string{}
var restAuditMap = map[string]uint32{}
func init() {
// Initialze restPermsMap from restPerms.
rps := strings.Split(strings.TrimSpace(restPerms), "\n\n")
for _, rp := range rps {
// Example rp: "GET /api/index\ncluster.bucket...!read".
rpa := strings.Split(rp, "\n")
ra := strings.Split(rpa[0], " ")
method := ra[0]
path := ra[1]
perm := rpa[1]
restPermsMap[method+":"+path] = perm
if len(rpa) > 2 {
eventId, _ := strconv.ParseUint(rpa[2], 0, 32)
restAuditMap[method+":"+path] = uint32(eventId)
}
}
}
// --------------------------------------------------------
func addUserAgentHeaderToRequest(req *http.Request) {
req.Header.Set("User-Agent", cbgt.UserAgentStr)
}
func checkAPIAuth(avh *AuthVersionHandler,
w http.ResponseWriter, req *http.Request, path string) (
allowed bool, username string) {
authType := ""
var mgr *cbgt.Manager
var adtSvc *audit.AuditSvc
if avh != nil {
mgr = avh.mgr
adtSvc = avh.adtSvc
}
if mgr != nil {
authType = mgr.GetOption("authType")
}
if authType == "" {
return true, ""
}
if authType != "cbauth" {
return false, ""
}
r := &restRequestParser{req: req}
perms, err := preparePerms(mgr, r, req.Method, path)
if err != nil {
requestBody, _ := io.ReadAll(req.Body)
rest.PropagateError(w, requestBody, fmt.Sprintf("rest_auth: preparePerms,"+
" err: %v", err), http.StatusBadRequest)
return false, ""
}
if len(perms) <= 0 {
return true, ""
}
addUserAgentHeaderToRequest(req)
creds, err := CBAuthWebCreds(req)
if err != nil {
requestBody, _ := io.ReadAll(req.Body)
rest.PropagateError(w, requestBody, fmt.Sprintf("rest_auth: cbauth.AuthWebCreds,"+
" err: %v", err), http.StatusForbidden)
if adtSvc != nil {
d := GetAuditEventData(AuditAccessDeniedEvent, req)
go adtSvc.Write(AuditAccessDeniedEvent, d)
}
return false, ""
}
for _, perm := range perms {
allowed, err = CBAuthIsAllowed(creds, perm)
if err != nil {
requestBody, _ := io.ReadAll(req.Body)
rest.PropagateError(w, requestBody, fmt.Sprintf("rest_auth: cbauth.IsAllowed,"+
" err: %v", err), http.StatusForbidden)
return false, ""
}
if !allowed {
forbiddenMessage := "permission to perform this action for the source."
split := strings.Split(perm, "!")
if len(split) >= 2 {
forbiddenMessage = split[len(split)-1] + " permission for the source."
}
CBAuthSendForbidden(w, forbiddenMessage)
if adtSvc != nil {
d := GetAuditEventData(AuditAccessDeniedEvent, req)
go adtSvc.Write(AuditAccessDeniedEvent, d)
}
log.Debugf("rest_auth: Permission denied for request from user: %v,"+
" (perm: %v) over path: %v",
log.Tag(log.UserData, creds.Name()), log.Tag(log.UserData, perm), path)
return false, ""
}
}
username = creds.Name()
if ok, msg := processRequest(username, path, req); !ok {
requestBody, _ := io.ReadAll(req.Body)
rest.PropagateError(w, requestBody, msg, http.StatusTooManyRequests)
return false, ""
}
return true, username
}
// --------------------------------------------------------
func sourceNamesForAlias(name string, indexDefsByName map[string]*cbgt.IndexDef,
visitedAliases map[string]bool) ([]string, error) {
var rv []string
if visitedAliases == nil {
visitedAliases = make(map[string]bool)
}
indexDef, exists := indexDefsByName[name]
if exists && indexDef != nil && indexDef.Type == "fulltext-alias" {
visitedAliases[name] = true
aliasParams, err := parseAliasParams(indexDef.Params)
if err != nil {
return nil, fmt.Errorf("error expanding fulltext-alias: %v", err)
}
aliasBucket, _ := getKeyspaceFromScopedIndexName(name)
for aliasTarget := range aliasParams.Targets {
// Check if this is a scoped alias target, in which case
// the source name can be retrieved from the name.
bucket, _ := getKeyspaceFromScopedIndexName(aliasTarget)
if len(bucket) > 0 {
rv = append(rv, bucket)
continue
} else if len(aliasBucket) > 0 {
// If the alias is scoped, then the alias target is scoped
// to the same keyspace as the alias during the PREPARE phase.
rv = append(rv, aliasBucket)
continue
}
aliasIndexDef, exists := indexDefsByName[aliasTarget]
// if alias target doesn't exist, do nothing
if exists {
if aliasIndexDef.Type == "fulltext-alias" {
if visitedAliases[aliasTarget] {
continue
}
// handle nested aliases with recursive call
nestedSources, err := sourceNamesForAlias(aliasTarget,
indexDefsByName, visitedAliases)
if err != nil {
return nil, err
}
rv = append(rv, nestedSources...)
} else {
sourceNames, err := getSourceNamesFromIndexDef(aliasIndexDef)
if err != nil {
return nil, err
}
rv = append(rv, sourceNames...)
}
}
}
}
return rv, nil
}
func getSourceNamesFromIndexDef(indexDef *cbgt.IndexDef) ([]string, error) {
if len(indexDef.Params) > 0 {
bleveParamBytes := []byte(indexDef.Params)
docConfig, _, _, err := jsonparser.Get(bleveParamBytes, "doc_config")
if err != nil {
// couldn't find doc_config to detect the mode
return []string{indexDef.SourceName}, nil
}
docConfigMode, _, _, _ := jsonparser.Get(docConfig, "mode")
if strings.HasPrefix(string(docConfigMode), ConfigModeCollPrefix) {
// look up the scope/collection details from the cache.
scopeName, collectionNames := metaFieldValCache.getScopeCollectionNames(indexDef.Name)
if len(scopeName) > 0 && len(collectionNames) > 0 {
sourceNames := make([]string, len(collectionNames))
for i := range collectionNames {
sourceNames[i] = indexDef.SourceName + ":" + scopeName + ":" + collectionNames[i]
}
return sourceNames, nil
}
// parse it again if the cache is empty like that in a unit test.
bmapping, _, _, err := jsonparser.Get(bleveParamBytes, "mapping")
if err != nil {
return nil, err
}
mapping := bleve.NewIndexMapping()
err = UnmarshalJSON(bmapping, mapping)
if err != nil {
return nil, err
}
sName, colNames, _, err := getScopeCollTypeMappings(mapping, true)
if err != nil {
return nil, err
}
sourceNames := make([]string, len(colNames))
for i, colName := range colNames {
sourceNames[i] = indexDef.SourceName + ":" + sName + ":" + colName
}
return sourceNames, nil
}
}
return []string{indexDef.SourceName}, nil
}
// an interface to abstract the bare minimum aspect of a cbgt.Manager
// that we need, so that we can stub the interface for testing
type definitionLookuper interface {
GetPIndex(pindexName string) *cbgt.PIndex
GetIndexDefs(refresh bool) (*cbgt.IndexDefs, map[string]*cbgt.IndexDef, error)
}
// requestParser is an interface which both the rest and rpc based
// services to implement for eliciting the bare minimum parameters
// needed for performing the authentication
type requestParser interface {
GetIndexName() (string, error)
GetPIndexName() (string, error)
GetIndexDef() (*cbgt.IndexDef, error)
GetRequest() (interface{}, string)
GetCollectionNames() ([]string, error)
GetBucketName() (string, error)
}
var errInvalidHttpRequest = fmt.Errorf("rest_auth: invalid http request")
type restRequestParser struct {
req *http.Request
}
func (p *restRequestParser) GetRequest() (interface{}, string) {
return p.req, "REST"
}
func (p *restRequestParser) GetIndexName() (string, error) {
return rest.IndexNameLookup(p.req), nil
}
func (p *restRequestParser) GetPIndexName() (string, error) {
pindexName := rest.PIndexNameLookup(p.req)
if pindexName != "" {
return pindexName, nil
}
return "", fmt.Errorf("rest_auth: restRequestParser, missing pindexName")
}
func (p *restRequestParser) GetBucketName() (string, error) {
bucketName := rest.BucketNameLookup(p.req)
if bucketName != "" {
return bucketName, nil
}
return "", fmt.Errorf("rest_auth: restRequestParser, missing bucketName")
}
func (p *restRequestParser) GetIndexDef() (*cbgt.IndexDef, error) {
var requestBody []byte
var err error
if p.req.Body != nil {
requestBody, err = io.ReadAll(p.req.Body)
if err != nil {
return nil, fmt.Errorf("rest_auth: restRequestParser, err: %v", err)
}
}
// reset req.Body so it can be read later by the handler
p.req.Body = io.NopCloser(bytes.NewReader(requestBody))
var indexDef cbgt.IndexDef
if len(requestBody) > 0 {
err := json.Unmarshal(requestBody, &indexDef)
if err != nil {
return nil, fmt.Errorf("rest_auth: restRequestParser, unmarshal err: %v", err)
}
}
if indexDef.Type == "" {
// if indexType wasn't found in the request body, attempt reading it
// from the form entries.
indexDef.Type = p.req.FormValue("indexType")
}
return &indexDef, nil
}
func (p *restRequestParser) GetCollectionNames() ([]string, error) {
var requestBody []byte
var err error
if p.req.Body != nil {
requestBody, err = io.ReadAll(p.req.Body)
if err != nil {
return nil, fmt.Errorf("rest_auth: restRequestParser, err: %v", err)
}
}
// reset req.Body so it can be read later by the handler
p.req.Body = io.NopCloser(bytes.NewReader(requestBody))
var rv []string
jsonparser.ArrayEach(requestBody, func(value []byte,
dataType jsonparser.ValueType, offset int, err error) {
rv = append(rv, string(value))
}, "collections")
return rv, nil
}
var errIndexNotFound = fmt.Errorf("index not found")
var errPIndexNotFound = fmt.Errorf("pindex not found")
func sourceNamesFromReq(mgr definitionLookuper, rp requestParser,
method, path string) ([]string, error) {
indexName, _ := rp.GetIndexName()
_, indexDefsByName, err := mgr.GetIndexDefs(false)
if err != nil {
return nil, err
}
if indexName != "" {
indexDef, exists := indexDefsByName[indexName]
if !exists {
// Force refresh of indexDefs and try again.
_, indexDefsByName, err = mgr.GetIndexDefs(true)
if err != nil {
return nil, err
}
indexDef, exists = indexDefsByName[indexName]
if !exists || indexDef == nil {
if method == "PUT" {
// Special case where PUT represents an index creation
// when there's no indexDef.
return findCouchbaseSourceNames(rp, indexName, indexDefsByName)
}
return nil, errIndexNotFound
}
}
var sourceNames []string
var currSourceNames []string
if indexDef.Type == "fulltext-alias" {
// this finds the sources in current definition
var visitedAliases map[string]bool
currSourceNames, err = sourceNamesForAlias(indexName, indexDefsByName, visitedAliases)
if err != nil {
return nil, err
}
sourceNames = append(sourceNames, currSourceNames...)
} else {
// first use the source in current definition
currSourceNames, err = getSourceNamesFromIndexDef(indexDef)
if err != nil {
return nil, err
}
// get the target collections from the request
targetColls, _ := rp.GetCollectionNames()
// authenticate against all the sourcenames if its a blanket query
if len(targetColls) == 0 {
return append(sourceNames, currSourceNames...), nil
}
// authenticate only against the given target collections
collMap := cbgt.StringsToMap(targetColls)
for _, sn := range currSourceNames {
pos := strings.LastIndex(sn, ":") + 1
if _, found := collMap[sn[pos:]]; found {
sourceNames = append(sourceNames, sn)
}
}
}
return sourceNames, nil
}
pindexName, err := rp.GetPIndexName()
if pindexName == "" || err != nil {
return nil, fmt.Errorf("missing indexName/pindexName, err: %v", err)
}
pindex := mgr.GetPIndex(pindexName)
if pindex == nil {
return nil, errPIndexNotFound
}
indexDef, exists := indexDefsByName[pindex.IndexName]
if !exists {
// Force refresh of indexDefs and try again.
_, indexDefsByName, err = mgr.GetIndexDefs(true)
if err != nil {
return nil, err
}
indexDef, _ = indexDefsByName[pindex.IndexName]
}
if indexDef != nil {
return getSourceNamesFromIndexDef(indexDef)
}
return nil, fmt.Errorf("invalid pindexName: %s", pindexName)
}
func preparePerms(mgr definitionLookuper, r requestParser,
method, path string) ([]string, error) {
perm := restPermsMap[method+":"+path]
if perm == "" {
perm = restPermDefault
} else if perm == "none" {
return nil, nil
} else if strings.Index(perm, "{}") >= 0 {
return nil, nil // Need dynamic post-filtering of REST response.
}
if strings.Index(perm, "<sourceName>") >= 0 {
sourceNames, err := sourceNamesFromReq(mgr, r, method, path)
if err != nil {
return nil, err
}
perms := make([]string, 0, len(sourceNames))
for _, sourceName := range sourceNames {
perms = append(perms,
decoratePermStrings(perm, sourceName))
}
return perms, nil
} else if strings.Index(perm, "<bucketName>") >= 0 {
bucketName, err := r.GetBucketName()
if err != nil {
return nil, err
}
perm = strings.ReplaceAll(perm, "<bucketName>", bucketName)
}
return []string{perm}, nil
}
func decoratePermStrings(perm, sourceName string) string {
// If the RBAC settings are done at the scope or collection
// level, then update the perm placeholder strings (refer rest_perm.go)
// accordingly before decorating it with the source details.
// This source enriched perm strings are further sent for
// authentications.
/*
Perm string for RBAC at bucket level “test”:
cluster.bucket[test].data.docs!read
Perm string for RBAC at bucket “test”, scope “s”:
cluster.scope[test:s].data.docs!read
Perm string for RBAC at bucket “test”, scope “s”, collection “c”:
cluster.collection[test:s:c].data.docs!read
*/
rbacLevel := strings.Count(sourceName, ":")
if rbacLevel == 0 {
perm = strings.ReplaceAll(perm, "collection", "bucket")
} else if rbacLevel == 1 {
perm = strings.ReplaceAll(perm, "collection", "scope")
}
return strings.ReplaceAll(perm, "<sourceName>", sourceName)
}
func findCouchbaseSourceNames(r requestParser, indexName string,
indexDefsByName map[string]*cbgt.IndexDef) (rv []string, err error) {
indexDef, err := r.GetIndexDef()
if err != nil || indexDef == nil {
return nil, err
}
if indexDef.Type == "fulltext-index" {
t, reqType := r.GetRequest()
req := t.(*http.Request)
// TODO handle this for RPCs.
if reqType == "REST" {
sourceType, _ := rest.ExtractSourceTypeName(req, indexDef, indexName)
if sourceType == cbgt.SOURCE_GOCOUCHBASE || sourceType == cbgt.SOURCE_GOCBCORE {
return getSourceNamesFromIndexDef(indexDef)
}
}
} else if indexDef.Type == "fulltext-alias" {
// create a copy of indexDefNames with the new one added
futureIndexDefsByName := make(map[string]*cbgt.IndexDef,
len(indexDefsByName)+1)
for k, v := range indexDefsByName {
futureIndexDefsByName[k] = v
}
futureIndexDefsByName[indexName] = indexDef
var visitedAliases map[string]bool
return sourceNamesForAlias(indexName, futureIndexDefsByName, visitedAliases)
}
return nil, nil
}
type CBAuthBasicLogin struct {
mgr *cbgt.Manager
}
func CBAuthBasicLoginHandler(mgr *cbgt.Manager) (*CBAuthBasicLogin, error) {
return &CBAuthBasicLogin{
mgr: mgr,
}, nil
}
func (h *CBAuthBasicLogin) ServeHTTP(
w http.ResponseWriter, req *http.Request) {
authType := ""
if h.mgr != nil {
authType = h.mgr.GetOption("authType")
}
if authType == "cbauth" {
addUserAgentHeaderToRequest(req)
creds, err := CBAuthWebCreds(req)
if err != nil {
requestBody, _ := io.ReadAll(req.Body)
rest.PropagateError(w, requestBody, fmt.Sprintf("rest_auth: cbauth.AuthWebCreds,"+
" err: %v", err), http.StatusForbidden)
return
}
if creds.Domain() == "anonymous" {
// force basic auth login by sending 401
CBAuthSendUnauthorized(w)
return
}
}
// redirect to /
http.Redirect(w, req, "/", http.StatusMovedPermanently)
}