Skip to content

Commit 8ec0a9a

Browse files
authored
Add integration tests for SSL certificate setup (#2303)
1 parent 99ad254 commit 8ec0a9a

7 files changed

+360
-68
lines changed

CHANGELOG.md

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
77

88
### Added
99

10+
- Added post-installation configuration integration test to configure SSL certificate
11+
support for SQL Server instance DSCSQLTEST in CI environment, enabling testing
12+
of encryption-related functionality. The new `PostInstallationConfiguration`
13+
integration test includes:
14+
- Self-signed SSL certificate creation and installation
15+
- Certificate configuration for SQL Server Database Engine
16+
- Service account permissions for certificate private key access
17+
- Certificate trust chain configuration
18+
- Verification that encryption is properly configured
19+
- Enabled previously skipped encryption tests in `Invoke-SqlDscQuery`
20+
- Added integration tests for `Connect-SqlDscDatabaseEngine` command to verify
21+
the `-Encrypt` parameter functionality
22+
[issue #2290](https://github.com/dsccommunity/SqlServerDsc/issues/2290).
1023
- Added integration tests for `Get-SqlDscDatabasePermission` command to ensure
1124
database permission retrieval functions correctly in real environments
1225
[issue #2221](https://github.com/dsccommunity/SqlServerDsc/issues/2221).

azure-pipelines.yml

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -290,9 +290,13 @@ stages:
290290
'tests/Integration/Commands/Import-SqlDscPreferredModule.Integration.Tests.ps1'
291291
# Group 1
292292
'tests/Integration/Commands/Install-SqlDscServer.Integration.Tests.ps1'
293+
# Group 2
294+
'tests/Integration/Commands/PostInstallationConfiguration.Integration.Tests.ps1'
295+
# Group 3
293296
'tests/Integration/Commands/Connect-SqlDscDatabaseEngine.Integration.Tests.ps1'
294297
'tests/Integration/Commands/Disconnect-SqlDscDatabaseEngine.Integration.Tests.ps1'
295-
# Group 2
298+
'tests/Integration/Commands/Invoke-SqlDscQuery.Integration.Tests.ps1'
299+
# Group 4
296300
'tests/Integration/Commands/Assert-SqlDscLogin.Integration.Tests.ps1'
297301
'tests/Integration/Commands/New-SqlDscLogin.Integration.Tests.ps1'
298302
'tests/Integration/Commands/Get-SqlDscLogin.Integration.Tests.ps1'
@@ -332,7 +336,6 @@ stages:
332336
'tests/Integration/Commands/Set-SqlDscDatabase.Integration.Tests.ps1'
333337
'tests/Integration/Commands/Test-SqlDscDatabase.Integration.Tests.ps1'
334338
'tests/Integration/Commands/Get-SqlDscDatabasePermission.Integration.Tests.ps1'
335-
'tests/Integration/Commands/Invoke-SqlDscQuery.Integration.Tests.ps1'
336339
'tests/Integration/Commands/Set-SqlDscDatabasePermission.Integration.Tests.ps1'
337340
'tests/Integration/Commands/ConvertTo-SqlDscDatabasePermission.Integration.Tests.ps1'
338341
'tests/Integration/Commands/Get-SqlDscAgentAlert.Integration.Tests.ps1'

tests/Integration/Commands/Connect-SqlDscDatabaseEngine.Integration.Tests.ps1

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,8 @@ Describe 'Connect-SqlDscDatabaseEngine' -Tag @('Integration_SQL2017', 'Integrati
7777
$sqlServerObject = Connect-SqlDscDatabaseEngine @connectSqlDscDatabaseEngineParameters
7878

7979
$sqlServerObject.Status.ToString() | Should -Match '^Online$'
80+
81+
Disconnect-SqlDscDatabaseEngine -ServerObject $sqlServerObject
8082
}
8183
}
8284
}
@@ -103,6 +105,8 @@ Describe 'Connect-SqlDscDatabaseEngine' -Tag @('Integration_SQL2017', 'Integrati
103105
$sqlServerObject = Connect-SqlDscDatabaseEngine @connectSqlDscDatabaseEngineParameters
104106

105107
$sqlServerObject.Status.ToString() | Should -Match '^Online$'
108+
109+
Disconnect-SqlDscDatabaseEngine -ServerObject $sqlServerObject
106110
}
107111
}
108112

