Skip to content

Commit

Permalink
Revert System.Text.Json change (#485)
Browse files Browse the repository at this point in the history
- Reverting system.text.json #393 PR due to #484.
- Adding warning message for single quotes in endpoint message.
- Did not change swix/swr dependencies.

---------

Co-authored-by: Jonathan Myers <11822817+jmyersmsft@users.noreply.github.com>
  • Loading branch information
embetten and jmyersmsft committed Mar 6, 2024
1 parent 057378f commit c045372
Show file tree
Hide file tree
Showing 7 changed files with 52 additions and 32 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,21 @@ public async Task HandleRequestAsync_ReturnsSuccess()
Assert.AreEqual(result.Password, "testToken");
}

[TestMethod]
public async Task HandleRequestAsync_ReturnsSuccessWhenSingleQuotesInJson()
{
Uri sourceUri = new Uri(@"http://example.pkgs.vsts.me/_packaging/TestFeed/nuget/v3/index.json");
string feedEndPointJsonEnvVar = EnvUtil.BuildTaskExternalEndpoints;
string feedEndPointJson = "{\'endpointCredentials\':[{\'endpoint\':\'http://example.pkgs.vsts.me/_packaging/TestFeed/nuget/v3/index.json\', \'username\': \'testUser\', \'password\':\'testToken\'}]}";

Environment.SetEnvironmentVariable(feedEndPointJsonEnvVar, feedEndPointJson);

var result = await vstsCredentialProvider.HandleRequestAsync(new GetAuthenticationCredentialsRequest(sourceUri, false, false, false), CancellationToken.None);
Assert.AreEqual(result.ResponseCode, MessageResponseCode.Success);
Assert.AreEqual(result.Username, "testUser");
Assert.AreEqual(result.Password, "testToken");
}

[TestMethod]
public async Task HandleRequestAsync_ReturnsSuccessWhenMultipleSourcesInJson()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
<PackageReference Include="Microsoft.VisualStudioEng.MicroBuild.Core" PrivateAssets="All" />
<PackageReference Include="NuGet.Protocol" />
<PackageReference Include="PowerArgs" />
<PackageReference Include="Newtonsoft.Json" />
<PackageReference Include="System.Text.Json" />
</ItemGroup>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
using NuGetCredentialProvider.Logging;
using NuGetCredentialProvider.Util;

Expand All @@ -18,12 +18,6 @@ public class VstsSessionTokenClient : IVstsSessionTokenClient
{
private const string TokenScope = "vso.packaging_write vso.drop_write";

private static readonly JsonSerializerOptions options = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
PropertyNameCaseInsensitive = true
};

private readonly Uri vstsUri;
private readonly string bearerToken;
private readonly IAuthUtil authUtil;
Expand Down Expand Up @@ -51,7 +45,7 @@ private HttpRequestMessage CreateRequest(Uri uri, DateTime? validTo)
};

request.Content = new StringContent(
JsonSerializer.Serialize(tokenRequest, options),
JsonConvert.SerializeObject(tokenRequest),
Encoding.UTF8,
"application/json");

