Skip to content

Commit c045372

Browse files
embettenjmyersmsft
andauthored
Revert System.Text.Json change (#485)
- 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>
1 parent 057378f commit c045372

File tree

7 files changed

+52
-32
lines changed

7 files changed

+52
-32
lines changed

CredentialProvider.Microsoft.Tests/CredentialProviders/VstsBuildTaskServiceEndpoint/VstsBuildTaskServiceEndpointCredentialProviderTests.cs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,21 @@ public async Task HandleRequestAsync_ReturnsSuccess()
8383
Assert.AreEqual(result.Password, "testToken");
8484
}
8585

86+
[TestMethod]
87+
public async Task HandleRequestAsync_ReturnsSuccessWhenSingleQuotesInJson()
88+
{
89+
Uri sourceUri = new Uri(@"http://example.pkgs.vsts.me/_packaging/TestFeed/nuget/v3/index.json");
90+
string feedEndPointJsonEnvVar = EnvUtil.BuildTaskExternalEndpoints;
91+
string feedEndPointJson = "{\'endpointCredentials\':[{\'endpoint\':\'http://example.pkgs.vsts.me/_packaging/TestFeed/nuget/v3/index.json\', \'username\': \'testUser\', \'password\':\'testToken\'}]}";
92+
93+
Environment.SetEnvironmentVariable(feedEndPointJsonEnvVar, feedEndPointJson);
94+
95+
var result = await vstsCredentialProvider.HandleRequestAsync(new GetAuthenticationCredentialsRequest(sourceUri, false, false, false), CancellationToken.None);
96+
Assert.AreEqual(result.ResponseCode, MessageResponseCode.Success);
97+
Assert.AreEqual(result.Username, "testUser");
98+
Assert.AreEqual(result.Password, "testToken");
99+
}
100+
86101
[TestMethod]
87102
public async Task HandleRequestAsync_ReturnsSuccessWhenMultipleSourcesInJson()
88103
{

CredentialProvider.Microsoft/CredentialProvider.Microsoft.csproj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@
3333
<PackageReference Include="Microsoft.VisualStudioEng.MicroBuild.Core" PrivateAssets="All" />
3434
<PackageReference Include="NuGet.Protocol" />
3535
<PackageReference Include="PowerArgs" />
36+
<PackageReference Include="Newtonsoft.Json" />
3637
<PackageReference Include="System.Text.Json" />
3738
</ItemGroup>
3839

CredentialProvider.Microsoft/CredentialProviders/Vsts/VstsSessionTokenClient.cs

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,9 @@
66
using System.Net.Http;
77
using System.Net.Http.Headers;
88
using System.Text;
9-
using System.Text.Json;
109
using System.Threading;
1110
using System.Threading.Tasks;
11+
using Newtonsoft.Json;
1212
using NuGetCredentialProvider.Logging;
1313
using NuGetCredentialProvider.Util;
1414

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

21-
private static readonly JsonSerializerOptions options = new JsonSerializerOptions
22-
{
23-
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
24-
PropertyNameCaseInsensitive = true
25-
};
26-
2721
private readonly Uri vstsUri;
2822
private readonly string bearerToken;
2923
private readonly IAuthUtil authUtil;
@@ -51,7 +45,7 @@ private HttpRequestMessage CreateRequest(Uri uri, DateTime? validTo)
5145
};
5246

5347
request.Content = new StringContent(
54-
JsonSerializer.Serialize(tokenRequest, options),
48+
JsonConvert.SerializeObject(tokenRequest),
5549
Encoding.UTF8,
5650
"application/json");
5751

