Skip to content
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

[Release 3.0] Fix async thread blocking issue on SqlConnection open for active directory authentication modes #1270

Merged
Merged
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 @@ -2352,7 +2352,9 @@ internal SqlFedAuthToken GetFedAuthToken(SqlFedAuthInfo fedAuthInfo)
}
else
{
_fedAuthToken = authProvider.AcquireTokenAsync(authParamsBuilder).Result.ToSqlFedAuthToken();
// We use Task.Run here in all places to execute task synchronously in the same context.
// Fixes block-over-async deadlock possibilities https://github.com/dotnet/SqlClient/issues/1209
_fedAuthToken = Task.Run(async () => await authProvider.AcquireTokenAsync(authParamsBuilder)).GetAwaiter().GetResult().ToSqlFedAuthToken();
_activeDirectoryAuthTimeoutRetryHelper.CachedToken = _fedAuthToken;
}
break;
Expand All @@ -2368,7 +2370,7 @@ internal SqlFedAuthToken GetFedAuthToken(SqlFedAuthInfo fedAuthInfo)
else
{
authParamsBuilder.WithUserId(ConnectionOptions.UserID);
_fedAuthToken = authProvider.AcquireTokenAsync(authParamsBuilder).Result.ToSqlFedAuthToken();
_fedAuthToken = Task.Run(async () => await authProvider.AcquireTokenAsync(authParamsBuilder)).GetAwaiter().GetResult().ToSqlFedAuthToken();
_activeDirectoryAuthTimeoutRetryHelper.CachedToken = _fedAuthToken;
}
break;
Expand All @@ -2384,13 +2386,13 @@ internal SqlFedAuthToken GetFedAuthToken(SqlFedAuthInfo fedAuthInfo)
{
username = _credential.UserId;
authParamsBuilder.WithUserId(username).WithPassword(_credential.Password);
_fedAuthToken = authProvider.AcquireTokenAsync(authParamsBuilder).Result.ToSqlFedAuthToken();
_fedAuthToken = Task.Run(async () => await authProvider.AcquireTokenAsync(authParamsBuilder)).GetAwaiter().GetResult().ToSqlFedAuthToken();
}
else
{
username = ConnectionOptions.UserID;
authParamsBuilder.WithUserId(username).WithPassword(ConnectionOptions.Password);
_fedAuthToken = authProvider.AcquireTokenAsync(authParamsBuilder).Result.ToSqlFedAuthToken();
_fedAuthToken = Task.Run(async () => await authProvider.AcquireTokenAsync(authParamsBuilder)).GetAwaiter().GetResult().ToSqlFedAuthToken();
}
_activeDirectoryAuthTimeoutRetryHelper.CachedToken = _fedAuthToken;
}
Expand Down Expand Up @@ -2444,8 +2446,9 @@ internal SqlFedAuthToken GetFedAuthToken(SqlFedAuthInfo fedAuthInfo)
|| _timeout.MillisecondsRemaining <= sleepInterval)
{
SqlClientEventSource.Log.TryTraceEvent("<sc.SqlInternalConnectionTds.GetFedAuthToken.MSALException error:> {0}", msalException.ErrorCode);

// Error[0]
SqlErrorCollection sqlErs = new SqlErrorCollection();
SqlErrorCollection sqlErs = new();
sqlErs.Add(new SqlError(0, (byte)0x00, (byte)TdsEnums.MIN_ERROR_CLASS, ConnectionOptions.DataSource, StringsHelper.GetString(Strings.SQL_MSALFailure, username, ConnectionOptions.Authentication.ToString("G")), ActiveDirectoryAuthentication.MSALGetAccessTokenFunctionName, 0));

// Error[1]
Expand Down Expand Up @@ -2632,7 +2635,7 @@ internal void OnFeatureExtAck(int featureId, byte[] data)
Debug.Assert(_tceVersionSupported <= TdsEnums.MAX_SUPPORTED_TCE_VERSION, "Client support TCE version 2");
_parser.IsColumnEncryptionSupported = true;
_parser.TceVersionSupported = _tceVersionSupported;
_parser.AreEnclaveRetriesSupported = _tceVersionSupported == 3;
_parser.AreEnclaveRetriesSupported = _tceVersionSupported == 3;

if (data.Length > 1)
{
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -1348,7 +1348,7 @@
<value>Failed to authenticate the user {0} in Active Directory (Authentication={1}).</value>
</data>
<data name="SQL_MSALInnerException" xml:space="preserve">
<value>Error code 0x{0}; state {1}</value>
<value>Error code 0x{0}</value>
</data>
<data name="SQL_ParsingErrorWithState" xml:space="preserve">
<value>Internal connection fatal error. Error state: {0}.</value>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -705,7 +705,7 @@ internal static string ColumnEncryptionSettingToString(SqlConnectionColumnEncryp

internal static bool IsValidAuthenticationTypeValue(SqlAuthenticationMethod value)
{
Debug.Assert(Enum.GetNames(typeof(SqlAuthenticationMethod)).Length == 9, "SqlAuthenticationMethod enum has changed, update needed");
Debug.Assert(Enum.GetNames(typeof(SqlAuthenticationMethod)).Length == 10, "SqlAuthenticationMethod enum has changed, update needed");
return value == SqlAuthenticationMethod.SqlPassword
|| value == SqlAuthenticationMethod.ActiveDirectoryPassword
|| value == SqlAuthenticationMethod.ActiveDirectoryIntegrated
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2790,7 +2790,9 @@ internal SqlFedAuthToken GetFedAuthToken(SqlFedAuthInfo fedAuthInfo)
}
else
{
fedAuthToken = authProvider.AcquireTokenAsync(authParamsBuilder).Result.ToSqlFedAuthToken();
// We use Task.Run here in all places to execute task synchronously in the same context.
// Fixes block-over-async deadlock possibilities https://github.com/dotnet/SqlClient/issues/1209
fedAuthToken = Task.Run(async () => await authProvider.AcquireTokenAsync(authParamsBuilder)).GetAwaiter().GetResult().ToSqlFedAuthToken();
_activeDirectoryAuthTimeoutRetryHelper.CachedToken = fedAuthToken;
}
break;
Expand All @@ -2806,7 +2808,7 @@ internal SqlFedAuthToken GetFedAuthToken(SqlFedAuthInfo fedAuthInfo)
else
{
authParamsBuilder.WithUserId(ConnectionOptions.UserID);
fedAuthToken = authProvider.AcquireTokenAsync(authParamsBuilder).Result.ToSqlFedAuthToken();
fedAuthToken = Task.Run(async () => await authProvider.AcquireTokenAsync(authParamsBuilder)).GetAwaiter().GetResult().ToSqlFedAuthToken();
_activeDirectoryAuthTimeoutRetryHelper.CachedToken = fedAuthToken;
}
break;
Expand All @@ -2822,13 +2824,13 @@ internal SqlFedAuthToken GetFedAuthToken(SqlFedAuthInfo fedAuthInfo)
{
username = _credential.UserId;
authParamsBuilder.WithUserId(username).WithPassword(_credential.Password);
fedAuthToken = authProvider.AcquireTokenAsync(authParamsBuilder).Result.ToSqlFedAuthToken();
fedAuthToken = Task.Run(async () => await authProvider.AcquireTokenAsync(authParamsBuilder)).GetAwaiter().GetResult().ToSqlFedAuthToken();
}
else
{
username = ConnectionOptions.UserID;
authParamsBuilder.WithUserId(username).WithPassword(ConnectionOptions.Password);
fedAuthToken = authProvider.AcquireTokenAsync(authParamsBuilder).Result.ToSqlFedAuthToken();
fedAuthToken = Task.Run(async () => await authProvider.AcquireTokenAsync(authParamsBuilder)).GetAwaiter().GetResult().ToSqlFedAuthToken();
}
_activeDirectoryAuthTimeoutRetryHelper.CachedToken = fedAuthToken;
}
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -2563,7 +2563,7 @@
<value>Fehler beim Authentifizieren des Benutzers "{0}" in Active Directory (Authentication={1}).</value>
</data>
<data name="SQL_MSALInnerException" xml:space="preserve">
<value>Fehlercode 0x{0}; Status {1}</value>
<value>Fehlercode 0x{0}</value>
</data>
<data name="SQL_ChangePasswordRequiresYukon" xml:space="preserve">
<value>ChangePassword erfordert SQL Server 9.0 oder höher.</value>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2563,7 +2563,7 @@
<value>Error al autenticar el usuario {0} en Active Directory (Authentication={1}).</value>
</data>
<data name="SQL_MSALInnerException" xml:space="preserve">
<value>Código de error 0x{0}; estado{1}</value>
<value>Código de error 0x{0}</value>
</data>
<data name="SQL_ChangePasswordRequiresYukon" xml:space="preserve">
<value>ChangePassword requiere SQL Server 9.0 o posterior.</value>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2563,7 +2563,7 @@
<value>Échec de l'authentification de l'utilisateur {0} dans Active Directory (Authentication={1}).</value>
</data>
<data name="SQL_MSALInnerException" xml:space="preserve">
<value>Code d'erreur 0x{0} ; état {1}</value>
<value>Code d'erreur 0x{0}</value>
</data>
<data name="SQL_ChangePasswordRequiresYukon" xml:space="preserve">
<value>ChangePassword requiert SQL Server 9.0 ou version ultérieure.</value>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2563,7 +2563,7 @@
<value>Non è possibile autenticare l'utente {0} in Active Directory (Authentication={1}).</value>
</data>
<data name="SQL_MSALInnerException" xml:space="preserve">
<value>Codice errore: 0x{0}. Stato: {1}</value>
<value>Codice errore: 0x{0}</value>
</data>
<data name="SQL_ChangePasswordRequiresYukon" xml:space="preserve">
<value>ChangePassword richiede SQL Server 9.0 o versione successiva.</value>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2563,7 +2563,7 @@
<value>ユーザー {0} を Active Directory (Authentication={1}) で認証できませんでした。</value>
</data>
<data name="SQL_MSALInnerException" xml:space="preserve">
<value>エラー コード 0x{0}、状態 {1}</value>
<value>エラー コード 0x{0}</value>
</data>
<data name="SQL_ChangePasswordRequiresYukon" xml:space="preserve">
<value>ChangePassword を使用するには SQL Server 9.0 以降が必要です。</value>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2563,7 +2563,7 @@
<value>Active Directory의 {0} 사용자를 인증하지 못했습니다(Authentication={1}).</value>
</data>
<data name="SQL_MSALInnerException" xml:space="preserve">
<value>오류 코드 0x{0}, 상태 {1}</value>
<value>오류 코드 0x{0}</value>
</data>
<data name="SQL_ChangePasswordRequiresYukon" xml:space="preserve">
<value>ChangePassword를 사용하려면 SQL Server 9.0 이상이 필요합니다.</value>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2563,7 +2563,7 @@
<value>Falha ao autenticar o usuário {0} no Active Directory (Authentication={1}).</value>
</data>
<data name="SQL_MSALInnerException" xml:space="preserve">
<value>Código do erro 0x{0}; estado {1}</value>
<value>Código do erro 0x{0}</value>
</data>
<data name="SQL_ChangePasswordRequiresYukon" xml:space="preserve">
<value>ChangePassword requer SQL Server 9.0 ou posterior.</value>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2563,7 +2563,7 @@
<value>Failed to authenticate the user {0} in Active Directory (Authentication={1}).</value>
</data>
<data name="SQL_MSALInnerException" xml:space="preserve">
<value>Error code 0x{0}; state {1}</value>
<value>Error code 0x{0}</value>
</data>
<data name="SQL_ChangePasswordRequiresYukon" xml:space="preserve">
<value>ChangePassword requires SQL Server 9.0 or later.</value>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2563,7 +2563,7 @@
<value>Не удалось проверить подлинность пользователя {0} в Active Directory (Authentication={1}).</value>
</data>
<data name="SQL_MSALInnerException" xml:space="preserve">
<value>Код ошибки 0x{0}; состояние {1}</value>
<value>Код ошибки 0x{0}</value>
</data>
<data name="SQL_ChangePasswordRequiresYukon" xml:space="preserve">
<value>Для ChangePassword требуется SQL Server 9.0 или более поздней версии.</value>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2563,7 +2563,7 @@
<value>未能对 Active Directory 中的用户 {0} 进行身份验证(Authentication={1})。</value>
</data>
<data name="SQL_MSALInnerException" xml:space="preserve">
<value>错误代码 0x{0};状态 {1}</value>
<value>错误代码 0x{0}</value>
</data>
<data name="SQL_ChangePasswordRequiresYukon" xml:space="preserve">
<value>ChangePassword 要求 SQL Server 9.0 或更高版本。</value>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2563,7 +2563,7 @@
<value>無法在 Active Directory (Authentication={1}) 中驗證使用者 {0}。</value>
</data>
<data name="SQL_MSALInnerException" xml:space="preserve">
<value>錯誤碼 0x {0}; 狀態 {1}</value>
<value>錯誤碼 0x {0}</value>
</data>
<data name="SQL_ChangePasswordRequiresYukon" xml:space="preserve">
<value>ChangePassword 需要 SQL Server 9.0 或更新的版本。</value>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -728,6 +728,29 @@ public static string GetValueString(object paramValue)
return paramValue.ToString();
}

public static string FetchKeyInConnStr(string connStr, string[] keys)
{
// tokenize connection string and find matching key
if (connStr != null && keys != null)
{
string[] connProps = connStr.Split(';');
foreach (string cp in connProps)
{
if (!string.IsNullOrEmpty(cp.Trim()))
{
foreach (var key in keys)
{
if (cp.Trim().ToLower().StartsWith(key.Trim().ToLower()))
{
return cp.Substring(cp.IndexOf('=') + 1);
}
}
}
}
}
return null;
}

public static string RemoveKeysInConnStr(string connStr, string[] keysToRemove)
{
// tokenize connection string and remove input keys.
Expand Down
Loading