blob: c22ef898a14d825aa2bbe462879f0351ae7af39d [file] [log] [blame]
khenaidooab1f7bd2019-11-14 14:00:27 -05001// Copyright 2017 The etcd Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package auth
16
17import (
18 "context"
19 "crypto/ecdsa"
20 "crypto/rsa"
21 "errors"
22 "time"
23
24 jwt "github.com/dgrijalva/jwt-go"
25 "go.uber.org/zap"
26)
27
28type tokenJWT struct {
29 lg *zap.Logger
30 signMethod jwt.SigningMethod
31 key interface{}
32 ttl time.Duration
33 verifyOnly bool
34}
35
36func (t *tokenJWT) enable() {}
37func (t *tokenJWT) disable() {}
38func (t *tokenJWT) invalidateUser(string) {}
39func (t *tokenJWT) genTokenPrefix() (string, error) { return "", nil }
40
41func (t *tokenJWT) info(ctx context.Context, token string, rev uint64) (*AuthInfo, bool) {
42 // rev isn't used in JWT, it is only used in simple token
43 var (
44 username string
45 revision uint64
46 )
47
48 parsed, err := jwt.Parse(token, func(token *jwt.Token) (interface{}, error) {
49 if token.Method.Alg() != t.signMethod.Alg() {
50 return nil, errors.New("invalid signing method")
51 }
52 switch k := t.key.(type) {
53 case *rsa.PrivateKey:
54 return &k.PublicKey, nil
55 case *ecdsa.PrivateKey:
56 return &k.PublicKey, nil
57 default:
58 return t.key, nil
59 }
60 })
61
62 if err != nil {
63 if t.lg != nil {
64 t.lg.Warn(
65 "failed to parse a JWT token",
66 zap.String("token", token),
67 zap.Error(err),
68 )
69 } else {
70 plog.Warningf("failed to parse jwt token: %s", err)
71 }
72 return nil, false
73 }
74
75 claims, ok := parsed.Claims.(jwt.MapClaims)
76 if !parsed.Valid || !ok {
77 if t.lg != nil {
78 t.lg.Warn("invalid JWT token", zap.String("token", token))
79 } else {
80 plog.Warningf("invalid jwt token: %s", token)
81 }
82 return nil, false
83 }
84
85 username = claims["username"].(string)
86 revision = uint64(claims["revision"].(float64))
87
88 return &AuthInfo{Username: username, Revision: revision}, true
89}
90
91func (t *tokenJWT) assign(ctx context.Context, username string, revision uint64) (string, error) {
92 if t.verifyOnly {
93 return "", ErrVerifyOnly
94 }
95
96 // Future work: let a jwt token include permission information would be useful for
97 // permission checking in proxy side.
98 tk := jwt.NewWithClaims(t.signMethod,
99 jwt.MapClaims{
100 "username": username,
101 "revision": revision,
102 "exp": time.Now().Add(t.ttl).Unix(),
103 })
104
105 token, err := tk.SignedString(t.key)
106 if err != nil {
107 if t.lg != nil {
108 t.lg.Warn(
109 "failed to sign a JWT token",
110 zap.String("user-name", username),
111 zap.Uint64("revision", revision),
112 zap.Error(err),
113 )
114 } else {
115 plog.Debugf("failed to sign jwt token: %s", err)
116 }
117 return "", err
118 }
119
120 if t.lg != nil {
121 t.lg.Info(
122 "created/assigned a new JWT token",
123 zap.String("user-name", username),
124 zap.Uint64("revision", revision),
125 zap.String("token", token),
126 )
127 } else {
128 plog.Debugf("jwt token: %s", token)
129 }
130 return token, err
131}
132
133func newTokenProviderJWT(lg *zap.Logger, optMap map[string]string) (*tokenJWT, error) {
134 var err error
135 var opts jwtOptions
136 err = opts.ParseWithDefaults(optMap)
137 if err != nil {
138 if lg != nil {
139 lg.Warn("problem loading JWT options", zap.Error(err))
140 } else {
141 plog.Errorf("problem loading JWT options: %s", err)
142 }
143 return nil, ErrInvalidAuthOpts
144 }
145
146 var keys = make([]string, 0, len(optMap))
147 for k := range optMap {
148 if !knownOptions[k] {
149 keys = append(keys, k)
150 }
151 }
152 if len(keys) > 0 {
153 if lg != nil {
154 lg.Warn("unknown JWT options", zap.Strings("keys", keys))
155 } else {
156 plog.Warningf("unknown JWT options: %v", keys)
157 }
158 }
159
160 key, err := opts.Key()
161 if err != nil {
162 return nil, err
163 }
164
165 t := &tokenJWT{
166 lg: lg,
167 ttl: opts.TTL,
168 signMethod: opts.SignMethod,
169 key: key,
170 }
171
172 switch t.signMethod.(type) {
173 case *jwt.SigningMethodECDSA:
174 if _, ok := t.key.(*ecdsa.PublicKey); ok {
175 t.verifyOnly = true
176 }
177 case *jwt.SigningMethodRSA, *jwt.SigningMethodRSAPSS:
178 if _, ok := t.key.(*rsa.PublicKey); ok {
179 t.verifyOnly = true
180 }
181 }
182
183 return t, nil
184}