Skip to content

Commit be44563

Browse files
authored
Invoke-DbaQuery, re-wire connection with integrated as another user (#9592)
1 parent 6b53882 commit be44563

File tree

4 files changed

+98
-15
lines changed

4 files changed

+98
-15
lines changed

public/Connect-DbaInstance.ps1

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -709,13 +709,19 @@ function Connect-DbaInstance {
709709
$authType = 'local '
710710
}
711711
if ($SqlCredential) {
712-
# support both ad\username and username@ad
713712
$username = ($SqlCredential.UserName).TrimStart("\")
714-
if ($username -like "*\*") {
715-
$domain, $login = $username.Split("\")
716-
$username = "$login@$domain"
713+
# support both ad\username and username@ad
714+
# username@ad works only for domain joined and workgroup
715+
# nobody remembers why, but username@ad is preferred
716+
# so we switch ad\username to username@ad only doing a raw guess
717+
# when USERDOMAIN -ne COMPUTERNAME, we're probably joined to ad
718+
if ($env:USERDOMAIN -ne $env:COMPUTERNAME) {
719+
if ($username -like "*\*") {
720+
$domain, $login = $username.Split("\")
721+
$username = "$login@$domain"
722+
}
717723
}
718-
if ($username -like '*@*') {
724+
if ($username -like '*@*' -or $username -like '*\*') {
719725
$authType += 'ad'
720726
} else {
721727
$authType += 'sql'

public/Invoke-DbaQuery.ps1

Lines changed: 83 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,8 @@ function Invoke-DbaQuery {
6464
.PARAMETER NoExec
6565
Use this switch to prepend SET NOEXEC ON and append SET NOEXEC OFF to each statement, useful for checking query formal errors
6666
67+
.PARAMETER AppendConnectionString
68+
Appends to the current connection string. Note that you cannot pass authentication information using this method. Use -SqlInstance and optionally -SqlCredential to set authentication information.
6769
6870
.NOTES
6971
Tags: Database, Query, Utility
@@ -152,8 +154,22 @@ function Invoke-DbaQuery {
152154
PS C:\> Invoke-DbaQuery -SqlInstance $server -Query 'SELECT * FROM bar WHERE SSN_col = @SSN' -SqlParameter @inputparamSSN
153155
154156
Creates an input parameter using Always Encrypted
157+
158+
.EXAMPLE
159+
PS C:\> $server = Connect-DbaInstance -SqlInstance AG1 -Database dbatools -MultiSubnetFailover -ConnectTimeout 60
160+
PS C:\> Invoke-DbaQuery -SqlInstance $server -Query 'SELECT foo FROM bar'
161+
162+
Reuses Connect-DbaInstance, leveraging advanced paramenters, to adhere to official guidelines to target FCI or AG listeners.
163+
See https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/sql/sqlclient-support-for-high-availability-disaster-recovery#connecting-with-multisubnetfailover
164+
165+
.EXAMPLE
166+
PS C:\> Invoke-DbaQuery -SqlInstance AG1 -Query 'SELECT foo FROM bar' -AppendConnectionString 'MultiSubnetFailover=true;Connect Timeout=60'
167+
168+
Leverages your own parameters, giving you full power, mimicking Connect-DbaInstance's `-MultiSubnetFailover -ConnectTimeout 60`, to adhere to official guidelines to target FCI or AG listeners.
169+
See https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/sql/sqlclient-support-for-high-availability-disaster-recovery#connecting-with-multisubnetfailover
155170
#>
156171
[CmdletBinding(DefaultParameterSetName = "Query")]
172+
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingConvertToSecureStringWithPlainText", "")]
157173
param (
158174
[Parameter(ValueFromPipeline)]
159175
[Parameter(ParameterSetName = 'Query', Position = 0)]
@@ -181,6 +197,7 @@ function Invoke-DbaQuery {
181197
[Microsoft.SqlServer.Management.Smo.Database[]]$InputObject,
182198
[switch]$ReadOnly,
183199
[switch]$NoExec,
200+
[string]$AppendConnectionString,
184201
[switch]$EnableException
185202
)
186203

@@ -394,15 +411,74 @@ function Invoke-DbaQuery {
394411
(-not $ReadOnly) -and # no readonly intent is requested and
395412
(-not $Database -or $instance.InputObject.ConnectionContext.DatabaseName -eq $Database) # the database is not set or the currently connected
396413
if ($startedWithAnOpenConnection) {
397-
Write-Message -Level Debug -Message "Current connection will be reused"
398-
$server = $instance.InputObject
414+
Write-Message -Level Debug -Message "Current connection can be reused"
415+
# We got another nightmare to solve, but fortunately @andreasjordan is "the king"
416+
# So. Here we are with a passed down "Server" instance. Problem is, we got two VERY different
417+
# libraries built with VERY different agendas. And we want to get the best of both worlds.
418+
# This is SUCH a nightmare because Invoke-DbaQuery is THE ONLY function that CAN use a Connection
419+
# (Microsoft.Data.SqlClient.SqlConnection) which can be used to run PARAMETRIZED queries.
420+
# So, recap of the recap:
421+
# 1. Microsoft.Data.SqlClient.SqlConnection:
422+
# PRO: is the only connection that can use Microsoft.Data.SqlClient.SqlCommand
423+
# that can use [Microsoft.Data.SqlClient.SqlParameter]s
424+
# CON: when using integrated auth, as in Integrated Security=True, cannot specify a DIFFERENT user than the current logged in one
425+
# 2. Microsoft.SqlServer.Management.Smo.Server
426+
# PRO: can specify a DIFFERENT user than the current logged in one via ConnectAsUser, ConnectAsUserName, ConnectAsUserPassword when Integrated Security=True
427+
# CON: cannot use Microsoft.Data.SqlClient.SqlCommand nor [Microsoft.Data.SqlClient.SqlParameter]s
428+
#
429+
# Till here, everything is clear: we want to reuse connection if we're sure the target is "95%" adherent to the supposed one
430+
# But, and that's a big but, the magic in Invoke-DbaQuery is making a Microsoft.SqlServer.Management.Smo.Server connection happen, let it "bleed" through here
431+
# land in Invoke-DbaAsync untouched, where it gets magically converted to a Microsoft.Data.SqlClient.SqlConnection, and we get the best of both worlds.
432+
# Thing is, the "magic" is rather ... not so magic. What it happens is that when the connection from Microsoft.SqlServer.Management.Smo.Server is "Open",
433+
# everything works fine, while if it's "Closed", Microsoft.Data.SqlClient.SqlConnection rehydrates a connection using the ConnectionString of Microsoft.SqlServer.Management.Smo.Server.
434+
# Microsoft.SqlServer.Management.Smo.Server is cheating though, because there's no connectionstring parameter that holds "log on as a different user", so, what happens is that
435+
# when Microsoft.Data.SqlClient.SqlConnection picks it up, rehydrates the connection that holds Integrated Security=True, and the information on "log on as a different user" is lost in
436+
# translation.
437+
# As anticipated, this happens ONLY when the connection is "Closed", because when it's "Open", no rehydration is needed, and everything works out of the box.
438+
# Now, another fancy thing: we want to use connection pooling by default, because pooling connection is more performant.
439+
# But, and that's the big but, when connection is pooled, it gets put in the "Closed" state which translates to "back to the pool, ready to be reused", as soon as no commands are actively used.
440+
# In dbatools world, that means pretty much that when we are here, it's always "Closed" UNLESS -NonPooledConnection is $true on Connect-DbaInstance, and that's why when we don't land here
441+
# we create a new instance with NonPooledConnection = $true ( see #8491 for details, also #7725 is still relevant)
442+
# If -NonPooled is passed, we instruct Microsoft.SqlServer.Management.Smo.Server we DON'T want pooling, so the connection stays "Open" (there's no pool to put it back),
443+
# and when it's "Open" we can leverage the fact that we already established a connection, verified the certificate, did the login handshake, etc AND when casting
444+
# to Microsoft.Data.SqlClient.SqlConnection it enables us to leverage [Microsoft.Data.SqlClient.SqlParameter]s !
445+
#
446+
# Again, here we are, but we cannot use the connection when an information is lost, which is that we are:
447+
# - Integrated Security=True
448+
# - using ConnectAsUser, ConnectAsUserName, ConnectAsUserPassword to "log on as a different user"
449+
450+
if ($instance.InputObject.ConnectionContext.ConnectAsUserName -ne '') {
451+
Write-Message -Level Debug -Message "Current connection cannot be reused because logging in as a different user"
452+
# We rebuild correct credentials from SMO informations
453+
$secStringPassword = ConvertTo-SecureString $instance.InputObject.ConnectionContext.ConnectAsUserPassword -AsPlainText -Force
454+
[PSCredential]$serverCredentialFromSMO = New-Object System.Management.Automation.PSCredential($instance.InputObject.ConnectionContext.ConnectAsUserName, $secStringPassword)
455+
$connDbaInstanceParams = @{
456+
SqlInstance = $instance
457+
SqlCredential = $serverCredentialFromSMO
458+
Database = $Database
459+
NonPooledConnection = $true # see #8491 for details, also #7725 is still relevant
460+
Verbose = $false
461+
AppendConnectionString = $AppendConnectionString
462+
}
463+
if ($ReadOnly) {
464+
$connDbaInstanceParams.ApplicationIntent = "ReadOnly"
465+
}
466+
467+
$server = Connect-DbaInstance @connDbaInstanceParams
468+
469+
} else {
470+
Write-Message -Level Debug -Message "Current connection will be reused"
471+
$server = $instance.InputObject
472+
}
473+
399474
} else {
400475
$connDbaInstanceParams = @{
401-
SqlInstance = $instance
402-
SqlCredential = $SqlCredential
403-
Database = $Database
404-
NonPooledConnection = $true # see #8491 for details, also #7725 is still relevant
405-
Verbose = $false
476+
SqlInstance = $instance
477+
SqlCredential = $SqlCredential
478+
Database = $Database
479+
NonPooledConnection = $true # see #8491 for details, also #7725 is still relevant
480+
Verbose = $false
481+
AppendConnectionString = $AppendConnectionString
406482
}
407483
if ($ReadOnly) {
408484
$connDbaInstanceParams.ApplicationIntent = "ReadOnly"

tests/Disable-DbaDbEncryption.Tests.ps1

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ Describe "Disable-DbaDbEncryption" -Tag "IntegrationTests" {
7878
}
7979

8080
It "Should complete without warnings" {
81-
$warn | Should -BeNullOrEmpty
81+
$warn | Where-Object { $_ -NotLike '*Connect-DbaInstance*'} | Should -BeNullOrEmpty
8282
}
8383

8484
It "Should disable encryption" {
@@ -99,7 +99,7 @@ Describe "Disable-DbaDbEncryption" -Tag "IntegrationTests" {
9999
}
100100

101101
It "Should complete without warnings" {
102-
$warn | Should -BeNullOrEmpty
102+
$warn | Where-Object { $_ -NotLike '*Connect-DbaInstance*'} | Should -BeNullOrEmpty
103103
}
104104

105105
It "Should disable encryption" {

tests/Invoke-DbaQuery.Tests.ps1

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,8 @@ Describe "$CommandName Unit Tests" -Tag 'UnitTests' {
2727
'ReadOnly',
2828
'EnableException',
2929
'CommandType',
30-
'NoExec'
30+
'NoExec',
31+
'AppendConnectionString'
3132
)
3233
}
3334
It "Should only contain our specific parameters" {

0 commit comments

Comments
 (0)