-
Notifications
You must be signed in to change notification settings - Fork 14
/
interceptors.go
416 lines (403 loc) · 11.7 KB
/
interceptors.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
package database
import (
"context"
"encoding/json"
"fmt"
"github.com/golang/protobuf/ptypes/empty"
"github.com/google/cel-go/cel"
"github.com/graphikDB/graphik/gen/grpc/go"
"github.com/graphikDB/graphik/helpers"
grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware"
grpc_auth "github.com/grpc-ecosystem/go-grpc-middleware/auth"
"github.com/lestrrat-go/jwx/jwa"
"github.com/lestrrat-go/jwx/jws"
"github.com/pkg/errors"
"go.etcd.io/bbolt"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/peer"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/structpb"
"io/ioutil"
"net/http"
"strings"
"time"
)
func (g *Graph) UnaryInterceptor() grpc.UnaryServerInterceptor {
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
if strings.Contains(info.FullMethod, "JoinCluster") {
return handler(ctx, req)
}
token, err := grpc_auth.AuthFromMD(ctx, "Bearer")
if err != nil {
return nil, err
}
ctx = g.tokenToContext(ctx, token)
tokenHash := helpers.Hash([]byte(token))
if val, ok := g.jwtCache.Get(tokenHash); ok {
payload := val.(map[string]interface{})
ctx, err := g.checkRequest(ctx, info.FullMethod, req, payload)
if err != nil {
return nil, err
}
hresp, err := handler(ctx, req)
if err != nil {
return hresp, err
}
if err := g.checkResponse(ctx, info.FullMethod, hresp, payload); err != nil {
return nil, err
}
return hresp, nil
}
ctx = g.methodToContext(ctx, info.FullMethod)
userinfoReq, err := http.NewRequest(http.MethodGet, g.openID.UserinfoEndpoint, nil)
if err != nil {
return nil, status.Errorf(codes.Unauthenticated, "failed to get userinfo: %s", err.Error())
}
userinfoReq.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
resp, err := http.DefaultClient.Do(userinfoReq)
if err != nil {
return nil, status.Errorf(codes.Unauthenticated, "failed to get userinfo: %s", err.Error())
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return nil, status.Errorf(codes.Unauthenticated, "failed to get userinfo: %v", resp.StatusCode)
}
bits, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, status.Errorf(codes.Unauthenticated, "failed to get userinfo: %s", err.Error())
}
payload := map[string]interface{}{}
if err := json.Unmarshal(bits, &payload); err != nil {
return nil, status.Errorf(codes.Unauthenticated, "failed to get userinfo: %s", err.Error())
}
g.jwtCache.Set(tokenHash, payload, 1*time.Hour)
ctx, err = g.checkRequest(ctx, info.FullMethod, req, payload)
if err != nil {
return nil, err
}
hresp, err := handler(ctx, req)
if err != nil {
return hresp, err
}
if err := g.checkResponse(ctx, info.FullMethod, hresp, payload); err != nil {
return nil, err
}
return hresp, nil
}
}
func (g *Graph) StreamInterceptor() grpc.StreamServerInterceptor {
return func(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
ctx := g.methodToContext(ss.Context(), info.FullMethod)
token, err := grpc_auth.AuthFromMD(ctx, "Bearer")
if err != nil {
return err
}
ctx = g.tokenToContext(ctx, token)
tokenHash := helpers.Hash([]byte(token))
if val, ok := g.jwtCache.Get(tokenHash); ok {
payload := val.(map[string]interface{})
if info.IsClientStream {
ctx, err := g.checkRequest(ctx, info.FullMethod, srv, payload)
if err != nil {
return err
}
wrapped := grpc_middleware.WrapServerStream(ss)
wrapped.WrappedContext = ctx
return handler(srv, wrapped)
} else {
if err := g.checkResponse(ctx, info.FullMethod, srv, payload); err != nil {
return err
}
}
}
userinfoReq, err := http.NewRequest(http.MethodGet, g.openID.UserinfoEndpoint, nil)
if err != nil {
return status.Errorf(codes.Unauthenticated, "failed to get userinfo: %s", err.Error())
}
userinfoReq.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
resp, err := http.DefaultClient.Do(userinfoReq)
if err != nil {
return status.Errorf(codes.Unauthenticated, "failed to get userinfo: %s", err.Error())
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return status.Errorf(codes.Unauthenticated, "failed to get userinfo: %v", resp.StatusCode)
}
bits, err := ioutil.ReadAll(resp.Body)
if err != nil {
return errors.Wrap(err, "failed to get userinfo")
}
payload := map[string]interface{}{}
if err := json.Unmarshal(bits, &payload); err != nil {
return status.Errorf(codes.Unauthenticated, "failed to get userinfo: %s", err.Error())
}
g.jwtCache.Set(tokenHash, payload, 1*time.Hour)
ctx, err = g.checkRequest(ctx, info.FullMethod, srv, payload)
if err != nil {
return err
}
wrapped := grpc_middleware.WrapServerStream(ss)
wrapped.WrappedContext = ctx
return handler(srv, wrapped)
}
}
func (a *Graph) userToContext(ctx context.Context, payload map[string]interface{}) (context.Context, *apipb.Doc, error) {
email, ok := payload["email"].(string)
if !ok {
return nil, nil, errors.New("email not present in userinfo")
}
var (
doc *apipb.Doc
err error
)
a.db.View(func(tx *bbolt.Tx) error {
doc, err = a.getDoc(ctx, tx, &apipb.Ref{
Gtype: string(userType),
Gid: email,
})
if err != nil {
return err
}
return nil
})
if doc == nil {
strct, err := structpb.NewStruct(payload)
if err != nil {
return nil, nil, err
}
doc, err = a.createIdentity(ctx, &apipb.DocConstructor{
Ref: &apipb.RefConstructor{
Gtype: string(userType),
Gid: email,
},
Attributes: strct,
})
if err != nil {
return nil, nil, err
}
}
return context.WithValue(ctx, authCtxKey, doc), doc, nil
}
func (s *Graph) getIdentity(ctx context.Context) *apipb.Doc {
val, ok := ctx.Value(authCtxKey).(*apipb.Doc)
if ok {
return val
}
val2, ok := ctx.Value(authCtxKey).(apipb.Doc)
if ok {
return &val2
}
return nil
}
func (r *Graph) getMethod(ctx context.Context) string {
val, ok := ctx.Value(methodCtxKey).(string)
if ok {
return val
}
return ""
}
func (r *Graph) methodToContext(ctx context.Context, path string) context.Context {
return context.WithValue(ctx, methodCtxKey, path)
}
func (r *Graph) tokenToContext(ctx context.Context, token string) context.Context {
return context.WithValue(ctx, tokenCtxKey, token)
}
func (r *Graph) getToken(ctx context.Context) string {
val, ok := ctx.Value(tokenCtxKey).(string)
if ok {
return val
}
return ""
}
func (g *Graph) verifyJWT(token string) (map[string]interface{}, error) {
message, err := jws.ParseString(token)
if err != nil {
return nil, err
}
g.jwksMu.RLock()
defer g.jwksMu.RUnlock()
if g.jwksSet == nil {
data := map[string]interface{}{}
if err := json.Unmarshal(message.Payload(), &data); err != nil {
return nil, err
}
return data, nil
}
if len(message.Signatures()) == 0 {
return nil, fmt.Errorf("zero jws signatures")
}
kid, ok := message.Signatures()[0].ProtectedHeaders().Get("kid")
if !ok {
return nil, fmt.Errorf("jws kid not found")
}
algI, ok := message.Signatures()[0].ProtectedHeaders().Get("alg")
if !ok {
return nil, fmt.Errorf("jw alg not found")
}
alg, ok := algI.(jwa.SignatureAlgorithm)
if !ok {
return nil, fmt.Errorf("alg type cast error")
}
keys := g.jwksSet.LookupKeyID(kid.(string))
if len(keys) == 0 {
return nil, errors.Errorf("failed to lookup kid: %s - zero keys", kid.(string))
}
var key interface{}
if err := keys[0].Raw(&key); err != nil {
return nil, err
}
payload, err := jws.Verify([]byte(token), alg, key)
if err != nil {
return nil, err
}
data := map[string]interface{}{}
if err := json.Unmarshal(payload, &data); err != nil {
return nil, err
}
return data, nil
}
func (g *Graph) checkRequest(ctx context.Context, method string, req interface{}, payload map[string]interface{}) (context.Context, error) {
ctx = g.methodToContext(ctx, method)
ctx, user, err := g.userToContext(ctx, payload)
if err != nil {
return nil, status.Errorf(codes.Unauthenticated, err.Error())
}
if g.isGraphikAdmin(user) {
return context.WithValue(ctx, bypassAuthorizersCtxKey, true), nil
}
var programs []cel.Program
g.rangeAuthorizers(func(a *authorizer) bool {
if a.authorizer.GetTargetRequests() && a.authorizer.GetMethod() == method {
programs = append(programs, a.program)
}
return true
})
if g.flgs.RequireResponseAuthorizers && len(programs) == 0 {
return nil, status.Errorf(
codes.PermissionDenied,
"zero registered request authorizers found for invoked gRPC method %s", method)
}
if len(programs) == 0 {
return ctx, nil
}
request := &apipb.AuthTarget{
User: user,
Headers: map[string]string{},
}
p, ok := peer.FromContext(ctx)
if ok {
request.Peer = p.Addr.String()
}
md, ok := metadata.FromIncomingContext(ctx)
if ok {
for k, val := range md {
if len(val) > 0 {
request.Headers[k] = val[0]
}
}
}
if val, ok := req.(apipb.Mapper); ok {
request.Target = apipb.NewStruct(val.AsMap())
} else if val, ok := req.(proto.Message); ok {
bits, _ := helpers.MarshalJSON(val)
reqMap := map[string]interface{}{}
if err := json.Unmarshal(bits, &reqMap); err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
request.Target = apipb.NewStruct(reqMap)
}
result, err := g.vm.Auth().Eval(request, programs...)
if err != nil {
return nil, err
}
if !result {
return nil, status.Errorf(codes.PermissionDenied, "request from %s.%s authorization = denied", user.GetRef().GetGtype(), user.GetRef().GetGid())
}
return ctx, nil
}
func (g *Graph) checkResponse(ctx context.Context, method string, response interface{}, payload map[string]interface{}) error {
if _, ok := response.(*empty.Empty); ok {
return nil
}
ctx = g.methodToContext(ctx, method)
var (
err error
user = g.getIdentity(ctx)
)
if user == nil {
ctx, user, err = g.userToContext(ctx, payload)
if err != nil {
return status.Errorf(codes.Unauthenticated, err.Error())
}
}
if g.isGraphikAdmin(user) {
return nil
}
var programs []cel.Program
g.rangeAuthorizers(func(a *authorizer) bool {
if a.authorizer.GetTargetResponses() && a.authorizer.GetMethod() == method {
programs = append(programs, a.program)
}
return true
})
if g.flgs.RequireResponseAuthorizers && len(programs) == 0 {
return status.Errorf(
codes.PermissionDenied,
"zero registered response authorizers found for invoked gRPC method %s", method)
}
if len(programs) == 0 {
return nil
}
request := &apipb.AuthTarget{
User: user,
Target: nil,
Headers: map[string]string{},
}
p, ok := peer.FromContext(ctx)
if ok {
request.Peer = p.Addr.String()
}
md, ok := metadata.FromIncomingContext(ctx)
if ok {
for k, val := range md {
if len(val) > 0 {
request.Headers[k] = val[0]
}
}
}
md, ok = metadata.FromOutgoingContext(ctx)
if ok {
for k, val := range md {
if len(val) > 0 {
request.Headers[k] = val[0]
}
}
}
if val, ok := response.(apipb.Mapper); ok {
request.Target = apipb.NewStruct(val.AsMap())
} else if val, ok := response.(proto.Message); ok {
bits, _ := helpers.MarshalJSON(val)
reqMap := map[string]interface{}{}
if err := json.Unmarshal(bits, &reqMap); err != nil {
return status.Error(codes.Internal, err.Error())
}
request.Target = apipb.NewStruct(reqMap)
}
result, err := g.vm.Auth().Eval(request, programs...)
if err != nil {
return err
}
if !result {
return status.Errorf(codes.PermissionDenied, "response to %s.%s authorization = denied", user.GetRef().GetGtype(), user.GetRef().GetGid())
}
return nil
}
func (g *Graph) isGraphikAdmin(user *apipb.Doc) bool {
if user.GetAttributes().GetFields() == nil {
return false
}
return helpers.ContainsString(user.GetAttributes().GetFields()["email"].GetStringValue(), g.flgs.RootUsers)
}