-
Notifications
You must be signed in to change notification settings - Fork 28
/
grpc_auth.go
247 lines (205 loc) · 5.92 KB
/
grpc_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
// Copyright 2019-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 (
"context"
"encoding/base64"
"fmt"
"strings"
"github.com/blevesearch/bleve/v2/search"
"github.com/couchbase/cbauth"
pb "github.com/couchbase/cbft/protobuf"
"github.com/couchbase/cbgt"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
)
type gRPCAuthKeyType string
var gRPCAuthHandlerKey = gRPCAuthKeyType("CheckRPCAuth")
type gRPCAuthHandler func(r requestParser) (bool, error)
// wrapAuthCallbacks embeds the right authentication callbacks
// into the context.
func wrapAuthCallbacks(req interface{},
ctx context.Context, rpcPath string) (newCtx context.Context, err error) {
newCtx, err = tryBasicAuth(req, ctx, rpcPath)
if err == nil {
return newCtx, nil
}
return ctx, err
}
func tryBasicAuth(req interface{}, ctx context.Context,
rpcPath string) (context.Context, error) {
srv := req.(*SearchService)
if srv == nil {
return nil, fmt.Errorf("invalid request type")
}
auth, err := extractMetaHeader(ctx, "authorization")
if err != nil {
return ctx, status.Errorf(codes.Unauthenticated,
"err: %v", err)
}
const prefix = "Basic "
if !strings.HasPrefix(auth, prefix) {
return ctx, status.Error(codes.Unauthenticated,
`missing "Basic " prefix in "Authorization" header`)
}
c, err := base64.StdEncoding.DecodeString(auth[len(prefix):])
if err != nil {
return ctx, status.Error(codes.Unauthenticated,
`invalid base64 in header`)
}
cs := string(c)
s := strings.IndexByte(cs, ':')
if s < 0 {
return ctx, status.Error(codes.Unauthenticated,
`invalid basic auth format`)
}
user, passwd := cs[:s], cs[s+1:]
creds, err := cbauth.Auth(user, passwd)
if err != nil {
return nil, status.Errorf(codes.Unauthenticated,
"error authenticating with cbauth%v", err)
}
var authFunc gRPCAuthHandler
aw := &authWrapper{mgr: srv.mgr, creds: creds,
path: rpcPath[strings.LastIndex(rpcPath, "/"):], method: "RPC"}
authFunc = aw.authenticate
nctx := context.WithValue(ctx, gRPCAuthHandlerKey, authFunc)
return nctx, nil
}
func extractOptionalHeader(ctx context.Context, header string) string {
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return ""
}
headerValue, ok := md[header]
if !ok {
return ""
}
if len(headerValue) != 1 {
return ""
}
return headerValue[0]
}
func extractMetaHeader(ctx context.Context, header string) (string, error) {
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return "", fmt.Errorf("no headers in request")
}
headerValue, ok := md[header]
if !ok {
return "", fmt.Errorf("no headers in request")
}
if len(headerValue) != 1 {
return "", fmt.Errorf("more than 1 header in request")
}
return headerValue[0], nil
}
type authWrapper struct {
mgr *cbgt.Manager
path string
method string
creds cbauth.Creds
}
func (a *authWrapper) authenticate(r requestParser) (bool, error) {
var authType string
if a.mgr != nil && a.mgr.Options() != nil {
authType = a.mgr.GetOption("authType")
}
if authType == "" {
return true, nil
}
if authType != "cbauth" {
return false, nil
}
perms, err := preparePerms(a.mgr, r, a.method, a.path)
if err != nil {
return false, fmt.Errorf("grpc_auth: preparePerms err: %v", err)
}
if len(perms) <= 0 {
return true, nil
}
for _, perm := range perms {
allowed, err := CBAuthIsAllowed(a.creds, perm)
if err != nil {
return false, err
}
if !allowed {
return false, err
}
}
ok, msg := processRequest(a.creds.Name(), a.path, r)
if !ok {
return false, fmt.Errorf("%s", msg)
}
return true, nil
}
// rpcRequestParser implements the requestParser interface
type rpcRequestParser struct {
indexName string
requestType string
request interface{}
}
func (rp *rpcRequestParser) GetIndexName() (string, error) {
return rp.indexName, nil
}
func (rp *rpcRequestParser) GetIndexDef() (*cbgt.IndexDef, error) {
return nil, nil // TODO when DDLs are supported over RPCs
}
func (rp *rpcRequestParser) GetCollectionNames() ([]string, error) {
return nil, nil // placeholder implementation.
}
func (rp *rpcRequestParser) GetBucketName() (string, error) {
return "", nil // placeholder implementation.
}
func (rp *rpcRequestParser) GetRequest() (interface{}, string) {
return rp.request, "RPC"
}
func (rp *rpcRequestParser) GetPIndexName() (string, error) {
// TODO - placeholder implementation, improve this as more
// and more pindex based RPCs are introduced.
if r, ok := rp.request.(*pb.SearchRequest); ok {
if r.QueryPIndexes != nil {
queryPIndexes := QueryPIndexes{}
err := UnmarshalJSON(r.QueryPIndexes, &queryPIndexes)
if err != nil {
return "", fmt.Errorf("missing pindexName, err: %v", err)
}
if len(queryPIndexes.PIndexNames) > 0 {
return queryPIndexes.PIndexNames[0], nil
}
}
}
return "", fmt.Errorf("missing pindexName")
}
// returns true if the scatter gather request is a pre-search
func isPreSearch(ctx context.Context) bool {
return extractOptionalHeader(ctx, search.PreSearchKey) == clusterActionScatterGatherPreSearch
}
func verifyRPCAuth(ctx context.Context, indexName string, req interface{}) error {
if _, err := extractMetaHeader(ctx, rpcClusterActionKey); err == nil {
return nil
}
var authHandler gRPCAuthHandler
if aw := ctx.Value(gRPCAuthHandlerKey); aw != nil {
authHandler = aw.(gRPCAuthHandler)
}
if authHandler == nil {
return fmt.Errorf("grpc_auth: invalid authHandler")
}
v, err := authHandler(
&rpcRequestParser{indexName: indexName,
request: req})
if err != nil {
return fmt.Errorf("grpc_auth: auth err: %v", err)
}
if !v {
return fmt.Errorf("grpc_auth: permission denied")
}
return nil
}