Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix Date-Time Parsing in GetDurationFromNowInSeconds for Multiple Formats #4964

Merged
merged 5 commits into from
Oct 22, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
init
GladwinJohnson committed Oct 21, 2024
commit 838ea28315e607216623b6188ac4b26da24fed4c
32 changes: 28 additions & 4 deletions src/client/Microsoft.Identity.Client/Utils/DateTimeHelpers.cs
Original file line number Diff line number Diff line change
@@ -63,15 +63,39 @@ public static long GetDurationFromWindowsTimestamp(string windowsTimestampInFutu
return (long)unixTimestamp - CurrDateTimeInUnixTimestamp();
}

public static long GetDurationFromNowInSeconds(string unixTimestampInFuture)
public static long GetDurationFromNowInSeconds(string expiresOn)
{
if (string.IsNullOrEmpty(unixTimestampInFuture))
if (string.IsNullOrEmpty(expiresOn))
{
return 0;
}

long expiresOnUnixTimestamp = long.Parse(unixTimestampInFuture, CultureInfo.InvariantCulture);
return expiresOnUnixTimestamp - CurrDateTimeInUnixTimestamp();
// First, try to parse as Unix timestamp (number of seconds since epoch)
if (long.TryParse(expiresOn, out long expiresOnUnixTimestamp))
{
return expiresOnUnixTimestamp - DateTimeHelpers.CurrDateTimeInUnixTimestamp();
}

// Try parsing as ISO 8601
if (DateTimeOffset.TryParse(expiresOn, null, DateTimeStyles.RoundtripKind, out DateTimeOffset expiresOnDateTime))
{
return (long)(expiresOnDateTime - DateTimeOffset.UtcNow).TotalSeconds;
}

// Try RFC 1123 format
if (DateTimeOffset.TryParseExact(expiresOn, "R", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out expiresOnDateTime))
{
return (long)(expiresOnDateTime - DateTimeOffset.UtcNow).TotalSeconds;
}

// Try parsing Unix timestamp in milliseconds
if (long.TryParse(expiresOn, out long expiresOnMillisTimestamp) && expiresOn.Length > 10)
{
return (expiresOnMillisTimestamp / 1000) - DateTimeHelpers.CurrDateTimeInUnixTimestamp();
}

// If no format works, throw an MSAL client exception
throw new MsalClientException("invalid_token_expiration_format", $"Failed to parse Expires On value. Invalid format for expiresOn: '{expiresOn}'.");
}

public static DateTimeOffset? DateTimeOffsetFromDuration(long? duration)
16 changes: 14 additions & 2 deletions tests/Microsoft.Identity.Test.Common/Core/Mocks/MockHelpers.cs
Original file line number Diff line number Diff line change
@@ -113,9 +113,21 @@ public static string GetBridgedHybridSpaTokenResponse(string spaAccountId)
",\"id_token_expires_in\":\"3600\"}";
}

public static string GetMsiSuccessfulResponse(int expiresInHours = 1)
public static string GetMsiSuccessfulResponse(int expiresInHours = 1, bool useIsoFormat = false)
{
string expiresOn = DateTimeHelpers.DateTimeToUnixTimestamp(DateTime.UtcNow.AddHours(expiresInHours));
string expiresOn;

if (useIsoFormat)
{
// Return ISO 8601 format
expiresOn = DateTime.UtcNow.AddHours(expiresInHours).ToString("o", CultureInfo.InvariantCulture);
}
else
{
// Return Unix timestamp format
expiresOn = DateTimeHelpers.DateTimeToUnixTimestamp(DateTime.UtcNow.AddHours(expiresInHours));
}

return
"{\"access_token\":\"" + TestConstants.ATSecret + "\",\"expires_on\":\"" + expiresOn + "\",\"resource\":\"https://management.azure.com/\",\"token_type\":" +
"\"Bearer\",\"client_id\":\"client_id\"}";
Original file line number Diff line number Diff line change
@@ -806,10 +806,13 @@ public async Task ManagedIdentityCacheTestAsync()
}

[DataTestMethod]
[DataRow(1, false)]
[DataRow(2, false)]
[DataRow(3, true)]
public async Task ManagedIdentityExpiresOnTestAsync(int expiresInHours, bool refreshOnHasValue)
[DataRow(1, false, false)]
[DataRow(2, false, false)]
[DataRow(3, true, false)]
[DataRow(1, false, true)]
[DataRow(2, false, true)]
[DataRow(3, true, true)]
public async Task ManagedIdentityExpiresOnTestAsync(int expiresInHours, bool refreshOnHasValue, bool useIsoFormat)
{
using (new EnvVariableContext())
using (var httpManager = new MockHttpManager(isManagedIdentity: true))
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Identity.Client;
using Microsoft.Identity.Client.Utils;
using Microsoft.Identity.Test.Common;
using Microsoft.Identity.Test.Common.Core.Helpers;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Microsoft.Identity.Test.Unit.UtilTests
{
[TestClass]
public class DateTimeHelperTests
{
[TestMethod]
public void TestGetDurationFromNowInSeconds()
{
// Arrange
var currentTime = DateTimeOffset.UtcNow;

// Unix timestamp (seconds since epoch)
string unixTimestamp = DateTimeHelpers.DateTimeToUnixTimestamp(currentTime);
long result = DateTimeHelpers.GetDurationFromNowInSeconds(unixTimestamp);
Assert.IsTrue(result >= 0, "Unix timestamp failed");

// ISO 8601 format
string iso8601 = currentTime.ToString("o", CultureInfo.InvariantCulture); // ISO 8601 with "o" format
result = DateTimeHelpers.GetDurationFromNowInSeconds(iso8601);
Assert.IsTrue(result >= 0, "ISO 8601 failed");

// RFC 1123 format
string rfc1123 = currentTime.ToString("R", CultureInfo.InvariantCulture); // RFC 1123 with "R" format
result = DateTimeHelpers.GetDurationFromNowInSeconds(rfc1123);
Assert.IsTrue(result >= 0, "RFC 1123 failed");

// Common format: MM/dd/yyyy HH:mm:ss
string commonFormat1 = currentTime.ToString("MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
result = DateTimeHelpers.GetDurationFromNowInSeconds(commonFormat1);
Assert.IsTrue(result >= 0, "Common Format 1 failed");

// Common format: yyyy-MM-dd HH:mm:ss
string commonFormat2 = currentTime.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
result = DateTimeHelpers.GetDurationFromNowInSeconds(commonFormat2);
Assert.IsTrue(result >= 0, "Common Format 2 failed");

// Invalid format: This should throw an MsalClientException
string invalidFormat = "invalid-date-format";
Assert.ThrowsException<MsalClientException>(() =>
{
DateTimeHelpers.GetDurationFromNowInSeconds(invalidFormat);
});
}
}
}