diff --git a/powershell/internal/checks/cisa/entra/Get-MtCisaPhishingResistantPolicy.ps1 b/powershell/internal/checks/cisa/entra/Get-MtCisaPhishingResistantPolicy.ps1 new file mode 100644 index 0000000000..2dd95c0b38 --- /dev/null +++ b/powershell/internal/checks/cisa/entra/Get-MtCisaPhishingResistantPolicy.ps1 @@ -0,0 +1,43 @@ +function Get-MtCisaPhishingResistantPolicy { + <# + .SYNOPSIS + Returns Conditional Access policies that enforce phishing-resistant MFA for all users and applications. + + .DESCRIPTION + User and group exclusions are counted only when they match configured emergency access accounts or groups. + Other exclusions are not counted because Maester has no matching SCuBA exclusion allowlists. + #> + [CmdletBinding()] + [OutputType([object[]])] + param( + [Parameter()] + [object[]] $EmergencyAccessAccounts = @() + ) + + $phishingResistantMethods = @('windowsHelloForBusiness', 'fido2', 'x509CertificateMultiFactor') + $emergencyAccessObjectIds = @(Get-MtEmergencyAccessAccount -Account $EmergencyAccessAccounts | ForEach-Object { $_.ObjectId }) + + $policies = Get-MtConditionalAccessPolicy | Where-Object { + $authenticationStrength = $_.grantControls.authenticationStrength + $allowedCombinations = @($authenticationStrength.allowedCombinations | Where-Object { $_ }) + $userAndGroupExclusions = @( + $_.conditions.users.excludeUsers + $_.conditions.users.excludeGroups + ) | Where-Object { $_ } + $unapprovedExclusions = @($userAndGroupExclusions | Where-Object { $_ -notin $emergencyAccessObjectIds }) + + $_.state -eq 'enabled' -and + $_.conditions.applications.includeApplications -contains 'All' -and + $_.conditions.users.includeUsers -contains 'All' -and + $unapprovedExclusions.Count -eq 0 -and + -not $_.conditions.users.excludeRoles -and + -not $_.conditions.applications.excludeApplications -and + $null -eq $_.conditions.users.excludeGuestsOrExternalUsers -and + $authenticationStrength -and ( + $allowedCombinations.Count -gt 0 -and + @($allowedCombinations | Where-Object { $_ -notin $phishingResistantMethods }).Count -eq 0 + ) + } + + return @($policies) +} diff --git a/powershell/internal/checks/cisa/entra/Test-MtCisaActivationNotification.ps1 b/powershell/internal/checks/cisa/entra/Test-MtCisaActivationNotification.ps1 index 451ab07cfb..14939165ad 100644 --- a/powershell/internal/checks/cisa/entra/Test-MtCisaActivationNotification.ps1 +++ b/powershell/internal/checks/cisa/entra/Test-MtCisaActivationNotification.ps1 @@ -52,7 +52,15 @@ role = $role.displayName activationNotify = $false } - $recipients = @(Get-MtRoleActivationNotificationRecipient -RoleDefinitionId $role.id) + try { + $recipients = @(Get-MtRoleActivationNotificationRecipient -RoleDefinitionId $role.id -ErrorAction Stop) + } catch { + if ($_.ErrorDetails.Message -match '"code"\s*:\s*"AadPremiumLicenseRequired"') { + Add-MtTestResultDetail -SkippedBecause NotLicensedEntraIDP2OrGovernance + return $null + } + throw + } $rolePolicy.activationNotify = $recipients.Count -gt 0 $rolePolicies += $rolePolicy diff --git a/powershell/internal/services/entra/Get-MtRoleActivationNotificationRecipient.ps1 b/powershell/internal/services/entra/Get-MtRoleActivationNotificationRecipient.ps1 index f44b72e249..9588f6d590 100644 --- a/powershell/internal/services/entra/Get-MtRoleActivationNotificationRecipient.ps1 +++ b/powershell/internal/services/entra/Get-MtRoleActivationNotificationRecipient.ps1 @@ -28,7 +28,7 @@ Filter = "scopeId eq '/' and scopeType eq 'DirectoryRole' and roleDefinitionId eq '$RoleDefinitionId'" QueryParameters = @{ expand = 'policy(expand=rules)' } } - $assignment = Invoke-MtGraphRequest @policySplat + $assignment = Invoke-MtGraphRequest @policySplat -ErrorAction Stop $rule = @($assignment.policy.rules) | Where-Object { $_.id -eq 'Notification_Admin_EndUser_Assignment' } | Select-Object -First 1 return [string[]]@($rule.notificationRecipients | Where-Object { $_ }) } diff --git a/powershell/tests/functions/Test-MtCisaAuthenticatorContext.Tests.ps1 b/powershell/tests/functions/Test-MtCisaAuthenticatorContext.Tests.ps1 new file mode 100644 index 0000000000..ec6d939132 --- /dev/null +++ b/powershell/tests/functions/Test-MtCisaAuthenticatorContext.Tests.ps1 @@ -0,0 +1,203 @@ +BeforeAll { + . "$PSScriptRoot/../helpers/Use-MtModuleFunction.ps1" + Use-MtModuleFunction -Name @( + 'Test-MtCisaAuthenticatorContext', + 'Get-MtCisaPhishingResistantPolicy', + 'Test-MtCisaPhishResistant' + ) + + function Get-TestPhishingResistantPolicy { + [pscustomobject]@{ + state = 'enabled' + conditions = [pscustomobject]@{ + applications = [pscustomobject]@{ + includeApplications = @('All') + excludeApplications = @() + } + users = [pscustomobject]@{ + includeUsers = @('All') + excludeUsers = @() + excludeGroups = @() + excludeRoles = @() + excludeGuestsOrExternalUsers = $null + } + } + grantControls = [pscustomobject]@{ + authenticationStrength = [pscustomobject]@{ + id = 'custom' + allowedCombinations = @('fido2', 'windowsHelloForBusiness') + } + } + } + } +} + +Describe 'CISA Microsoft Authenticator context and software OTP' { + BeforeEach { + $script:ResultMarkdown = $null + $script:SkippedBecause = $null + $script:ConditionalAccessPolicies = @() + $script:EmergencyAccessAccounts = @() + $script:AuthenticatorPolicy = [pscustomobject]@{ + id = 'MicrosoftAuthenticator' + state = 'enabled' + includeTargets = @(@{ id = 'all_users' }) + isSoftwareOathEnabled = $false + featureSettings = @{ + displayAppInformationRequiredState = @{ state = 'enabled'; includeTarget = @{ id = 'all_users' } } + displayLocationInformationRequiredState = @{ state = 'enabled'; includeTarget = @{ id = 'all_users' } } + } + } + $script:AuthenticationMethodPolicyConfig = @( + $script:AuthenticatorPolicy + [pscustomobject]@{ id = 'Email'; state = 'enabled' } + ) + Mock -ModuleName Maester Get-MtAuthenticationMethodPolicyConfig { + $script:AuthenticationMethodPolicyConfig + } + Mock -ModuleName Maester Get-MtConditionalAccessPolicy { + $script:ConditionalAccessPolicies + } + Mock -ModuleName Maester Get-MtEmergencyAccessAccount { + param($Account) + @($Account | ForEach-Object { [pscustomobject]@{ ObjectId = $_.Id } }) + } + Mock -ModuleName Maester Add-MtTestResultDetail { + param($Result, $SkippedBecause) + $script:ResultMarkdown = $Result + $script:SkippedBecause = $SkippedBecause + } + } + + It 'skips when the Microsoft Authenticator policy is disabled' { + $script:AuthenticatorPolicy.state = 'disabled' + + Test-MtCisaAuthenticatorContext | Should -BeNull + $script:SkippedBecause | Should -Be 'NotApplicable' + } + + It 'skips when no Microsoft Authenticator policy is returned' { + $script:AuthenticationMethodPolicyConfig = @( + [pscustomobject]@{ id = 'Email'; state = 'enabled' } + ) + + Test-MtCisaAuthenticatorContext | Should -BeNull + $script:SkippedBecause | Should -Be 'NotApplicable' + } + + It 'errors when no authentication method configurations are returned' { + $script:AuthenticationMethodPolicyConfig = @() + + { Test-MtCisaAuthenticatorContext } | Should -Throw '*No authentication method configurations were returned*' + $script:SkippedBecause | Should -BeNullOrEmpty + } + + It 'skips when ScubaGear would mark phishing-resistant MFA as enforced' { + $script:ConditionalAccessPolicies = @(Get-TestPhishingResistantPolicy) + + Test-MtCisaAuthenticatorContext | Should -BeNull + $script:SkippedBecause | Should -Be 'NotApplicable' + Get-MtCisaPhishingResistantPolicy | Should -HaveCount 1 + Test-MtCisaPhishResistant | Should -BeTrue + } + + It 'allows phishing-resistant policies that exclude configured emergency access accounts' { + $policy = Get-TestPhishingResistantPolicy + $policy.conditions.users.excludeUsers = @('emergency-user') + $policy.conditions.users.excludeGroups = @('emergency-group') + $script:ConditionalAccessPolicies = @($policy) + $script:EmergencyAccessAccounts = @( + [pscustomobject]@{ Id = 'emergency-user'; Type = 'user' } + [pscustomobject]@{ Id = 'emergency-group'; Type = 'group' } + ) + + Test-MtCisaAuthenticatorContext -EmergencyAccessAccounts $script:EmergencyAccessAccounts | Should -BeNull + $script:SkippedBecause | Should -Be 'NotApplicable' + Get-MtCisaPhishingResistantPolicy -EmergencyAccessAccounts $script:EmergencyAccessAccounts | Should -HaveCount 1 + Test-MtCisaPhishResistant -EmergencyAccessAccounts $script:EmergencyAccessAccounts | Should -BeTrue + } + + It 'does not allow additional user exclusions beyond configured emergency access accounts' { + $policy = Get-TestPhishingResistantPolicy + $policy.conditions.users.excludeUsers = @('emergency-user', 'other-user') + $script:ConditionalAccessPolicies = @($policy) + $script:EmergencyAccessAccounts = @([pscustomobject]@{ Id = 'emergency-user'; Type = 'user' }) + + Test-MtCisaAuthenticatorContext -EmergencyAccessAccounts $script:EmergencyAccessAccounts | Should -BeTrue + $script:SkippedBecause | Should -BeNullOrEmpty + Get-MtCisaPhishingResistantPolicy -EmergencyAccessAccounts $script:EmergencyAccessAccounts | Should -BeNullOrEmpty + } + + It 'does not skip when a phishing-resistant policy has role exclusions' { + $policy = Get-TestPhishingResistantPolicy + $policy.conditions.users.excludeRoles = @('Global Administrator') + $script:ConditionalAccessPolicies = @($policy) + + Test-MtCisaAuthenticatorContext | Should -BeTrue + $script:SkippedBecause | Should -BeNullOrEmpty + Get-MtCisaPhishingResistantPolicy | Should -BeNullOrEmpty + } + + It 'does not skip when a phishing-resistant policy excludes users, groups, apps, or guests' { + $policy = Get-TestPhishingResistantPolicy + $policy.conditions.users.excludeUsers = @('user-id') + $policy.conditions.users.excludeGroups = @('group-id') + $policy.conditions.applications.excludeApplications = @('app-id') + $policy.conditions.users.excludeGuestsOrExternalUsers = [pscustomobject]@{ + guestOrExternalUserTypes = 'b2bCollaborationGuest' + } + $script:ConditionalAccessPolicies = @($policy) + + Test-MtCisaAuthenticatorContext | Should -BeTrue + $script:SkippedBecause | Should -BeNullOrEmpty + Get-MtCisaPhishingResistantPolicy | Should -BeNullOrEmpty + } + + It 'does not skip when an authentication strength allows a non-phishing-resistant method' { + $policy = Get-TestPhishingResistantPolicy + $policy.grantControls.authenticationStrength.allowedCombinations = @('fido2', 'password,sms') + $script:ConditionalAccessPolicies = @($policy) + + Test-MtCisaAuthenticatorContext | Should -BeTrue + $script:SkippedBecause | Should -BeNullOrEmpty + Get-MtCisaPhishingResistantPolicy | Should -BeNullOrEmpty + } + + It 'does not skip when a phishing-resistant policy does not include all users' { + $policy = Get-TestPhishingResistantPolicy + $policy.conditions.users.includeUsers = @('group-id') + $script:ConditionalAccessPolicies = @($policy) + + Test-MtCisaAuthenticatorContext | Should -BeTrue + $script:SkippedBecause | Should -BeNullOrEmpty + Get-MtCisaPhishingResistantPolicy | Should -BeNullOrEmpty + } + + It 'passes with Authenticator software OTP disabled even when Email OTP is enabled' { + Test-MtCisaAuthenticatorContext | Should -BeTrue + $script:ResultMarkdown | Should -Match 'software OTP \(not Email OTP\) disabled' + } + + It 'fails with Authenticator software OTP enabled despite both context settings being enabled' { + $script:AuthenticatorPolicy.isSoftwareOathEnabled = $true + + Test-MtCisaAuthenticatorContext | Should -BeFalse + $script:ResultMarkdown | Should -Match '\| Microsoft Authenticator software OTP \(not Email OTP\) disabled \| ❌ Fail \|' + } + + It 'does not label missing Authenticator software OTP data as passing' { + $script:AuthenticatorPolicy.isSoftwareOathEnabled = $null + + Test-MtCisaAuthenticatorContext | Should -BeFalse + $script:ResultMarkdown | Should -Match '\| Microsoft Authenticator software OTP \(not Email OTP\) disabled \| ❌ Fail \|' + } + + It 'still fails when application or location context is disabled' -ForEach @( + @{ Setting = 'displayAppInformationRequiredState' } + @{ Setting = 'displayLocationInformationRequiredState' } + ) { + $script:AuthenticatorPolicy.featureSettings[$Setting].state = 'disabled' + + Test-MtCisaAuthenticatorContext | Should -BeFalse + } +} diff --git a/powershell/tests/functions/Test-MtCisaDeprecatedExchange.Tests.ps1 b/powershell/tests/functions/Test-MtCisaDeprecatedExchange.Tests.ps1 new file mode 100644 index 0000000000..49e54e6e49 --- /dev/null +++ b/powershell/tests/functions/Test-MtCisaDeprecatedExchange.Tests.ps1 @@ -0,0 +1,34 @@ +BeforeAll { + . "$PSScriptRoot/../helpers/Use-MtModuleFunction.ps1" + Use-MtModuleFunction -Name @( + 'Test-MtCisaDlpAlternate', + 'Test-MtCheckCISAMSEXO92', + 'Test-MtCisaEmailFilterAlternative', + 'Test-MtCisaMailboxIntelligence' + ) +} + +Describe 'Deprecated CISA Exchange checks' { + BeforeEach { + $script:SkippedBecause = $null + $script:SkippedCustomReason = $null + + Mock -ModuleName Maester Add-MtTestResultDetail { + param($SkippedBecause, $SkippedCustomReason) + + $script:SkippedBecause = $SkippedBecause + $script:SkippedCustomReason = $SkippedCustomReason + } + } + + It ' skips the retired control' -ForEach @( + @{ CheckName = 'Test-MtCisaDlpAlternate' } + @{ CheckName = 'Test-MtCheckCISAMSEXO92' } + @{ CheckName = 'Test-MtCisaEmailFilterAlternative' } + @{ CheckName = 'Test-MtCisaMailboxIntelligence' } + ) { + & $CheckName | Should -BeNull + $script:SkippedBecause | Should -Be 'Custom' + $script:SkippedCustomReason | Should -Match 'removed' + } +} diff --git a/powershell/tests/functions/Test-MtCisaPimLicense.Tests.ps1 b/powershell/tests/functions/Test-MtCisaPimLicense.Tests.ps1 new file mode 100644 index 0000000000..6ae5387a86 --- /dev/null +++ b/powershell/tests/functions/Test-MtCisaPimLicense.Tests.ps1 @@ -0,0 +1,182 @@ +BeforeAll { + . "$PSScriptRoot/../helpers/Use-MtModuleFunction.ps1" + Use-MtModuleFunction -Name @( + 'Test-MtCisaPermanentRoleAssignment', + 'Test-MtCisaUnmanagedRoleAssignment', + 'Test-MtCisaRequireActivationApproval', + 'Test-MtCisaAssignmentNotification', + 'Test-MtCheckCISAMSAAD78', + 'Test-MtCheckCISAMSAAD79' + ) + + function Get-TestPimErrorRecord { + param([string] $Code) + + $record = [System.Management.Automation.ErrorRecord]::new( + [System.Exception]::new('Response status code does not indicate success: 400 (Bad Request).'), + 'InvokeGraphHttpResponseException', + [System.Management.Automation.ErrorCategory]::InvalidOperation, + $null + ) + $record.ErrorDetails = [System.Management.Automation.ErrorDetails]::new( + "{`"error`":{`"code`":`"$Code`",`"message`":`"PIM request rejected.`"}}" + ) + return $record + } +} + +Describe 'CISA PIM API licence rejection: ' -ForEach @( + @{ CheckName = 'Test-MtCisaPermanentRoleAssignment' } + @{ CheckName = 'Test-MtCisaUnmanagedRoleAssignment' } + @{ CheckName = 'Test-MtCisaRequireActivationApproval' } + @{ CheckName = 'Test-MtCisaAssignmentNotification' } + @{ CheckName = 'Test-MtCheckCISAMSAAD78' } + @{ CheckName = 'Test-MtCheckCISAMSAAD79' } +) { + BeforeEach { + $script:SkippedBecause = $null + $script:Compliant = $true + Mock -ModuleName Maester Get-MtLicenseInformation { 'P2' } + Mock -ModuleName Maester Get-MtRole { + @( + [pscustomobject]@{ id = '62e90394-69f5-4237-9190-012177145e10'; displayName = 'Global Administrator' } + [pscustomobject]@{ id = '194ae4cb-b126-40b2-bd5b-6091b380977d'; displayName = 'Security Administrator' } + ) + } + Mock -ModuleName Maester Add-MtTestResultDetail { + param($SkippedBecause) + $script:SkippedBecause = $SkippedBecause + } + Mock -ModuleName Maester Invoke-MtGraphRequest { + if ($RelativeUri -eq 'roleManagement/directory/roleAssignmentSchedules') { + return [pscustomobject]@{ + createdUsing = if ($script:Compliant) { 'request-1' } else { $null } + scheduleInfo = @{ + startDateTime = if ($script:Compliant) { '2026-01-01T00:00:00Z' } else { $null } + expiration = @{ type = if ($script:Compliant) { 'afterDateTime' } else { 'noExpiration' } } + } + principal = [pscustomobject]@{ + id = 'user-1' + displayName = 'Test user' + '@odata.type' = '#microsoft.graph.user' + } + } + } + return [pscustomobject]@{ + policy = @{ + rules = @( + [pscustomobject]@{ + '@odata.type' = '#microsoft.graph.unifiedRoleManagementPolicyApprovalRule' + setting = @{ isApprovalRequired = $script:Compliant } + } + foreach ($id in @( + 'Notification_Admin_Admin_Eligibility', + 'Notification_Admin_Admin_Assignment', + 'Notification_Admin_EndUser_Assignment' + )) { + [pscustomobject]@{ + id = $id + notificationRecipients = if ($script:Compliant) { @('monitor@example.com') } else { @() } + } + } + ) + } + } + } + } + + It 'skips instead of returning a verdict when the API rejects the licence' { + Mock -ModuleName Maester Invoke-MtGraphRequest { + throw (Get-TestPimErrorRecord -Code 'AadPremiumLicenseRequired') + } + + & $CheckName | Should -BeNullOrEmpty + $script:SkippedBecause | Should -Be 'NotLicensedEntraIDP2OrGovernance' + Should -Invoke Invoke-MtGraphRequest -ModuleName Maester -Exactly 1 + } + + It 'requests terminating API errors before interpreting PIM data' { + Mock -ModuleName Maester Invoke-MtGraphRequest { + param($ErrorAction) + + Write-Error -ErrorRecord (Get-TestPimErrorRecord -Code 'AadPremiumLicenseRequired') -ErrorAction $ErrorAction + } + + & $CheckName | Should -BeNullOrEmpty + $script:SkippedBecause | Should -Be 'NotLicensedEntraIDP2OrGovernance' + Should -Invoke Invoke-MtGraphRequest -ModuleName Maester -Exactly 1 -ParameterFilter { $ErrorAction -eq 'Stop' } + } + + It 'propagates instead of treating it as a licence skip' -ForEach @( + @{ Code = 'Authorization_RequestDenied' } + @{ Code = 'InternalServerError' } + ) { + Mock -ModuleName Maester Invoke-MtGraphRequest { + throw (Get-TestPimErrorRecord -Code $Code) + } + + { & $CheckName } | Should -Throw -ErrorId 'InvokeGraphHttpResponseException' + $script:SkippedBecause | Should -BeNullOrEmpty + } + + It 'preserves a passing verdict for compliant PIM data' { + & $CheckName | Should -BeTrue + $script:SkippedBecause | Should -BeNullOrEmpty + } + + It 'preserves a failing verdict for noncompliant PIM data' { + $script:Compliant = $false + + & $CheckName | Should -BeFalse + $script:SkippedBecause | Should -BeNullOrEmpty + } +} + +Describe 'CISA PIM native-engine outcome: ' -ForEach @( + @{ Id = 'CISA.MS.AAD.7.4' } + @{ Id = 'CISA.MS.AAD.7.5' } + @{ Id = 'CISA.MS.AAD.7.6' } + @{ Id = 'CISA.MS.AAD.7.7' } + @{ Id = 'CISA.MS.AAD.7.8' } + @{ Id = 'CISA.MS.AAD.7.9' } +) { + BeforeEach { + Mock -ModuleName Maester Test-MtConnection { $true } + Mock -ModuleName Maester Get-MgContext { $null } + Mock -ModuleName Maester Get-MtLicenseInformation { 'P2' } + Mock -ModuleName Maester Get-MtRole { + @( + [pscustomobject]@{ id = '62e90394-69f5-4237-9190-012177145e10'; displayName = 'Global Administrator' } + [pscustomobject]@{ id = '194ae4cb-b126-40b2-bd5b-6091b380977d'; displayName = 'Security Administrator' } + ) + } + $script:PimConfig = [pscustomobject]@{ + Environment = [pscustomobject]@{ + Licenses = @('AAD_PREMIUM_P2') + Services = [pscustomobject]@{ Graph = $true } + } + } + } + + It 'reports a licence rejection as Skipped, not Passed, Failed or Error' { + Mock -ModuleName Maester Invoke-MtGraphRequest { + throw (Get-TestPimErrorRecord -Code 'AadPremiumLicenseRequired') + } + + $row = Invoke-MtTest -Id $Id -Config $script:PimConfig + + $row.Result | Should -Be 'Skipped' + $row.ResultDetail.TestSkipped | Should -Be 'NotLicensedEntraIDP2OrGovernance' + } + + It 'reports permission failures as Error, not a licence skip' { + Mock -ModuleName Maester Invoke-MtGraphRequest { + throw (Get-TestPimErrorRecord -Code 'Authorization_RequestDenied') + } + + $row = Invoke-MtTest -Id $Id -Config $script:PimConfig + + $row.Result | Should -Be 'Error' + $row.ReasonCode | Should -Be 'TestError' + } +} diff --git a/powershell/tests/functions/Test-MtCisaSpfDirective.Tests.ps1 b/powershell/tests/functions/Test-MtCisaSpfDirective.Tests.ps1 index 73f6296119..dd25d4afcd 100644 --- a/powershell/tests/functions/Test-MtCisaSpfDirective.Tests.ps1 +++ b/powershell/tests/functions/Test-MtCisaSpfDirective.Tests.ps1 @@ -3,31 +3,46 @@ # Check functions that became native tests are not exported. Use-MtModuleFunction -Name Test-MtCisaSpfDirective - function New-TestSpfRecord { - [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Test helper that only builds test data.')] + function Get-TestSpfRecord { param( - [string]$DomainName, - # The SPF record, or the text the lookup returns when it finds none. - [string]$Record + [string] $DomainName = 'example.gov', + [string] $Record, + [string] $Mechanism = '', + [string] $Qualifier = '?', + [string] $Modifier = '' ) - $spfRecord = $Record + $spfRecord = $null $spfLookups = @() - if ($Record -like 'v=spf1*') { - $terms = foreach ($term in ($Record -split '\s+' | Select-Object -Skip 1)) { - $isAll = $term -match '^(?[-~?+]?)all$' - [pscustomobject]@{ - directive = $term - qualifier = if ($isAll) { $Matches.qualifier } else { '' } - mechanism = if ($isAll) { 'all' } elseif ($term -like 'include:*') { 'include' } else { '' } - mechanismTarget = if ($term -like 'include:*') { $term.Substring(8) } else { '' } - modifier = if ($term -like 'redirect=*') { 'redirect' } else { '' } + if ($PSBoundParameters.ContainsKey('Record')) { + $spfRecord = $Record + if ($Record -like 'v=spf1*') { + $terms = foreach ($term in ($Record -split '\s+' | Select-Object -Skip 1)) { + $isAll = $term -match '^(?[-~?+]?)all$' + [pscustomobject]@{ + directive = $term + qualifier = if ($isAll) { $Matches.qualifier } else { '' } + mechanism = if ($isAll) { 'all' } elseif ($term -like 'include:*') { 'include' } else { '' } + mechanismTarget = if ($term -like 'include:*') { $term.Substring(8) } else { '' } + modifier = if ($term -like 'redirect=*') { 'redirect' } else { '' } + } } + $spfRecord = [pscustomobject]@{ record = $Record; terms = @($terms) } + $spfLookups = @($terms | Where-Object { $_.mechanism -eq 'include' } | ForEach-Object { + [pscustomobject]@{ SPFSourceDomain = $_.mechanismTarget; Include = $true } + }) } - $spfRecord = [pscustomobject]@{ record = $Record; terms = @($terms) } - $spfLookups = @($terms | Where-Object { $_.mechanism -eq 'include' } | ForEach-Object { - [pscustomobject]@{ SPFSourceDomain = $_.mechanismTarget; Include = $true } - }) + } else { + $terms = @( + [pscustomobject]@{ + directive = if ($Modifier) { "$Modifier=example.gov" } else { "$Qualifier$Mechanism" } + qualifier = $Qualifier + mechanism = $Mechanism + mechanismTarget = '' + modifier = $Modifier + } + ) + $spfRecord = [pscustomobject]@{ terms = $terms } } return [pscustomobject]@{ @@ -38,24 +53,114 @@ } } +Describe 'Test-MtCisaSpfDirective' { + BeforeEach { + $script:TestSpfRecord = $null + $script:TestResultMarkdown = $null + $script:SkippedBecause = $null + $script:AcceptedDomains = @( + [pscustomobject]@{ + DomainName = 'example.gov' + SendingFromDomainDisabled = $false + IsCoexistenceDomain = $false + } + ) + + Mock -ModuleName Maester Get-MtExo { + return $script:AcceptedDomains + } + Mock -ModuleName Maester Get-MailAuthenticationRecord { return $script:TestSpfRecord } + Mock -ModuleName Maester Add-MtTestResultDetail { + param($Result, $SkippedBecause) + + $script:TestResultMarkdown = $Result + $script:SkippedBecause = $SkippedBecause + } + } + + It 'fails rather than skipping when accepted-domain retrieval returns