@@ -83,6 +77,7 @@ public async Task<string> CreateSessionTokenAsync(VstsTokenType tokenType, DateT
8377
string serializedResponse;
8478
if (response.StatusCode == System.Net.HttpStatusCode.BadRequest)
8579
{
80+
8681
request.Dispose();
8782
response.Dispose();
8883

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

105-
var responseToken = JsonSerializer.Deserialize<VstsSessionToken>(serializedResponse, options);
100+
var responseToken = JsonConvert.DeserializeObject<VstsSessionToken>(serializedResponse);
106101

107102
if (validTo.Subtract(responseToken.ValidTo.Value).TotalHours > 1.0)
108103
{

CredentialProvider.Microsoft/CredentialProviders/VstsBuildTaskServiceEndpoint/VstsBuildTaskServiceEndpointCredentialProvider.cs

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,9 @@
44

55
using System;
66
using System.Collections.Generic;
7-
using System.Text.Json;
8-
using System.Text.Json.Serialization;
97
using System.Threading;
108
using System.Threading.Tasks;
9+
using Newtonsoft.Json;
1110
using NuGet.Protocol.Plugins;
1211
using NuGetCredentialProvider.Util;
1312
using ILogger = NuGetCredentialProvider.Logging.ILogger;
@@ -16,17 +15,17 @@ namespace NuGetCredentialProvider.CredentialProviders.VstsBuildTaskServiceEndpoi
1615
{
1716
public class EndpointCredentials
1817
{
19-
[JsonPropertyName("endpoint")]
18+
[JsonProperty("endpoint")]
2019
public string Endpoint { get; set; }
21-
[JsonPropertyName("username")]
20+
[JsonProperty("username")]
2221
public string Username { get; set; }
23-
[JsonPropertyName("password")]
22+
[JsonProperty("password")]
2423
public string Password { get; set; }
2524
}
2625

2726
public class EndpointCredentialsContainer
2827
{
29-
[JsonPropertyName("endpointCredentials")]
28+
[JsonProperty("endpointCredentials")]
3029
public EndpointCredentials[] EndpointCredentials { get; set; }
3130
}
3231

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

3736
// Dictionary that maps an endpoint string to EndpointCredentials
3837
private Dictionary<string, EndpointCredentials> Credentials => LazyCredentials.Value;
39-
38+
4039
public VstsBuildTaskServiceEndpointCredentialProvider(ILogger logger)
4140
: base(logger)
4241
{
@@ -109,8 +108,12 @@ private Dictionary<string, EndpointCredentials> ParseJsonToDictionary()
109108
{
110109
// Parse JSON from VSS_NUGET_EXTERNAL_FEED_ENDPOINTS
111110
Verbose(Resources.ParsingJson);
111+
if (!string.IsNullOrWhiteSpace(feedEndPointsJson) && feedEndPointsJson.Contains("':"))
112+
{
113+
Warning(Resources.InvalidJsonWarning);
114+
}
112115
Dictionary<string, EndpointCredentials> credsResult = new Dictionary<string, EndpointCredentials>(StringComparer.OrdinalIgnoreCase);
113-
EndpointCredentialsContainer endpointCredentials = JsonSerializer.Deserialize<EndpointCredentialsContainer>(feedEndPointsJson);
116+
EndpointCredentialsContainer endpointCredentials = JsonConvert.DeserializeObject<EndpointCredentialsContainer>(feedEndPointsJson);
114117
if (endpointCredentials == null)
115118
{
116119
Verbose(Resources.NoEndpointsFound);

CredentialProvider.Microsoft/Program.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,10 @@
55
using System;
66
using System.Collections.Generic;
77
using System.IO;
8-
using System.Text.Json;
98
using System.Threading;
109
using System.Threading.Tasks;
1110
using Microsoft.Artifacts.Authentication;
11+
using Newtonsoft.Json;
1212
using NuGet.Common;
1313
using NuGet.Protocol.Plugins;
1414
using NuGetCredentialProvider.CredentialProviders;
@@ -165,7 +165,7 @@ public static async Task<int> Main(string[] args)
165165
if (parsedArgs.OutputFormat == OutputFormat.Json)
166166
{
167167
// Manually write the JSON output, since we don't use ConsoleLogger in JSON mode (see above)
168-
Console.WriteLine(JsonSerializer.Serialize(new CredentialResult(resultUsername, resultPassword)));
168+
Console.WriteLine(JsonConvert.SerializeObject(new CredentialResult(resultUsername, resultPassword)));
169169
}
170170
else
171171
{

CredentialProvider.Microsoft/Resources.resx

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -473,4 +473,8 @@ Provide MSAL Cache Location
473473
<data name="SessionTokenCacheCancelMessage" xml:space="preserve">
474474
<value>Canceling SessionToken cache operation.</value>
475475
</data>
476+
<data name="InvalidJsonWarning" xml:space="preserve">
477+
<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>
478+
479+
</data>
476480
</root>

CredentialProvider.Microsoft/Util/SessionTokenCache.cs

Lines changed: 15 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,8 @@
55
using System;
66
using System.Collections.Generic;
77
using System.IO;
8-
using System.Text.Json;
98
using System.Threading;
9+
using Newtonsoft.Json;
1010
using NuGetCredentialProvider.Logging;
1111

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

30-
private Dictionary<string, string> Cache
30+
private Dictionary<Uri, string> Cache
3131
{
3232
get
3333
{
@@ -48,7 +48,7 @@ private Dictionary<string, string> Cache
4848
if (this.cancellationToken.IsCancellationRequested)
4949
{
5050
logger.Verbose(Resources.SessionTokenCacheCancelMessage);
51-
return new Dictionary<string, string>();
51+
return new Dictionary<Uri, string>();
5252
}
5353
}
5454
}
@@ -75,7 +75,7 @@ private Dictionary<string, string> Cache
7575

7676
public string this[Uri key]
7777
{
78-
get => Cache[key.ToString()];
78+
get => Cache[key];
7979
set
8080
{
8181
bool mutexHeld = false, dummy;
@@ -108,7 +108,7 @@ public string this[Uri key]
108108
mutexHeld = true;
109109

110110
var cache = Cache;
111-
cache[key.ToString()] = value;
111+
cache[key] = value;
112112
WriteFileBytes(Serialize(cache));
113113
}
114114
finally
@@ -124,14 +124,14 @@ public string this[Uri key]
124124

125125
public bool ContainsKey(Uri key)
126126
{
127-
return Cache.ContainsKey(key.ToString());
127+
return Cache.ContainsKey(key);
128128
}
129129

130130
public bool TryGetValue(Uri key, out string value)
131131
{
132132
try
133133
{
134-
return Cache.TryGetValue(key.ToString(), out value);
134+
return Cache.TryGetValue(key, out value);
135135
}
136136
catch (Exception e)
137137
{
@@ -180,7 +180,7 @@ public void Remove(Uri key)
180180
mutexHeld = true;
181181

182182
var cache = Cache;
183-
cache.Remove(key.ToString());
183+
cache.Remove(key);
184184
WriteFileBytes(Serialize(cache));
185185
}
186186
finally
@@ -193,19 +193,21 @@ public void Remove(Uri key)
193193
}
194194
}
195195

196-
private Dictionary<string, string> Deserialize(byte[] data)
196+
private Dictionary<Uri, string> Deserialize(byte[] data)
197197
{
198198
if (data == null)
199199
{
200-
return new Dictionary<string, string>();
200+
return new Dictionary<Uri, string>();
201201
}
202202

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

206-
private byte[] Serialize(Dictionary<string, string> data)
207+
private byte[] Serialize(Dictionary<Uri, string> data)
207208
{
208-
return JsonSerializer.SerializeToUtf8Bytes(data);
209+
var serialized = JsonConvert.SerializeObject(data);
210+
return System.Text.Encoding.UTF8.GetBytes(serialized);
209211
}
210212

211213
private byte[] ReadFileBytes()

0 commit comments

Comments
 (0)