Expand Down Expand Up @@ -83,6 +77,7 @@ public async Task<string> CreateSessionTokenAsync(VstsTokenType tokenType, DateT
string serializedResponse;
if (response.StatusCode == System.Net.HttpStatusCode.BadRequest)
{

request.Dispose();
response.Dispose();

Expand All @@ -102,7 +97,7 @@ public async Task<string> CreateSessionTokenAsync(VstsTokenType tokenType, DateT
serializedResponse = await response.Content.ReadAsStringAsync();
}

var responseToken = JsonSerializer.Deserialize<VstsSessionToken>(serializedResponse, options);
var responseToken = JsonConvert.DeserializeObject<VstsSessionToken>(serializedResponse);

if (validTo.Subtract(responseToken.ValidTo.Value).TotalHours > 1.0)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,9 @@

using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
using NuGet.Protocol.Plugins;
using NuGetCredentialProvider.Util;
using ILogger = NuGetCredentialProvider.Logging.ILogger;
Expand All @@ -16,17 +15,17 @@ namespace NuGetCredentialProvider.CredentialProviders.VstsBuildTaskServiceEndpoi
{
public class EndpointCredentials
{
[JsonPropertyName("endpoint")]
[JsonProperty("endpoint")]
public string Endpoint { get; set; }
[JsonPropertyName("username")]
[JsonProperty("username")]
public string Username { get; set; }
[JsonPropertyName("password")]
[JsonProperty("password")]
public string Password { get; set; }
}

public class EndpointCredentialsContainer
{
[JsonPropertyName("endpointCredentials")]
[JsonProperty("endpointCredentials")]
public EndpointCredentials[] EndpointCredentials { get; set; }
}

Expand All @@ -36,7 +35,7 @@ public sealed class VstsBuildTaskServiceEndpointCredentialProvider : CredentialP

// Dictionary that maps an endpoint string to EndpointCredentials
private Dictionary<string, EndpointCredentials> Credentials => LazyCredentials.Value;

public VstsBuildTaskServiceEndpointCredentialProvider(ILogger logger)
: base(logger)
{
Expand Down Expand Up @@ -109,8 +108,12 @@ private Task<GetAuthenticationCredentialsResponse> GetResponse(string username,
{
// Parse JSON from VSS_NUGET_EXTERNAL_FEED_ENDPOINTS
Verbose(Resources.ParsingJson);
if (!string.IsNullOrWhiteSpace(feedEndPointsJson) && feedEndPointsJson.Contains("':"))
{
Warning(Resources.InvalidJsonWarning);
}
Dictionary<string, EndpointCredentials> credsResult = new Dictionary<string, EndpointCredentials>(StringComparer.OrdinalIgnoreCase);
EndpointCredentialsContainer endpointCredentials = JsonSerializer.Deserialize<EndpointCredentialsContainer>(feedEndPointsJson);
EndpointCredentialsContainer endpointCredentials = JsonConvert.DeserializeObject<EndpointCredentialsContainer>(feedEndPointsJson);
if (endpointCredentials == null)
{
Verbose(Resources.NoEndpointsFound);
Expand Down
4 changes: 2 additions & 2 deletions CredentialProvider.Microsoft/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Artifacts.Authentication;
using Newtonsoft.Json;
using NuGet.Common;
using NuGet.Protocol.Plugins;
using NuGetCredentialProvider.CredentialProviders;
Expand Down Expand Up @@ -165,7 +165,7 @@ public static async Task<int> Main(string[] args)
if (parsedArgs.OutputFormat == OutputFormat.Json)
{
// Manually write the JSON output, since we don't use ConsoleLogger in JSON mode (see above)
Console.WriteLine(JsonSerializer.Serialize(new CredentialResult(resultUsername, resultPassword)));
Console.WriteLine(JsonConvert.SerializeObject(new CredentialResult(resultUsername, resultPassword)));
}
else
{
Expand Down
4 changes: 4 additions & 0 deletions CredentialProvider.Microsoft/Resources.resx
Original file line number Diff line number Diff line change
Expand Up @@ -473,4 +473,8 @@ Provide MSAL Cache Location
<data name="SessionTokenCacheCancelMessage" xml:space="preserve">
<value>Canceling SessionToken cache operation.</value>
</data>
<data name="InvalidJsonWarning" xml:space="preserve">
<value>Detected invalid single quote charater in JSON input. Migrate to double quotes to avoid breaking in future versions. See https://www.rfc-editor.org/rfc/rfc8259.html#section-7 for more information.</value>

</data>
</root>
28 changes: 15 additions & 13 deletions CredentialProvider.Microsoft/Util/SessionTokenCache.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using System.Threading;
using Newtonsoft.Json;
using NuGetCredentialProvider.Logging;

namespace NuGetCredentialProvider.Util
Expand All @@ -27,7 +27,7 @@ public SessionTokenCache(string cacheFilePath, ILogger logger, CancellationToken
this.mutexName = @"Global\" + cacheFilePath.Replace(Path.DirectorySeparatorChar, '_');
}

private Dictionary<string, string> Cache
private Dictionary<Uri, string> Cache
{
get
{
Expand All @@ -48,7 +48,7 @@ public SessionTokenCache(string cacheFilePath, ILogger logger, CancellationToken
if (this.cancellationToken.IsCancellationRequested)
{
logger.Verbose(Resources.SessionTokenCacheCancelMessage);
return new Dictionary<string, string>();
return new Dictionary<Uri, string>();
}
}
}
Expand All @@ -75,7 +75,7 @@ public SessionTokenCache(string cacheFilePath, ILogger logger, CancellationToken

public string this[Uri key]
{
get => Cache[key.ToString()];
get => Cache[key];
set
{
bool mutexHeld = false, dummy;
Expand Down Expand Up @@ -108,7 +108,7 @@ public SessionTokenCache(string cacheFilePath, ILogger logger, CancellationToken
mutexHeld = true;

var cache = Cache;
cache[key.ToString()] = value;
cache[key] = value;
WriteFileBytes(Serialize(cache));
}
finally
Expand All @@ -124,14 +124,14 @@ public SessionTokenCache(string cacheFilePath, ILogger logger, CancellationToken

public bool ContainsKey(Uri key)
{
return Cache.ContainsKey(key.ToString());
return Cache.ContainsKey(key);
}

public bool TryGetValue(Uri key, out string value)
{
try
{
return Cache.TryGetValue(key.ToString(), out value);
return Cache.TryGetValue(key, out value);
}
catch (Exception e)
{
Expand Down Expand Up @@ -180,7 +180,7 @@ public void Remove(Uri key)
mutexHeld = true;

var cache = Cache;
cache.Remove(key.ToString());
cache.Remove(key);
WriteFileBytes(Serialize(cache));
}
finally
Expand All @@ -193,19 +193,21 @@ public void Remove(Uri key)
}
}

private Dictionary<string, string> Deserialize(byte[] data)
private Dictionary<Uri, string> Deserialize(byte[] data)
{
if (data == null)
{
return new Dictionary<string, string>();
return new Dictionary<Uri, string>();
}

return JsonSerializer.Deserialize<Dictionary<string, string>>(data);
var serialized = System.Text.Encoding.UTF8.GetString(data);
return JsonConvert.DeserializeObject<Dictionary<Uri, string>>(serialized);
}

private byte[] Serialize(Dictionary<string, string> data)
private byte[] Serialize(Dictionary<Uri, string> data)
{
return JsonSerializer.SerializeToUtf8Bytes(data);
var serialized = JsonConvert.SerializeObject(data);
return System.Text.Encoding.UTF8.GetBytes(serialized);
}

private byte[] ReadFileBytes()
Expand Down

0 comments on commit c045372

Please sign in to comment.