simple_token_test.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. "testing"
  18. "go.uber.org/zap"
  19. )
  20. // TestSimpleTokenDisabled ensures that TokenProviderSimple behaves correctly when
  21. // disabled.
  22. func TestSimpleTokenDisabled(t *testing.T) {
  23. initialState := newTokenProviderSimple(zap.NewExample(), dummyIndexWaiter)
  24. explicitlyDisabled := newTokenProviderSimple(zap.NewExample(), dummyIndexWaiter)
  25. explicitlyDisabled.enable()
  26. explicitlyDisabled.disable()
  27. for _, tp := range []*tokenSimple{initialState, explicitlyDisabled} {
  28. ctx := context.WithValue(context.WithValue(context.TODO(), AuthenticateParamIndex{}, uint64(1)), AuthenticateParamSimpleTokenPrefix{}, "dummy")
  29. token, err := tp.assign(ctx, "user1", 0)
  30. if err != nil {
  31. t.Fatal(err)
  32. }
  33. authInfo, ok := tp.info(ctx, token, 0)
  34. if ok {
  35. t.Errorf("expected (true, \"user1\") got (%t, %s)", ok, authInfo.Username)
  36. }
  37. tp.invalidateUser("user1") // should be no-op
  38. }
  39. }
  40. // TestSimpleTokenAssign ensures that TokenProviderSimple can correctly assign a
  41. // token, look it up with info, and invalidate it by user.
  42. func TestSimpleTokenAssign(t *testing.T) {
  43. tp := newTokenProviderSimple(zap.NewExample(), dummyIndexWaiter)
  44. tp.enable()
  45. ctx := context.WithValue(context.WithValue(context.TODO(), AuthenticateParamIndex{}, uint64(1)), AuthenticateParamSimpleTokenPrefix{}, "dummy")
  46. token, err := tp.assign(ctx, "user1", 0)
  47. if err != nil {
  48. t.Fatal(err)
  49. }
  50. authInfo, ok := tp.info(ctx, token, 0)
  51. if !ok || authInfo.Username != "user1" {
  52. t.Errorf("expected (true, \"token2\") got (%t, %s)", ok, authInfo.Username)
  53. }
  54. tp.invalidateUser("user1")
  55. _, ok = tp.info(context.TODO(), token, 0)
  56. if ok {
  57. t.Errorf("expected ok == false after user is invalidated")
  58. }
  59. }