Skip to content

Commit

Permalink
Fix overflow issue in token cache. (#6190)
Browse files Browse the repository at this point in the history
* Fix overflow issue in token cache.

* Add test
  • Loading branch information
ahsonkhan authored Nov 7, 2024
1 parent 9770fb7 commit ac3321c
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 1 deletion.
2 changes: 2 additions & 0 deletions sdk/identity/azure-identity/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)_)
Expand Down
4 changes: 3 additions & 1 deletion sdk/identity/azure-identity/src/token_cache.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
17 changes: 17 additions & 0 deletions sdk/identity/azure-identity/test/ut/token_cache_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,23 @@ class TestableTokenCache final : public TokenCache {

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;
Expand Down

0 comments on commit ac3321c

Please sign in to comment.