diff --git a/powershell/Maester.psm1 b/powershell/Maester.psm1 index ff65045908..df4bbbe243 100644 --- a/powershell/Maester.psm1 +++ b/powershell/Maester.psm1 @@ -33,6 +33,10 @@ $__MtSession = @{ SpoCache = @{} # Cache for SharePoint Online tenant settings retrieved via PnP FabricCache = @{} # Fabric admin API data cached for the current test run GitHubCache = @{} # Per-session REST response cache; cleared each Invoke-Maester run + TeamsCache = @{} # Teams admin API data cached for the current test run + TeamsAuthCache = @{} # Teams unified settings MSAL client; retained until disconnect + TeamsUseDeviceCode = $false # Whether Connect-Maester requested device-code authentication + TeamsEnvironmentName = $null # Explicit Teams PowerShell environment, when provided ADCache = @{} # Active Directory data cache ADConnection = $null # Active Directory connection state ADCredential = $null # Active Directory credential retained only for the connected session diff --git a/powershell/internal/checks/cisa/teams/Get-MtCisaTeamsFederationConfigurations.ps1 b/powershell/internal/checks/cisa/teams/Get-MtCisaTeamsFederationConfigurations.ps1 new file mode 100644 index 0000000000..4e7d7a303c --- /dev/null +++ b/powershell/internal/checks/cisa/teams/Get-MtCisaTeamsFederationConfigurations.ps1 @@ -0,0 +1,16 @@ +function Get-MtCisaTeamsFederationConfigurations { + [CmdletBinding()] + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification = 'Teams can return multiple federation configurations.')] + [OutputType([object[]])] + param() + + if (-not $__MtSession.TeamsCache.ContainsKey('FederationConfigurations')) { + $__MtSession.TeamsCache['FederationConfigurations'] = @(Get-CsTenantFederationConfiguration -ErrorAction Stop) + } + + $configurations = @($__MtSession.TeamsCache['FederationConfigurations']) + if ($configurations.Count -eq 0) { + throw 'Teams returned no tenant federation configurations.' + } + return $configurations +} diff --git a/powershell/internal/checks/cisa/teams/Get-MtCisaTeamsGlobalMeetingBroadcastPolicy.ps1 b/powershell/internal/checks/cisa/teams/Get-MtCisaTeamsGlobalMeetingBroadcastPolicy.ps1 new file mode 100644 index 0000000000..d6f11a6ac7 --- /dev/null +++ b/powershell/internal/checks/cisa/teams/Get-MtCisaTeamsGlobalMeetingBroadcastPolicy.ps1 @@ -0,0 +1,16 @@ +function Get-MtCisaTeamsGlobalMeetingBroadcastPolicy { + [CmdletBinding()] + [OutputType([object])] + param() + + $cacheKey = 'GlobalMeetingBroadcastPolicy' + if (-not $__MtSession.TeamsCache.ContainsKey($cacheKey)) { + $policies = @(Get-CsTeamsMeetingBroadcastPolicy -Identity Global -ErrorAction Stop) + if ($policies.Count -ne 1 -or $policies[0].Identity -ne 'Global') { + throw 'Teams did not return exactly one Global meeting broadcast policy.' + } + $__MtSession.TeamsCache[$cacheKey] = $policies[0] + } + + return $__MtSession.TeamsCache[$cacheKey] +} diff --git a/powershell/internal/checks/cisa/teams/Get-MtCisaTeamsGlobalMeetingPolicy.ps1 b/powershell/internal/checks/cisa/teams/Get-MtCisaTeamsGlobalMeetingPolicy.ps1 new file mode 100644 index 0000000000..92418cbfaa --- /dev/null +++ b/powershell/internal/checks/cisa/teams/Get-MtCisaTeamsGlobalMeetingPolicy.ps1 @@ -0,0 +1,7 @@ +function Get-MtCisaTeamsGlobalMeetingPolicy { + [CmdletBinding()] + param() + + $policies = Get-MtCisaTeamsMeetingPolicies -GlobalOnly + return $policies[0] +} diff --git a/powershell/internal/checks/cisa/teams/Get-MtCisaTeamsMeetingPolicies.ps1 b/powershell/internal/checks/cisa/teams/Get-MtCisaTeamsMeetingPolicies.ps1 new file mode 100644 index 0000000000..f419ef8d33 --- /dev/null +++ b/powershell/internal/checks/cisa/teams/Get-MtCisaTeamsMeetingPolicies.ps1 @@ -0,0 +1,29 @@ +function Get-MtCisaTeamsMeetingPolicies { + [CmdletBinding()] + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification = 'The Teams cmdlet returns a collection of meeting policies.')] + [OutputType([object[]])] + param( + [switch]$GlobalOnly + ) + + if (-not $__MtSession.TeamsCache.ContainsKey('MeetingPolicies')) { + $__MtSession.TeamsCache['MeetingPolicies'] = @(Get-CsTeamsMeetingPolicy -ErrorAction Stop) + } + + $allPolicies = @($__MtSession.TeamsCache['MeetingPolicies']) + if ($allPolicies.Count -eq 0) { + throw 'Teams returned no meeting policies.' + } + + $policies = if ($GlobalOnly) { + @($allPolicies | Where-Object { $_.Identity -eq 'Global' }) + } else { + $allPolicies + } + + if ($GlobalOnly -and ($policies.Count -ne 1 -or $policies[0].Identity -ne 'Global')) { + throw 'Teams did not return exactly one Global meeting policy.' + } + + return $policies +} diff --git a/powershell/internal/checks/cisa/teams/Test-MtCisaTeamsAppControl.ps1 b/powershell/internal/checks/cisa/teams/Test-MtCisaTeamsAppControl.ps1 new file mode 100644 index 0000000000..3157691929 --- /dev/null +++ b/powershell/internal/checks/cisa/teams/Test-MtCisaTeamsAppControl.ps1 @@ -0,0 +1,64 @@ +function Test-MtCisaTeamsAppControl { + [CmdletBinding()] + [OutputType([bool])] + param( + [Parameter(Mandatory)] + [ValidateSet('DefaultApp', 'GlobalApp', 'PrivateApp')] + [string]$SettingName, + [Parameter(Mandatory)] + [string]$AppType + ) + + $settings = @(Get-MtTeamsUnifiedTenantSettings) + $setting = $settings | Where-Object { $_.SettingName -eq $SettingName } | Select-Object -First 1 + $policyProperty = switch ($SettingName) { + 'DefaultApp' { 'DefaultCatalogAppsType' } + 'GlobalApp' { 'GlobalCatalogAppsType' } + 'PrivateApp' { 'PrivateCatalogAppsType' } + } + + $rows = @() + if ($setting) { + $value = [string]$setting.SettingValue + $passed = $value -eq 'None' + $rows += [pscustomobject]@{ + Policy = 'Org-wide setting' + Value = $value + Pass = $passed + } + } else { + if (-not $__MtSession.TeamsCache.ContainsKey('AppPermissionPolicies')) { + $__MtSession.TeamsCache['AppPermissionPolicies'] = @(Get-CsTeamsAppPermissionPolicy -ErrorAction Stop) + } + $policies = @($__MtSession.TeamsCache['AppPermissionPolicies']) + if ($policies.Count -eq 0) { + throw 'Teams returned no app permission policies.' + } + + $rows = foreach ($policy in $policies) { + $type = $policy.PSObject.Properties[$policyProperty] + if ($null -eq $type -or $type.Value -notin @('AllowedAppList', 'BlockedAppList')) { + throw "Teams app permission policy '$($policy.Identity)' did not return a supported value for $policyProperty." + } + + [pscustomobject]@{ + Policy = $policy.Identity + Value = $type.Value + Pass = $type.Value -eq 'AllowedAppList' + } + } + $passed = @($rows | Where-Object { -not $_.Pass }).Count -eq 0 + } + + $markdown = if ($passed) { + "Well done. $AppType apps are restricted to the approved set.`n`n" + } else { + "$AppType apps are not restricted to the approved set.`n`n" + } + $markdown += "| Policy or setting | Value | Result |`n| --- | --- | --- |`n" + foreach ($row in $rows) { + $markdown += "| $($row.Policy) | $($row.Value) | $(if ($row.Pass) { 'Pass' } else { 'Fail' }) |`n" + } + Add-MtTestResultDetail -Result $markdown.TrimEnd() + return $passed +} diff --git a/powershell/internal/checks/cisa/teams/Test-MtCisaTeamsIsUSGovernment.ps1 b/powershell/internal/checks/cisa/teams/Test-MtCisaTeamsIsUSGovernment.ps1 new file mode 100644 index 0000000000..0c4c74d2e9 --- /dev/null +++ b/powershell/internal/checks/cisa/teams/Test-MtCisaTeamsIsUSGovernment.ps1 @@ -0,0 +1,12 @@ +function Test-MtCisaTeamsIsUSGovernment { + [CmdletBinding()] + [OutputType([bool])] + param() + + $context = Get-MgContext -ErrorAction Stop + if (-not $context) { + throw 'A Microsoft Graph context is required to determine the Teams environment.' + } + return ($context.Environment -in @('USGov', 'USGovDoD') -or + $__MtSession.TeamsEnvironmentName -in @('TeamsGCCH', 'TeamsDOD')) +} diff --git a/powershell/internal/checks/cisa/teams/Test-MtCisaTeamsMeetingPolicyBoolean.ps1 b/powershell/internal/checks/cisa/teams/Test-MtCisaTeamsMeetingPolicyBoolean.ps1 new file mode 100644 index 0000000000..10472f7ec3 --- /dev/null +++ b/powershell/internal/checks/cisa/teams/Test-MtCisaTeamsMeetingPolicyBoolean.ps1 @@ -0,0 +1,39 @@ +function Test-MtCisaTeamsMeetingPolicyBoolean { + [CmdletBinding()] + [OutputType([bool])] + param( + [Parameter(Mandatory)] + [string]$SettingName, + [Parameter(Mandatory)] + [bool]$ExpectedValue, + [Parameter(Mandatory)] + [string]$PolicyDescription + ) + + $policies = Get-MtCisaTeamsMeetingPolicies + $results = foreach ($policy in $policies) { + $setting = $policy.PSObject.Properties[$SettingName] + if ($null -eq $setting -or $setting.Value -isnot [bool]) { + throw "Teams meeting policy '$($policy.Identity)' did not return a Boolean value for $SettingName." + } + + [pscustomobject]@{ + Policy = $policy.Identity + Value = $setting.Value + Pass = $setting.Value -eq $ExpectedValue + } + } + + $passed = @($results | Where-Object { -not $_.Pass }).Count -eq 0 + $markdown = if ($passed) { + "Well done. $PolicyDescription is configured for every meeting policy.`n`n" + } else { + "$PolicyDescription is not configured for every meeting policy.`n`n" + } + $markdown += "| Policy | $SettingName | Result |`n| --- | --- | --- |`n" + foreach ($row in $results) { + $markdown += "| $($row.Policy) | $($row.Value) | $(if ($row.Pass) { 'Pass' } else { 'Fail' }) |`n" + } + Add-MtTestResultDetail -Result $markdown.TrimEnd() + return $passed +} diff --git a/powershell/internal/services/teams/Get-MtTeamsUnifiedSettingsAccessToken.ps1 b/powershell/internal/services/teams/Get-MtTeamsUnifiedSettingsAccessToken.ps1 new file mode 100644 index 0000000000..be9e1a38f0 --- /dev/null +++ b/powershell/internal/services/teams/Get-MtTeamsUnifiedSettingsAccessToken.ps1 @@ -0,0 +1,86 @@ +function Get-MtTeamsUnifiedSettingsAccessToken { + [CmdletBinding()] + param( + [Parameter(Mandatory)] + [object]$Context + ) + + $tenantId = [string]$Context.TenantId + $clientId = '12128f48-ec9e-42f0-b203-ea49fb6af367' + [string[]]$scope = @('08ff1ce2-4973-4b08-86a3-ebed13badc7f/.default') + $authority = "https://login.microsoftonline.com/$tenantId" + $cacheKey = "$tenantId|$($Context.Environment)" + + if (-not ('Microsoft.Identity.Client.PublicClientApplicationBuilder' -as [type])) { + $authenticationModule = Get-Module Microsoft.Graph.Authentication | Sort-Object Version -Descending | Select-Object -First 1 + if (-not $authenticationModule) { + throw 'Microsoft.Graph.Authentication must be loaded before acquiring a Teams unified settings token.' + } + + $dependencyFolder = if ($PSVersionTable.PSEdition -eq 'Core') { 'Core' } else { 'Desktop' } + $msalPath = Join-Path $authenticationModule.ModuleBase "Dependencies\$dependencyFolder\Microsoft.Identity.Client.dll" + if (-not (Test-Path -LiteralPath $msalPath)) { + throw "Microsoft.Identity.Client.dll was not found at '$msalPath'." + } + $null = Add-Type -Path $msalPath -ErrorAction Stop + } + + if (-not $__MtSession.TeamsAuthCache.ContainsKey('Clients')) { + $__MtSession.TeamsAuthCache['Clients'] = @{} + } + + $clients = $__MtSession.TeamsAuthCache['Clients'] + if (-not $clients.ContainsKey($cacheKey)) { + $clients[$cacheKey] = [Microsoft.Identity.Client.PublicClientApplicationBuilder]::Create($clientId). + WithAuthority($authority). + WithRedirectUri('http://localhost'). + Build() + } + $application = $clients[$cacheKey] + + $accounts = @($application.GetAccountsAsync().GetAwaiter().GetResult()) + $account = $null + if ($Context.Account) { + $account = $accounts | Where-Object { $_.Username -eq [string]$Context.Account } | Select-Object -First 1 + } + + $result = $null + if ($account) { + try { + $result = $application.AcquireTokenSilent($scope, $account).ExecuteAsync().GetAwaiter().GetResult() + } catch [Microsoft.Identity.Client.MsalUiRequiredException] { + Write-Verbose 'Silent token acquisition requires user interaction.' + } + } + + if (-not $result -and $__MtSession.TeamsUseDeviceCode) { + $deviceCodeType = 'Microsoft.Identity.Client.DeviceCodeResult' -as [type] + if (-not $deviceCodeType) { + throw 'Microsoft.Identity.Client.DeviceCodeResult is unavailable for Teams device-code authentication.' + } + + $messageSource = [System.Threading.Tasks.TaskCompletionSource[string]]::new([System.Threading.Tasks.TaskCreationOptions]::RunContinuationsAsynchronously) + $deviceCodeCallback = Get-MtTeamsUnifiedSettingsDeviceCodeCallback -DeviceCodeType $deviceCodeType -MessageSource $messageSource + $tokenTask = $application.AcquireTokenWithDeviceCode($scope, $deviceCodeCallback).ExecuteAsync() + $waitTask = [System.Threading.Tasks.Task]::WhenAny( + [System.Threading.Tasks.Task[]]@($tokenTask, $messageSource.Task) + ) + $null = $waitTask.GetAwaiter().GetResult() + if ($messageSource.Task.IsCompleted) { + Write-MtHostLine ($messageSource.Task.GetAwaiter().GetResult()) + } + $result = $tokenTask.GetAwaiter().GetResult() + } elseif (-not $result) { + $interactiveRequest = $application.AcquireTokenInteractive($scope).WithUseEmbeddedWebView($false) + if ($Context.Account) { + $interactiveRequest = $interactiveRequest.WithLoginHint([string]$Context.Account) + } + $result = $interactiveRequest.ExecuteAsync().GetAwaiter().GetResult() + } + + if (-not $result -or [string]::IsNullOrWhiteSpace($result.AccessToken)) { + throw 'Microsoft identity platform returned no access token for Teams unified app settings.' + } + + return $result.AccessToken +} diff --git a/powershell/internal/services/teams/Get-MtTeamsUnifiedSettingsDeviceCodeCallback.ps1 b/powershell/internal/services/teams/Get-MtTeamsUnifiedSettingsDeviceCodeCallback.ps1 new file mode 100644 index 0000000000..cdf369c2d2 --- /dev/null +++ b/powershell/internal/services/teams/Get-MtTeamsUnifiedSettingsDeviceCodeCallback.ps1 @@ -0,0 +1,39 @@ +function Get-MtTeamsUnifiedSettingsDeviceCodeCallback { + [CmdletBinding()] + [OutputType([System.Delegate])] + param( + [Parameter(Mandatory)] + [type]$DeviceCodeType, + [Parameter(Mandatory)] + [System.Threading.Tasks.TaskCompletionSource[string]]$MessageSource + ) + + $callbackFactoryType = 'MaesterTeamsDeviceCodeCallbackFactory' -as [type] + if (-not $callbackFactoryType) { + $callbackFactorySource = @' +using System; +using System.Linq.Expressions; +using System.Threading.Tasks; + +public static class MaesterTeamsDeviceCodeCallbackFactory +{ + public static Delegate Create(Type deviceCodeType, TaskCompletionSource messageSource) + { + var deviceCode = Expression.Parameter(deviceCodeType, "deviceCode"); + var message = Expression.Property(deviceCode, "Message"); + var trySetResult = typeof(TaskCompletionSource).GetMethod("TrySetResult", new[] { typeof(string) }); + var captureMessage = Expression.Call(Expression.Constant(messageSource), trySetResult, message); + var completedTask = Expression.Property(null, typeof(Task).GetProperty("CompletedTask")); + var callbackBody = Expression.Block(captureMessage, completedTask); + var callbackType = typeof(Func<,>).MakeGenericType(deviceCodeType, typeof(Task)); + return Expression.Lambda(callbackType, callbackBody, deviceCode).Compile(); + } +} +'@ + $null = Add-Type -TypeDefinition $callbackFactorySource -ErrorAction Stop + $callbackFactoryType = 'MaesterTeamsDeviceCodeCallbackFactory' -as [type] + } + + $createMethod = $callbackFactoryType.GetMethod('Create') + return $createMethod.Invoke($null, @($DeviceCodeType, $MessageSource)) +} diff --git a/powershell/internal/services/teams/Get-MtTeamsUnifiedTenantSettings.ps1 b/powershell/internal/services/teams/Get-MtTeamsUnifiedTenantSettings.ps1 new file mode 100644 index 0000000000..3f1b53729d --- /dev/null +++ b/powershell/internal/services/teams/Get-MtTeamsUnifiedTenantSettings.ps1 @@ -0,0 +1,56 @@ +function Get-MtTeamsUnifiedTenantSettings { + [CmdletBinding()] + [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseSingularNouns', '', Justification = 'The Teams API returns a collection of settings.')] + param() + + $context = Get-MgContext -ErrorAction Stop + if (-not $context) { + throw 'A Microsoft Graph context is required to retrieve Teams unified app settings.' + } + + $tenantId = [string]$context.TenantId + if ([string]::IsNullOrWhiteSpace($tenantId)) { + throw 'The Microsoft Graph context does not include a tenant ID.' + } + + if (($context.Environment -and $context.Environment -ne 'Global') -or + $__MtSession.TeamsEnvironmentName -in @('TeamsChina', 'TeamsGCCH', 'TeamsDOD')) { + return $null + } + if ($context.AuthType -ne 'Delegated') { + return $null + } + + $cacheKey = "UnifiedAppSettings:$tenantId" + if ($__MtSession.TeamsCache.ContainsKey($cacheKey)) { + return $__MtSession.TeamsCache[$cacheKey] + } + + $accessToken = Get-MtTeamsUnifiedSettingsAccessToken -Context $context + $response = Invoke-RestMethod ` + -Uri 'https://substrate.office.com/AdminAppCatalog/ps/v2/admin/unifiedApp/settings' ` + -Method Get ` + -Headers @{ Authorization = "Bearer $accessToken" } ` + -ErrorAction Stop + + if ($null -eq $response) { + throw 'The Teams unified app settings API returned an empty response.' + } + + $settings = if ($response.PSObject.Properties['value']) { + @($response.value) + } else { + @($response) + } + + foreach ($setting in $settings) { + if ($null -eq $setting -or + $null -eq $setting.PSObject.Properties['SettingName'] -or + $null -eq $setting.PSObject.Properties['SettingValue']) { + throw 'The Teams unified app settings API returned a setting without SettingName or SettingValue.' + } + } + + $__MtSession.TeamsCache[$cacheKey] = $settings + return $settings +} diff --git a/powershell/internal/session/Clear-ModuleVariable.ps1 b/powershell/internal/session/Clear-ModuleVariable.ps1 index 2c4eb15b76..5641bf0eee 100644 --- a/powershell/internal/session/Clear-ModuleVariable.ps1 +++ b/powershell/internal/session/Clear-ModuleVariable.ps1 @@ -34,6 +34,7 @@ $__MtSession.GitHubCache = @{} $__MtSession.SpoCache = @{} $__MtSession.FabricCache = @{} + $__MtSession.TeamsCache = @{} $__MtSession.Console = $null $__MtSession.ReportAttachments = $null # $__MtSession.Connections = @() # Do not clear connections as they are used to track the connection state. This module variable should only be set by Connect-Maester and Disconnect-Maester. diff --git a/powershell/public/connect/Connect-Maester.ps1 b/powershell/public/connect/Connect-Maester.ps1 index e09e2e5b5d..28a97cde16 100644 --- a/powershell/public/connect/Connect-Maester.ps1 +++ b/powershell/public/connect/Connect-Maester.ps1 @@ -554,6 +554,8 @@ 'MicrosoftTeams' { if ($Service -contains 'Teams' -or $Service -contains 'All') { + $__MtSession.TeamsUseDeviceCode = $UseDeviceCode.IsPresent + $__MtSession.TeamsEnvironmentName = $TeamsEnvironmentName Write-Verbose 'Connecting to Microsoft Teams' try { $teamsParams = @{ ErrorAction = 'Stop' } diff --git a/powershell/public/connect/Disconnect-Maester.ps1 b/powershell/public/connect/Disconnect-Maester.ps1 index 3e183aa42c..e8d5405b66 100644 --- a/powershell/public/connect/Disconnect-Maester.ps1 +++ b/powershell/public/connect/Disconnect-Maester.ps1 @@ -71,6 +71,11 @@ } if ($MyInvocation.InvocationName -notmatch '(^|\\)Disconnect-MtGraph$') { + $__MtSession.TeamsCache = @{} + $__MtSession.TeamsAuthCache = @{} + $__MtSession.TeamsUseDeviceCode = $false + $__MtSession.TeamsEnvironmentName = $null + # The service list can be replaced by another Connect-Maester call. Clean up a loaded # ADOPS session too, without importing an optional module just to disconnect it. try { diff --git a/powershell/public/run/Invoke-MtTest.ps1 b/powershell/public/run/Invoke-MtTest.ps1 index 26875dc2d9..d0acb5d4b4 100644 --- a/powershell/public/run/Invoke-MtTest.ps1 +++ b/powershell/public/run/Invoke-MtTest.ps1 @@ -66,6 +66,7 @@ Write-Verbose "Invoke-MtTest: Id=$($Id -join ', ') Path=$Path" $tests = [System.Collections.Generic.List[object]]::new() + $reloadBuiltInSourceTests = $false if ($Path) { if (-not (Test-Path -LiteralPath $Path)) { Write-Error "The path '$Path' does not exist."; return } $root = if (Test-Path -LiteralPath $Path -PathType Container) { (Resolve-Path -LiteralPath $Path).Path } else { Split-Path (Resolve-Path -LiteralPath $Path).Path -Parent } @@ -83,7 +84,20 @@ if ($inPath) { $tests.Add($t) } } } else { - foreach ($t in @(Get-MtNativeTestInventory -Path $Path -Root $root)) { $tests.Add($t) } + # Built-in tests in a source checkout need Maester's module scope for private helpers. + $testRoot = [System.IO.Path]::GetFullPath((Get-MtMaesterTestFolderPath)) + $fullPath = [System.IO.Path]::GetFullPath((Resolve-Path -LiteralPath $Path).Path) + $comparison = if ($IsWindows) { [System.StringComparison]::OrdinalIgnoreCase } else { [System.StringComparison]::Ordinal } + $separator = [System.IO.Path]::DirectorySeparatorChar + $testRootPrefix = $testRoot.TrimEnd($separator, [System.IO.Path]::AltDirectorySeparatorChar) + $separator + $customRoot = Join-Path $testRoot 'custom' + $customRootPrefix = $customRoot.TrimEnd($separator, [System.IO.Path]::AltDirectorySeparatorChar) + $separator + $withinTestRoot = [string]::Equals($fullPath, $testRoot, $comparison) -or $fullPath.StartsWith($testRootPrefix, $comparison) + $withinCustomRoot = [string]::Equals($fullPath, $customRoot, [System.StringComparison]::OrdinalIgnoreCase) -or $fullPath.StartsWith($customRootPrefix, [System.StringComparison]::OrdinalIgnoreCase) + $isBuiltInPath = $withinTestRoot -and -not $withinCustomRoot + $reloadBuiltInSourceTests = $isBuiltInPath + $inventoryRoot = if ($isBuiltInPath) { $testRoot } else { $root } + foreach ($t in @(Get-MtNativeTestInventory -Path $Path -Root $inventoryRoot -BuiltIn:$isBuiltInPath)) { $tests.Add($t) } } } if ($Id) { @@ -108,6 +122,63 @@ if ($tests.Count -eq 0) { Write-Error 'No native tests to run.'; return } if ($Parameter -and $tests.Count -ne 1) { Write-Error "-Parameter can be used only when exactly one test is selected; $($tests.Count) are."; return } + if ($reloadBuiltInSourceTests) { + $maester = $ExecutionContext.SessionState.Module + $loadTestFile = [scriptblock]::Create('. $args[0]') + $reloadedTests = [System.Collections.Generic.List[object]]::new() + $catalog = @(Get-MtTestCatalog) + foreach ($test in @($tests | Where-Object { $_.BuiltIn -and $_.File -and $_.Errors.Count -eq 0 })) { + $collision = @($catalog | Where-Object { + ($_.Id -eq $test.Id -or $_.FunctionName -eq $test.FunctionName) -and + -not [string]::Equals($_.File, $test.File, $comparison) + }) + if ($collision.Count -gt 0) { + $test.Errors.Add([pscustomobject]@{ + Code = 'DuplicateId' + Message = if ($collision.Id -contains $test.Id) { + "Another test file has the ID $($test.Id)." + } + else { + "Another test file defines the function $($test.FunctionName)." + } + Line = $test.Line + }) + continue + } + # Promote the refreshed function from this command's scope to module scope for path and ID runs. + try { + $null = $maester.SessionState.InvokeCommand.InvokeScript($false, $loadTestFile, $null, @($test.File)) + $function = Get-Item -LiteralPath "Function:\$($test.FunctionName)" -ErrorAction Stop + Set-Item -LiteralPath "Function:\script:$($test.FunctionName)" -Value $function.ScriptBlock -ErrorAction Stop + if ($test.InstanceSource) { + $sourceFunction = Get-Item -LiteralPath "Function:\$($test.InstanceSource)" -ErrorAction Stop + Set-Item -LiteralPath "Function:\script:$($test.InstanceSource)" -Value $sourceFunction.ScriptBlock -ErrorAction Stop + } + $reloadedTests.Add($test) + } catch { + $test.Errors.Add([pscustomobject]@{ + Code = 'LoadFailed' + Message = "The file could not be loaded: $($_.Exception.Message)" + Line = 1 + }) + } + } + + if ($reloadedTests.Count -gt 0) { + # ID-based runs use the cached parameter and attribute metadata as well as the refreshed function. + foreach ($test in $reloadedTests) { + $index = 0 + while ($index -lt $catalog.Count -and $catalog[$index].Id -ne $test.Id) { $index++ } + if ($index -lt $catalog.Count) { + $catalog[$index] = $test + } else { + $catalog += $test + } + } + $script:__MtTestCatalog = $catalog + } + } + # Called by a test during an Invoke-Maester run, the run's config is kept; otherwise it is resolved for # this call (the config a finished run leaves in the session must not apply to a later standalone call). $savedConfig = $__MtSession.MaesterConfig diff --git a/powershell/tests/fixtures/golden/selection.json b/powershell/tests/fixtures/golden/selection.json index ae970e7cfd..31f14b4a4c 100644 --- a/powershell/tests/fixtures/golden/selection.json +++ b/powershell/tests/fixtures/golden/selection.json @@ -21,7 +21,7 @@ "AD" ] }, - "SelectedCount": 582, + "SelectedCount": 596, "SelectedFamilies": [ "MT.1024", "MT.1059", @@ -314,6 +314,20 @@ "CISA.MS.SHAREPOINT.3.1", "CISA.MS.SHAREPOINT.3.2", "CISA.MS.SHAREPOINT.3.3", + "CISA.MS.TEAMS.1.1", + "CISA.MS.TEAMS.1.2", + "CISA.MS.TEAMS.1.3", + "CISA.MS.TEAMS.1.4", + "CISA.MS.TEAMS.1.5", + "CISA.MS.TEAMS.1.6", + "CISA.MS.TEAMS.1.7", + "CISA.MS.TEAMS.2.1", + "CISA.MS.TEAMS.2.2", + "CISA.MS.TEAMS.2.3", + "CISA.MS.TEAMS.4.1", + "CISA.MS.TEAMS.5.1", + "CISA.MS.TEAMS.5.2", + "CISA.MS.TEAMS.5.3", "DISA.V-267314", "DISA.V-267334", "DISA.V-267341", @@ -771,7 +785,7 @@ "AD" ] }, - "SelectedCount": 538, + "SelectedCount": 552, "SelectedFamilies": [ "MT.1024", "MT.1059", @@ -1064,6 +1078,20 @@ "CISA.MS.SHAREPOINT.3.1", "CISA.MS.SHAREPOINT.3.2", "CISA.MS.SHAREPOINT.3.3", + "CISA.MS.TEAMS.1.1", + "CISA.MS.TEAMS.1.2", + "CISA.MS.TEAMS.1.3", + "CISA.MS.TEAMS.1.4", + "CISA.MS.TEAMS.1.5", + "CISA.MS.TEAMS.1.6", + "CISA.MS.TEAMS.1.7", + "CISA.MS.TEAMS.2.1", + "CISA.MS.TEAMS.2.2", + "CISA.MS.TEAMS.2.3", + "CISA.MS.TEAMS.4.1", + "CISA.MS.TEAMS.5.1", + "CISA.MS.TEAMS.5.2", + "CISA.MS.TEAMS.5.3", "DISA.V-267314", "DISA.V-267334", "DISA.V-267341", @@ -1330,7 +1358,7 @@ "AD" ] }, - "SelectedCount": 598, + "SelectedCount": 612, "SelectedFamilies": [ "MT.1024", "MT.1033", @@ -1626,6 +1654,20 @@ "CISA.MS.SHAREPOINT.3.1", "CISA.MS.SHAREPOINT.3.2", "CISA.MS.SHAREPOINT.3.3", + "CISA.MS.TEAMS.1.1", + "CISA.MS.TEAMS.1.2", + "CISA.MS.TEAMS.1.3", + "CISA.MS.TEAMS.1.4", + "CISA.MS.TEAMS.1.5", + "CISA.MS.TEAMS.1.6", + "CISA.MS.TEAMS.1.7", + "CISA.MS.TEAMS.2.1", + "CISA.MS.TEAMS.2.2", + "CISA.MS.TEAMS.2.3", + "CISA.MS.TEAMS.4.1", + "CISA.MS.TEAMS.5.1", + "CISA.MS.TEAMS.5.2", + "CISA.MS.TEAMS.5.3", "DISA.V-267314", "DISA.V-267334", "DISA.V-267341", @@ -1951,7 +1993,7 @@ "AD" ] }, - "SelectedCount": 609, + "SelectedCount": 623, "SelectedFamilies": [ "MT.1024", "MT.1059", @@ -2245,6 +2287,20 @@ "CISA.MS.SHAREPOINT.3.1", "CISA.MS.SHAREPOINT.3.2", "CISA.MS.SHAREPOINT.3.3", + "CISA.MS.TEAMS.1.1", + "CISA.MS.TEAMS.1.2", + "CISA.MS.TEAMS.1.3", + "CISA.MS.TEAMS.1.4", + "CISA.MS.TEAMS.1.5", + "CISA.MS.TEAMS.1.6", + "CISA.MS.TEAMS.1.7", + "CISA.MS.TEAMS.2.1", + "CISA.MS.TEAMS.2.2", + "CISA.MS.TEAMS.2.3", + "CISA.MS.TEAMS.4.1", + "CISA.MS.TEAMS.5.1", + "CISA.MS.TEAMS.5.2", + "CISA.MS.TEAMS.5.3", "DISA.V-267303", "DISA.V-267309", "DISA.V-267314", @@ -2581,7 +2637,7 @@ "AD" ] }, - "SelectedCount": 639, + "SelectedCount": 653, "SelectedFamilies": [ "MT.1024", "MT.1033", @@ -2878,6 +2934,20 @@ "CISA.MS.SHAREPOINT.3.1", "CISA.MS.SHAREPOINT.3.2", "CISA.MS.SHAREPOINT.3.3", + "CISA.MS.TEAMS.1.1", + "CISA.MS.TEAMS.1.2", + "CISA.MS.TEAMS.1.3", + "CISA.MS.TEAMS.1.4", + "CISA.MS.TEAMS.1.5", + "CISA.MS.TEAMS.1.6", + "CISA.MS.TEAMS.1.7", + "CISA.MS.TEAMS.2.1", + "CISA.MS.TEAMS.2.2", + "CISA.MS.TEAMS.2.3", + "CISA.MS.TEAMS.4.1", + "CISA.MS.TEAMS.5.1", + "CISA.MS.TEAMS.5.2", + "CISA.MS.TEAMS.5.3", "DISA.V-267303", "DISA.V-267309", "DISA.V-267314", @@ -3441,7 +3511,7 @@ "AD" ] }, - "SelectedCount": 538, + "SelectedCount": 552, "SelectedFamilies": [ "MT.1024", "MT.1059", @@ -3734,6 +3804,20 @@ "CISA.MS.SHAREPOINT.3.1", "CISA.MS.SHAREPOINT.3.2", "CISA.MS.SHAREPOINT.3.3", + "CISA.MS.TEAMS.1.1", + "CISA.MS.TEAMS.1.2", + "CISA.MS.TEAMS.1.3", + "CISA.MS.TEAMS.1.4", + "CISA.MS.TEAMS.1.5", + "CISA.MS.TEAMS.1.6", + "CISA.MS.TEAMS.1.7", + "CISA.MS.TEAMS.2.1", + "CISA.MS.TEAMS.2.2", + "CISA.MS.TEAMS.2.3", + "CISA.MS.TEAMS.4.1", + "CISA.MS.TEAMS.5.1", + "CISA.MS.TEAMS.5.2", + "CISA.MS.TEAMS.5.3", "DISA.V-267314", "DISA.V-267334", "DISA.V-267341", @@ -4006,7 +4090,7 @@ "AD" ] }, - "SelectedCount": 595, + "SelectedCount": 609, "SelectedFamilies": [ "MT.1024", "MT.1033", @@ -4303,6 +4387,20 @@ "CISA.MS.SHAREPOINT.3.1", "CISA.MS.SHAREPOINT.3.2", "CISA.MS.SHAREPOINT.3.3", + "CISA.MS.TEAMS.1.1", + "CISA.MS.TEAMS.1.2", + "CISA.MS.TEAMS.1.3", + "CISA.MS.TEAMS.1.4", + "CISA.MS.TEAMS.1.5", + "CISA.MS.TEAMS.1.6", + "CISA.MS.TEAMS.1.7", + "CISA.MS.TEAMS.2.1", + "CISA.MS.TEAMS.2.2", + "CISA.MS.TEAMS.2.3", + "CISA.MS.TEAMS.4.1", + "CISA.MS.TEAMS.5.1", + "CISA.MS.TEAMS.5.2", + "CISA.MS.TEAMS.5.3", "DISA.V-267303", "DISA.V-267309", "DISA.V-267314", diff --git a/powershell/tests/functions/CisaTeamsChecks.Tests.ps1 b/powershell/tests/functions/CisaTeamsChecks.Tests.ps1 new file mode 100644 index 0000000000..70e1bdda7f --- /dev/null +++ b/powershell/tests/functions/CisaTeamsChecks.Tests.ps1 @@ -0,0 +1,312 @@ +BeforeAll { + Import-Module "$PSScriptRoot/../../Maester.psd1" -Force + $script:cisaTeamsBroadcastTestPath = Join-Path $PSScriptRoot '../../../tests/cisa/teams/Test.CISA.MS.TEAMS.1.7.ps1' + $script:cisaTeamsRecordingTestPath = Join-Path $PSScriptRoot '../../../tests/cisa/teams/Test.CISA.MS.TEAMS.1.6.ps1' + + $script:createdTeamsStubs = @() + $teamsStubs = @{ + 'Get-CsTeamsMeetingPolicy' = { + [CmdletBinding()] + param([string]$Identity) + $null = $PSBoundParameters + } + 'Get-CsTeamsAppPermissionPolicy' = { + [CmdletBinding()] + param([string]$Identity) + $null = $PSBoundParameters + } + 'Get-CsTenantFederationConfiguration' = { + [CmdletBinding()] + param() + } + 'Get-CsTeamsMeetingBroadcastPolicy' = { + [CmdletBinding()] + param([string]$Identity) + $null = $PSBoundParameters + } + 'Get-CsTeamsClientConfiguration' = { + [CmdletBinding()] + param([string]$Identity) + $null = $PSBoundParameters + } + } + foreach ($name in $teamsStubs.Keys) { + if (-not (Get-Command $name -ErrorAction SilentlyContinue)) { + Set-Item -Path "Function:global:$name" -Value $teamsStubs[$name] + $script:createdTeamsStubs += $name + } + } +} + +AfterAll { + foreach ($name in $script:createdTeamsStubs) { + Remove-Item -Path "Function:global:$name" -ErrorAction SilentlyContinue + } +} + +Describe 'CISA Teams checks' { + BeforeEach { + InModuleScope Maester { + $__MtSession.TeamsCache = @{} + } + Mock Add-MtTestResultDetail -ModuleName Maester {} + } + + It 'Runs a built-in test by path in the Maester module scope' { + Mock Test-MtConnection -ModuleName Maester { @($Service) -contains 'Teams' } + Mock Get-CsTeamsMeetingPolicy -ModuleName Maester { + [pscustomobject]@{ Identity = 'Global'; AllowCloudRecording = $false } + } + + $row = Invoke-MtTest -Path $script:cisaTeamsRecordingTestPath -Config @{ Environment = @{ Services = @{ Teams = $true } } } + + $row.Result | Should -Be 'Passed' + $row.Source | Should -Be 'Maester' + Should -Invoke Get-CsTeamsMeetingPolicy -ModuleName Maester -Times 1 -Exactly + } + + It 'Checks every meeting policy for a Boolean setting' { + Mock Get-CsTeamsMeetingPolicy -ModuleName Maester { + @( + [pscustomobject]@{ Identity = 'Global'; AllowAnonymousUsersToStartMeeting = $false } + [pscustomobject]@{ Identity = 'Custom'; AllowAnonymousUsersToStartMeeting = $false } + ) + } + + InModuleScope Maester { + Test-MtCisaTeamsMeetingPolicyBoolean -SettingName AllowAnonymousUsersToStartMeeting -ExpectedValue $false -PolicyDescription 'Anonymous meeting start' | Should -BeTrue + } + Should -Invoke Get-CsTeamsMeetingPolicy -ModuleName Maester -Times 1 -Exactly + } + + It 'Fails a meeting policy when the setting differs from the baseline' { + Mock Get-CsTeamsMeetingPolicy -ModuleName Maester { + @( + [pscustomobject]@{ Identity = 'Global'; AllowAnonymousUsersToStartMeeting = $false } + [pscustomobject]@{ Identity = 'Custom'; AllowAnonymousUsersToStartMeeting = $true } + ) + } + + InModuleScope Maester { + Test-MtCisaTeamsMeetingPolicyBoolean -SettingName AllowAnonymousUsersToStartMeeting -ExpectedValue $false -PolicyDescription 'Anonymous meeting start' | Should -BeFalse + } + } + + It 'Errors when a meeting policy does not return the checked setting' { + Mock Get-CsTeamsMeetingPolicy -ModuleName Maester { + [pscustomobject]@{ Identity = 'Global' } + } + + { InModuleScope Maester { Test-MtCisaTeamsMeetingPolicyBoolean -SettingName AllowAnonymousUsersToStartMeeting -ExpectedValue $false -PolicyDescription 'Anonymous meeting start' } } | Should -Throw '*did not return a Boolean value*' + } + + It 'Caches all meeting policies when a check also requests the Global policy' { + Mock Get-CsTeamsMeetingPolicy -ModuleName Maester { + @( + [pscustomobject]@{ Identity = 'Global' } + [pscustomobject]@{ Identity = 'Custom' } + ) + } + + InModuleScope Maester { + @(Get-MtCisaTeamsMeetingPolicies) | Should -HaveCount 2 + (Get-MtCisaTeamsGlobalMeetingPolicy).Identity | Should -Be 'Global' + } + Should -Invoke Get-CsTeamsMeetingPolicy -ModuleName Maester -Times 1 -Exactly + } + + It 'Passes external federation when disabled' { + Mock Get-MtCisaTeamsFederationConfigurations -ModuleName Maester { + [pscustomobject]@{ AllowFederatedUsers = $false } + } + + InModuleScope Maester { + Test-MtCisaTeamsExternalAccessScope | Should -BeTrue + } + } + + It 'Fails external federation when all known domains are allowed' { + Mock Get-MtCisaTeamsFederationConfigurations -ModuleName Maester { + $domains = [pscustomobject]@{} + $domains.PSObject.TypeNames.Insert(0, 'AllowAllKnownDomains') + [pscustomobject]@{ + AllowFederatedUsers = $true + AllowedDomains = $domains + } + } + + InModuleScope Maester { + Test-MtCisaTeamsExternalAccessScope | Should -BeFalse + } + } + + It 'Passes external federation when only configured domains are allowed' { + Mock Get-MtCisaTeamsFederationConfigurations -ModuleName Maester { + [pscustomobject]@{ + AllowFederatedUsers = $true + AllowedDomains = [pscustomobject]@{ AllowedDomain = @('contoso.com') } + } + } + + InModuleScope Maester { + Test-MtCisaTeamsExternalAccessScope | Should -BeTrue + } + } + + It 'Does not mistake a restricted domain name for the allow-all policy' { + Mock Get-MtCisaTeamsFederationConfigurations -ModuleName Maester { + [pscustomobject]@{ + AllowFederatedUsers = $true + AllowedDomains = [pscustomobject]@{ AllowedDomain = @('allowallknowndomains.com') } + } + } + + InModuleScope Maester { + Test-MtCisaTeamsExternalAccessScope | Should -BeTrue + } + } + + It 'Caches tenant federation configurations for the current run' { + Mock Get-CsTenantFederationConfiguration -ModuleName Maester { + [pscustomobject]@{ AllowFederatedUsers = $false } + } + + InModuleScope Maester { + @(Get-MtCisaTeamsFederationConfigurations) | Should -HaveCount 1 + @(Get-MtCisaTeamsFederationConfigurations) | Should -HaveCount 1 + } + Should -Invoke Get-CsTenantFederationConfiguration -ModuleName Maester -Times 1 -Exactly + } + + It 'Passes CISA 1.7 when the Global policy does not always record' { + Mock Get-CsTeamsMeetingBroadcastPolicy -ModuleName Maester { + [pscustomobject]@{ Identity = 'Global'; BroadcastRecordingMode = 'OrganizerCanRecord' } + } + + InModuleScope Maester -Parameters @{ TestPath = $script:cisaTeamsBroadcastTestPath } { + . $TestPath + Test-MtCisaTeamsBroadcastRecording | Should -BeTrue + Test-MtCisaTeamsBroadcastRecording | Should -BeTrue + } + Should -Invoke Get-CsTeamsMeetingBroadcastPolicy -ModuleName Maester -Times 1 -Exactly + } + + It 'Fails CISA 1.7 when the Global policy is set to always record' { + Mock Get-CsTeamsMeetingBroadcastPolicy -ModuleName Maester { + [pscustomobject]@{ Identity = 'Global'; BroadcastRecordingMode = 'AlwaysEnabled' } + } + + InModuleScope Maester -Parameters @{ TestPath = $script:cisaTeamsBroadcastTestPath } { + . $TestPath + Test-MtCisaTeamsBroadcastRecording | Should -BeFalse + } + } + + It 'Errors when CISA 1.7 cannot assess the Global recording setting' { + Mock Get-CsTeamsMeetingBroadcastPolicy -ModuleName Maester { + [pscustomobject]@{ Identity = 'Global' } + } + + InModuleScope Maester -Parameters @{ TestPath = $script:cisaTeamsBroadcastTestPath } { + . $TestPath + { Test-MtCisaTeamsBroadcastRecording } | Should -Throw '*did not return BroadcastRecordingMode*' + } + } + + It 'Fails external federation when any configuration allows all domains' { + Mock Get-MtCisaTeamsFederationConfigurations -ModuleName Maester { + $domains = [pscustomobject]@{} + $domains.PSObject.TypeNames.Insert(0, 'AllowAllKnownDomains') + @( + [pscustomobject]@{ Identity = 'Global'; AllowFederatedUsers = $false } + [pscustomobject]@{ Identity = 'Tag:Custom'; AllowFederatedUsers = $true; AllowedDomains = $domains } + ) + } + + InModuleScope Maester { + Test-MtCisaTeamsExternalAccessScope | Should -BeFalse + } + } + + It 'Fails unmanaged inbound contact when any configuration allows it' { + Mock Test-MtCisaTeamsIsUSGovernment -ModuleName Maester { $false } + Mock Get-MtCisaTeamsFederationConfigurations -ModuleName Maester { + @( + [pscustomobject]@{ Identity = 'Global'; AllowTeamsConsumerInbound = $false; AllowTeamsConsumer = $true } + [pscustomobject]@{ Identity = 'Tag:Custom'; AllowTeamsConsumerInbound = $true; AllowTeamsConsumer = $true } + ) + } + + InModuleScope Maester { + Test-MtCisaTeamsUnmanagedInboundContact | Should -BeFalse + } + } + + It 'Passes unmanaged inbound contact when every configuration blocks inbound contact' { + Mock Test-MtCisaTeamsIsUSGovernment -ModuleName Maester { $false } + Mock Get-MtCisaTeamsFederationConfigurations -ModuleName Maester { + @( + [pscustomobject]@{ Identity = 'Global'; AllowTeamsConsumerInbound = $false; AllowTeamsConsumer = $true } + [pscustomobject]@{ Identity = 'Tag:Custom'; AllowTeamsConsumerInbound = $true; AllowTeamsConsumer = $false } + ) + } + + InModuleScope Maester { + Test-MtCisaTeamsUnmanagedInboundContact | Should -BeTrue + } + } + + It 'Fails unmanaged outbound contact when any configuration allows it' { + Mock Test-MtCisaTeamsIsUSGovernment -ModuleName Maester { $false } + Mock Get-MtCisaTeamsFederationConfigurations -ModuleName Maester { + @( + [pscustomobject]@{ Identity = 'Global'; AllowTeamsConsumer = $false } + [pscustomobject]@{ Identity = 'Tag:Custom'; AllowTeamsConsumer = $true } + ) + } + + InModuleScope Maester { + Test-MtCisaTeamsUnmanagedOutboundContact | Should -BeFalse + } + } + + It 'Uses an available unified org-wide app setting instead of legacy policies' { + Mock Get-MtTeamsUnifiedTenantSettings -ModuleName Maester { + @([pscustomobject]@{ SettingName = 'GlobalApp'; SettingValue = 'None' }) + } + Mock Get-CsTeamsAppPermissionPolicy -ModuleName Maester { throw 'Legacy policies should not be queried.' } + + InModuleScope Maester { + Test-MtCisaTeamsAppControl -SettingName GlobalApp -AppType Third-party | Should -BeTrue + } + Should -Invoke Get-CsTeamsAppPermissionPolicy -ModuleName Maester -Times 0 -Exactly + } + + It 'Fails an available unified org-wide app setting that is not None' { + Mock Get-MtTeamsUnifiedTenantSettings -ModuleName Maester { + @([pscustomobject]@{ SettingName = 'PrivateApp'; SettingValue = 'All' }) + } + Mock Get-CsTeamsAppPermissionPolicy -ModuleName Maester { throw 'Legacy policies should not be queried.' } + + InModuleScope Maester { + Test-MtCisaTeamsAppControl -SettingName PrivateApp -AppType Custom | Should -BeFalse + } + Should -Invoke Get-CsTeamsAppPermissionPolicy -ModuleName Maester -Times 0 -Exactly + } + + It 'Falls back to all legacy app permission policies when the unified setting is unavailable' { + Mock Get-MtTeamsUnifiedTenantSettings -ModuleName Maester { $null } + Mock Get-CsTeamsAppPermissionPolicy -ModuleName Maester { + @( + [pscustomobject]@{ Identity = 'Global'; DefaultCatalogAppsType = 'AllowedAppList' } + [pscustomobject]@{ Identity = 'Custom'; DefaultCatalogAppsType = 'BlockedAppList' } + ) + } + + InModuleScope Maester { + Test-MtCisaTeamsAppControl -SettingName DefaultApp -AppType Microsoft | Should -BeFalse + Test-MtCisaTeamsAppControl -SettingName DefaultApp -AppType Microsoft | Should -BeFalse + } + Should -Invoke Get-CsTeamsAppPermissionPolicy -ModuleName Maester -Times 1 -Exactly + } +} diff --git a/powershell/tests/functions/Clear-ModuleVariable.Tests.ps1 b/powershell/tests/functions/Clear-ModuleVariable.Tests.ps1 index 23afa4bb0b..ab9d08c938 100644 --- a/powershell/tests/functions/Clear-ModuleVariable.Tests.ps1 +++ b/powershell/tests/functions/Clear-ModuleVariable.Tests.ps1 @@ -9,6 +9,7 @@ Describe 'Clear-ModuleVariable — GitHub session lifecycle' { $__MtSession.GitHubAuthHeader = @{ Authorization = 'Bearer testtoken' } $__MtSession.GitHubCache = @{ somekey = 'cached-value' } } + } AfterEach { @@ -49,3 +50,17 @@ Describe 'Clear-ModuleVariable — GitHub session lifecycle' { } } } + +Describe 'Clear-ModuleVariable - Teams API cache lifecycle' { + It 'Clears per-run Teams settings but preserves the connected MSAL client' { + InModuleScope Maester { + $client = [pscustomobject]@{ Cached = $true } + $__MtSession.TeamsCache = @{ 'UnifiedAppSettings:tenant' = @('setting') } + $__MtSession.TeamsAuthCache = @{ Clients = @{ tenant = $client } } + Clear-ModuleVariable + + $__MtSession.TeamsCache.Count | Should -Be 0 + $__MtSession.TeamsAuthCache.Clients.tenant.Cached | Should -BeTrue + } + } +} diff --git a/powershell/tests/functions/Connect-Maester.Tests.ps1 b/powershell/tests/functions/Connect-Maester.Tests.ps1 index 950f319473..1691ff22c6 100644 --- a/powershell/tests/functions/Connect-Maester.Tests.ps1 +++ b/powershell/tests/functions/Connect-Maester.Tests.ps1 @@ -1,4 +1,4 @@ -BeforeAll { +BeforeAll { Import-Module "$PSScriptRoot/../../Maester.psd1" -Force # Keep -Service All tests isolated from optional service modules that may not be installed. @@ -303,6 +303,10 @@ Describe 'Connect-Maester connection summary' { Should -Invoke Connect-MicrosoftTeams -ModuleName Maester -Times 1 -Exactly -ParameterFilter { $UseDeviceAuthentication -and $TeamsEnvironmentName -eq 'TeamsGCCH' } + InModuleScope Maester { + $__MtSession.TeamsUseDeviceCode | Should -BeTrue + $__MtSession.TeamsEnvironmentName | Should -Be 'TeamsGCCH' + } } Context 'When an Az context from another tenant already exists' { diff --git a/powershell/tests/functions/Disconnect-Maester.Tests.ps1 b/powershell/tests/functions/Disconnect-Maester.Tests.ps1 index b3eeca9561..635725a78b 100644 --- a/powershell/tests/functions/Disconnect-Maester.Tests.ps1 +++ b/powershell/tests/functions/Disconnect-Maester.Tests.ps1 @@ -1,4 +1,4 @@ -BeforeAll { +BeforeAll { Import-Module "$PSScriptRoot/../../Maester.psd1" -Force } @@ -177,6 +177,7 @@ Describe 'Disconnect-Maester - Active Directory session lifecycle' { Connected = $true DomainController = 'dc01.contoso.com' } + $__MtSession.ADCredential = [PSCredential]::new('CONTOSO\Maester', ([System.Security.SecureString]::new())) $__MtSession.ADCache = @{ DomainState = [PSCustomObject]@{ Domain = 'contoso.com' } } } @@ -216,6 +217,29 @@ Describe 'Disconnect-Maester - Active Directory session lifecycle' { } } +Describe 'Disconnect-Maester - Teams unified settings authentication lifecycle' { + BeforeEach { + Mock Get-Module -ModuleName Maester { $null } -ParameterFilter { $Name -eq 'ADOPS' } + InModuleScope Maester { + $__MtSession.Connections = @() + $__MtSession.TeamsCache = @{ 'UnifiedAppSettings:tenant' = @('stale') } + $__MtSession.TeamsAuthCache = @{ Clients = @{ tenant = 'cached-client' } } + $__MtSession.TeamsUseDeviceCode = $true + $__MtSession.TeamsEnvironmentName = 'TeamsGCCH' + } + } + + It 'Clears the Teams authentication client and device-code preference' { + Disconnect-Maester + InModuleScope Maester { + $__MtSession.TeamsCache.Count | Should -Be 0 + $__MtSession.TeamsAuthCache.Count | Should -Be 0 + $__MtSession.TeamsUseDeviceCode | Should -BeFalse + $__MtSession.TeamsEnvironmentName | Should -BeNullOrEmpty + } + } +} + Describe 'Disconnect-Maester - service disconnects' { BeforeAll { # The Exchange Online and Teams modules are optional; stand in for their commands when they are not installed. diff --git a/powershell/tests/functions/TeamsUnifiedSettings.Tests.ps1 b/powershell/tests/functions/TeamsUnifiedSettings.Tests.ps1 new file mode 100644 index 0000000000..cb0969c701 --- /dev/null +++ b/powershell/tests/functions/TeamsUnifiedSettings.Tests.ps1 @@ -0,0 +1,297 @@ +BeforeAll { + Import-Module "$PSScriptRoot/../../Maester.psd1" -Force + + if (-not ('MaesterTestDeviceCodeResult' -as [type])) { + $null = Add-Type -TypeDefinition @' +public sealed class MaesterTestDeviceCodeResult +{ + public MaesterTestDeviceCodeResult(string message) + { + Message = message; + } + + public string Message { get; } +} + +public static class MaesterTestDeviceCodeCallbackInvoker +{ + public static System.Threading.Tasks.Task Invoke(System.Delegate callback, object deviceCode) + { + return System.Threading.Tasks.Task.Run(async () => + await (System.Threading.Tasks.Task)callback.DynamicInvoke(deviceCode)); + } +} + +public sealed class MaesterTestUnifiedTokenClient +{ + public System.Threading.Tasks.Task GetAccountsAsync() + { + return System.Threading.Tasks.Task.FromResult(new object[0]); + } + + public MaesterTestUnifiedTokenRequest AcquireTokenInteractive(System.Collections.Generic.IEnumerable scopes) + { + return new MaesterTestUnifiedTokenRequest(); + } +} + +public sealed class MaesterTestUnifiedTokenRequest +{ + public MaesterTestUnifiedTokenRequest WithUseEmbeddedWebView(bool enabled) { return this; } + public MaesterTestUnifiedTokenRequest WithLoginHint(string account) { return this; } + public System.Threading.Tasks.Task ExecuteAsync() + { + return System.Threading.Tasks.Task.FromResult(new MaesterTestUnifiedTokenResult()); + } +} + +public sealed class MaesterTestUnifiedTokenResult +{ + public string AccessToken { get { return "interactive-test-token"; } } +} +'@ -ErrorAction Stop + } + + if (-not ('MaesterTestUnifiedDeviceCodeClient' -as [type])) { + $null = Add-Type -TypeDefinition @' +using System; +using System.Collections.Generic; +using System.Threading.Tasks; + +public sealed class MaesterTestUnifiedDeviceCodeClient +{ + private readonly TaskCompletionSource _tokenSource = new TaskCompletionSource(); + + public bool TokenWasReleasedWhilePending { get; private set; } + + public Task GetAccountsAsync() + { + return Task.FromResult(new object[0]); + } + + public MaesterTestUnifiedDeviceCodeRequest AcquireTokenWithDeviceCode(IEnumerable scopes, Delegate callback) + { + return new MaesterTestUnifiedDeviceCodeRequest(this); + } + + public Task GetTokenTask() + { + Task.Delay(5000).ContinueWith(_ => _tokenSource.TrySetException(new TimeoutException("The host did not release the device-code token."))); + return _tokenSource.Task; + } + + public void ReleaseTokenFromHost() + { + TokenWasReleasedWhilePending = !_tokenSource.Task.IsCompleted; + _tokenSource.TrySetResult(new MaesterTestUnifiedDeviceCodeResult()); + } +} + +public sealed class MaesterTestUnifiedDeviceCodeRequest +{ + private readonly MaesterTestUnifiedDeviceCodeClient _client; + + public MaesterTestUnifiedDeviceCodeRequest(MaesterTestUnifiedDeviceCodeClient client) + { + _client = client; + } + + public Task ExecuteAsync() + { + return _client.GetTokenTask(); + } +} + +public sealed class MaesterTestUnifiedDeviceCodeResult +{ + public string AccessToken { get { return "device-code-test-token"; } } +} +'@ -ErrorAction Stop + } + +} + +Describe 'Get-MtTeamsUnifiedSettingsAccessToken' { + BeforeAll { + Import-Module Microsoft.Graph.Authentication -ErrorAction Stop + } + + It 'Passes scopes to the MSAL interactive overload and returns its access token' { + InModuleScope Maester { + $tenantId = '11111111-1111-1111-1111-111111111111' + $__MtSession.TeamsUseDeviceCode = $false + $__MtSession.TeamsAuthCache = @{ + Clients = @{ "$tenantId|Global" = [MaesterTestUnifiedTokenClient]::new() } + } + $context = [pscustomobject]@{ + TenantId = $tenantId + Environment = 'Global' + Account = 'admin@contoso.com' + } + + Get-MtTeamsUnifiedSettingsAccessToken -Context $context | + Should -Be 'interactive-test-token' + } + } + + It 'Writes device-code instructions directly to the host before waiting for a token' { + $tenantId = '11111111-1111-1111-1111-111111111111' + $context = [pscustomobject]@{ + TenantId = $tenantId + Environment = 'Global' + Account = $null + } + $client = [MaesterTestUnifiedDeviceCodeClient]::new() + + $output = @( + InModuleScope Maester -Parameters @{ Context = $context; Client = $client } { + $__MtSession.TeamsUseDeviceCode = $true + $__MtSession.TeamsAuthCache = @{ + Clients = @{ "$($Context.TenantId)|$($Context.Environment)" = $Client } + } + $script:deviceCodeTestClient = $Client + Mock Get-MtTeamsUnifiedSettingsDeviceCodeCallback { + $null = $MessageSource.TrySetResult('Use the displayed code to sign in.') + } + Mock Write-MtHostLine { + $null = $script:deviceCodeTestClient.ReleaseTokenFromHost() + } + + try { + Get-MtTeamsUnifiedSettingsAccessToken -Context $Context 6>&1 + } finally { + $script:deviceCodeTestClient = $null + } + } + ) + + @($output | Where-Object { $_ -is [System.Management.Automation.InformationRecord] }) | + Should -BeNullOrEmpty + $output | Should -Contain 'device-code-test-token' + $client.TokenWasReleasedWhilePending | Should -BeTrue + Should -Invoke Write-MtHostLine -ModuleName Maester -Times 1 -Exactly -ParameterFilter { + $Text -eq 'Use the displayed code to sign in.' + } + } +} + +Describe 'Get-MtTeamsUnifiedTenantSettings' { + BeforeEach { + InModuleScope Maester { + $__MtSession.TeamsCache = @{} + $__MtSession.TeamsAuthCache = @{} + $__MtSession.TeamsEnvironmentName = $null + } + Mock Get-MgContext -ModuleName Maester { + [pscustomobject]@{ + TenantId = '11111111-1111-1111-1111-111111111111' + Environment = 'Global' + AuthType = 'Delegated' + Account = 'admin@contoso.com' + } + } + Mock Get-MtTeamsUnifiedSettingsAccessToken -ModuleName Maester { + 'test-token' + } + Mock Invoke-RestMethod -ModuleName Maester { + @([pscustomobject]@{ SettingName = 'DefaultApp'; SettingValue = 'None' }) + } + } + + It 'Retrieves settings with a delegated token and caches them for the current run' { + $first = InModuleScope Maester { @(Get-MtTeamsUnifiedTenantSettings) } + $second = InModuleScope Maester { @(Get-MtTeamsUnifiedTenantSettings) } + + $first | Should -HaveCount 1 + $first[0].SettingName | Should -Be 'DefaultApp' + $second[0].SettingValue | Should -Be 'None' + Should -Invoke Get-MtTeamsUnifiedSettingsAccessToken -ModuleName Maester -Times 1 -Exactly + Should -Invoke Invoke-RestMethod -ModuleName Maester -Times 1 -Exactly -ParameterFilter { + $Uri -eq 'https://substrate.office.com/AdminAppCatalog/ps/v2/admin/unifiedApp/settings' -and + $Method -eq 'Get' -and + $Headers.Authorization -eq 'Bearer test-token' + } + } + + It 'Uses legacy policies in US Government environments' { + Mock Get-MgContext -ModuleName Maester { + [pscustomobject]@{ + TenantId = '11111111-1111-1111-1111-111111111111' + Environment = 'USGov' + AuthType = 'Delegated' + } + } + + InModuleScope Maester { Get-MtTeamsUnifiedTenantSettings } | Should -BeNullOrEmpty + Should -Invoke Invoke-RestMethod -ModuleName Maester -Times 0 -Exactly + } + + It 'Uses legacy policies in US Government DoD environments' { + Mock Get-MgContext -ModuleName Maester { + [pscustomobject]@{ + TenantId = '11111111-1111-1111-1111-111111111111' + Environment = 'USGovDoD' + AuthType = 'Delegated' + } + } + + InModuleScope Maester { Get-MtTeamsUnifiedTenantSettings } | Should -BeNullOrEmpty + Should -Invoke Invoke-RestMethod -ModuleName Maester -Times 0 -Exactly + } + + It 'Uses legacy policies when Teams is connected to GCC High' { + InModuleScope Maester { + $__MtSession.TeamsEnvironmentName = 'TeamsGCCH' + } + + InModuleScope Maester { Get-MtTeamsUnifiedTenantSettings } | Should -BeNullOrEmpty + Should -Invoke Invoke-RestMethod -ModuleName Maester -Times 0 -Exactly + } + + It 'Uses legacy policies for app-only authentication' { + Mock Get-MgContext -ModuleName Maester { + [pscustomobject]@{ + TenantId = '11111111-1111-1111-1111-111111111111' + Environment = 'Global' + AuthType = 'AppOnly' + } + } + + InModuleScope Maester { Get-MtTeamsUnifiedTenantSettings } | Should -BeNullOrEmpty + Should -Invoke Invoke-RestMethod -ModuleName Maester -Times 0 -Exactly + } + + It 'Throws when the unified settings API returns a malformed setting' { + Mock Invoke-RestMethod -ModuleName Maester { + @([pscustomobject]@{ SettingName = 'DefaultApp' }) + } + + { InModuleScope Maester { Get-MtTeamsUnifiedTenantSettings } } | Should -Throw '*without SettingName or SettingValue*' + } + + It 'Surfaces API request failures instead of silently falling back' { + Mock Invoke-RestMethod -ModuleName Maester { throw 'request failed' } + + { InModuleScope Maester { Get-MtTeamsUnifiedTenantSettings } } | Should -Throw '*request failed*' + } + + It 'Throws when no Graph context is available' { + Mock Get-MgContext -ModuleName Maester { $null } + + { InModuleScope Maester { Get-MtTeamsUnifiedTenantSettings } } | Should -Throw '*Graph context is required*' + } + + It 'Captures the device-code message through a managed callback' { + $messageSource = [System.Threading.Tasks.TaskCompletionSource[string]]::new() + $deviceCode = [MaesterTestDeviceCodeResult]::new('Use the displayed code to sign in.') + $callback = InModuleScope Maester -Parameters @{ + DeviceCodeType = $deviceCode.GetType() + MessageSource = $messageSource + } { + Get-MtTeamsUnifiedSettingsDeviceCodeCallback -DeviceCodeType $DeviceCodeType -MessageSource $MessageSource + } + + [MaesterTestDeviceCodeCallbackInvoker]::Invoke($callback, $deviceCode).GetAwaiter().GetResult() + $messageSource.Task.GetAwaiter().GetResult() | Should -Be 'Use the displayed code to sign in.' + } +} diff --git a/powershell/tests/functions/engine/Frameworks.Tests.ps1 b/powershell/tests/functions/engine/Frameworks.Tests.ps1 index 06a6372fd8..75eb9ee1af 100644 --- a/powershell/tests/functions/engine/Frameworks.Tests.ps1 +++ b/powershell/tests/functions/engine/Frameworks.Tests.ps1 @@ -1,4 +1,4 @@ -# Benchmarks and framework files (docs/proposals/maester-3.0-test-attributes.md, section 6): the Frameworks a +# Benchmarks and framework files (docs/proposals/maester-3.0-test-attributes.md, section 6): the Frameworks a # suite.json declares, the framework files beside it, the Control that maps a test to a requirement, Benchmark and # Control on a test, on its rows and in the catalog, what the catalog build rejects, and what a run does with a # custom suite whose framework file is wrong. @@ -336,7 +336,7 @@ Describe 'Benchmark of the tests shipped with Maester' { It 'Gives every test a Benchmark of