From 06eb7fb204a6f06a5c8f206f062842e5eaf4f3fd Mon Sep 17 00:00:00 2001 From: Tim Cuthbertson Date: Wed, 15 Nov 2023 18:27:50 +1100 Subject: [PATCH] bugfix: refresh before token expires, not after --- .../client/util/cache/AuthorizationCache.scala | 4 ++-- .../client/cache/AuthorizationCacheTest.scala | 16 ++++++++++++++++ 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/kubernetes-client/src/com/goyeau/kubernetes/client/util/cache/AuthorizationCache.scala b/kubernetes-client/src/com/goyeau/kubernetes/client/util/cache/AuthorizationCache.scala index dc560606..0d9a0913 100644 --- a/kubernetes-client/src/com/goyeau/kubernetes/client/util/cache/AuthorizationCache.scala +++ b/kubernetes-client/src/com/goyeau/kubernetes/client/util/cache/AuthorizationCache.scala @@ -38,8 +38,8 @@ object AuthorizationCache { case Some(cached) => F.realTimeInstant .flatMap { now => - val shouldRenew = - cached.expirationTimestamp.exists(_.isBefore(now.minusSeconds(refreshBeforeExpiration.toSeconds))) + val minExpiry = now.plusSeconds(refreshBeforeExpiration.toSeconds) + val shouldRenew = cached.expirationTimestamp.exists(_.isBefore(minExpiry)) if (shouldRenew) getAndCacheToken.flatMap { case Some(token) => token.pure[F] diff --git a/kubernetes-client/test/src/com/goyeau/kubernetes/client/cache/AuthorizationCacheTest.scala b/kubernetes-client/test/src/com/goyeau/kubernetes/client/cache/AuthorizationCacheTest.scala index f9d2f668..24941c7b 100644 --- a/kubernetes-client/test/src/com/goyeau/kubernetes/client/cache/AuthorizationCacheTest.scala +++ b/kubernetes-client/test/src/com/goyeau/kubernetes/client/cache/AuthorizationCacheTest.scala @@ -10,6 +10,7 @@ import org.http4s.{AuthScheme, Credentials} import org.http4s.headers.Authorization import cats.effect.unsafe.implicits.global import java.time.Instant +import scala.concurrent.duration.* class AuthorizationCacheTest extends FunSuite { @@ -73,6 +74,21 @@ class AuthorizationCacheTest extends FunSuite { io.unsafeRunSync() } + test(s"retrieve the token when it's going to expire within refreshBeforeExpiration") { + val io = for { + counter <- IO.ref(1) + auth = mkAuthorization( + expirationTimestamp = IO.realTimeInstant.map(_.plusSeconds(40).some), + token = counter.getAndUpdate(_ + 1).map(i => s"test-token-$i") + ) + cache <- AuthorizationCache[IO](retrieve = auth, refreshBeforeExpiration = 1.minute) + obtained <- (1 to 5).toList.traverse(i => cache.get.product(i.pure)) + } yield obtained.foreach { case (obtained, i) => + assertEquals(obtained, Authorization(Credentials.Token(AuthScheme.Bearer, s"test-token-$i"))) + } + io.unsafeRunSync() + } + test(s"fail if cannot retrieve the token when it's expired") { val io = for { counter <- IO.ref(1)