simple_token.go 5.7 KB

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