Repository navigation
Improve WAM authentication diagnostics for windowless hosts #4858
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
mdaigle
merged 4 commits into
dotnet:main
from
priyankatiwari08:priyankatiwari08-dev/automation/wam-windowless-diagnostic
Oct 26, 2026
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
0b871ee
Improve WAM missing-window authentication diagnostics
priyankatiwari08 922c1ef
Isolate shared MSAL client cache in windowless interactive test
priyankatiwari08 e93d8fc
Address review feedback on WAM missing-window diagnostics
priyankatiwari08 dee0758
Merge branch 'main' into priyankatiwari08-dev/automation/wam-windowle…
mdaigle File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
138 changes: 138 additions & 0 deletions
138
src/Microsoft.Data.SqlClient.Extensions/Azure/test/WamBrokerErrorTests.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,138 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
| // See the LICENSE file in the project root for more information. | ||
|
|
||
| using System.Runtime.InteropServices; | ||
| using Microsoft.Identity.Client; | ||
|
|
||
| namespace Microsoft.Data.SqlClient.Extensions.Azure.Test; | ||
|
|
||
| /// <summary> | ||
| /// Verifies missing-window diagnostics without opening UI or contacting Entra ID. | ||
| /// </summary> | ||
| [Collection(SqlAuthenticationProviderCollection.Name)] | ||
| public class WamBrokerErrorTests | ||
| { | ||
| /// <summary> | ||
| /// Both first-party and custom applications using WAM receive actionable guidance on Windows. | ||
| /// Other platforms retain the original MSAL diagnostic. | ||
| /// </summary> | ||
| [Theory] | ||
| [InlineData(null)] | ||
| [InlineData("11111111-2222-3333-4444-555555555555")] | ||
| public async Task AcquireTokenAsync_MissingWamWindow_ExplainsSupportedAlternatives(string? applicationClientId) | ||
| { | ||
| var provider = new ActiveDirectoryAuthenticationProvider( | ||
| new ActiveDirectoryAuthenticationProviderOptions | ||
| { | ||
| ApplicationClientId = applicationClientId, | ||
| UseWamBroker = true, | ||
| }); | ||
| provider.SetParentActivityOrWindowFunc( | ||
| () => throw new InvalidOperationException("Window discovery must not precede MSAL token acquisition.")); | ||
| var cause = new MsalClientException("window_handle_required", "Original MSAL diagnostic."); | ||
|
|
||
| AuthenticationException exception = await AcquireWithMsalExceptionAsync( | ||
| provider, SqlAuthenticationMethod.ActiveDirectoryInteractive, cause); | ||
|
|
||
| Assert.Equal(SqlAuthenticationMethod.ActiveDirectoryInteractive, exception.Method); | ||
| Assert.Equal(cause.ErrorCode, exception.FailureCode); | ||
| Assert.Same(cause, exception.InnerException); | ||
| Assert.False(exception.ShouldRetry); | ||
| Assert.Equal(0, exception.RetryPeriod); | ||
| Assert.Contains(cause.Message, exception.Message); | ||
|
|
||
| if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) | ||
| { | ||
| Assert.Contains("parent window handle", exception.Message); | ||
| Assert.Contains("SetParentActivityOrWindowFunc", exception.Message); | ||
| Assert.Contains("Active Directory Default", exception.Message); | ||
| Assert.Contains("ApplicationClientId", exception.Message); | ||
| Assert.Contains("UseWamBroker", exception.Message); | ||
| Assert.Contains("first-party", exception.Message); | ||
| } | ||
| else | ||
| { | ||
| Assert.Equal($"Failed to acquire access token for {exception.Method}: {cause.Message}", exception.Message); | ||
| } | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Non-broker flows, other authentication methods, and unrelated MSAL failures are not | ||
| /// relabeled as missing WAM windows. | ||
| /// </summary> | ||
| [Theory] | ||
| [InlineData(SqlAuthenticationMethod.ActiveDirectoryInteractive, false, "window_handle_required")] | ||
| [InlineData(SqlAuthenticationMethod.ActiveDirectoryDeviceCodeFlow, true, "window_handle_required")] | ||
| [InlineData(SqlAuthenticationMethod.ActiveDirectoryIntegrated, true, "window_handle_required")] | ||
| [InlineData(SqlAuthenticationMethod.ActiveDirectoryInteractive, true, "authentication_canceled")] | ||
| public async Task AcquireTokenAsync_OtherMsalFailures_PreservesDiagnostic( | ||
| SqlAuthenticationMethod method, bool useWamBroker, string errorCode) | ||
| { | ||
| var provider = new ActiveDirectoryAuthenticationProvider( | ||
| new ActiveDirectoryAuthenticationProviderOptions | ||
| { | ||
| ApplicationClientId = "11111111-2222-3333-4444-555555555555", | ||
| UseWamBroker = useWamBroker, | ||
| }); | ||
| var cause = new MsalClientException(errorCode, "Original MSAL diagnostic."); | ||
|
|
||
| AuthenticationException exception = await AcquireWithMsalExceptionAsync(provider, method, cause); | ||
|
|
||
| Assert.Equal(method, exception.Method); | ||
| Assert.Equal(errorCode, exception.FailureCode); | ||
| Assert.Same(cause, exception.InnerException); | ||
| Assert.False(exception.ShouldRetry); | ||
| Assert.Equal($"Failed to acquire access token for {method}: {cause.Message}", exception.Message); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Installs an isolated MSAL client whose cache callback throws the supplied exception, | ||
| /// exercising the provider's real exception translation without a network request. | ||
| /// The cache entry is removed even if an assertion fails. | ||
| /// </summary> | ||
| /// <param name="provider">The provider configuration under test.</param> | ||
| /// <param name="method">The authentication method under test.</param> | ||
| /// <param name="cause">The MSAL failure to propagate through token acquisition.</param> | ||
| /// <returns>The translated authentication failure.</returns> | ||
| private static async Task<AuthenticationException> AcquireWithMsalExceptionAsync( | ||
| ActiveDirectoryAuthenticationProvider provider, SqlAuthenticationMethod method, MsalClientException cause) | ||
| { | ||
| string authority = $"https://login.microsoftonline.com/{Guid.NewGuid()}"; | ||
| string redirectUri = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) | ||
| ? provider.UseWamBroker | ||
| ? $"ms-appx-web://microsoft.aad.brokerplugin/{provider.ApplicationClientId}" | ||
| #if NETFRAMEWORK | ||
| : "https://login.microsoftonline.com/common/oauth2/nativeclient" | ||
| #else | ||
| : "http://localhost" | ||
| #endif | ||
| : "http://localhost"; | ||
|
|
||
| var key = new ActiveDirectoryAuthenticationProvider.PublicClientAppKey( | ||
| authority, redirectUri, provider.ApplicationClientId | ||
| #if NETFRAMEWORK | ||
| , null | ||
| #endif | ||
| ); | ||
| IPublicClientApplication app = PublicClientApplicationBuilder.Create(provider.ApplicationClientId) | ||
| .WithAuthority(authority) | ||
| .WithRedirectUri(redirectUri) | ||
| .Build(); | ||
| app.UserTokenCache.SetBeforeAccess(_ => throw cause); | ||
|
|
||
| var cache = ActiveDirectoryAuthenticationProvider.s_pcaMap; | ||
| Assert.True(cache.TryAdd(key, app)); | ||
| try | ||
| { | ||
| var parameters = new SqlAuthenticationParameters( | ||
| method, "test-server", "test-database", "https://database.windows.net/", | ||
| authority, userId: null, password: null, connectionId: Guid.NewGuid(), connectionTimeout: 30); | ||
| return await Assert.ThrowsAsync<AuthenticationException>(() => provider.AcquireTokenAsync(parameters)); | ||
| } | ||
| finally | ||
| { | ||
| cache.TryRemove(key, out _); | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
65 changes: 65 additions & 0 deletions
65
src/Microsoft.Data.SqlClient.Extensions/Azure/test/WindowlessInteractiveConnectionTests.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,65 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
| // See the LICENSE file in the project root for more information. | ||
|
|
||
| namespace Microsoft.Data.SqlClient.Extensions.Azure.Test; | ||
|
|
||
| /// <summary> | ||
| /// Exercises the windowless WAM diagnostic through real Azure SQL login handshakes. | ||
| /// </summary> | ||
| [Collection(SqlAuthenticationProviderCollection.Name)] | ||
| public class WindowlessInteractiveConnectionTests | ||
| { | ||
| /// <summary> | ||
| /// Both connection-opening APIs surface the actionable WAM error when no parent window | ||
| /// is supplied. A unique login hint prevents reuse of a silently cached account. | ||
| /// </summary> | ||
| [ConditionalTheory(typeof(Config), nameof(Config.OnWindows), nameof(Config.IsAzureSqlConnectionString))] | ||
| [Trait("category", "interactive")] | ||
| [InlineData(false)] | ||
| [InlineData(true)] | ||
| public async Task Open_MissingParentWindow_ExplainsSupportedAlternatives(bool async) | ||
| { | ||
| var builder = new SqlConnectionStringBuilder(Config.TCPConnectionString) | ||
| { | ||
| Authentication = SqlAuthenticationMethod.ActiveDirectoryInteractive, | ||
| IntegratedSecurity = false, | ||
| UserID = $"windowless-{Guid.NewGuid():N}@example.invalid", | ||
| Pooling = false, | ||
| }; | ||
| builder.Remove("Password"); | ||
|
|
||
| var provider = new ActiveDirectoryAuthenticationProvider(); | ||
| provider.SetParentActivityOrWindowFunc(() => IntPtr.Zero); | ||
|
Copilot marked this conversation as resolved.
Resolved
|
||
| SqlAuthenticationProvider? original = | ||
| SqlAuthenticationProvider.GetProvider(SqlAuthenticationMethod.ActiveDirectoryInteractive); | ||
| Assert.NotNull(original); | ||
|
|
||
| // Cached MSAL clients capture the window callback of the provider that created them, | ||
| // and their cache key does not include the provider. Clear the cache so this test uses | ||
| // its zero-window callback and does not leave that callback behind for later tests. | ||
| ActiveDirectoryAuthenticationProvider.ClearUserTokenCache(); | ||
|
|
||
| try | ||
| { | ||
| SqlAuthenticationProvider.SetProvider(SqlAuthenticationMethod.ActiveDirectoryInteractive, provider); | ||
| using var connection = new SqlConnection(builder.ConnectionString); | ||
|
|
||
| SqlException exception = async | ||
| ? await Assert.ThrowsAsync<SqlException>(() => connection.OpenAsync()) | ||
| : Assert.Throws<SqlException>(() => connection.Open()); | ||
|
|
||
| Assert.Contains("window_handle_required", exception.Message); | ||
| Assert.Contains("parent window handle", exception.Message); | ||
| Assert.Contains("SetParentActivityOrWindowFunc", exception.Message); | ||
| Assert.Contains("Active Directory Default", exception.Message); | ||
| Assert.Contains("ApplicationClientId", exception.Message); | ||
| Assert.Contains("UseWamBroker", exception.Message); | ||
| } | ||
| finally | ||
| { | ||
| SqlAuthenticationProvider.SetProvider(SqlAuthenticationMethod.ActiveDirectoryInteractive, original!); | ||
| ActiveDirectoryAuthenticationProvider.ClearUserTokenCache(); | ||
| } | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.