simple_token.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. // Copyright 2016 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. // CAUTION: This randum number based token mechanism is only for testing purpose.
  16. // JWT based mechanism will be added in the near future.
  17. import (
  18. "context"
  19. "crypto/rand"
  20. "fmt"
  21. "math/big"
  22. "strconv"
  23. "strings"
  24. "sync"
  25. "time"
  26. )
  27. const (
  28. letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
  29. defaultSimpleTokenLength = 16
  30. )
  31. // var for testing purposes
  32. var (
  33. simpleTokenTTL = 5 * time.Minute
  34. simpleTokenTTLResolution = 1 * time.Second
  35. )
  36. type simpleTokenTTLKeeper struct {
  37. tokens map[string]time.Time
  38. donec chan struct{}
  39. stopc chan struct{}
  40. deleteTokenFunc func(string)
  41. mu *sync.Mutex
  42. }
  43. func (tm *simpleTokenTTLKeeper) stop() {
  44. select {
  45. case tm.stopc <- struct{}{}:
  46. case <-tm.donec:
  47. }
  48. <-tm.donec
  49. }
  50. func (tm *simpleTokenTTLKeeper) addSimpleToken(token string) {
  51. tm.tokens[token] = time.Now().Add(simpleTokenTTL)
  52. }
  53. func (tm *simpleTokenTTLKeeper) resetSimpleToken(token string) {
  54. if _, ok := tm.tokens[token]; ok {
  55. tm.tokens[token] = time.Now().Add(simpleTokenTTL)
  56. }
  57. }
  58. func (tm *simpleTokenTTLKeeper) deleteSimpleToken(token string) {
  59. delete(tm.tokens, token)
  60. }
  61. func (tm *simpleTokenTTLKeeper) run() {
  62. tokenTicker := time.NewTicker(simpleTokenTTLResolution)
  63. defer func() {
  64. tokenTicker.Stop()
  65. close(tm.donec)
  66. }()
  67. for {
  68. select {
  69. case <-tokenTicker.C:
  70. nowtime := time.Now()
  71. tm.mu.Lock()
  72. for t, tokenendtime := range tm.tokens {
  73. if nowtime.After(tokenendtime) {
  74. tm.deleteTokenFunc(t)
  75. delete(tm.tokens, t)
  76. }
  77. }
  78. tm.mu.Unlock()
  79. case <-tm.stopc:
  80. return
  81. }
  82. }
  83. }
  84. type tokenSimple struct {
  85. indexWaiter func(uint64) <-chan struct{}
  86. simpleTokenKeeper *simpleTokenTTLKeeper
  87. simpleTokensMu sync.Mutex
  88. simpleTokens map[string]string // token -> username
  89. }
  90. func (t *tokenSimple) genTokenPrefix() (string, error) {
  91. ret := make([]byte, defaultSimpleTokenLength)
  92. for i := 0; i < defaultSimpleTokenLength; i++ {
  93. bInt, err := rand.Int(rand.Reader, big.NewInt(int64(len(letters))))
  94. if err != nil {
  95. return "", err
  96. }
  97. ret[i] = letters[bInt.Int64()]
  98. }
  99. return string(ret), nil
  100. }
  101. func (t *tokenSimple) assignSimpleTokenToUser(username, token string) {
  102. t.simpleTokensMu.Lock()
  103. defer t.simpleTokensMu.Unlock()
  104. if t.simpleTokenKeeper == nil {
  105. return
  106. }
  107. _, ok := t.simpleTokens[token]
  108. if ok {
  109. plog.Panicf("token %s is alredy used", token)
  110. }
  111. t.simpleTokens[token] = username
  112. t.simpleTokenKeeper.addSimpleToken(token)
  113. }
  114. func (t *tokenSimple) invalidateUser(username string) {
  115. if t.simpleTokenKeeper == nil {
  116. return
  117. }
  118. t.simpleTokensMu.Lock()
  119. for token, name := range t.simpleTokens {
  120. if strings.Compare(name, username) == 0 {
  121. delete(t.simpleTokens, token)
  122. t.simpleTokenKeeper.deleteSimpleToken(token)
  123. }
  124. }
  125. t.simpleTokensMu.Unlock()
  126. }
  127. func (t *tokenSimple) enable() {
  128. delf := func(tk string) {
  129. if username, ok := t.simpleTokens[tk]; ok {
  130. plog.Infof("deleting token %s for user %s", tk, username)
  131. delete(t.simpleTokens, tk)
  132. }
  133. }
  134. t.simpleTokenKeeper = &simpleTokenTTLKeeper{
  135. tokens: make(map[string]time.Time),
  136. donec: make(chan struct{}),
  137. stopc: make(chan struct{}),
  138. deleteTokenFunc: delf,
  139. mu: &t.simpleTokensMu,
  140. }
  141. go t.simpleTokenKeeper.run()
  142. }
  143. func (t *tokenSimple) disable() {
  144. t.simpleTokensMu.Lock()
  145. tk := t.simpleTokenKeeper
  146. t.simpleTokenKeeper = nil
  147. t.simpleTokens = make(map[string]string) // invalidate all tokens
  148. t.simpleTokensMu.Unlock()
  149. if tk != nil {
  150. tk.stop()
  151. }
  152. }
  153. func (t *tokenSimple) info(ctx context.Context, token string, revision uint64) (*AuthInfo, bool) {
  154. if !t.isValidSimpleToken(ctx, token) {
  155. return nil, false
  156. }
  157. t.simpleTokensMu.Lock()
  158. username, ok := t.simpleTokens[token]
  159. if ok && t.simpleTokenKeeper != nil {
  160. t.simpleTokenKeeper.resetSimpleToken(token)
  161. }
  162. t.simpleTokensMu.Unlock()
  163. return &AuthInfo{Username: username, Revision: revision}, ok
  164. }
  165. func (t *tokenSimple) assign(ctx context.Context, username string, rev uint64) (string, error) {
  166. // rev isn't used in simple token, it is only used in JWT
  167. index := ctx.Value(AuthenticateParamIndex{}).(uint64)
  168. simpleTokenPrefix := ctx.Value(AuthenticateParamSimpleTokenPrefix{}).(string)
  169. token := fmt.Sprintf("%s.%d", simpleTokenPrefix, index)
  170. t.assignSimpleTokenToUser(username, token)
  171. return token, nil
  172. }
  173. func (t *tokenSimple) isValidSimpleToken(ctx context.Context, token string) bool {
  174. splitted := strings.Split(token, ".")
  175. if len(splitted) != 2 {
  176. return false
  177. }
  178. index, err := strconv.Atoi(splitted[1])
  179. if err != nil {
  180. return false
  181. }
  182. select {
  183. case <-t.indexWaiter(uint64(index)):
  184. return true
  185. case <-ctx.Done():
  186. }
  187. return false
  188. }
  189. func newTokenProviderSimple(indexWaiter func(uint64) <-chan struct{}) *tokenSimple {
  190. return &tokenSimple{
  191. simpleTokens: make(map[string]string),
  192. indexWaiter: indexWaiter,
  193. }
  194. }