-
Notifications
You must be signed in to change notification settings - Fork 3
/
certificate_validation.go
71 lines (57 loc) · 2.26 KB
/
certificate_validation.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
package aviation
import (
"context"
"github.com/evergreen-ci/gimlet"
"github.com/pkg/errors"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/peer"
)
// Return a gRPC UnaryServerInterceptor which checks the certifcate user's
// validity against the given user manager.
func MakeCertificateUserValidationUnaryInterceptor(um gimlet.UserManager) grpc.UnaryServerInterceptor {
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
p, ok := peer.FromContext(ctx)
if !ok {
return nil, grpc.Errorf(codes.Unauthenticated, "missing peer info from context")
}
tlsAuth, ok := p.AuthInfo.(credentials.TLSInfo)
if !ok {
return nil, grpc.Errorf(codes.Unauthenticated, "unexpected peer transport credentials")
}
username := tlsAuth.State.VerifiedChains[0][0].Subject.CommonName
usr, err := um.GetUserByID(username)
if err != nil {
return nil, grpc.Errorf(codes.Unauthenticated, "%+v", errors.Wrapf(err, "finding user '%s'", username))
}
if usr == nil {
return nil, grpc.Errorf(codes.Unauthenticated, "user associated with certificate no longer valid!")
}
return handler(ctx, req)
}
}
// Return a gRPC UnaryStreamInterceptor which checks the certifcate user's
// validity against the given user manager.
func MakeCertificateUserValidationStreamInterceptor(um gimlet.UserManager) grpc.StreamServerInterceptor {
return func(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) (err error) {
ctx := stream.Context()
p, ok := peer.FromContext(ctx)
if !ok {
return grpc.Errorf(codes.Unauthenticated, "missing peer info from context")
}
tlsAuth, ok := p.AuthInfo.(credentials.TLSInfo)
if !ok {
return grpc.Errorf(codes.Unauthenticated, "unexpected peer transport credentials")
}
username := tlsAuth.State.VerifiedChains[0][0].Subject.CommonName
usr, err := um.GetUserByID(username)
if err != nil {
return grpc.Errorf(codes.Unauthenticated, "%+v", errors.Wrapf(err, "finding user '%s'", username))
}
if usr == nil {
return grpc.Errorf(codes.Unauthenticated, "user associated with certificate no longer valid!")
}
return handler(srv, stream)
}
}