diff --git a/sdk/identity/azure-identity/CHANGELOG.md b/sdk/identity/azure-identity/CHANGELOG.md index 871f21e59..0a252a027 100644 --- a/sdk/identity/azure-identity/CHANGELOG.md +++ b/sdk/identity/azure-identity/CHANGELOG.md @@ -8,6 +8,8 @@ ### Bugs Fixed +- Fix overflow issue in token cache. + ### Other Changes - [[#6086]](https://github.com/Azure/azure-sdk-for-cpp/pull/6086) Correct minimum version specification for the Azure Core dependency. (A community contribution, courtesy of _[jdblischak](https://github.com/jdblischak)_) diff --git a/sdk/identity/azure-identity/src/token_cache.cpp b/sdk/identity/azure-identity/src/token_cache.cpp index 5c470d658..20457f97e 100644 --- a/sdk/identity/azure-identity/src/token_cache.cpp +++ b/sdk/identity/azure-identity/src/token_cache.cpp @@ -18,7 +18,9 @@ bool TokenCache::IsFresh( DateTime::duration minimumExpiration, std::chrono::system_clock::time_point now) { - return item->AccessToken.ExpiresOn > (DateTime(now) + minimumExpiration); + // Even if ExpiresOn is unset, the default and lowest value of DateTime is time_point of 0 + // Therefore, there is no risk of underflow with subtracting duration::max(). + return (item->AccessToken.ExpiresOn - minimumExpiration) > DateTime(now); } namespace { diff --git a/sdk/identity/azure-identity/test/ut/token_cache_test.cpp b/sdk/identity/azure-identity/test/ut/token_cache_test.cpp index 550dd7150..bdf1ba058 100644 --- a/sdk/identity/azure-identity/test/ut/token_cache_test.cpp +++ b/sdk/identity/azure-identity/test/ut/token_cache_test.cpp @@ -42,6 +42,23 @@ public: using namespace std::chrono_literals; +TEST(TokenCache, IsFreshOverflow) +{ + TestableTokenCache tokenCache; + + EXPECT_EQ(tokenCache.m_cache.size(), 0UL); + + DateTime const Tomorrow = std::chrono::system_clock::now() + 24h; + + auto const token1 = tokenCache.GetToken("A", {}, DateTime::duration::max(), [=]() { + AccessToken result; + result.Token = "T1"; + result.ExpiresOn = Tomorrow; + return result; + }); + EXPECT_EQ(token1.Token, "T1"); +} + TEST(TokenCache, GetReuseRefresh) { TestableTokenCache tokenCache;