@@ -122,6 +126,49 @@ Describe 'Connect-SqlDscDatabaseEngine' -Tag @('Integration_SQL2017', 'Integrati
122126
$sqlServerObject = Connect-SqlDscDatabaseEngine @connectSqlDscDatabaseEngineParameters
123127

124128
$sqlServerObject.Status.ToString() | Should -Match '^Online$'
129+
130+
Disconnect-SqlDscDatabaseEngine -ServerObject $sqlServerObject
131+
}
132+
}
133+
134+
Context 'When using Encrypt parameter' {
135+
It 'Should enable EncryptConnection property on the ConnectionContext' {
136+
$sqlAdministratorUserName = 'SqlAdmin' # Using computer name as NetBIOS name throw exception.
137+
$sqlAdministratorPassword = ConvertTo-SecureString -String 'P@ssw0rd1' -AsPlainText -Force
138+
139+
$connectSqlDscDatabaseEngineParameters = @{
140+
InstanceName = 'DSCSQLTEST'
141+
Credential = [System.Management.Automation.PSCredential]::new($sqlAdministratorUserName, $sqlAdministratorPassword)
142+
Encrypt = $true
143+
Verbose = $true
144+
ErrorAction = 'Stop'
145+
}
146+
147+
$sqlServerObject = Connect-SqlDscDatabaseEngine @connectSqlDscDatabaseEngineParameters
148+
149+
$sqlServerObject.Status.ToString() | Should -Match '^Online$'
150+
$sqlServerObject.ConnectionContext.EncryptConnection | Should -BeTrue
151+
152+
Disconnect-SqlDscDatabaseEngine -ServerObject $sqlServerObject
153+
}
154+
155+
It 'Should not enable EncryptConnection property when Encrypt parameter is not used' {
156+
$sqlAdministratorUserName = 'SqlAdmin' # Using computer name as NetBIOS name throw exception.
157+
$sqlAdministratorPassword = ConvertTo-SecureString -String 'P@ssw0rd1' -AsPlainText -Force
158+
159+
$connectSqlDscDatabaseEngineParameters = @{
160+
InstanceName = 'DSCSQLTEST'
161+
Credential = [System.Management.Automation.PSCredential]::new($sqlAdministratorUserName, $sqlAdministratorPassword)
162+
Verbose = $true
163+
ErrorAction = 'Stop'
164+
}
165+
166+
$sqlServerObject = Connect-SqlDscDatabaseEngine @connectSqlDscDatabaseEngineParameters
167+
168+
$sqlServerObject.Status.ToString() | Should -Match '^Online$'
169+
$sqlServerObject.ConnectionContext.EncryptConnection | Should -BeFalse
170+
171+
Disconnect-SqlDscDatabaseEngine -ServerObject $sqlServerObject
125172
}
126173
}
127174
}

tests/Integration/Commands/Get-SqlDscConfigurationOption.Integration.Tests.ps1

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,9 +39,25 @@ Describe 'Get-SqlDscConfigurationOption' -Tag @('Integration_SQL2017', 'Integrat
3939
$script:mockSqlAdminCredential = [System.Management.Automation.PSCredential]::new($mockSqlAdministratorUserName, $mockSqlAdministratorPassword)
4040

4141
$script:serverObject = Connect-SqlDscDatabaseEngine -InstanceName $script:mockInstanceName -Credential $script:mockSqlAdminCredential
42+
43+
# Get the original value of 'Agent XPs' to restore later
44+
$agentXPsOption = Get-SqlDscConfigurationOption -ServerObject $script:serverObject -Name 'Agent XPs' -ErrorAction 'Stop'
45+
$script:originalAgentXPsValue = $agentXPsOption.ConfigValue
46+
47+
# Set Agent XPs to 1 if it's not already set
48+
if ($script:originalAgentXPsValue -ne 1)
49+
{
50+
Set-SqlDscConfigurationOption -ServerObject $script:serverObject -Name 'Agent XPs' -Value 1 -Force -ErrorAction 'Stop'
51+
}
4252
}
4353

