From 5209ce7587d4f8da37d7492d91d0aac1b91ab249 Mon Sep 17 00:00:00 2001 From: Googler Date: Wed, 28 Aug 2024 02:14:40 -0700 Subject: [PATCH] Fix cache duration computation in CredentialCacheExpiry. Also use the supplied current time instead of calling Instant.now(). I don't know how to meaningfully test this; there's so little going on that the test would essentially mirror the implementation. Fixes #23429. PiperOrigin-RevId: 668351088 Change-Id: I12f1575e5280330c61361e4cf1b7d9f9231f16eb --- .../credentialhelper/CredentialCacheExpiry.java | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/src/main/java/com/google/devtools/build/lib/authandtls/credentialhelper/CredentialCacheExpiry.java b/src/main/java/com/google/devtools/build/lib/authandtls/credentialhelper/CredentialCacheExpiry.java index 2a8f38526074f8..7a3d098239a886 100644 --- a/src/main/java/com/google/devtools/build/lib/authandtls/credentialhelper/CredentialCacheExpiry.java +++ b/src/main/java/com/google/devtools/build/lib/authandtls/credentialhelper/CredentialCacheExpiry.java @@ -32,7 +32,7 @@ public void setDefaultCacheDuration(Duration duration) { this.defaultCacheDuration = Preconditions.checkNotNull(duration); } - private Duration getExpirationTime(GetCredentialsResponse response) { + private Duration getExpirationTime(GetCredentialsResponse response, Instant currentTime) { Preconditions.checkNotNull(response); var expires = response.getExpires(); @@ -40,8 +40,7 @@ private Duration getExpirationTime(GetCredentialsResponse response) { return defaultCacheDuration; } - var now = Instant.now(); - return Duration.between(expires.get(), now); + return Duration.between(currentTime, expires.get()); } @Override @@ -49,7 +48,7 @@ public long expireAfterCreate(URI uri, GetCredentialsResponse response, long cur Preconditions.checkNotNull(uri); Preconditions.checkNotNull(response); - return getExpirationTime(response).toNanos(); + return getExpirationTime(response, Instant.ofEpochMilli(nanoToMilli(currentTime))).toNanos(); } @Override @@ -58,7 +57,7 @@ public long expireAfterUpdate( Preconditions.checkNotNull(uri); Preconditions.checkNotNull(response); - return getExpirationTime(response).toNanos(); + return getExpirationTime(response, Instant.ofEpochMilli(nanoToMilli(currentTime))).toNanos(); } @CanIgnoreReturnValue @@ -71,4 +70,8 @@ public long expireAfterRead( // We don't extend the duration on access. return currentDuration; } + + private static final long nanoToMilli(long nano) { + return Duration.ofNanos(nano).toMillis(); + } }