Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
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
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,9 @@ public async Task<AuthenticationResult> RunAsync(CancellationToken cancellationT
}
AuthenticationRequestParameters.RequestContext.Logger.ErrorPii(ex);

LogFailureTelemetryToOtel(ex.ErrorCode, apiEvent, apiEvent.CacheInfo);
LogFailureTelemetryToOtel(
ex.ErrorCode, apiEvent, apiEvent.CacheInfo,
(ex as MsalServiceException)?.ErrorCodes?.FirstOrDefault());
throw;
}
catch (Exception ex)
Expand All @@ -133,7 +135,7 @@ private void LogSuccessTelemetryToOtel(AuthenticationResult authenticationResult
AuthenticationRequestParameters.RequestContext.Logger);
}

private void LogFailureTelemetryToOtel(string errorCodeToLog, ApiEvent apiEvent, CacheRefreshReason cacheRefreshReason)
private void LogFailureTelemetryToOtel(string errorCodeToLog, ApiEvent apiEvent, CacheRefreshReason cacheRefreshReason, string rawStsErrorCode = null)
{
// Log metrics
ServiceBundle.PlatformProxy.OtelInstrumentation.LogFailureMetrics(
Expand All @@ -143,7 +145,8 @@ private void LogFailureTelemetryToOtel(string errorCodeToLog, ApiEvent apiEvent,
apiEvent.CallerSdkApiId,
apiEvent.CallerSdkVersion,
cacheRefreshReason,
apiEvent.TokenType);
apiEvent.TokenType,
rawStsErrorCode);
}

private Tuple<string, string> ParseScopesForTelemetry()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Identity.Client.Cache.Items;
Expand Down Expand Up @@ -124,7 +125,8 @@ internal static void ProcessFetchInBackground(
callerSdkId,
callerSdkVersion,
CacheRefreshReason.ProactivelyRefreshed,
apiEvent.TokenType);
apiEvent.TokenType,
ex.ErrorCodes?.FirstOrDefault());
}
catch (OperationCanceledException ex)
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Diagnostics;

Copilot AI Apr 29, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

using System.Diagnostics; appears unused in this file. Consider removing it to avoid unnecessary imports (and potential analyzer noise) since the code only uses types from System.Diagnostics.Metrics.

Suggested change
using System.Diagnostics;

Copilot uses AI. Check for mistakes.
using System.Diagnostics.Metrics;
using Microsoft.Identity.Client.Cache;
using Microsoft.Identity.Client.Core;
Expand Down Expand Up @@ -204,19 +205,27 @@ public void LogFailureMetrics(string platform,
string callerSdkId,
string callerSdkVersion,
CacheRefreshReason cacheRefreshReason,
int tokenType)
int tokenType,
string rawStsErrorCode = null)
{
if (s_failureCounter.Value.Enabled)
if (!s_failureCounter.Value.Enabled)
return;

var tags = new TagList
{
s_failureCounter.Value.Add(1,
new(TelemetryConstants.MsalVersion, MsalIdHelper.GetMsalVersion()),
new(TelemetryConstants.Platform, platform),
new(TelemetryConstants.ErrorCode, errorCode),
new(TelemetryConstants.ApiId, apiId),
new(TelemetryConstants.CallerSdkId, callerSdkId ?? string.Empty + "," + callerSdkVersion ?? string.Empty),
new(TelemetryConstants.CacheRefreshReason, cacheRefreshReason),
new(TelemetryConstants.TokenType, tokenType));
}
{ TelemetryConstants.MsalVersion, MsalIdHelper.GetMsalVersion() },
{ TelemetryConstants.Platform, platform },
{ TelemetryConstants.ErrorCode, errorCode },
{ TelemetryConstants.ApiId, apiId },
{ TelemetryConstants.CallerSdkId, callerSdkId ?? string.Empty + "," + callerSdkVersion ?? string.Empty },
{ TelemetryConstants.CacheRefreshReason, cacheRefreshReason },
Comment thread
ssmelov marked this conversation as resolved.
{ TelemetryConstants.TokenType, tokenType }
};

if (!string.IsNullOrEmpty(rawStsErrorCode))
tags.Add(TelemetryConstants.RawStsErrorCode, rawStsErrorCode);
Comment thread
bgavrilMS marked this conversation as resolved.
Comment thread
ssmelov marked this conversation as resolved.

s_failureCounter.Value.Add(1, in tags);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,13 @@ internal void IncrementSuccessCounter(string platform,
ILoggerAdapter logger,
int TokenType);

internal void LogFailureMetrics(string platform,
string errorCode,
internal void LogFailureMetrics(string platform,
string errorCode,
ApiEvent.ApiIds apiId,
string callerSdkId,
string callerSdkVersion,
CacheRefreshReason cacheRefreshReason,
int tokenType);
int tokenType,
string rawStsErrorCode = null);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,14 @@ public void LogSuccessMetrics(
// No op
}

