From 8cdf8c8797611e90cbf282806f8da4fe46da1158 Mon Sep 17 00:00:00 2001 From: Svilen Sultanov Date: Thu, 26 Dec 2019 22:40:25 +0100 Subject: [PATCH] Adjusting the integration testing --- .../MSFT_xExchReceiveConnector.psm1 | 68 +++++- ...ExchReceiveConnector.Integration.Tests.ps1 | 231 +++++++++--------- tests/TestHelpers/xExchangeTestHelper.psm1 | 16 +- 3 files changed, 191 insertions(+), 124 deletions(-) diff --git a/source/DSCResources/MSFT_xExchReceiveConnector/MSFT_xExchReceiveConnector.psm1 b/source/DSCResources/MSFT_xExchReceiveConnector/MSFT_xExchReceiveConnector.psm1 index db95b487..aee6a298 100644 --- a/source/DSCResources/MSFT_xExchReceiveConnector/MSFT_xExchReceiveConnector.psm1 +++ b/source/DSCResources/MSFT_xExchReceiveConnector/MSFT_xExchReceiveConnector.psm1 @@ -39,10 +39,54 @@ function Get-TargetResource # Establish remote PowerShell session Get-RemoteExchangeSession -Credential $Credential -CommandsToLoad 'Get-ReceiveConnector' -Verbose:$VerbosePreference - $connector = Get-ReceiveConnector -Identity $Identity + $connector = Get-ReceiveConnector -Identity $Identity -ErrorAction SilentlyContinue if ($null -ne $connector) { + if ($adObject = $Identity.Split('\')[1]) + { + $adPermissions = Get-ADPermission -Identity $adObject | Where-Object { $_.IsInherited -eq $false -and $null -ne $_.ExtendedRights } + } + else + { + $adPermissions = Get-ADPermission -Identity $Identity | Where-Object { $_.IsInherited -eq $false -and $null -ne $_.ExtendedRights } + } + + $userNames = $adPermissions.User | Select-Object -Property RawIdentity -Unique | ForEach-Object -MemberName RawIdentity + $ExtendedRightAllowEntries = [System.Collections.Generic.List[Microsoft.Management.Infrastructure.CimInstance]]::new() + $ExtendedRightDenyEntries = [System.Collections.Generic.List[Microsoft.Management.Infrastructure.CimInstance]]::new() + + foreach ($user in $userNames) + { + $allowPermissions = ($adPermissions | Where-Object -FilterScript { $_.User.RawIdentity -eq $user -and $_.Deny -eq $false } | + ForEach-Object -MemberName ExtendedRights | ForEach-Object -MemberName RawIdentity) -join ',' + $denyPermissions = ($adPermissions | Where-Object -FilterScript { $_.User.RawIdentity -eq $user -and $_.Deny -eq $true } | + ForEach-Object -MemberName ExtendedRights | ForEach-Object -MemberName RawIdentity) -join ',' + + if ($allowPermissions) + { + $ExtendedRightAllowEntries.Add( + ( + New-CimInstance -ClassName MSFT_KeyValuePair -Property @{ + key = $user + value = $allowPermissions + } -ClientOnly + ) + ) + } + if ($denyPermissions) + { + $ExtendedRightDenyEntries.Add( + ( + New-CimInstance -ClassName MSFT_KeyValuePair -Property @{ + key = $user + value = $denyPermissions + } -ClientOnly + ) + ) + } + } + $returnValue = @{ Identity = [System.String] $Identity AdvertiseClientSettings = [System.Boolean] $connector.AdvertiseClientSettings @@ -474,6 +518,7 @@ function Set-TargetResource if ($connector['Ensure'] -eq 'Present') { Remove-FromPSBoundParametersUsingHashtable -PSBoundParametersIn $PSBoundParameters -ParamsToKeep 'Identity', 'DomainController' + Write-Verbose -Message 'Removing the receive connector.' Remove-ReceiveConnector @PSBoundParameters -Confirm:$false } @@ -481,7 +526,7 @@ function Set-TargetResource else { # Remove Credential and Ensure so we don't pass it into the next command - Remove-FromPSBoundParametersUsingHashtable -PSBoundParametersIn $PSBoundParameters -ParamsToRemove 'Credential', 'Ensure' + Remove-FromPSBoundParametersUsingHashtable -PSBoundParametersIn $PSBoundParameters -ParamsToRemove 'Credential', 'Ensure', 'ExtendedRightAllowEntries', 'ExtendedRightDenyEntries' Set-EmptyStringParamsToNull -PSBoundParametersIn $PSBoundParameters @@ -492,7 +537,7 @@ function Set-TargetResource $originalPSBoundParameters = @{ } + $PSBoundParameters # The following aren't valid for New-ReceiveConnector - Remove-FromPSBoundParametersUsingHashtable -PSBoundParametersIn $PSBoundParameters -ParamsToRemove 'Identity', 'BareLinefeedRejectionEnabled', 'ExtendedRightAllowEntries', 'ExtendedRightDenyEntries' + Remove-FromPSBoundParametersUsingHashtable -PSBoundParametersIn $PSBoundParameters -ParamsToRemove 'Identity', 'BareLinefeedRejectionEnabled' # Parse out the server name and connector name from the given Identity $serverName, $connectorName = $Identity.Split('\') @@ -503,15 +548,19 @@ function Set-TargetResource 'Name' = $connectorName } + Write-Verbose -Message 'Creating the receive connector.' + # Create the connector New-ReceiveConnector @PSBoundParameters - # Remove the two props we added - Remove-FromPSBoundParametersUsingHashtable -PSBoundParametersIn $PSBoundParameters -ParamsToRemove 'Server', 'Name' - # Add original props back Add-ToPSBoundParametersFromHashtable -PSBoundParametersIn $PSBoundParameters -ParamsToAdd $originalPSBoundParameters + # Remove the two props we added + Remove-FromPSBoundParametersUsingHashtable -PSBoundParametersIn $PSBoundParameters -ParamsToRemove 'Server', 'Name', 'Usage' + + Write-Verbose -Message 'Setting the receive connector properties.' + Set-ReceiveConnector @PSBoundParameters } else @@ -1175,11 +1224,6 @@ function Test-TargetResource $testResults = $false } - if (!(Test-ExchangeSetting -Name 'Usage' -Type 'Array' -ExpectedValue $Usage -ActualValue $connector.Usage -PSBoundParametersIn $PSBoundParameters -Verbose:$VerbosePreference)) - { - $testResults = $false - } - if ($ExtendedRightAllowEntries) { $splat = @{ @@ -1257,7 +1301,7 @@ function Test-ExtendedRightsPresent { foreach ($Value in $($Right.Value.Split(','))) { - $permissionsFound = $ADPermissions | Where-Object { ($_.User.RawIdentity -match $Right.Key) -and ($_.ExtendedRights.RawIdentity -eq $Value) } + $permissionsFound = $ADPermissions | Where-Object { ($_.User.RawIdentity -eq $Right.Key) -and ($_.ExtendedRights.RawIdentity -eq $Value) } if ($null -ne $permissionsFound) { if (($Deny -eq $true -and $permissionsFound.Deny.ToBool() -eq $false) -or diff --git a/tests/Integration/MSFT_xExchReceiveConnector.Integration.Tests.ps1 b/tests/Integration/MSFT_xExchReceiveConnector.Integration.Tests.ps1 index ff714447..113f6a02 100644 --- a/tests/Integration/MSFT_xExchReceiveConnector.Integration.Tests.ps1 +++ b/tests/Integration/MSFT_xExchReceiveConnector.Integration.Tests.ps1 @@ -29,141 +29,152 @@ if ($exchangeInstalled) # Set configuration with default values $extendedRightAllowEntries = $(New-CimInstance -ClassName MSFT_KeyValuePair -Namespace root/microsoft/Windows/DesiredStateConfiguration -ClientOnly -Property @{ - Key = 'NT AUTHORITY\ANONYMOUS LOGON'; ` - Value = 'Ms-Exch-SMTP-Accept-Any-Recipient,ms-Exch-Bypass-Anti-Spam'}) + Key = 'NT AUTHORITY\ANONYMOUS LOGON' + Value = 'Ms-Exch-SMTP-Accept-Any-Recipient,ms-Exch-Bypass-Anti-Spam' + } + ) $testParams = @{ - Identity = "$($env:computername)\AnonymousRelay $($env:computername)" - Credential = $shellCredentials - Ensure = 'Present' - ExtendedRightAllowEntries = $extendedRightAllowEntries - AdvertiseClientSettings = $false - AuthMechanism = 'Tls', 'ExternalAuthoritative' - Banner = '220 Pester' - BareLinefeedRejectionEnabled = $false - BinaryMimeEnabled = $true - Bindings = '192.168.0.100:25' - ChunkingEnabled = $true - Comment = 'Connector for relaying' - ConnectionInactivityTimeout = '00:05:00' - ConnectionTimeout = '00:10:00' - DefaultDomain = '' - DeliveryStatusNotificationEnabled = $true - DomainSecureEnabled = $false - EightBitMimeEnabled = $true - EnableAuthGSSAPI = $false - Enabled = $true - EnhancedStatusCodesEnabled = $true - ExtendedProtectionPolicy = 'none' - Fqdn = "$($env:computername).pester.com" - LongAddressesEnabled = $false - MaxAcknowledgementDelay = '00:00:00' - MaxHeaderSize = '128KB' - MaxHopCount = '60' - MaxInboundConnection = '5000' - MaxInboundConnectionPercentagePerSource = '100' - MaxInboundConnectionPerSource = '50' - MaxLocalHopCount = '12' - MaxLogonFailures = '3' - MaxMessageSize = '35MB' - MaxProtocolErrors = '5' - MaxRecipientsPerMessage = '5000' - MessageRateLimit = 'Unlimited' - MessageRateSource = 'IPAddress' - OrarEnabled = $false - PermissionGroups = 'AnonymousUsers', 'ExchangeServers' - PipeliningEnabled = $true - ProtocolLoggingLevel = 'Verbose' - RemoteIPRanges = '192.16.7.99' - RequireEHLODomain = $false - RequireTLS = $false - ServiceDiscoveryFqdn = '' - SizeEnabled = 'EnabledwithoutValue' - SuppressXAnonymousTls = $false - TarpitInterval = '00:00:00' - TlsCertificateName = $null - TlsDomainCapabilities = 'contoso.com:AcceptOorgProtocol' - TransportRole = 'FrontendTransport' - Usage = 'Custom' + Identity = "$($env:computername)\AnonymousRelay $($env:computername)" + Credential = $shellCredentials + Ensure = 'Present' + ExtendedRightAllowEntries = $extendedRightAllowEntries + AdvertiseClientSettings = $false + AuthMechanism = 'Tls', 'ExternalAuthoritative' + Banner = '220 Pester' + BareLinefeedRejectionEnabled = $false + BinaryMimeEnabled = $true + Bindings = '192.168.0.100:25' + ChunkingEnabled = $true + Comment = 'Connector for relaying' + ConnectionInactivityTimeout = '00:05:00' + ConnectionTimeout = '00:10:00' + DefaultDomain = '' + DeliveryStatusNotificationEnabled = $true + DomainSecureEnabled = $false + EightBitMimeEnabled = $true + EnableAuthGSSAPI = $false + Enabled = $true + EnhancedStatusCodesEnabled = $true + ExtendedProtectionPolicy = 'none' + Fqdn = "$($env:computername).pester.com" + LongAddressesEnabled = $false + MaxAcknowledgementDelay = '00:00:00' + MaxHeaderSize = '128KB' + MaxHopCount = '60' + MaxInboundConnection = '5000' + MaxInboundConnectionPercentagePerSource = '100' + MaxInboundConnectionPerSource = '50' + MaxLocalHopCount = '12' + MaxLogonFailures = '3' + MaxMessageSize = '35MB' + MaxProtocolErrors = '5' + MaxRecipientsPerMessage = '5000' + MessageRateLimit = 'Unlimited' + MessageRateSource = 'IPAddress' + OrarEnabled = $false + PermissionGroups = 'AnonymousUsers', 'ExchangeServers' + PipeliningEnabled = $true + ProtocolLoggingLevel = 'Verbose' + RemoteIPRanges = '192.16.7.99' + RequireEHLODomain = $false + RequireTLS = $false + ServiceDiscoveryFqdn = '' + SizeEnabled = 'EnabledwithoutValue' + SuppressXAnonymousTls = $false + TarpitInterval = '00:00:00' + TlsCertificateName = $null + TlsDomainCapabilities = 'contoso.com:AcceptOorgProtocol' + TransportRole = 'FrontendTransport' + Usage = 'Custom' + } + + $getParams = @{ + Identity = "$($env:computername)\AnonymousRelay $($env:computername)" + Credential = $shellCredentials + Ensure = 'Present' } $expectedGetResults = @{ - ExtendedRightAllowEntries = $extendedRightAllowEntries - AdvertiseClientSettings = $false - AuthMechanism = 'Tls', 'ExternalAuthoritative' - Banner = '220 Pester' - BareLinefeedRejectionEnabled = $false - BinaryMimeEnabled = $true - Bindings = '192.168.0.100:25' - ChunkingEnabled = $true - Comment = 'Connector for relaying' - ConnectionInactivityTimeout = '00:05:00' - ConnectionTimeout = '00:10:00' - DefaultDomain = '' - # DomainController = '' - DeliveryStatusNotificationEnabled = $true - DomainSecureEnabled = $false - EightBitMimeEnabled = $true - EnableAuthGSSAPI = $false - Enabled = $true - EnhancedStatusCodesEnabled = $true - ExtendedProtectionPolicy = 'none' - Fqdn = "$($env:computername).pester.com" - LongAddressesEnabled = $false - MaxAcknowledgementDelay = '00:00:00' - MaxHeaderSize = '128 KB (131,072 bytes)' - MaxHopCount = '60' - MaxInboundConnection = '5000' - MaxInboundConnectionPercentagePerSource = '100' - MaxInboundConnectionPerSource = '50' - MaxLocalHopCount = '12' - MaxLogonFailures = '3' - MaxMessageSize = '35 MB (36,700,160 bytes)' - MaxProtocolErrors = '5' - MaxRecipientsPerMessage = '5000' - MessageRateLimit = 'Unlimited' - MessageRateSource = 'IPAddress' - OrarEnabled = $false - PermissionGroups = [System.String[]] @('AnonymousUsers', 'ExchangeServers', 'Custom') - PipeliningEnabled = $true - ProtocolLoggingLevel = 'Verbose' - RemoteIPRanges = '192.16.7.99' - RequireEHLODomain = $false - RequireTLS = $false - ServiceDiscoveryFqdn = '' - SizeEnabled = 'EnabledwithoutValue' - SuppressXAnonymousTls = $false - TarpitInterval = '00:00:00' - TlsCertificateName = '' - TlsDomainCapabilities = 'contoso.com:AcceptOorgProtocol' - TransportRole = 'FrontendTransport' + ExtendedRightAllowEntries = $extendedRightAllowEntries + AdvertiseClientSettings = $false + AuthMechanism = 'Tls', 'ExternalAuthoritative' + Banner = '220 Pester' + BareLinefeedRejectionEnabled = $false + BinaryMimeEnabled = $true + Bindings = '192.168.0.100:25' + ChunkingEnabled = $true + Comment = 'Connector for relaying' + ConnectionInactivityTimeout = '00:05:00' + ConnectionTimeout = '00:10:00' + DefaultDomain = '' + # DomainController = '' + DeliveryStatusNotificationEnabled = $true + DomainSecureEnabled = $false + EightBitMimeEnabled = $true + EnableAuthGSSAPI = $false + Enabled = $true + EnhancedStatusCodesEnabled = $true + ExtendedProtectionPolicy = 'none' + Fqdn = "$($env:computername).pester.com" + LongAddressesEnabled = $false + MaxAcknowledgementDelay = '00:00:00' + MaxHeaderSize = '128 KB (131,072 bytes)' + MaxHopCount = '60' + MaxInboundConnection = '5000' + MaxInboundConnectionPercentagePerSource = '100' + MaxInboundConnectionPerSource = '50' + MaxLocalHopCount = '12' + MaxLogonFailures = '3' + MaxMessageSize = '35 MB (36,700,160 bytes)' + MaxProtocolErrors = '5' + MaxRecipientsPerMessage = '5000' + MessageRateLimit = 'Unlimited' + MessageRateSource = 'IPAddress' + OrarEnabled = $false + PermissionGroups = [System.String[]] @('AnonymousUsers', 'ExchangeServers', 'Custom') + PipeliningEnabled = $true + ProtocolLoggingLevel = 'Verbose' + RemoteIPRanges = '192.16.7.99' + RequireEHLODomain = $false + RequireTLS = $false + ServiceDiscoveryFqdn = '' + SizeEnabled = 'EnabledwithoutValue' + SuppressXAnonymousTls = $false + TarpitInterval = '00:00:00' + TlsCertificateName = '' + TlsDomainCapabilities = 'contoso.com:AcceptOorgProtocol' + TransportRole = 'FrontendTransport' } - Test-TargetResourceFunctionality -Params $testParams -ContextLabel 'Create Receive Connector' -ExpectedGetResults $expectedGetResults + Test-TargetResourceFunctionality -Params $testParams -GetParams $getParams -ContextLabel 'Create Receive Connector' -ExpectedGetResults $expectedGetResults # Modify configuration $extendedRightDenyEntries = $(New-CimInstance -ClassName MSFT_KeyValuePair -Namespace root/microsoft/Windows/DesiredStateConfiguration ` - -Property @{Key = 'Domain Users'; Value = 'ms-Exch-Bypass-Anti-Spam'} -ClientOnly) + -Property @{Key = "$($env:USERDOMAIN)\Domain Users"; Value = 'ms-Exch-Bypass-Anti-Spam' } -ClientOnly) $testParams.ExtendedRightDenyEntries = $extendedRightDenyEntries $expectedGetResults.ExtendedRightDenyEntries = $extendedRightDenyEntries - Test-TargetResourceFunctionality -Params $testParams -ContextLabel 'Modify Receive Connector' -ExpectedGetResults $expectedGetResults + Test-TargetResourceFunctionality -Params $testParams -GetParams $getParams -ContextLabel 'Modify Receive Connector' -ExpectedGetResults $expectedGetResults # Modify configuration $testParams.Ensure = 'Absent' - $expectedGetResults = $null + $getParams.Ensure = 'Absent' + $expectedGetResults = @{ + Ensure = 'Absent' + } - Test-TargetResourceFunctionality -Params $testParams -ContextLabel 'Remove Receive Connector' -ExpectedGetResults $expectedGetResults + Test-TargetResourceFunctionality -Params $testParams -GetParams $getParams -ContextLabel 'Remove Receive Connector' -ExpectedGetResults $expectedGetResults # Try to remove the same receive connector again. This should not cause any errors. $testStartTime = [DateTime]::Now - Test-TargetResourceFunctionality -Params $testParams -ContextLabel 'Attempt Removal of Already Removed Receive Connector' -ExpectedGetResults $expectedGetResults + Test-TargetResourceFunctionality -Params $testParams -GetParams $getParams -ContextLabel 'Attempt Removal of Already Removed Receive Connector' -ExpectedGetResults $expectedGetResults Context 'When Get-ReceiveConnector is called and the connector is absent' { It 'Should not cause an error to be logged in the event log' { Get-EventLog -LogName 'MSExchange Management' -After $testStartTime -ErrorAction SilentlyContinue | ` - Where-Object -FilterScript {$_.Message -like '*Cmdlet failed. Cmdlet Get-ReceiveConnector, parameters -Identity*'} |` + Where-Object -FilterScript { $_.Message -like '*Cmdlet failed. Cmdlet Get-ReceiveConnector, parameters -Identity*' } |` Should -Be $null } } diff --git a/tests/TestHelpers/xExchangeTestHelper.psm1 b/tests/TestHelpers/xExchangeTestHelper.psm1 index 95353d6d..52e7769b 100644 --- a/tests/TestHelpers/xExchangeTestHelper.psm1 +++ b/tests/TestHelpers/xExchangeTestHelper.psm1 @@ -27,6 +27,10 @@ function Test-TargetResourceFunctionality [System.Collections.Hashtable] $Params, + [Parameter()] + [System.Collections.Hashtable] + $GetParams, + [Parameter()] [System.String] $ContextLabel, @@ -48,6 +52,10 @@ function Test-TargetResourceFunctionality $Params.Add('Verbose', $true) $addedVerbose = $true } + if ($null -eq $GetParams) + { + $GetParams = $Params + } [System.Boolean] $testResult = Test-TargetResource @Params @@ -55,7 +63,7 @@ function Test-TargetResourceFunctionality Set-TargetResource @Params - [System.Collections.Hashtable] $getResult = Get-TargetResource @Params + [System.Collections.Hashtable] $getResult = Get-TargetResource @GetParams [System.Boolean] $testResult = Test-TargetResource @Params # The ExpectedGetResults are $null, so let's check that what we got back is $null @@ -82,7 +90,7 @@ function Test-TargetResourceFunctionality { if ($getResult.ContainsKey($key)) { - switch ((Get-Command Get-TargetResource).Parameters[$key].ParameterType) + switch ((Get-Command Set-TargetResource).Parameters[$key].ParameterType) { ([System.String[]]) { @@ -92,6 +100,10 @@ function Test-TargetResourceFunctionality { $getValueMatchesForKey = $getResult[$key].UserName -like $ExpectedGetResults[$key].UserName } + ([Microsoft.Management.Infrastructure.CimInstance[]]) + { + $getValueMatchesForKey = Test-CimArrayContainsSubArray -Array $getResult[$key] -SubArray $ExpectedGetResults[$key] + } default { $getValueMatchesForKey = ($getResult[$key] -eq $ExpectedGetResults[$key])