jwt.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. // 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. package auth
  15. import (
  16. "context"
  17. "crypto/rsa"
  18. "io/ioutil"
  19. "time"
  20. jwt "github.com/dgrijalva/jwt-go"
  21. "go.uber.org/zap"
  22. )
  23. type tokenJWT struct {
  24. lg *zap.Logger
  25. signMethod string
  26. signKey *rsa.PrivateKey
  27. verifyKey *rsa.PublicKey
  28. ttl time.Duration
  29. }
  30. func (t *tokenJWT) enable() {}
  31. func (t *tokenJWT) disable() {}
  32. func (t *tokenJWT) invalidateUser(string) {}
  33. func (t *tokenJWT) genTokenPrefix() (string, error) { return "", nil }
  34. func (t *tokenJWT) info(ctx context.Context, token string, rev uint64) (*AuthInfo, bool) {
  35. // rev isn't used in JWT, it is only used in simple token
  36. var (
  37. username string
  38. revision uint64
  39. )
  40. parsed, err := jwt.Parse(token, func(token *jwt.Token) (interface{}, error) {
  41. return t.verifyKey, nil
  42. })
  43. switch err.(type) {
  44. case nil:
  45. if !parsed.Valid {
  46. if t.lg != nil {
  47. t.lg.Warn("invalid JWT token", zap.String("token", token))
  48. } else {
  49. plog.Warningf("invalid jwt token: %s", token)
  50. }
  51. return nil, false
  52. }
  53. claims := parsed.Claims.(jwt.MapClaims)
  54. username = claims["username"].(string)
  55. revision = uint64(claims["revision"].(float64))
  56. default:
  57. if t.lg != nil {
  58. t.lg.Warn(
  59. "failed to parse a JWT token",
  60. zap.String("token", token),
  61. zap.Error(err),
  62. )
  63. } else {
  64. plog.Warningf("failed to parse jwt token: %s", err)
  65. }
  66. return nil, false
  67. }
  68. return &AuthInfo{Username: username, Revision: revision}, true
  69. }
  70. func (t *tokenJWT) assign(ctx context.Context, username string, revision uint64) (string, error) {
  71. // Future work: let a jwt token include permission information would be useful for
  72. // permission checking in proxy side.
  73. tk := jwt.NewWithClaims(jwt.GetSigningMethod(t.signMethod),
  74. jwt.MapClaims{
  75. "username": username,
  76. "revision": revision,
  77. "exp": time.Now().Add(t.ttl).Unix(),
  78. })
  79. token, err := tk.SignedString(t.signKey)
  80. if err != nil {
  81. if t.lg != nil {
  82. t.lg.Warn(
  83. "failed to sign a JWT token",
  84. zap.String("user-name", username),
  85. zap.Uint64("revision", revision),
  86. zap.Error(err),
  87. )
  88. } else {
  89. plog.Debugf("failed to sign jwt token: %s", err)
  90. }
  91. return "", err
  92. }
  93. if t.lg != nil {
  94. t.lg.Info(
  95. "created/assigned a new JWT token",
  96. zap.String("user-name", username),
  97. zap.Uint64("revision", revision),
  98. zap.String("token", token),
  99. )
  100. } else {
  101. plog.Debugf("jwt token: %s", token)
  102. }
  103. return token, err
  104. }
  105. func prepareOpts(lg *zap.Logger, opts map[string]string) (jwtSignMethod, jwtPubKeyPath, jwtPrivKeyPath string, ttl time.Duration, err error) {
  106. for k, v := range opts {
  107. switch k {
  108. case "sign-method":
  109. jwtSignMethod = v
  110. case "pub-key":
  111. jwtPubKeyPath = v
  112. case "priv-key":
  113. jwtPrivKeyPath = v
  114. case "ttl":
  115. ttl, err = time.ParseDuration(v)
  116. if err != nil {
  117. if lg != nil {
  118. lg.Warn(
  119. "failed to parse JWT TTL option",
  120. zap.String("ttl-value", v),
  121. zap.Error(err),
  122. )
  123. } else {
  124. plog.Errorf("failed to parse ttl option (%s)", err)
  125. }
  126. return "", "", "", 0, ErrInvalidAuthOpts
  127. }
  128. default:
  129. if lg != nil {
  130. lg.Warn("unknown JWT token option", zap.String("option", k))
  131. } else {
  132. plog.Errorf("unknown token specific option: %s", k)
  133. }
  134. return "", "", "", 0, ErrInvalidAuthOpts
  135. }
  136. }
  137. if len(jwtSignMethod) == 0 {
  138. return "", "", "", 0, ErrInvalidAuthOpts
  139. }
  140. return jwtSignMethod, jwtPubKeyPath, jwtPrivKeyPath, ttl, nil
  141. }
  142. func newTokenProviderJWT(lg *zap.Logger, opts map[string]string) (*tokenJWT, error) {
  143. jwtSignMethod, jwtPubKeyPath, jwtPrivKeyPath, ttl, err := prepareOpts(lg, opts)
  144. if err != nil {
  145. return nil, ErrInvalidAuthOpts
  146. }
  147. if ttl == 0 {
  148. ttl = 5 * time.Minute
  149. }
  150. t := &tokenJWT{
  151. lg: lg,
  152. ttl: ttl,
  153. }
  154. t.signMethod = jwtSignMethod
  155. verifyBytes, err := ioutil.ReadFile(jwtPubKeyPath)
  156. if err != nil {
  157. if lg != nil {
  158. lg.Warn(
  159. "failed to read JWT public key",
  160. zap.String("public-key-path", jwtPubKeyPath),
  161. zap.Error(err),
  162. )
  163. } else {
  164. plog.Errorf("failed to read public key (%s) for jwt: %s", jwtPubKeyPath, err)
  165. }
  166. return nil, err
  167. }
  168. t.verifyKey, err = jwt.ParseRSAPublicKeyFromPEM(verifyBytes)
  169. if err != nil {
  170. if lg != nil {
  171. lg.Warn(
  172. "failed to parse JWT public key",
  173. zap.String("public-key-path", jwtPubKeyPath),
  174. zap.Error(err),
  175. )
  176. } else {
  177. plog.Errorf("failed to parse public key (%s): %s", jwtPubKeyPath, err)
  178. }
  179. return nil, err
  180. }
  181. signBytes, err := ioutil.ReadFile(jwtPrivKeyPath)
  182. if err != nil {
  183. if lg != nil {
  184. lg.Warn(
  185. "failed to read JWT private key",
  186. zap.String("private-key-path", jwtPrivKeyPath),
  187. zap.Error(err),
  188. )
  189. } else {
  190. plog.Errorf("failed to read private key (%s) for jwt: %s", jwtPrivKeyPath, err)
  191. }
  192. return nil, err
  193. }
  194. t.signKey, err = jwt.ParseRSAPrivateKeyFromPEM(signBytes)
  195. if err != nil {
  196. if lg != nil {
  197. lg.Warn(
  198. "failed to parse JWT private key",
  199. zap.String("private-key-path", jwtPrivKeyPath),
  200. zap.Error(err),
  201. )
  202. } else {
  203. plog.Errorf("failed to parse private key (%s): %s", jwtPrivKeyPath, err)
  204. }
  205. return nil, err
  206. }
  207. return t, nil
  208. }