public void LogFailureMetrics(string platform,
string errorCode,
ApiEvent.ApiIds apiId,
public void LogFailureMetrics(string platform,
string errorCode,
ApiEvent.ApiIds apiId,
string callerSdkId,
string callerSdkVersion,
CacheRefreshReason cacheRefreshReason,
int tokenType)
int tokenType,
string rawStsErrorCode = null)
{
// No op
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ internal static class TelemetryConstants
public const string CacheInfoTelemetry = "CacheInfoTelemetry";
public const string CacheRefreshReason = "CacheRefreshReason";
public const string ErrorCode = "ErrorCode";
public const string StsErrorCode = "StsErrorCode";
public const string RawStsErrorCode = "RawStsErrorCode";
public const string ErrorMessage = "ErrorMessage";
public const string Duration = "Duration";
public const string DurationInUs = "DurationInUs";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -415,7 +415,74 @@ private void CreateApplication()
.BuildConcrete();
}

private void VerifyMetrics(int expectedMetricCount, List<Metric> exportedMetrics,
[TestMethod]
public async Task MsalFailure_ServiceException_RawStsErrorCodeTag_IncludedAsync()
{
using (_harness = CreateTestHarness())
{
CreateApplication();

_harness.HttpManager.AddInstanceDiscoveryMockHandler();
_harness.HttpManager.AddTokenResponse(TokenResponseType.InvalidClient);

MsalServiceException ex = await AssertException.TaskThrowsAsync<MsalServiceException>(
() => _cca.AcquireTokenForClient(TestConstants.s_scopeForAnotherResource)
.WithExtraQueryParameters(extraQueryParams)
.WithTenantId(TestConstants.Utid)
.ExecuteAsync(CancellationToken.None)).ConfigureAwait(false);

Assert.IsNotNull(ex.ErrorCodes, "ErrorCodes should be populated from IDP response.");

s_meterProvider.ForceFlush();

var failureMetric = _exportedMetrics.First(m => m.Name == "MsalFailure");
Comment thread
ssmelov marked this conversation as resolved.
foreach (var metricPoint in failureMetric.GetMetricPoints())
{
var tags = GetTagDictionary(metricPoint.Tags);
Assert.IsTrue(tags.ContainsKey(TelemetryConstants.RawStsErrorCode),
"RawStsErrorCode tag should be present when the IDP response contains error_codes.");
Assert.AreEqual(ex.ErrorCodes.FirstOrDefault(), tags[TelemetryConstants.RawStsErrorCode]);
}
Comment thread
ssmelov marked this conversation as resolved.
Comment thread
neha-bhargava marked this conversation as resolved.
}
}

[TestMethod]
public async Task MsalFailure_ClientException_RawStsErrorCodeTag_NotIncludedAsync()
{
using (_harness = CreateTestHarness())
{
CreateApplication();

// Null scope triggers MsalClientException before any HTTP call — no ErrorCodes
MsalClientException ex = await AssertException.TaskThrowsAsync<MsalClientException>(
() => _cca.AcquireTokenForClient(null)
.WithExtraQueryParameters(extraQueryParams)
.WithTenantId(TestConstants.Utid)
.ExecuteAsync(CancellationToken.None)).ConfigureAwait(false);

Assert.IsNotNull(ex);

s_meterProvider.ForceFlush();

var failureMetric = _exportedMetrics.First(m => m.Name == "MsalFailure");
Comment thread
neha-bhargava marked this conversation as resolved.
foreach (var metricPoint in failureMetric.GetMetricPoints())
{
var tags = GetTagDictionary(metricPoint.Tags);
Assert.IsFalse(tags.ContainsKey(TelemetryConstants.RawStsErrorCode),
"RawStsErrorCode tag should not be present for non-service exceptions.");
}
}
}

private static IDictionary<string, object> GetTagDictionary(ReadOnlyTagCollection tags)
{
var dict = new Dictionary<string, object>();
foreach (var tag in tags)
dict[tag.Key] = tag.Value;
return dict;
}
Comment thread
ssmelov marked this conversation as resolved.

private void VerifyMetrics(int expectedMetricCount, List<Metric> exportedMetrics,
long expectedSuccessfulRequests, long expectedFailedRequests)
{
Assert.HasCount(expectedMetricCount, exportedMetrics, "Count of metrics recorded is not as expected.");
Expand Down Expand Up @@ -467,7 +534,10 @@ private void VerifyMetrics(int expectedMetricCount, List<Metric> exportedMetrics
foreach (var metricPoint in exportedItem.GetMetricPoints())
{
totalFailedRequests += metricPoint.GetSumLong();
AssertTags(metricPoint.Tags, expectedTags, true);
var pointExpectedTags = new List<string>(expectedTags);
if (GetTagDictionary(metricPoint.Tags).ContainsKey(TelemetryConstants.RawStsErrorCode))
pointExpectedTags.Add(TelemetryConstants.RawStsErrorCode);
AssertTags(metricPoint.Tags, pointExpectedTags, true);
}

Assert.AreEqual(expectedFailedRequests, totalFailedRequests);
Expand Down
Loading