4454
AfterAll {
55+
# Restore the original value of 'Agent XPs' if it was not 1
56+
if ($script:originalAgentXPsValue -ne 1)
57+
{
58+
Set-SqlDscConfigurationOption -ServerObject $script:serverObject -Name 'Agent XPs' -Value $script:originalAgentXPsValue -Force -ErrorAction 'Stop'
59+
}
60+
4561
Disconnect-SqlDscDatabaseEngine -ServerObject $script:serverObject
4662
}
4763

tests/Integration/Commands/Invoke-SqlDscQuery.Integration.Tests.ps1

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -145,8 +145,7 @@ INSERT INTO TestTable (Name, Value) VALUES ('Test1', 100), ('Test2', 200), ('Tes
145145
}
146146

147147
Context 'When using optional parameters with ByServerName parameter set' {
148-
# Using Encrypt in the CI is not possible until we add the required support (certificate) in the CI.
149-
It 'Should execute query with Encrypt parameter' -Skip {
148+
It 'Should execute query with Encrypt parameter' {
150149
$null = Invoke-SqlDscQuery -ServerName $script:mockComputerName -InstanceName $script:mockInstanceName -Credential $script:mockSqlAdminCredential -DatabaseName $script:testDatabaseName -Query 'SELECT 1 as TestValue' -Encrypt -PassThru -Force -ErrorAction 'Stop'
151150
}
152151

Lines changed: 213 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,213 @@
1+
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseDeclaredVarsMoreThanAssignments', '', Justification = 'Suppressing this rule because Script Analyzer does not understand Pester syntax.')]
2+
param ()
3+
4+
BeforeDiscovery {
5+
try
6+
{
7+
if (-not (Get-Module -Name 'DscResource.Test'))
8+
{
9+
# Assumes dependencies have been resolved, so if this module is not available, run 'noop' task.
10+
if (-not (Get-Module -Name 'DscResource.Test' -ListAvailable))
11+
{
12+
# Redirect all streams to $null, except the error stream (stream 2)
13+
& "$PSScriptRoot/../../../build.ps1" -Tasks 'noop' 3>&1 4>&1 5>&1 6>&1 > $null
14+
}
15+
16+
# If the dependencies have not been resolved, this will throw an error.
17+
Import-Module -Name 'DscResource.Test' -Force -ErrorAction 'Stop'
18+
}
19+
}
20+
catch [System.IO.FileNotFoundException]
21+
{
22+
throw 'DscResource.Test module dependency not found. Please run ".\build.ps1 -ResolveDependency -Tasks noop" first.'
23+
}
24+
}
25+
26+
BeforeAll {
27+
$script:moduleName = 'SqlServerDsc'
28+
29+
Import-Module -Name $script:moduleName -Force -ErrorAction 'Stop'
30+
}
31+
32+
# cSpell: ignore DSCSQLTEST
33+
Describe 'PostInstallationConfiguration' -Tag @('Integration_SQL2017', 'Integration_SQL2019', 'Integration_SQL2022') {
34+
Context 'When configuring SSL certificate for encryption support on DSCSQLTEST instance' {
35+
BeforeAll {
36+
$script:instanceName = 'DSCSQLTEST'
37+
$script:computerName = Get-ComputerName
38+
$script:computerNameFqdn = Get-ComputerName -FullyQualifiedDomainName
39+
$script:serviceAccountName = 'svc-SqlPrimary'
40+
}
41+
42+
It 'Should verify the SQL Server instance is running with the expected service account' {
43+
$serviceName = "MSSQL`$$script:instanceName"
44+
$service = Get-CimInstance -ClassName 'Win32_Service' -Filter "Name='$serviceName'" -ErrorAction 'Stop'
45+
46+
$service | Should -Not -BeNullOrEmpty
47+
$service.State | Should -Be 'Running'
48+
$service.StartName | Should -BeLike "*\$script:serviceAccountName"
49+
}
50+
51+
It 'Should create a self-signed certificate for SQL Server encryption' {
52+
# Create self-signed certificate with proper configuration for SQL Server
53+
$certificateParams = @{
54+
Type = 'SSLServerAuthentication'
55+
Subject = "CN=$script:computerName"
56+
DnsName = @(
57+
$script:computerName
58+
$script:computerNameFqdn
59+
'localhost'
60+
)
61+
KeyAlgorithm = 'RSA'
62+
KeyLength = 2048
63+
HashAlgorithm = 'SHA256'
64+
TextExtension = '2.5.29.37={text}1.3.6.1.5.5.7.3.1'
65+
NotAfter = (Get-Date).AddYears(3)
66+
KeySpec = 'KeyExchange'
67+
Provider = 'Microsoft RSA SChannel Cryptographic Provider'
68+
CertStoreLocation = 'cert:\LocalMachine\My'
69+
}
70+
71+
$script:certificate = New-SelfSignedCertificate @certificateParams -ErrorAction 'Stop'
72+
73+
$script:certificate | Should -Not -BeNullOrEmpty
74+
$script:certificate.Thumbprint | Should -Not -BeNullOrEmpty
75+
$script:certificateThumbprint = $script:certificate.Thumbprint
76+
}
77+
78+
It 'Should export the certificate to file' {
79+
$script:certificatePath = Join-Path -Path $env:TEMP -ChildPath 'SqlServerEncryption.cer'
80+
81+
Export-Certificate -Cert $script:certificate -FilePath $script:certificatePath -ErrorAction 'Stop'
82+
83+
Test-Path -Path $script:certificatePath | Should -BeTrue
84+
}
85+
86+
It 'Should import certificate to Trusted Root Certification Authorities' {
87+
# Import to trusted root for self-signed certificates
88+
Import-Certificate -FilePath $script:certificatePath -CertStoreLocation 'Cert:\LocalMachine\Root' -ErrorAction 'Stop'
89+
90+
# Verify certificate is in trusted root
91+
$trustedCert = Get-ChildItem -Path 'Cert:\LocalMachine\Root' | Where-Object -FilterScript { $_.Thumbprint -eq $script:certificateThumbprint }
92+
$trustedCert | Should -Not -BeNullOrEmpty
93+
}
94+
95+
It 'Should grant SQL Server service account permission to certificate private key' {
96+
# Get the certificate from the Personal store
97+
$cert = Get-ChildItem -Path "Cert:\LocalMachine\My\$script:certificateThumbprint" -ErrorAction 'Stop'
98+
99+
# Get the private key
100+
$rsaCert = [System.Security.Cryptography.X509Certificates.RSACertificateExtensions]::GetRSAPrivateKey($cert)
101+
$privateKeyPath = $rsaCert.Key.UniqueName
102+
103+
# Build the full path to the private key file
104+
$privateKeyFile = Join-Path -Path "$env:ALLUSERSPROFILE\Microsoft\Crypto\RSA\MachineKeys" -ChildPath $privateKeyPath
105+
106+
# Verify the private key file exists
107+
Test-Path -Path $privateKeyFile | Should -BeTrue
108+
109+
# Grant read permission to the SQL Server service account
110+
$acl = Get-Acl -Path $privateKeyFile -ErrorAction 'Stop'
111+
$accessRule = [System.Security.AccessControl.FileSystemAccessRule]::new(
112+
$script:serviceAccountName,
113+
[System.Security.AccessControl.FileSystemRights]::Read,
114+
[System.Security.AccessControl.AccessControlType]::Allow
115+
)
116+
$acl.AddAccessRule($accessRule)
117+
Set-Acl -Path $privateKeyFile -AclObject $acl -ErrorAction 'Stop'
118+
119+
# Verify permission was granted
120+
$updatedAcl = Get-Acl -Path $privateKeyFile -ErrorAction 'Stop'
121+
$serviceAccountAccess = $updatedAcl.Access | Where-Object -FilterScript {
122+
$_.IdentityReference -like "*$script:serviceAccountName*" -and $_.FileSystemRights -match 'Read'
123+
}
124+
$serviceAccountAccess | Should -Not -BeNullOrEmpty
125+
}
126+
127+
It 'Should configure SQL Server instance to use the certificate' {
128+
# Get the SQL Server instance registry key path
129+
# For named instance DSCSQLTEST, the registry path includes the instance name
130+
$registryPath = "HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL*.$script:instanceName\MSSQLServer\SuperSocketNetLib"
131+
132+
# Find the actual registry path (version number varies)
133+
$actualRegistryPath = Get-Item -Path $registryPath -ErrorAction 'Stop' | Select-Object -First 1 -ExpandProperty Name
134+
$actualRegistryPath = "Registry::$actualRegistryPath"
135+
136+
# Set the certificate thumbprint (without spaces)
137+
$thumbprintValue = $script:certificateThumbprint -replace '\s', ''
138+
Set-ItemProperty -Path $actualRegistryPath -Name 'Certificate' -Value $thumbprintValue -ErrorAction 'Stop'
139+
140+
# Verify the certificate was set
141+
$setCertificate = Get-ItemProperty -Path $actualRegistryPath -Name 'Certificate' -ErrorAction 'Stop'
142+
$setCertificate.Certificate | Should -Be $thumbprintValue
143+
}
144+
145+
It 'Should restart SQL Server service to apply certificate changes' {
146+
$serviceName = "MSSQL`$$script:instanceName"
147+
148+
# Restart the SQL Server service
149+
Restart-Service -Name $serviceName -Force -ErrorAction 'Stop'
150+
151+
# Wait for service to be running
152+
$maxRetries = 30
153+
$retryCount = 0
154+
do {
155+
Start-Sleep -Seconds 2
156+
$service = Get-Service -Name $serviceName -ErrorAction 'Stop'
157+
$retryCount++
158+
} while ($service.Status -ne 'Running' -and $retryCount -lt $maxRetries)
159+
160+
$service.Status | Should -Be 'Running'
161+
162+
Write-Verbose -Message "SQL Server instance $script:instanceName restarted with SSL certificate configuration" -Verbose
163+
}
164+
165+
It 'Should verify SQL Server is online without using the certificate for encryption' {
166+
# Connect to SQL Server and verify encryption is available
167+
$sqlAdministratorUserName = 'SqlAdmin'
168+
$sqlAdministratorPassword = ConvertTo-SecureString -String 'P@ssw0rd1' -AsPlainText -Force
169+
$credential = [System.Management.Automation.PSCredential]::new($sqlAdministratorUserName, $sqlAdministratorPassword)
170+
171+
$serverObject = Connect-SqlDscDatabaseEngine -InstanceName $script:instanceName -Credential $credential -ErrorAction 'Stop'
172+
173+
# The server should be online
174+
$serverObject.Status.ToString() | Should -Match '^Online$'
175+
176+
# Clean up
177+
Disconnect-SqlDscDatabaseEngine -ServerObject $serverObject -ErrorAction 'Stop'
178+
}
179+
180+
It 'Should verify the connection is using encryption via DMV query' {
181+
# Connect to SQL Server with encryption enabled
182+
$sqlAdministratorUserName = 'SqlAdmin'
183+
$sqlAdministratorPassword = ConvertTo-SecureString -String 'P@ssw0rd1' -AsPlainText -Force
184+
$credential = [System.Management.Automation.PSCredential]::new($sqlAdministratorUserName, $sqlAdministratorPassword)
185+
186+
$serverObject = Connect-SqlDscDatabaseEngine -InstanceName $script:instanceName -Credential $credential -Encrypt -ErrorAction 'Stop'
187+
188+
# Query sys.dm_exec_connections to verify encryption is being used
189+
# See: https://learn.microsoft.com/en-us/sql/database-engine/configure-windows/configure-sql-server-encryption?view=sql-server-ver17#verify-network-encryption
190+
$encryptionQuery = @"
191+
SELECT
192+
session_id,
193+
encrypt_option,
194+
net_transport
195+
FROM sys.dm_exec_connections
196+
WHERE session_id = @@SPID
197+
"@
198+
199+
$result = Invoke-SqlDscQuery -ServerObject $serverObject -DatabaseName 'master' -Query $encryptionQuery -PassThru -Force -ErrorAction 'Stop'
200+
201+
# Verify the connection is encrypted
202+
$result | Should -Not -BeNullOrEmpty
203+
$result.Tables[0].Rows.Count | Should -Be 1
204+
$result.Tables[0].Rows[0]['encrypt_option'] | Should -Be 'TRUE'
205+
206+
# Clean up
207+
Disconnect-SqlDscDatabaseEngine -ServerObject $serverObject -ErrorAction 'Stop'
208+
209+
Write-Verbose -Message "Verified encrypted connection using sys.dm_exec_connections DMV" -Verbose
210+
Write-Verbose -Message "SSL certificate successfully configured for SQL Server instance $script:instanceName" -Verbose
211+
}
212+
}
213+
}

0 commit comments

Comments
 (0)