simple_token.go 5.3 KB

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