simple_token_test.go 2.2 KB

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