Skip to content
Draft
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
76 changes: 76 additions & 0 deletions src/Cli.Tests/SqlClientAuthenticationTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using System.Reflection;
using Azure.DataApiBuilder.Core.AuthenticationHelpers;
using Microsoft.Data.SqlClient;

namespace Cli.Tests;

[TestClass]
[DoNotParallelize]
public sealed class SqlClientAuthenticationTests
{
private const string CLIENT_ID = "11111111-1111-1111-1111-111111111111";
private readonly string? _originalClientId =
Environment.GetEnvironmentVariable(UserDelegatedAuthOptions.DAB_OBO_CLIENT_ID_ENV_VAR);
private readonly Dictionary<SqlAuthenticationMethod, SqlAuthenticationProvider?> _originalProviders =
Enum.GetValues<SqlAuthenticationMethod>().ToDictionary(method => method, SqlAuthenticationProvider.GetProvider);

[TestCleanup]
public void Cleanup()
{
Environment.SetEnvironmentVariable(UserDelegatedAuthOptions.DAB_OBO_CLIENT_ID_ENV_VAR, _originalClientId);
foreach ((SqlAuthenticationMethod method, SqlAuthenticationProvider? provider) in _originalProviders)
{
if (provider is not null)
{
Assert.IsTrue(SqlAuthenticationProvider.SetProvider(method, provider));
}
}
}

[TestMethod]
public void RegisterProviders_ConfiguredClientId_RegistersSharedProviderForEverySupportedMethod()
{
Environment.SetEnvironmentVariable(UserDelegatedAuthOptions.DAB_OBO_CLIENT_ID_ENV_VAR, CLIENT_ID);

SqlClientAuthentication.RegisterProviders();

SqlAuthenticationProvider provider = SqlAuthenticationProvider.GetProvider(SqlAuthenticationMethod.ActiveDirectoryInteractive);
Assert.IsInstanceOfType<ActiveDirectoryAuthenticationProvider>(provider);
// SqlClient does not expose the constructor's client ID through its public API.
FieldInfo? clientIdField = typeof(ActiveDirectoryAuthenticationProvider)
.GetField("_applicationClientId", BindingFlags.Instance | BindingFlags.NonPublic);
Assert.IsNotNull(clientIdField);
Assert.AreEqual(CLIENT_ID, clientIdField.GetValue(provider));

foreach (SqlAuthenticationMethod method in Enum.GetValues<SqlAuthenticationMethod>())
{
if (provider.IsSupported(method))
{
Assert.AreSame(provider, SqlAuthenticationProvider.GetProvider(method), method.ToString());
}
else
{
Assert.AreSame(_originalProviders[method], SqlAuthenticationProvider.GetProvider(method), method.ToString());
}
}
}

[TestMethod]
[DataRow(null)]
[DataRow("")]
[DataRow(" \t")]
public void RegisterProviders_NoClientId_PreservesExistingProviders(string? clientId)
{
Environment.SetEnvironmentVariable(UserDelegatedAuthOptions.DAB_OBO_CLIENT_ID_ENV_VAR, clientId);

SqlClientAuthentication.RegisterProviders();

foreach ((SqlAuthenticationMethod method, SqlAuthenticationProvider? provider) in _originalProviders)
{
Assert.AreSame(provider, SqlAuthenticationProvider.GetProvider(method), method.ToString());
}
}
}
2 changes: 2 additions & 0 deletions src/Cli/ConfigGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
using Azure.DataApiBuilder.Config.ObjectModel;
using Azure.DataApiBuilder.Config.ObjectModel.Embeddings;
using Azure.DataApiBuilder.Core;
using Azure.DataApiBuilder.Core.AuthenticationHelpers;
using Azure.DataApiBuilder.Core.Configurations;
using Azure.DataApiBuilder.Core.Resolvers;
using Azure.DataApiBuilder.Core.Telemetry.Product;
Expand Down Expand Up @@ -4000,6 +4001,7 @@ public static bool TrySimulateAutoentities(AutoConfigSimulateOptions options, Fi

try
{
SqlClientAuthentication.RegisterProviders();
using SqlConnection connection = new(connectionString);
connection.Open();

Expand Down
6 changes: 6 additions & 0 deletions src/Config/ObjectModel/DataSource.cs
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,12 @@ public record UserDelegatedAuthOptions(
/// <summary>
/// Environment variable name for the API App Registration client ID, required for either OBO credential method.
/// This is not the client ID of the Managed Identity used for federation.
/// When set, DAB also passes this ID to SqlClient's ActiveDirectoryAuthenticationProvider
/// and registers it process-wide for all supported authentication methods, including metadata
/// and CLI autoentities connections. Blank values leave SqlClient's existing providers unchanged.
/// Public-client authentication flows require the corresponding Entra app registration configuration.
/// This does not change DefaultAzureCredential or override the identities selected by
/// managed identity, service principal, or workload identity authentication.
/// Uses DAB-specific prefix to avoid conflict with AZURE_CLIENT_ID which is
/// interpreted by DefaultAzureCredential/ManagedIdentityCredential as a
/// User-Assigned Managed Identity ID.
Expand Down
35 changes: 35 additions & 0 deletions src/Core/AuthenticationHelpers/SqlClientAuthentication.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using Azure.DataApiBuilder.Config.ObjectModel;
using Microsoft.Data.SqlClient;

namespace Azure.DataApiBuilder.Core.AuthenticationHelpers;

/// <summary>
/// Configures SqlClient authentication with the application identity used for OBO.
/// </summary>
internal static class SqlClientAuthentication
{
/// <summary>
/// Registers a shared provider for every authentication method it supports.
/// Leaves SqlClient's existing providers unchanged when no application client ID is configured.
/// </summary>
internal static void RegisterProviders()
{
string? clientId = Environment.GetEnvironmentVariable(UserDelegatedAuthOptions.DAB_OBO_CLIENT_ID_ENV_VAR);
if (string.IsNullOrWhiteSpace(clientId))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

this is an important fallback, if OBO is not enabled/setup, this clientId will be null. Just want to make sure, in that situation, the existing default app client id will still be valid for EntraAuth modes, right?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

when SqlClient drops support for non-WAM broker enabled workflows by removing localhost reply URLs, would this fallback scenario continue to work when OBO is not enabled?

{
return;
}

ActiveDirectoryAuthenticationProvider provider = new(clientId);
foreach (SqlAuthenticationMethod method in Enum.GetValues<SqlAuthenticationMethod>())
{
if (provider.IsSupported(method) && !SqlAuthenticationProvider.SetProvider(method, provider))
{
throw new InvalidOperationException($"Failed to register the SqlClient authentication provider for {method}.");
}
}
}
}
2 changes: 2 additions & 0 deletions src/Core/Resolvers/MsSqlQueryExecutor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
using Azure.Core;
using Azure.DataApiBuilder.Config;
using Azure.DataApiBuilder.Config.ObjectModel;
using Azure.DataApiBuilder.Core.AuthenticationHelpers;
using Azure.DataApiBuilder.Core.Authorization;
using Azure.DataApiBuilder.Core.Configurations;
using Azure.DataApiBuilder.Core.Models;
Expand Down Expand Up @@ -101,6 +102,7 @@ public MsSqlQueryExecutor(
httpContextAccessor,
handler)
{
SqlClientAuthentication.RegisterProviders();
_dataSourceAccessTokenUsage = new Dictionary<string, bool>();
_dataSourceToSessionContextUsage = new Dictionary<string, bool>();
_dataSourceUserDelegatedAuth = new Dictionary<string, UserDelegatedAuthOptions>();
Expand Down
Loading