Skip to content

Commit 0d8f6b0

Browse files
authored
Merge pull request #27541 from msJinLei/auth_telemetry
Collected Authentication Method for Telemetry
2 parents a420b24 + 7123442 commit 0d8f6b0

File tree

48 files changed

+423
-116
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

48 files changed

+423
-116
lines changed

src/Accounts/Accounts.Test/AccessTokenCmdletTest.cs

+5-5
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414

1515
using Microsoft.Azure.Commands.Common.Authentication;
1616
using Microsoft.Azure.Commands.Common.Authentication.Abstractions;
17+
using Microsoft.Azure.Commands.Common.Authentication.Abstractions.Interfaces;
1718
using Microsoft.Azure.Commands.Common.Authentication.Models;
1819
using Microsoft.Azure.Commands.Profile;
1920
using Microsoft.Azure.Commands.Profile.Models;
@@ -28,6 +29,7 @@
2829
using Moq;
2930

3031
using System;
32+
using System.Collections.Generic;
3133
using System.Linq;
3234
using System.Security;
3335

@@ -49,7 +51,7 @@ public AccessTokenCmdletTests(ITestOutputHelper output)
4951
{
5052
TestExecutionHelpers.SetUpSessionAndProfile();
5153
XunitTracingInterceptor.AddToContext(new XunitTracingInterceptor(output));
52-
54+
AzureSession.Instance.RegisterComponent<AuthenticationTelemetry>(AuthenticationTelemetry.Name, () => new AuthenticationTelemetry());
5355
var defaultContext = new AzureContext(
5456
new AzureSubscription()
5557
{
@@ -97,8 +99,7 @@ public void TestGetAccessTokenAsPlainText()
9799
It.IsAny<SecureString>(),
98100
It.IsAny<string>(),
99101
It.IsAny<Action<string>>(),
100-
It.IsAny<IAzureTokenCache>(),
101-
It.IsAny<string>())).Returns(new MockAccessToken
102+
It.IsAny<IDictionary<string, object>>())).Returns(new MockAccessToken
102103
{
103104
UserId = expected.UserId,
104105
LoginType = LoginType.OrgId,
@@ -146,8 +147,7 @@ public void TestGetAccessTokenAsSecureString()
146147
It.IsAny<SecureString>(),
147148
It.IsAny<string>(),
148149
It.IsAny<Action<string>>(),
149-
It.IsAny<IAzureTokenCache>(),
150-
It.IsAny<string>())).Returns(new MockAccessToken
150+
It.IsAny<IDictionary<string, object>>())).Returns(new MockAccessToken
151151
{
152152
UserId = expected.UserId,
153153
LoginType = LoginType.OrgId,

src/Accounts/Accounts.Test/AutosaveTests.cs

+1-2
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,6 @@
2222
using Xunit.Abstractions;
2323
using Microsoft.Azure.Commands.Common.Authentication.Abstractions;
2424
using System;
25-
using System.Security;
2625
using Microsoft.Azure.Commands.Profile.Context;
2726
using Microsoft.Azure.Commands.ScenarioTest;
2827
using Microsoft.Azure.Commands.ResourceManager.Common;
@@ -57,7 +56,6 @@ private AzKeyStore SetMockedAzKeyStore()
5756

5857
void ResetState()
5958
{
60-
6159
TestExecutionHelpers.SetUpSessionAndProfile();
6260
ResourceManagerProfileProvider.InitializeResourceManagerProfile(true);
6361
// prevent token acquisition
@@ -69,6 +67,7 @@ void ResetState()
6967
PowerShellTokenCacheProvider tokenProvider = new InMemoryTokenCacheProvider();
7068
AzureSession.Instance.RegisterComponent(PowerShellTokenCacheProvider.PowerShellTokenCacheProviderKey, () => tokenProvider, true);
7169
AzureSession.Instance.RegisterComponent(AzKeyStore.Name, () => keyStore, true);
70+
AzureSession.Instance.RegisterComponent<AuthenticationTelemetry>(AuthenticationTelemetry.Name, () => new AuthenticationTelemetry());
7271
}
7372

7473
[Fact]

src/Accounts/Accounts.Test/AzureRMProfileTests.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,6 @@
4141
using System.Management.Automation;
4242
using System.Net.Http;
4343
using System.Runtime.InteropServices;
44-
using System.Runtime.Serialization.Formatters.Binary;
4544
using System.Text.Json;
4645
using System.Threading;
4746
using System.Threading.Tasks;
@@ -176,6 +175,7 @@ public AzureRMProfileTests(ITestOutputHelper output)
176175
{
177176
TestExecutionHelpers.SetUpSessionAndProfile();
178177
XunitTracingInterceptor.AddToContext(new XunitTracingInterceptor(output));
178+
AzureSession.Instance.RegisterComponent<AuthenticationTelemetry>(AuthenticationTelemetry.Name, () => new AuthenticationTelemetry());
179179
}
180180

181181
[Fact]

src/Accounts/Accounts.Test/AzureSessionTestInitializer.cs

+1
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ public static void Initialize()
3333
AzureSession.Instance.RegisterComponent(AuthenticatorBuilder.AuthenticatorBuilderKey, () => builder);
3434
AzureSession.Instance.RegisterComponent(nameof(AzureCredentialFactory), () => new AzureCredentialFactory());
3535
AzureSession.Instance.RegisterComponent(nameof(MsalAccessTokenAcquirerFactory), () => new MsalAccessTokenAcquirerFactory());
36+
AzureSession.Instance.RegisterComponent<AuthenticationTelemetry>(AuthenticationTelemetry.Name, () => new AuthenticationTelemetry());
3637
}
3738

3839
}

