Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions powershell/Maester.psm1
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
@@ -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
}
Original file line number Diff line number Diff line change
@@ -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]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
function Get-MtCisaTeamsGlobalMeetingPolicy {
[CmdletBinding()]
param()

$policies = Get-MtCisaTeamsMeetingPolicies -GlobalOnly
return $policies[0]
}
Original file line number Diff line number Diff line change
@@ -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
}
Original file line number Diff line number Diff line change
@@ -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
}
Original file line number Diff line number Diff line change
@@ -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'))
}
Original file line number Diff line number Diff line change
@@ -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
}
Original file line number Diff line number Diff line change
@@ -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
}
Original file line number Diff line number Diff line change
@@ -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<string> messageSource)
{
var deviceCode = Expression.Parameter(deviceCodeType, "deviceCode");
var message = Expression.Property(deviceCode, "Message");
var trySetResult = typeof(TaskCompletionSource<string>).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))
}
Original file line number Diff line number Diff line change
@@ -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
}
1 change: 1 addition & 0 deletions powershell/internal/session/Clear-ModuleVariable.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Loading
Loading