token_manager_test.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  1. /*
  2. Copyright 2018 The Kubernetes Authors.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package token
  14. import (
  15. "fmt"
  16. "testing"
  17. "time"
  18. authenticationv1 "k8s.io/api/authentication/v1"
  19. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  20. "k8s.io/apimachinery/pkg/types"
  21. "k8s.io/apimachinery/pkg/util/clock"
  22. )
  23. func TestTokenCachingAndExpiration(t *testing.T) {
  24. type suite struct {
  25. clock *clock.FakeClock
  26. tg *fakeTokenGetter
  27. mgr *Manager
  28. }
  29. cases := []struct {
  30. name string
  31. exp time.Duration
  32. f func(t *testing.T, s *suite)
  33. }{
  34. {
  35. name: "rotate hour token expires in the last 12 minutes",
  36. exp: time.Hour,
  37. f: func(t *testing.T, s *suite) {
  38. s.clock.SetTime(s.clock.Now().Add(50 * time.Minute))
  39. if _, err := s.mgr.GetServiceAccountToken("a", "b", getTokenRequest()); err != nil {
  40. t.Fatalf("unexpected error: %v", err)
  41. }
  42. if s.tg.count != 2 {
  43. t.Fatalf("expected token to be refreshed: call count was %d", s.tg.count)
  44. }
  45. },
  46. },
  47. {
  48. name: "rotate 24 hour token that expires in 40 hours",
  49. exp: 40 * time.Hour,
  50. f: func(t *testing.T, s *suite) {
  51. s.clock.SetTime(s.clock.Now().Add(25 * time.Hour))
  52. if _, err := s.mgr.GetServiceAccountToken("a", "b", getTokenRequest()); err != nil {
  53. t.Fatalf("unexpected error: %v", err)
  54. }
  55. if s.tg.count != 2 {
  56. t.Fatalf("expected token to be refreshed: call count was %d", s.tg.count)
  57. }
  58. },
  59. },
  60. {
  61. name: "rotate hour token fails, old token is still valid, doesn't error",
  62. exp: time.Hour,
  63. f: func(t *testing.T, s *suite) {
  64. s.clock.SetTime(s.clock.Now().Add(50 * time.Minute))
  65. tg := &fakeTokenGetter{
  66. err: fmt.Errorf("err"),
  67. }
  68. s.mgr.getToken = tg.getToken
  69. tr, err := s.mgr.GetServiceAccountToken("a", "b", getTokenRequest())
  70. if err != nil {
  71. t.Fatalf("unexpected error: %v", err)
  72. }
  73. if tr.Status.Token != "foo" {
  74. t.Fatalf("unexpected token: %v", tr.Status.Token)
  75. }
  76. },
  77. },
  78. }
  79. for _, c := range cases {
  80. t.Run(c.name, func(t *testing.T) {
  81. clock := clock.NewFakeClock(time.Time{}.Add(30 * 24 * time.Hour))
  82. expSecs := int64(c.exp.Seconds())
  83. s := &suite{
  84. clock: clock,
  85. mgr: NewManager(nil),
  86. tg: &fakeTokenGetter{
  87. tr: &authenticationv1.TokenRequest{
  88. Spec: authenticationv1.TokenRequestSpec{
  89. ExpirationSeconds: &expSecs,
  90. },
  91. Status: authenticationv1.TokenRequestStatus{
  92. Token: "foo",
  93. ExpirationTimestamp: metav1.Time{Time: clock.Now().Add(c.exp)},
  94. },
  95. },
  96. },
  97. }
  98. s.mgr.getToken = s.tg.getToken
  99. s.mgr.clock = s.clock
  100. if _, err := s.mgr.GetServiceAccountToken("a", "b", getTokenRequest()); err != nil {
  101. t.Fatalf("unexpected error: %v", err)
  102. }
  103. if s.tg.count != 1 {
  104. t.Fatalf("unexpected client call, got: %d, want: 1", s.tg.count)
  105. }
  106. if _, err := s.mgr.GetServiceAccountToken("a", "b", getTokenRequest()); err != nil {
  107. t.Fatalf("unexpected error: %v", err)
  108. }
  109. if s.tg.count != 1 {
  110. t.Fatalf("expected token to be served from cache: saw %d", s.tg.count)
  111. }
  112. c.f(t, s)
  113. })
  114. }
  115. }
  116. func TestRequiresRefresh(t *testing.T) {
  117. start := time.Now()
  118. cases := []struct {
  119. now, exp time.Time
  120. expectRefresh bool
  121. }{
  122. {
  123. now: start.Add(10 * time.Minute),
  124. exp: start.Add(60 * time.Minute),
  125. expectRefresh: false,
  126. },
  127. {
  128. now: start.Add(50 * time.Minute),
  129. exp: start.Add(60 * time.Minute),
  130. expectRefresh: true,
  131. },
  132. {
  133. now: start.Add(25 * time.Hour),
  134. exp: start.Add(60 * time.Hour),
  135. expectRefresh: true,
  136. },
  137. {
  138. now: start.Add(70 * time.Minute),
  139. exp: start.Add(60 * time.Minute),
  140. expectRefresh: true,
  141. },
  142. }
  143. for i, c := range cases {
  144. t.Run(fmt.Sprint(i), func(t *testing.T) {
  145. clock := clock.NewFakeClock(c.now)
  146. secs := int64(c.exp.Sub(start).Seconds())
  147. tr := &authenticationv1.TokenRequest{
  148. Spec: authenticationv1.TokenRequestSpec{
  149. ExpirationSeconds: &secs,
  150. },
  151. Status: authenticationv1.TokenRequestStatus{
  152. ExpirationTimestamp: metav1.Time{Time: c.exp},
  153. },
  154. }
  155. mgr := NewManager(nil)
  156. mgr.clock = clock
  157. rr := mgr.requiresRefresh(tr)
  158. if rr != c.expectRefresh {
  159. t.Fatalf("unexpected requiresRefresh result, got: %v, want: %v", rr, c.expectRefresh)
  160. }
  161. })
  162. }
  163. }
  164. func TestDeleteServiceAccountToken(t *testing.T) {
  165. type request struct {
  166. name, namespace string
  167. tr authenticationv1.TokenRequest
  168. shouldFail bool
  169. }
  170. cases := []struct {
  171. name string
  172. requestIndex []int
  173. deletePodUID []types.UID
  174. expLeftIndex []int
  175. }{
  176. {
  177. name: "delete none with all success requests",
  178. requestIndex: []int{0, 1, 2},
  179. expLeftIndex: []int{0, 1, 2},
  180. },
  181. {
  182. name: "delete one with all success requests",
  183. requestIndex: []int{0, 1, 2},
  184. deletePodUID: []types.UID{"fake-uid-1"},
  185. expLeftIndex: []int{1, 2},
  186. },
  187. {
  188. name: "delete two with all success requests",
  189. requestIndex: []int{0, 1, 2},
  190. deletePodUID: []types.UID{"fake-uid-1", "fake-uid-3"},
  191. expLeftIndex: []int{1},
  192. },
  193. {
  194. name: "delete all with all suceess requests",
  195. requestIndex: []int{0, 1, 2},
  196. deletePodUID: []types.UID{"fake-uid-1", "fake-uid-2", "fake-uid-3"},
  197. },
  198. {
  199. name: "delete no pod with failed requests",
  200. requestIndex: []int{0, 1, 2, 3},
  201. deletePodUID: []types.UID{},
  202. expLeftIndex: []int{0, 1, 2},
  203. },
  204. {
  205. name: "delete other pod with failed requests",
  206. requestIndex: []int{0, 1, 2, 3},
  207. deletePodUID: []types.UID{"fake-uid-2"},
  208. expLeftIndex: []int{0, 2},
  209. },
  210. {
  211. name: "delete no pod with request which success after failure",
  212. requestIndex: []int{0, 1, 2, 3, 4},
  213. deletePodUID: []types.UID{},
  214. expLeftIndex: []int{0, 1, 2, 4},
  215. },
  216. {
  217. name: "delete the pod which success after failure",
  218. requestIndex: []int{0, 1, 2, 3, 4},
  219. deletePodUID: []types.UID{"fake-uid-4"},
  220. expLeftIndex: []int{0, 1, 2},
  221. },
  222. {
  223. name: "delete other pod with request which success after failure",
  224. requestIndex: []int{0, 1, 2, 3, 4},
  225. deletePodUID: []types.UID{"fake-uid-1"},
  226. expLeftIndex: []int{1, 2, 4},
  227. },
  228. {
  229. name: "delete some pod not in the set",
  230. requestIndex: []int{0, 1, 2},
  231. deletePodUID: []types.UID{"fake-uid-100", "fake-uid-200"},
  232. expLeftIndex: []int{0, 1, 2},
  233. },
  234. }
  235. for _, c := range cases {
  236. t.Run(c.name, func(t *testing.T) {
  237. requests := []request{
  238. {
  239. name: "fake-name-1",
  240. namespace: "fake-namespace-1",
  241. tr: authenticationv1.TokenRequest{
  242. Spec: authenticationv1.TokenRequestSpec{
  243. BoundObjectRef: &authenticationv1.BoundObjectReference{
  244. UID: "fake-uid-1",
  245. Name: "fake-name-1",
  246. },
  247. },
  248. },
  249. shouldFail: false,
  250. },
  251. {
  252. name: "fake-name-2",
  253. namespace: "fake-namespace-2",
  254. tr: authenticationv1.TokenRequest{
  255. Spec: authenticationv1.TokenRequestSpec{
  256. BoundObjectRef: &authenticationv1.BoundObjectReference{
  257. UID: "fake-uid-2",
  258. Name: "fake-name-2",
  259. },
  260. },
  261. },
  262. shouldFail: false,
  263. },
  264. {
  265. name: "fake-name-3",
  266. namespace: "fake-namespace-3",
  267. tr: authenticationv1.TokenRequest{
  268. Spec: authenticationv1.TokenRequestSpec{
  269. BoundObjectRef: &authenticationv1.BoundObjectReference{
  270. UID: "fake-uid-3",
  271. Name: "fake-name-3",
  272. },
  273. },
  274. },
  275. shouldFail: false,
  276. },
  277. {
  278. name: "fake-name-4",
  279. namespace: "fake-namespace-4",
  280. tr: authenticationv1.TokenRequest{
  281. Spec: authenticationv1.TokenRequestSpec{
  282. BoundObjectRef: &authenticationv1.BoundObjectReference{
  283. UID: "fake-uid-4",
  284. Name: "fake-name-4",
  285. },
  286. },
  287. },
  288. shouldFail: true,
  289. },
  290. {
  291. //exactly the same with last one, besides it will success
  292. name: "fake-name-4",
  293. namespace: "fake-namespace-4",
  294. tr: authenticationv1.TokenRequest{
  295. Spec: authenticationv1.TokenRequestSpec{
  296. BoundObjectRef: &authenticationv1.BoundObjectReference{
  297. UID: "fake-uid-4",
  298. Name: "fake-name-4",
  299. },
  300. },
  301. },
  302. shouldFail: false,
  303. },
  304. }
  305. testMgr := NewManager(nil)
  306. testMgr.clock = clock.NewFakeClock(time.Time{}.Add(30 * 24 * time.Hour))
  307. successGetToken := func(_, _ string, tr *authenticationv1.TokenRequest) (*authenticationv1.TokenRequest, error) {
  308. tr.Status = authenticationv1.TokenRequestStatus{
  309. ExpirationTimestamp: metav1.Time{Time: testMgr.clock.Now().Add(10 * time.Hour)},
  310. }
  311. return tr, nil
  312. }
  313. failGetToken := func(_, _ string, tr *authenticationv1.TokenRequest) (*authenticationv1.TokenRequest, error) {
  314. return nil, fmt.Errorf("fail tr")
  315. }
  316. for _, index := range c.requestIndex {
  317. req := requests[index]
  318. if req.shouldFail {
  319. testMgr.getToken = failGetToken
  320. } else {
  321. testMgr.getToken = successGetToken
  322. }
  323. testMgr.GetServiceAccountToken(req.namespace, req.name, &req.tr)
  324. }
  325. for _, uid := range c.deletePodUID {
  326. testMgr.DeleteServiceAccountToken(uid)
  327. }
  328. if len(c.expLeftIndex) != len(testMgr.cache) {
  329. t.Errorf("%s got unexpected result: expected left cache size is %d, got %d", c.name, len(c.expLeftIndex), len(testMgr.cache))
  330. }
  331. for _, leftIndex := range c.expLeftIndex {
  332. r := requests[leftIndex]
  333. _, ok := testMgr.get(keyFunc(r.name, r.namespace, &r.tr))
  334. if !ok {
  335. t.Errorf("%s got unexpected result: expected token request %v exist in cache, but not", c.name, r)
  336. }
  337. }
  338. })
  339. }
  340. }
  341. type fakeTokenGetter struct {
  342. count int
  343. tr *authenticationv1.TokenRequest
  344. err error
  345. }
  346. func (ftg *fakeTokenGetter) getToken(name, namespace string, tr *authenticationv1.TokenRequest) (*authenticationv1.TokenRequest, error) {
  347. ftg.count++
  348. return ftg.tr, ftg.err
  349. }
  350. func TestCleanup(t *testing.T) {
  351. cases := []struct {
  352. name string
  353. relativeExp time.Duration
  354. expectedCacheSize int
  355. }{
  356. {
  357. name: "don't cleanup unexpired tokens",
  358. relativeExp: -1 * time.Hour,
  359. expectedCacheSize: 0,
  360. },
  361. {
  362. name: "cleanup expired tokens",
  363. relativeExp: time.Hour,
  364. expectedCacheSize: 1,
  365. },
  366. }
  367. for _, c := range cases {
  368. t.Run(c.name, func(t *testing.T) {
  369. clock := clock.NewFakeClock(time.Time{}.Add(24 * time.Hour))
  370. mgr := NewManager(nil)
  371. mgr.clock = clock
  372. mgr.set("key", &authenticationv1.TokenRequest{
  373. Status: authenticationv1.TokenRequestStatus{
  374. ExpirationTimestamp: metav1.Time{Time: mgr.clock.Now().Add(c.relativeExp)},
  375. },
  376. })
  377. mgr.cleanup()
  378. if got, want := len(mgr.cache), c.expectedCacheSize; got != want {
  379. t.Fatalf("unexpected number of cache entries after cleanup, got: %d, want: %d", got, want)
  380. }
  381. })
  382. }
  383. }
  384. func TestKeyFunc(t *testing.T) {
  385. type tokenRequestUnit struct {
  386. name string
  387. namespace string
  388. tr *authenticationv1.TokenRequest
  389. }
  390. getKeyFunc := func(u tokenRequestUnit) string {
  391. return keyFunc(u.name, u.namespace, u.tr)
  392. }
  393. cases := []struct {
  394. name string
  395. trus []tokenRequestUnit
  396. target tokenRequestUnit
  397. shouldHit bool
  398. }{
  399. {
  400. name: "hit",
  401. trus: []tokenRequestUnit{
  402. {
  403. name: "foo-sa",
  404. namespace: "foo-ns",
  405. tr: &authenticationv1.TokenRequest{
  406. Spec: authenticationv1.TokenRequestSpec{
  407. Audiences: []string{"foo1", "foo2"},
  408. ExpirationSeconds: getInt64Point(2000),
  409. BoundObjectRef: &authenticationv1.BoundObjectReference{
  410. Kind: "pod",
  411. Name: "foo-pod",
  412. UID: "foo-uid",
  413. },
  414. },
  415. },
  416. },
  417. {
  418. name: "ame-sa",
  419. namespace: "ame-ns",
  420. tr: &authenticationv1.TokenRequest{
  421. Spec: authenticationv1.TokenRequestSpec{
  422. Audiences: []string{"ame1", "ame2"},
  423. ExpirationSeconds: getInt64Point(2000),
  424. BoundObjectRef: &authenticationv1.BoundObjectReference{
  425. Kind: "pod",
  426. Name: "ame-pod",
  427. UID: "ame-uid",
  428. },
  429. },
  430. },
  431. },
  432. },
  433. target: tokenRequestUnit{
  434. name: "foo-sa",
  435. namespace: "foo-ns",
  436. tr: &authenticationv1.TokenRequest{
  437. Spec: authenticationv1.TokenRequestSpec{
  438. Audiences: []string{"foo1", "foo2"},
  439. ExpirationSeconds: getInt64Point(2000),
  440. BoundObjectRef: &authenticationv1.BoundObjectReference{
  441. Kind: "pod",
  442. Name: "foo-pod",
  443. UID: "foo-uid",
  444. },
  445. },
  446. },
  447. },
  448. shouldHit: true,
  449. },
  450. {
  451. name: "not hit due to different ExpirationSeconds",
  452. trus: []tokenRequestUnit{
  453. {
  454. name: "foo-sa",
  455. namespace: "foo-ns",
  456. tr: &authenticationv1.TokenRequest{
  457. Spec: authenticationv1.TokenRequestSpec{
  458. Audiences: []string{"foo1", "foo2"},
  459. ExpirationSeconds: getInt64Point(2000),
  460. BoundObjectRef: &authenticationv1.BoundObjectReference{
  461. Kind: "pod",
  462. Name: "foo-pod",
  463. UID: "foo-uid",
  464. },
  465. },
  466. },
  467. },
  468. },
  469. target: tokenRequestUnit{
  470. name: "foo-sa",
  471. namespace: "foo-ns",
  472. tr: &authenticationv1.TokenRequest{
  473. Spec: authenticationv1.TokenRequestSpec{
  474. Audiences: []string{"foo1", "foo2"},
  475. //everthing is same besides ExpirationSeconds
  476. ExpirationSeconds: getInt64Point(2001),
  477. BoundObjectRef: &authenticationv1.BoundObjectReference{
  478. Kind: "pod",
  479. Name: "foo-pod",
  480. UID: "foo-uid",
  481. },
  482. },
  483. },
  484. },
  485. shouldHit: false,
  486. },
  487. {
  488. name: "not hit due to different BoundObjectRef",
  489. trus: []tokenRequestUnit{
  490. {
  491. name: "foo-sa",
  492. namespace: "foo-ns",
  493. tr: &authenticationv1.TokenRequest{
  494. Spec: authenticationv1.TokenRequestSpec{
  495. Audiences: []string{"foo1", "foo2"},
  496. ExpirationSeconds: getInt64Point(2000),
  497. BoundObjectRef: &authenticationv1.BoundObjectReference{
  498. Kind: "pod",
  499. Name: "foo-pod",
  500. UID: "foo-uid",
  501. },
  502. },
  503. },
  504. },
  505. },
  506. target: tokenRequestUnit{
  507. name: "foo-sa",
  508. namespace: "foo-ns",
  509. tr: &authenticationv1.TokenRequest{
  510. Spec: authenticationv1.TokenRequestSpec{
  511. Audiences: []string{"foo1", "foo2"},
  512. ExpirationSeconds: getInt64Point(2000),
  513. BoundObjectRef: &authenticationv1.BoundObjectReference{
  514. Kind: "pod",
  515. //everthing is same besides BoundObjectRef.Name
  516. Name: "diff-pod",
  517. UID: "foo-uid",
  518. },
  519. },
  520. },
  521. },
  522. shouldHit: false,
  523. },
  524. }
  525. for _, c := range cases {
  526. t.Run(c.name, func(t *testing.T) {
  527. mgr := NewManager(nil)
  528. mgr.clock = clock.NewFakeClock(time.Time{}.Add(30 * 24 * time.Hour))
  529. for _, tru := range c.trus {
  530. mgr.set(getKeyFunc(tru), &authenticationv1.TokenRequest{
  531. Status: authenticationv1.TokenRequestStatus{
  532. //make sure the token cache would not be cleaned by token manager clenaup func
  533. ExpirationTimestamp: metav1.Time{Time: mgr.clock.Now().Add(50 * time.Minute)},
  534. },
  535. })
  536. }
  537. _, hit := mgr.get(getKeyFunc(c.target))
  538. if hit != c.shouldHit {
  539. t.Errorf("%s got unexpected hit result: expected to be %t, got %t", c.name, c.shouldHit, hit)
  540. }
  541. })
  542. }
  543. }
  544. func getTokenRequest() *authenticationv1.TokenRequest {
  545. return &authenticationv1.TokenRequest{
  546. Spec: authenticationv1.TokenRequestSpec{
  547. Audiences: []string{"foo1", "foo2"},
  548. ExpirationSeconds: getInt64Point(2000),
  549. BoundObjectRef: &authenticationv1.BoundObjectReference{
  550. Kind: "pod",
  551. Name: "foo-pod",
  552. UID: "foo-uid",
  553. },
  554. },
  555. }
  556. }
  557. func getInt64Point(v int64) *int64 {
  558. return &v
  559. }