src/Accounts/Accounts.Test/ContextCmdletTests.cs

+1
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@ public ContextCmdletTests(ITestOutputHelper output)
6666
string profilePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), Resources.AzureDirectoryName);
6767
azKeyStore = new AzKeyStore(profilePath, AzureSession.Instance.KeyStoreFile, true, storageMocker.Object);
6868
AzureSession.Instance.RegisterComponent(AzKeyStore.Name, () => azKeyStore, true);
69+
AzureSession.Instance.RegisterComponent<AuthenticationTelemetry>(AuthenticationTelemetry.Name, () => new AuthenticationTelemetry());
6970
}
7071

7172
[Fact]

src/Accounts/Accounts.Test/EnvironmentCmdletTests.cs

+1
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ public EnvironmentCmdletTests(ITestOutputHelper output)
5050
XunitTracingInterceptor.AddToContext(new XunitTracingInterceptor(output));
5151
dataStore = new MemoryDataStore();
5252
AzureSession.Instance.DataStore = dataStore;
53+
AzureSession.Instance.RegisterComponent<AuthenticationTelemetry>(AuthenticationTelemetry.Name, () => new AuthenticationTelemetry());
5354
}
5455

5556
private void Cleanup()

src/Accounts/Accounts.Test/ErrorResolutionTests.cs

+5
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,9 @@
1313
// ----------------------------------------------------------------------------------
1414

