Skip to content

Commit

Permalink
Fix some static analyzer issues in tests around certs and TLS
Browse files Browse the repository at this point in the history
  • Loading branch information
bgavrilMS committed Jul 25, 2023
1 parent 2439c36 commit 9b9fb8d
Show file tree
Hide file tree
Showing 15 changed files with 152 additions and 129 deletions.
19 changes: 0 additions & 19 deletions tests/Microsoft.Identity.Test.Common/TestConstants.cs
Original file line number Diff line number Diff line change
Expand Up @@ -198,25 +198,6 @@ public static HashSet<string> s_scope
public const string iOSBrokerErrorMetadataValue = @"{""home_account_id"":""test_home"", ""username"" : """ + Username + @""" }";
public const string DefaultGraphScope = "https://graph.microsoft.com/.default";

//This value is only for testing purposes. It is for a certificate that is not used for anything other than running tests
public const string _defaultx5cValue = @"MIIDHzCCAgegAwIBAgIQM6NFYNBJ9rdOiK+C91ZzFDANBgkqhkiG9w0BAQsFADAgMR4wHAYDVQQDExVBQ1MyQ2xpZW50Q2VydGlmaWNhdGUwHhcNMTIwNTIyMj
IxMTIyWhcNMzAwNTIyMDcwMDAwWjAgMR4wHAYDVQQDExVBQ1MyQ2xpZW50Q2VydGlmaWNhdGUwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCh7HjK
YyVMDZDT64OgtcGKWxHmK2wqzi2LJb65KxGdNfObWGxh5HQtjzrgHDkACPsgyYseqxhGxHh8I/TR6wBKx/AAKuPHE8jB4hJ1W6FczPfb7FaMV9xP0qNQrbNGZU
YbCdy7U5zIw4XrGq22l6yTqpCAh59DLufd4d7x8fCgUDV3l1ZwrncF0QrBRzns/O9Ex9pXsi2DzMa1S1PKR81D9q5QSW7LZkCgSSqI6W0b5iodx/a3RBvW3l7d
noW2fPqkZ4iMcntGNqgsSGtbXPvUR3fFdjmg+xq9FfqWyNxShlZg4U+wE1v4+kzTJxd9sgD1V0PKgW57zyzdOmTyFPJFAgMBAAGjVTBTMFEGA1UdAQRKMEiAEM
9qihCt+12P5FrjVMAEYjShIjAgMR4wHAYDVQQDExVBQ1MyQ2xpZW50Q2VydGlmaWNhdGWCEDOjRWDQSfa3ToivgvdWcxQwDQYJKoZIhvcNAQELBQADggEBAIm6
gBOkSdYjXgOvcJGgE4FJkKAMQzAhkdYq5+stfUotG6vZNL3nVOOA6aELMq/ENhrJLC3rTwLOIgj4Cy+B7BxUS9GxTPphneuZCBzjvqhzP5DmLBs8l8qu10XAsh
y1NFZmB24rMoq8C+HPOpuVLzkwBr+qcCq7ry2326auogvVMGaxhHlwSLR4Q1OhRjKs8JctCk2+5Qs1NHfawa7jWHxdAK6cLm7Rv/c0ig2Jow7wRaI5ciAcEjX7
m1t9gRT1mNeeluL4cZa6WyVXqXc6U2wfR5DY6GOMUubN5Nr1n8Czew8TPfab4OG37BuEMNmBpqoRrRgFnDzVtItOnhuFTa0=";

public static string Defaultx5cValue
{
get
{
return Regex.Replace(_defaultx5cValue, @"\r\n?|\n", string.Empty);
}
}

public const string Bearer = "Bearer";
public const string Pop = "PoP";

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,6 @@ public class B2CUsernamePasswordIntegrationTests

private static readonly string[] s_b2cScopes = { "https://msidlabb2c.onmicrosoft.com/msidlabb2capi/read" };

[ClassInitialize]
public static void ClassInitialize(TestContext context)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
}

// If test fails with "user needs to consent to the application, do an interactive request" error,
// Do the following:
// 1) Add in code to pull the user's password, and put a breakpoint there.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,6 @@ public class LongRunningOnBehalfOfTests
private readonly KeyVaultSecretsProvider _keyVault = new KeyVaultSecretsProvider(KeyVaultInstance.MsalTeam);

#region Test Hooks
[ClassInitialize]
public static void ClassInitialize(TestContext context)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
}

[TestInitialize]
public void TestInitialize()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,6 @@ public class OnBehalfOfTests
private readonly KeyVaultSecretsProvider _keyVaultMsidLab = new KeyVaultSecretsProvider(KeyVaultInstance.MSIDLab);

#region Test Hooks
[ClassInitialize]
public static void ClassInitialize(TestContext context)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
}

[TestInitialize]
public void TestInitialize()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,12 +48,6 @@ public class UsernamePasswordIntegrationTests
private const string B2CROPCAuthority = "https://msidlabb2c.b2clogin.com/tfp/msidlabb2c.onmicrosoft.com/B2C_1_ROPC_Auth";
private static readonly string[] s_b2cScopes = { "https://msidlabb2c.onmicrosoft.com/msidlabb2capi/read" };

[ClassInitialize]
public static void ClassInitialize(TestContext context)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
}

[TestInitialize]
public void TestInitialize()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,6 @@ public class ConfidentialClientAuthorizationTests
[ClassInitialize]
public static void ClassInitialize(TestContext context)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
s_secretProvider = new KeyVaultSecretsProvider(KeyVaultInstance.MsalTeam);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,6 @@ public class DeviceCodeFlow
/// </summary>
public TestContext TestContext { get; set; }

[ClassInitialize]
public static void ClassInitialize(TestContext context)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
}

#endregion MSTest Hooks

[TestMethod]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,6 @@ public class FociTests
/// </summary>
public TestContext TestContext { get; set; }

[ClassInitialize]
public static void ClassInitialize(TestContext context)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
}

[TestInitialize]
public void TestInitialize()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,6 @@ public partial class InteractiveFlowTests
/// </summary>
public TestContext TestContext { get; set; }

[ClassInitialize]
public static void ClassInitialize(TestContext context)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
}

[TestInitialize]
public void TestInitialize()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,6 @@ public class InfrastructureTests
/// </summary>
public TestContext TestContext { get; set; }

[ClassInitialize]
public static void ClassInitialize(TestContext context)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
}

[TestInitialize]
public void TestInitialize()
{
Expand Down
58 changes: 58 additions & 0 deletions tests/Microsoft.Identity.Test.Unit/Helpers/CertHelper.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
using System.Collections.Generic;
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography;
using System.Text;

namespace Microsoft.Identity.Test.Common.Core.Helpers
{
public static class CertHelper
{
private static X509Certificate2 s_x509Certificate2 = null;

public static X509Certificate2 GetOrCreateTestCert()
{
// create the cert if it doesn't exist. use a lock to prevent multiple threads from creating the cert

if (s_x509Certificate2 == null)
{
lock (typeof(CertHelper))
{
if (s_x509Certificate2 == null)
{
s_x509Certificate2 = CreateTestCert();
}
}
}

return s_x509Certificate2;
}

private static X509Certificate2 CreateTestCert()
{
using (RSA rsa = RSA.Create(4096))
{
CertificateRequest parentReq = new CertificateRequest(
"CN=Test Cert",
rsa,
HashAlgorithmName.SHA256,
RSASignaturePadding.Pkcs1);

parentReq.CertificateExtensions.Add(
new X509BasicConstraintsExtension(true, false, 0, true));

parentReq.CertificateExtensions.Add(
new X509SubjectKeyIdentifierExtension(parentReq.PublicKey, false));

X509Certificate2 cert = parentReq.CreateSelfSigned(
DateTimeOffset.UtcNow,
DateTimeOffset.UtcNow.AddDays(1));

return cert;
}
}
}
}
49 changes: 47 additions & 2 deletions tests/Microsoft.Identity.Test.Unit/MetricsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,15 @@
using System;
using System.Linq;
using System.Net.Http;
using System.Security.Claims;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Identity.Client;
using Microsoft.Identity.Client.UI;
using Microsoft.Identity.Test.Common.Core.Mocks;
using Microsoft.Identity.Test.Common.Mocks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NSubstitute;

namespace Microsoft.Identity.Test.Unit
{
Expand Down Expand Up @@ -52,7 +54,7 @@ public async Task MetricsUpdatedSucessfully_AcquireTokenForClient_Async()
Assert.IsTrue(result.AuthenticationResultMetadata.DurationInCacheInMs > 0);
Assert.IsTrue(result.AuthenticationResultMetadata.DurationTotalInMs > 0);
Assert.AreEqual(
"https://login.microsoftonline.com/common/oauth2/v2.0/token",
"https://login.microsoftonline.com/common/oauth2/v2.0/token",
result.AuthenticationResultMetadata.TokenEndpoint);
Assert.AreEqual(1, Metrics.TotalAccessTokensFromIdP);
Assert.AreEqual(0, Metrics.TotalAccessTokensFromCache);
Expand Down Expand Up @@ -160,6 +162,49 @@ public async Task RefreshReasonExpired_ConfidentialClient_Async()
}
}

[TestMethod]
public void IdWebAccountExtension()
{
// copied from https://github.com/AzureAD/microsoft-identity-web/blob/master/src/Microsoft.Identity.Web/AccountExtensions.cs#L13
static ClaimsPrincipal ToClaimsPrincipal(IAccount account)
{
ClaimsIdentity identity = new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.Upn, account.Username),
});

if (!string.IsNullOrEmpty(account.HomeAccountId?.ObjectId))
{
identity.AddClaim(new Claim("oid", account.HomeAccountId.ObjectId));
}

if (!string.IsNullOrEmpty(account.HomeAccountId?.TenantId))
{
identity.AddClaim(new Claim("tid", account.HomeAccountId.TenantId));
}

return new ClaimsPrincipal(identity);
}

var username = "[email protected]";
var oid = "objectId";
var tid = "tenantId";

IAccount account = Substitute.For<IAccount>();
account.Username.Returns(username);
var accId = new AccountId("identifier", oid, tid);
account.HomeAccountId.Returns(accId);

var claimsIdentityResult = ToClaimsPrincipal(account).Identity as ClaimsIdentity;

Assert.IsNotNull(claimsIdentityResult);
Assert.AreEqual(3, claimsIdentityResult.Claims.Count());
Assert.AreEqual(username, claimsIdentityResult.FindFirst(ClaimTypes.Upn)?.Value);
Assert.AreEqual(oid, claimsIdentityResult.FindFirst("oid")?.Value);
Assert.AreEqual(tid, claimsIdentityResult.FindFirst("tid")?.Value);

}

[TestMethod]
public async Task RefreshReasonExpired_AcquireTokenSilent_Async()
{
Expand Down Expand Up @@ -255,7 +300,7 @@ private PublicClientApplication CreatePca(MockHttpManager httpManager, bool popu
.WithAuthority(new Uri(ClientApplicationBase.DefaultAuthority), false)
.WithHttpManager(httpManager)
.BuildConcrete();

if (populateUserCache)
{
TokenCacheHelper.PopulateCache(pca.UserTokenCacheInternal.Accessor);
Expand Down
Loading

0 comments on commit 9b9fb8d

Please sign in to comment.