-
Notifications
You must be signed in to change notification settings - Fork 5
/
interceptor.go
83 lines (69 loc) · 2.13 KB
/
interceptor.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
package clientauth
import (
"context"
"crypto/tls"
"crypto/x509"
"errors"
"strings"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/peer"
)
const (
AuthorizationKey = "authorization"
BearerPrefix = "Bearer "
)
type AuthProvider struct {
Disabled bool
}
func UserInfoFromClientCert(cert *x509.Certificate) UserInfo {
cn := cert.Subject.CommonName
a := strings.SplitN(cn, " ", 2)
rolestr := a[0]
user := rolestr
if len(a) > 1 {
user = a[1]
}
return UserInfo{Role: RoleFromStr(rolestr), User: user}
}
var ErrZeroVerifiedChains = errors.New("AuthProvider could not find a client cert.")
var ErrZeroVerifiedChains2 = errors.New("AuthProvider requires len(VerifiedChains[0]) > 0.")
func UserInfoFromTLSConnectionState(tcs *tls.ConnectionState) (UserInfo, error) {
vcs := tcs.VerifiedChains
if len(vcs) == 0 {
return AnonymousUserInfo, ErrZeroVerifiedChains
}
vc := vcs[0]
if len(vc) == 0 {
return AnonymousUserInfo, ErrZeroVerifiedChains2
}
return UserInfoFromClientCert(vc[0]), nil
}
func (p AuthProvider) UnaryServerInterceptor() grpc.UnaryServerInterceptor {
if p.Disabled {
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
ctx = ContextWithUserInfo(ctx, NoauthUserInfo)
return handler(ctx, req)
}
}
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, "AuthProvider requires metadata.")
}
if p.AuthInfo == nil {
return nil, grpc.Errorf(codes.Unauthenticated, "AuthProvider requires grpc Peer with AuthInfo.")
}
ti, ok := p.AuthInfo.(credentials.TLSInfo)
if !ok {
return nil, grpc.Errorf(codes.Unauthenticated, "AuthProvider requires grpc Peer with credentails.TLSInfo.")
}
ui, err := UserInfoFromTLSConnectionState(&ti.State)
if err != nil {
return nil, grpc.Errorf(codes.Unauthenticated, "%v", err)
}
ctx = ContextWithUserInfo(ctx, ui)
return handler(ctx, req)
}
}