1515
using Hyak.Common;
16+
17+
using Microsoft.Azure.Commands.Common.Authentication;
18+
using Microsoft.Azure.Commands.Common.Authentication.Abstractions;
1619
using Microsoft.Azure.Commands.Profile.Errors;
1720
using Microsoft.Azure.Commands.ScenarioTest;
1821
using Microsoft.WindowsAzure.Commands.Common.Test.Mocks;
@@ -43,6 +46,7 @@ public TestHyakException(string message, CloudHttpRequestErrorInfo request, Clou
4346
public void DoesNotThrowWithNullError()
4447
{
4548
TestExecutionHelpers.SetUpSessionAndProfile();
49+
AzureSession.Instance.RegisterComponent<AuthenticationTelemetry>(AuthenticationTelemetry.Name, () => new AuthenticationTelemetry());
4650
var cmdlet = new ResolveError();
4751
var output = cmdlet.ExecuteCmdletInPipeline<AzureErrorRecord>("Resolve-Error");
4852
Assert.True(output == null || output.Count == 0);
@@ -168,6 +172,7 @@ public void HandlesNullValuesInArmExceptions()
168172
public void LastParameterFindsLastError()
169173
{
170174
TestExecutionHelpers.SetUpSessionAndProfile();
175+
AzureSession.Instance.RegisterComponent<AuthenticationTelemetry>(AuthenticationTelemetry.Name, () => new AuthenticationTelemetry());
171176
var mock = new MockCommandRuntime();
172177
var cmdlet = new ResolveError { CommandRuntime = mock };
173178
var message = "RuntimeErrorMessage";

src/Accounts/Accounts.Test/ProfileCmdletTests.cs

+1
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@ public ProfileCmdletTests(ITestOutputHelper output)
5555
AzureSession.Instance.DataStore = dataStore;
5656
commandRuntimeMock = new MockCommandRuntime();
5757
AzureSession.Instance.AuthenticationFactory = new MockTokenAuthenticationFactory();
58+
AzureSession.Instance.RegisterComponent<AuthenticationTelemetry>(AuthenticationTelemetry.Name, () => new AuthenticationTelemetry());
5859
keyStore = SetMockedAzKeyStore();
5960
}
6061

src/Accounts/Accounts.Test/SilentReAuthByTenantCmdletTest.cs

+2-2
Original file line numberDiff line numberDiff line change
@@ -36,8 +36,6 @@
3636
using System.Threading.Tasks;
3737
using Xunit;
3838
using Xunit.Abstractions;
39-
using Microsoft.CodeAnalysis.CSharp.Syntax;
40-
using Microsoft.Azure.Commands.Common.Authentication.Factories;
4139

4240
namespace Microsoft.Azure.Commands.ResourceManager.Common.Test
4341
{
@@ -326,6 +324,8 @@ private void InitializeSession()
326324
DefaultContext = defaultContext
327325
};
328326
cmdlet.profileClient = new RMProfileClient(profile);
327+
328+
AzureSession.Instance.RegisterComponent<AuthenticationTelemetry>(AuthenticationTelemetry.Name, () => new AuthenticationTelemetry());
329329
}
330330

331331
~SilentReAuthByTenantCmdletTest()

src/Accounts/Accounts.Test/TenantCmdletMockTests.cs

+1-2
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@
2020
using Microsoft.Azure.Commands.ScenarioTest;
2121
using Microsoft.Azure.Commands.TestFx.Mocks;
2222
using Microsoft.Azure.ServiceManagement.Common.Models;
23-
using Microsoft.WindowsAzure.Commands.Common.Test.Mocks;
2423
using Microsoft.WindowsAzure.Commands.ScenarioTest;
2524
using Microsoft.WindowsAzure.Commands.Utilities.Common;
2625
using Moq;
@@ -55,7 +54,7 @@ public TenantCmdletMockTests(ITestOutputHelper output)
5554
{
5655
TestExecutionHelpers.SetUpSessionAndProfile();
5756
XunitTracingInterceptor.AddToContext(new XunitTracingInterceptor(output));
58-
57+
AzureSession.Instance.RegisterComponent<AuthenticationTelemetry>(AuthenticationTelemetry.Name, () => new AuthenticationTelemetry());
5958
AzureSession.Instance.AuthenticationFactory = new MockTokenAuthenticationFactory();
6059
((MockTokenAuthenticationFactory)AzureSession.Instance.AuthenticationFactory).TokenProvider = (account, environment, tenant) =>
6160
new MockAccessToken

src/Accounts/Accounts/Account/ConnectAzureRmAccount.cs

+3-2
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
using Microsoft.Azure.Commands.Common.Authentication;
1818
using Microsoft.Azure.Commands.Common.Authentication.Abstractions;
1919
using Microsoft.Azure.Commands.Common.Authentication.Abstractions.Core;
20+
using Microsoft.Azure.Commands.Common.Authentication.Abstractions.Interfaces;
2021
using Microsoft.Azure.Commands.Common.Authentication.Abstractions.Models;
2122
using Microsoft.Azure.Commands.Common.Authentication.Config.Models;
2223
using Microsoft.Azure.Commands.Common.Authentication.Factories;
@@ -517,8 +518,7 @@ public override void ExecuteCmdlet()
517518
return;
518519
}
519520

520-
IHttpOperationsFactory httpClientFactory = null;
521-
AzureSession.Instance.TryGetComponent(HttpClientOperationsFactory.Name, out httpClientFactory);
521+
AzureSession.Instance.TryGetComponent(HttpClientOperationsFactory.Name, out IHttpOperationsFactory httpClientFactory);
522522

523523
SetContextWithOverwritePrompt((localProfile, profileClient, name) =>
524524
{
@@ -860,6 +860,7 @@ public void OnImport()
860860
AzureSession.Instance.RegisterComponent(nameof(MsalAccessTokenAcquirerFactory), () => new MsalAccessTokenAcquirerFactory());
861861
AzureSession.Instance.RegisterComponent<ISshCredentialFactory>(nameof(ISshCredentialFactory), () => new SshCredentialFactory());
862862
AzureSession.Instance.RegisterComponent<IOutputSanitizer>(nameof(IOutputSanitizer), () => new OutputSanitizer());
863+
AzureSession.Instance.RegisterComponent<AuthenticationTelemetry>(AuthenticationTelemetry.Name, () => new AuthenticationTelemetry());
863864
#if DEBUG || TESTCOVERAGE
864865
AzureSession.Instance.RegisterComponent<ITestCoverage>(nameof(ITestCoverage), () => new TestCoverage());
865866
#endif

src/Accounts/Accounts/ChangeLog.md

+2
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@
1919
-->
2020

2121
## Upcoming Release
22+
* Fix token in auxiliary authentication header.
23+
* Collected authentication method for telemetry in end process of cmdlet.
2224

2325
## Version 4.1.0
2426
* Added AppConfiguration ResourceId and Suffix endpoints for Mooncake and USGov clouds to fix issue [#24219]

src/Accounts/Accounts/Common/AzureContextModificationCmdlet.cs

+2-1
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,8 @@ protected virtual void ModifyContext(Action<AzureRmProfile, RMProfileClient> con
4747
{
4848
var client = new RMProfileClient(profile)
4949
{
50-
WarningLog = (s) => WriteWarning(s)
50+
WarningLog = (s) => WriteWarning(s),
51+
CmdletContext = _cmdletContext
5152
};
5253
contextAction(profile.ToProfile(), client);
5354
}

src/Accounts/Accounts/CommonModule/ContextAdapter.cs

+24-9
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,9 @@
2828
using System.Management.Automation;
2929
using Microsoft.Azure.Commands.Profile.Properties;
3030
using Azure.Identity;
31+
using Microsoft.Azure.Commands.Common.Authentication.Abstractions.Interfaces;
32+
using Microsoft.Azure.Commands.Common.Authentication.Abstractions.Extensions;
33+
using Microsoft.Azure.Commands.Common.Authentication.Factories;
3134

3235
namespace Microsoft.Azure.Commands.Common
3336
{
@@ -75,7 +78,7 @@ public void OnNewRequest(InvocationInfo invocationInfo, string correlationId, st
7578
{
7679
prependStep(UniqueId.Instance.SendAsync);
7780
appendStep(new UserAgent(invocationInfo).SendAsync);
78-
appendStep(this.SendHandler(GetDefaultContext(_provider, invocationInfo), AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId));
81+
appendStep(this.SendHandler(GetDefaultContext(_provider, invocationInfo), AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId, new AzureCmdletContext(correlationId)));
7982
}
8083

8184
internal void AddRequestUserAgentHandler(
@@ -118,7 +121,12 @@ internal void AddAuthorizeRequestHandler(
118121
{
119122
endpointResourceIdKey = endpointResourceIdKey ?? AzureEnvironment.Endpoint.ActiveDirectoryServiceEndpointResourceId;
120123
var context = GetDefaultContext(_provider, invocationInfo);
121-
return await AuthenticationHelper(context, endpointResourceIdKey, endpointSuffixKey, request, cancelToken, cancelAction, signal, next);
124+
ICmdletContext cmdletContext = AzureCmdletContext.CmdletNone;
125+
if (extensibleParameters.ContainsKey(AuthenticationFactory.CmdletContextParameterName))
126+
{
127+
cmdletContext = extensibleParameters[AuthenticationFactory.CmdletContextParameterName] as ICmdletContext;
128+
}
129+
return await AuthenticationHelper(context, endpointResourceIdKey, endpointSuffixKey, request, cancelToken, cancelAction, signal, next, cmdletContext);
122130
});
123131
}
124132

@@ -193,9 +201,10 @@ public object GetParameterValue(string resourceId, string moduleName, Invocation
193201
return string.Empty;
194202
}
195203

196-
internal async Task<HttpResponseMessage> AuthenticationHelper(IAzureContext context, string endpointResourceIdKey, string endpointSuffixKey, HttpRequestMessage request, CancellationToken cancelToken, Action cancelAction, SignalDelegate signal, NextDelegate next, TokenAudienceConverterDelegate tokenAudienceConverter = null)
204+
internal async Task<HttpResponseMessage> AuthenticationHelper(IAzureContext context, string endpointResourceIdKey, string endpointSuffixKey, HttpRequestMessage request, CancellationToken cancelToken, Action cancelAction, SignalDelegate signal, NextDelegate next, ICmdletContext cmdletContext, TokenAudienceConverterDelegate tokenAudienceConverter = null)
197205
{
198-
IAccessToken accessToken = await AuthorizeRequest(context, request, cancelToken, endpointResourceIdKey, endpointSuffixKey, tokenAudienceConverter);
206+
var extensiableParameters = cmdletContext?.ToExtensibleParameters();
207+
IAccessToken accessToken = await AuthorizeRequest(context, request, cancelToken, endpointResourceIdKey, endpointSuffixKey, tokenAudienceConverter, extensiableParameters);
199208
using (var newRequest = await request.CloneWithContent(request.RequestUri, request.Method))
200209
{
201210
var response = await next(request, cancelToken, cancelAction, signal);
@@ -232,13 +241,14 @@ internal async Task<HttpResponseMessage> AuthenticationHelper(IAzureContext cont
232241
/// </summary>
233242
/// <param name="context"></param>
234243
/// <param name="resourceId"></param>
244+
/// <param name="cmdletContext"></param>
235245
/// <returns></returns>
236-
internal Func<HttpRequestMessage, CancellationToken, Action, SignalDelegate, NextDelegate, Task<HttpResponseMessage>> SendHandler(IAzureContext context, string resourceId)
246+
internal Func<HttpRequestMessage, CancellationToken, Action, SignalDelegate, NextDelegate, Task<HttpResponseMessage>> SendHandler(IAzureContext context, string resourceId, ICmdletContext cmdletContext)
237247
{
238248
return async (request, cancelToken, cancelAction, signal, next) =>
239249
{
240250
PatchRequestUri(context, request);
241-
return await AuthenticationHelper(context, resourceId, resourceId, request, cancelToken, cancelAction, signal, next);
251+
return await AuthenticationHelper(context, resourceId, resourceId, request, cancelToken, cancelAction, signal, next, cmdletContext);
242252
};
243253
}
244254

@@ -249,12 +259,12 @@ internal Func<HttpRequestMessage, CancellationToken, Action, SignalDelegate, Nex
249259
/// <param name="endpointResourceIdKey"></param>
250260
/// <param name="request"></param>
251261
/// <param name="endpointSuffixKey"></param>
252-
/// <param name="extensibleParamters"></param>
262+
/// <param name="extensibleParameters"></param>
253263
/// <param name="tokenAudienceConverter"></param>
254264
/// <param name="cancellationToken"></param>
255265
/// <returns></returns>
256266
internal async Task<IAccessToken> AuthorizeRequest(IAzureContext context, HttpRequestMessage request, CancellationToken cancellationToken, string endpointResourceIdKey,
257-
string endpointSuffixKey, TokenAudienceConverterDelegate tokenAudienceConverter = null, IDictionary<string, object> extensibleParamters = null)
267+
string endpointSuffixKey, TokenAudienceConverterDelegate tokenAudienceConverter = null, IDictionary<string, object> extensibleParameters = null)
258268
{
259269
if (context == null || context.Account == null || context.Environment == null)
260270
{
@@ -269,7 +279,12 @@ internal async Task<IAccessToken> AuthorizeRequest(IAzureContext context, HttpRe
269279
var tokenAudience = tokenAudienceConverter.Invoke(info.CurEnvEndpointResourceId, info.CurEnvEndpointSuffix, info.BaseEnvEndpointResourceId, info.BaseEnvEndpointSuffix, request.RequestUri);
270280
endpointResourceIdKey = tokenAudience ?? endpointResourceIdKey;
271281
}
272-
var authToken = _authenticator.Authenticate(context.Account, context.Environment, context.Tenant.Id, null, "Never", null, endpointResourceIdKey);
282+
var optionalParameters = new Dictionary<string, object>() { { AuthenticationFactory.ResourceIdParameterName, endpointResourceIdKey } };
283+
if (extensibleParameters != null && extensibleParameters.ContainsKey(AuthenticationFactory.CmdletContextParameterName))
284+
{
285+
optionalParameters.Add(AuthenticationFactory.CmdletContextParameterName, extensibleParameters[AuthenticationFactory.CmdletContextParameterName]);
286+
}
287+
var authToken = _authenticator.Authenticate(context.Account, context.Environment, context.Tenant.Id, null, "Never", null, optionalParameters);
273288
authToken.AuthorizeRequest((type, token) => request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(type, token));
274289
return authToken;
275290
}, cancellationToken);

src/Accounts/Accounts/CommonModule/EnvironmentExtensions.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -342,7 +342,7 @@ internal static void CheckAndEnqueue<T>(this ConcurrentQueue<T> queue, T item)
342342

343343
internal static bool TryDequeueIfNotNull<T>(this ConcurrentQueue<T> queue, out T result)
344344
{
345-
result = default(T);
345+
result = default;
346346
if (null == queue)
347347
{
348348
return false;

src/Accounts/Accounts/Context/GetAzureRMContext.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ public override void ExecuteCmdlet()
8484
var defaultProfile = DefaultProfile as AzureRmProfile;
8585
if (defaultProfile != null && string.Equals(AzureSession.Instance?.ARMContextSaveMode, "CurrentUser"))
8686
{
87-
defaultProfile.RefreshContextsFromCache();
87+
defaultProfile.RefreshContextsFromCache(_cmdletContext);
8888
}
8989
}
9090
catch (Exception e)

0 commit comments

Comments
 (0)