Tests/Plan.Tests.ps1

#Requires -Modules Pester
# Plan rules: merge modes, protection, caps, validation, warnings, visibility impact and the plan fingerprint.

BeforeAll {
    . (Join-Path $PSScriptRoot 'TestHelpers.ps1')

    function Initialize-PlanTenant {
        param([string]$Profile)
        $p = @{ Mode = 'ReadWrite' }
        if ($Profile) { $p.Profile = $Profile }
        [void](Connect-TestTenant @p)
        InSTM { [void](Update-STMScopeTags); [void](Update-STMRoleAssignments) }
        # Deterministic starting tags on a handful of device categories (Supported, Patch).
        $script:cat = @(Get-MockObjects -Type DeviceCategory | ForEach-Object id)
    }

    function Get-Item1 { param($Plan, $Id) $Plan.Items | Where-Object Id -eq $Id }
}

Describe 'Merge modes' {
    BeforeEach { Mock -ModuleName IntuneScopeTagManager Start-Sleep { }; Initialize-PlanTenant }

    It 'Add merges and de-duplicates' {
        Set-MockTags -Type DeviceCategory -Id $cat[0] -Tags '1', '4'
        $p = New-STMChangePlan -Operations @(New-Op DeviceCategory $cat[0] Add @('Pilot', '4', 'corp-windows'))
        $i = Get-Item1 $p $cat[0]
        $i.State | Should -Be 'Ready'
        $i.After -join ',' | Should -Be '1,4,8'
        $i.Added -join ',' | Should -Be '8'
        $i.Removed.Count | Should -Be 0
    }

    It 'Remove takes tags away' {
        Set-MockTags -Type DeviceCategory -Id $cat[0] -Tags '1', '4', '8'
        $i = Get-Item1 (New-STMChangePlan -Operations @(New-Op DeviceCategory $cat[0] Remove @('Region-East'))) $cat[0]
        $i.After -join ',' | Should -Be '1,8'
        $i.Removed -join ',' | Should -Be '4'
    }

    It 'Replace sets exactly the given tags (Set is an alias)' {
        Set-MockTags -Type DeviceCategory -Id $cat[0] -Tags '1', '4'
        Set-MockTags -Type DeviceCategory -Id $cat[1] -Tags '1', '4'
        $p = New-STMChangePlan -Operations @((New-Op DeviceCategory $cat[0] Replace @('2', '3')), (New-Op DeviceCategory $cat[1] Set @('5')))
        (Get-Item1 $p $cat[0]).After -join ',' | Should -Be '2,3'
        (Get-Item1 $p $cat[1]).After -join ',' | Should -Be '5'
    }

    It 'several operations on one object apply in order' {
        Set-MockTags -Type DeviceCategory -Id $cat[0] -Tags '1'
        $p = New-STMChangePlan -Operations @((New-Op DeviceCategory $cat[0] Replace @('2', '3')), (New-Op DeviceCategory $cat[0] Add @('8')), (New-Op DeviceCategory $cat[0] Remove @('2')))
        $p.Items.Count | Should -Be 1
        $p.Items[0].After -join ',' | Should -Be '3,8'
    }

    It 'a change that ends where it started is NoChange and the plan cannot be applied' {
        Set-MockTags -Type DeviceCategory -Id $cat[0] -Tags '1'
        $p = New-STMChangePlan -Operations @(New-Op DeviceCategory $cat[0] Add @('1'))
        $p.Items[0].State | Should -Be 'NoChange'
        $p.CanApply | Should -BeFalse
    }

    It 'tags given as one ;-separated string are split' {
        Set-MockTags -Type DeviceCategory -Id $cat[0] -Tags '1'
        $p = New-STMChangePlan -Operations @([pscustomobject]@{ Type = 'DeviceCategory'; Id = $cat[0]; Mode = 'Add'; Tags = 'Pilot;Region-West' })
        $p.Items[0].After -join ',' | Should -Be '1,5,8'
    }

    It 'a bad mode blocks the object' {
        $p = New-STMChangePlan -Operations @(New-Op DeviceCategory $cat[0] Frobnicate @('1'))
        $p.Items[0].State | Should -Be 'Blocked'
        $p.Items[0].Issues -join ' ' | Should -Match 'not Add, Remove or Replace'
    }

    It 'Add with no tags is blocked' {
        $p = New-STMChangePlan -Operations @(New-Op DeviceCategory $cat[0] Add @())
        $p.Items[0].Issues -join ' ' | Should -Match 'needs at least one scope tag'
    }
}

Describe 'Validation' {
    BeforeEach { Mock -ModuleName IntuneScopeTagManager Start-Sleep { }; Initialize-PlanTenant }

    It 'unknown tag name is an error' {
        $p = New-STMChangePlan -Operations @(New-Op DeviceCategory $cat[0] Add @('No-Such-Tag'))
        $p.Items[0].State | Should -Be 'Blocked'
        $p.Items[0].Issues -join ' ' | Should -Match "No-Such-Tag' does not exist"
    }

    It 'unknown tag id is an error' {
        $p = New-STMChangePlan -Operations @(New-Op DeviceCategory $cat[0] Add @('99'))
        $p.Items[0].Issues -join ' ' | Should -Match "'99' does not exist"
    }

    It 'an ambiguous tag name is an error that asks for the id' {
        InSTM { $script:STMMock.Collections['deviceManagement/roleScopeTags'].Add([pscustomobject]@{ id = '9'; displayName = 'pilot'; description = ''; isBuiltIn = $false }); [void](Update-STMScopeTags) }
        $p = New-STMChangePlan -Operations @(New-Op DeviceCategory $cat[0] Add @('Pilot'))
        $p.Items[0].State | Should -Be 'Blocked'
        $p.Items[0].Issues -join ' ' | Should -Match 'matches several tags \(8, 9\); use the tag id'
        # The id still works.
        (New-STMChangePlan -Operations @(New-Op DeviceCategory $cat[0] Add @('9'))).Items[0].Issues.Count | Should -Be 0
    }

    It 'tag names are case-insensitive and "default" maps to 0' {
        Set-MockTags -Type DeviceCategory -Id $cat[0] -Tags '1'
        $p = New-STMChangePlan -Operations @(New-Op DeviceCategory $cat[0] Add @('DEFAULT', 'pilot'))
        $p.Items[0].After -join ',' | Should -Be '0,1,8'
    }

    It 'unknown object type and missing object are blocked' {
        $p = New-STMChangePlan -Operations @((New-Op NotAType 'x' Add @('1')), (New-Op DeviceCategory 'no-such-id' Add @('1')))
        (Get-Item1 $p 'x').Issues -join ' ' | Should -Match "Unknown object type 'NotAType'"
        (Get-Item1 $p 'no-such-id').Issues -join ' ' | Should -Match 'not found'
        $p.Summary.Blocked | Should -Be 2
    }

    It 'objects whose type does not support scope tags are blocked' {
        $legacy = Get-MockObjects -Type DeviceConfiguration | Where-Object { $_.supportsScopeTags -eq $false } | Select-Object -First 1
        $p = New-STMChangePlan -Operations @(New-Op DeviceConfiguration $legacy.id Add @('8'))
        $p.Items[0].State | Should -Be 'Blocked'
        $p.Items[0].Issues -join ' ' | Should -Match 'Not supported'
    }

    It 'objects whose tags were not returned are blocked' {
        $d = (Get-MockObjects -Type ManagedDevice)[0]
        InSTM { $script:STMMock.Options.DeviceListOmitsTags = $true; [void](Start-STMDeviceLoad); do { $x = Step-STMDeviceLoad } while (-not $x.Done) }
        $p = New-STMChangePlan -Operations @(New-Op ManagedDevice $d.id Add @('8'))
        $p.Items[0].Issues -join ' ' | Should -Match 'did not return scope tags'
    }
}

Describe 'Protected tag (PAW-Protected)' {
    BeforeEach { Mock -ModuleName IntuneScopeTagManager Start-Sleep { } }

    It 'objects carrying PAW-Protected are blocked (demo default protects PAW-Protected)' {
        Initialize-PlanTenant
        Set-MockTags -Type DeviceCategory -Id $cat[0] -Tags '1', '7'
        $p = New-STMChangePlan -Operations @(New-Op DeviceCategory $cat[0] Add @('8'))
        $p.Items[0].State | Should -Be 'Blocked'
        $p.Items[0].Issues -join ' ' | Should -Match 'Protected: already carries PAW-Protected'
    }

    It 'the Production profile blocks the plan when the protected tag cannot be resolved (Block)' {
        Initialize-PlanTenant -Profile Production
        (Get-STMState).Settings.ProtectedTagMissingBehavior | Should -Be 'Block'
        InSTM { $script:STM.Settings.ProtectedScopeTagNames = @('PAW-Missing') }
        Set-MockTags -Type DeviceCategory -Id $cat[0] -Tags '1'
        $p = New-STMChangePlan -Operations @(New-Op DeviceCategory $cat[0] Add @('8'))
        $p.Items[0].State | Should -Be 'Ready'
        $p.CanApply | Should -BeFalse
        $p.PlanIssues -join ' ' | Should -Match 'missing \[PAW-Missing\].*blocked'
    }

    It 'an ambiguous protected tag also blocks under Block' {
        Initialize-PlanTenant -Profile Production
        InSTM { $script:STMMock.Collections['deviceManagement/roleScopeTags'].Add([pscustomobject]@{ id = '9'; displayName = 'PAW-Protected'; description = ''; isBuiltIn = $false }); [void](Update-STMScopeTags) }
        Set-MockTags -Type DeviceCategory -Id $cat[0] -Tags '1'
        $p = New-STMChangePlan -Operations @(New-Op DeviceCategory $cat[0] Add @('8'))
        $p.CanApply | Should -BeFalse
        $p.PlanIssues -join ' ' | Should -Match 'ambiguous \[PAW-Protected\]'
    }

    It 'the Lab profile (Warn) lets the plan apply when the protected tag cannot be resolved' {
        Initialize-PlanTenant -Profile Lab
        (Get-STMState).Settings.ProtectedTagMissingBehavior | Should -Be 'Warn'
        InSTM { $script:STM.Settings.ProtectedScopeTagNames = @('PAW-Missing') }
        Set-MockTags -Type DeviceCategory -Id $cat[0] -Tags '1'
        $p = New-STMChangePlan -Operations @(New-Op DeviceCategory $cat[0] Add @('8'))
        $p.CanApply | Should -BeTrue
        $p.PlanIssues.Count | Should -Be 0
    }
}

Describe 'Per-run change cap' {
    BeforeEach {
        Mock -ModuleName IntuneScopeTagManager Start-Sleep { }
        Initialize-PlanTenant
        InSTM { $script:STM.Settings.MaxChangesPerRun = 2 }
        $script:ops = @($cat[0..2] | ForEach-Object { Set-MockTags -Type DeviceCategory -Id $_ -Tags '1'; New-Op DeviceCategory $_ Add @('8') })
    }

    It 'blocks a plan over the cap' {
        $p = New-STMChangePlan -Operations $ops
        $p.Summary.Ready | Should -Be 3
        $p.Summary.CapExceeded | Should -BeTrue
        $p.CanApply | Should -BeFalse
        $p.PlanIssues -join ' ' | Should -Match 'exceed the per-run cap of 2'
    }

    It 'an override without a reason is still blocked' {
        $p = New-STMChangePlan -Operations $ops -OverrideCap
        $p.CanApply | Should -BeFalse
        $p.PlanIssues -join ' ' | Should -Match 'needs a reason'
    }

    It 'an override with a reason can be applied and keeps the reason' {
        $p = New-STMChangePlan -Operations $ops -OverrideCap -OverrideReason 'CAB-1234 approved'
        $p.CanApply | Should -BeTrue
        $p.OverrideReason | Should -Be 'CAB-1234 approved'
    }

    It 'a plan at the cap is fine' {
        (New-STMChangePlan -Operations $ops[0..1]).CanApply | Should -BeTrue
    }
}

Describe 'No explicit tags, Default and devices' {
    BeforeEach { Mock -ModuleName IntuneScopeTagManager Start-Sleep { }; Initialize-PlanTenant }

    It 'removing every explicit tag needs -AllowNoExplicitTags' {
        Set-MockTags -Type DeviceCategory -Id $cat[0] -Tags '1'
        $p = New-STMChangePlan -Operations @(New-Op DeviceCategory $cat[0] Remove @('1'))
        $p.Items[0].State | Should -Be 'Blocked'
        $p.Items[0].Issues -join ' ' | Should -Match 'leave no scope tags'
        $p2 = New-STMChangePlan -Operations @(New-Op DeviceCategory $cat[0] Replace @()) -AllowNoExplicitTags
        $p2.Items[0].State | Should -Be 'Ready'
        $p2.Items[0].After.Count | Should -Be 0
        $p2.AllowNoExplicitTags | Should -BeTrue
    }

    It 'removing Default while keeping other tags warns' {
        Set-MockTags -Type DeviceCategory -Id $cat[0] -Tags '0', '2'
        $p = New-STMChangePlan -Operations @(New-Op DeviceCategory $cat[0] Remove @('Default'))
        $p.Items[0].State | Should -Be 'Ready'
        $p.Items[0].Warnings -join ' ' | Should -Match 'Removes Default'
    }

    It 'changing a group-assigned tag on a device warns that Intune re-applies it' {
        $d = (Get-MockObjects -Type ManagedDevice | Where-Object { @($_.roleScopeTagIds) -notcontains '7' })[0]
        Set-MockTags -Type ManagedDevice -Id $d.id -Tags '1'
        $p = New-STMChangePlan -Operations @(New-Op ManagedDevice $d.id Add @('Servers-Kiosk'))
        $p.Items[0].Warnings -join ' ' | Should -Match 'Servers-Kiosk.*assigned to groups'
        # Same change on a non-device object: no such warning.
        Set-MockTags -Type DeviceCategory -Id $cat[0] -Tags '1'
        (New-STMChangePlan -Operations @(New-Op DeviceCategory $cat[0] Add @('Servers-Kiosk'))).Items[0].Warnings -join ' ' | Should -Not -Match 'assigned to groups'
    }

    It 'a device not in the loaded inventory is read live' {
        $d = (Get-MockObjects -Type ManagedDevice)[3]
        Set-MockTags -Type ManagedDevice -Id $d.id -Tags '2'
        $p = New-STMChangePlan -Operations @(New-Op ManagedDevice $d.id Add @('8'))
        $p.Items[0].Name | Should -Be $d.deviceName
        $p.Items[0].Before -join ',' | Should -Be '2'
    }

    It 'LabVerify types carry a warning' {
        $cp = (Get-MockObjects -Type ConfigurationPolicy)[0]
        Set-MockTags -Type ConfigurationPolicy -Id $cp.id -Tags '1'
        $p = New-STMChangePlan -Operations @(New-Op ConfigurationPolicy $cp.id Add @('8'))
        $p.Items[0].State | Should -Be 'Ready'
        $p.Items[0].Warnings -join ' ' | Should -Match 'not yet verified in a lab tenant'
        # A Supported type does not.
        Set-MockTags -Type DeviceCategory -Id $cat[0] -Tags '1'
        (New-STMChangePlan -Operations @(New-Op DeviceCategory $cat[0] Add @('8'))).Items[0].Warnings -join ' ' | Should -Not -Match 'lab tenant'
    }
}

Describe 'Visibility impact' {
    BeforeEach { Mock -ModuleName IntuneScopeTagManager Start-Sleep { }; Initialize-PlanTenant }

    It 'moving from Region-East to Region-West loses Help desk East and gains Help desk West' {
        Set-MockTags -Type DeviceCategory -Id $cat[0] -Tags '4'
        $p = New-STMChangePlan -Operations @(New-Op DeviceCategory $cat[0] Replace @('Region-West'))
        $i = $p.Items[0]
        $i.VisibilityLost | Should -Be @('Help desk East (Help Desk Operator)')
        $i.VisibilityGained | Should -Be @('Help desk West (Help Desk Operator)')
        $i.Warnings -join ' ' | Should -Match 'Loses visibility: Help desk East'
        $p.Summary.VisibilityChanges | Should -Be 1
    }

    It 'adding Pilot gains Mobile admins and loses nobody' {
        Set-MockTags -Type DeviceCategory -Id $cat[0] -Tags '1'
        $i = (New-STMChangePlan -Operations @(New-Op DeviceCategory $cat[0] Add @('Pilot'))).Items[0]
        $i.VisibilityGained | Should -Be @('Mobile admins (Mobile Platform Admin (custom))')
        $i.VisibilityLost.Count | Should -Be 0
    }

    It 'an untagged object counts as Default for visibility' {
        Set-MockTags -Type DeviceCategory -Id $cat[0] -Tags @()
        $i = (New-STMChangePlan -Operations @(New-Op DeviceCategory $cat[0] Add @('Region-East'))).Items[0]
        $i.VisibilityLost | Should -Be @('Intune readers (Read Only Operator)')
        $i.VisibilityGained | Should -Be @('Help desk East (Help Desk Operator)')
    }

    It 'warns when no scoped role assignment can see the object afterwards' {
        Set-MockTags -Type DeviceCategory -Id $cat[0] -Tags '1'
        $i = (New-STMChangePlan -Operations @(New-Op DeviceCategory $cat[0] Replace @('Servers-Kiosk'))).Items[0]
        $i.Warnings -join ' ' | Should -Match 'no scoped Intune role assignment can see the object'
    }
}

Describe 'Visibility impact without a prior inventory load' {
    BeforeEach { Mock -ModuleName IntuneScopeTagManager Start-Sleep { } }

    It 'Regression: New-STMChangePlan straight after connecting still reports visibility changes' {
        [void](Connect-TestTenant -Mode ReadWrite)
        $c = (Get-MockObjects -Type DeviceCategory)[0].id
        Set-MockTags -Type DeviceCategory -Id $c -Tags '4'
        $i = (New-STMChangePlan -Operations @(New-Op DeviceCategory $c Replace @('Region-West'))).Items[0]
        $i.VisibilityLost | Should -Be @('Help desk East (Help Desk Operator)')
    }
}

Describe 'Plan fingerprint' {
    BeforeEach {
        Mock -ModuleName IntuneScopeTagManager Start-Sleep { }
        Initialize-PlanTenant
        Set-MockTags -Type DeviceCategory -Id $cat[0] -Tags '1'
        Set-MockTags -Type DeviceCategory -Id $cat[1] -Tags '2'
        $script:ops = @((New-Op DeviceCategory $cat[0] Add @('8')), (New-Op DeviceCategory $cat[1] Add @('8')))
    }

    It 'is a SHA-256 hex string and is stable for the same input' {
        $a = New-STMChangePlan -Operations $ops
        $b = New-STMChangePlan -Operations $ops
        $a.Hash | Should -Match '^[0-9a-f]{64}$'
        $a.PlanId | Should -Not -Be $b.PlanId
        $b.Hash | Should -Be $a.Hash
        # Order of operations does not matter.
        (New-STMChangePlan -Operations @($ops[1], $ops[0])).Hash | Should -Be $a.Hash
    }

    It 'changes when the planned tags change' {
        $a = New-STMChangePlan -Operations $ops
        $b = New-STMChangePlan -Operations @((New-Op DeviceCategory $cat[0] Add @('5')), $ops[1])
        $b.Hash | Should -Not -Be $a.Hash
    }

    It 'changes when the current tags change' {
        $a = New-STMChangePlan -Operations $ops
        Set-MockTags -Type DeviceCategory -Id $cat[0] -Tags '1', '4'
        (New-STMChangePlan -Operations $ops).Hash | Should -Not -Be $a.Hash
    }

    It 'changes with the tenant' {
        $a = New-STMChangePlan -Operations $ops
        $h = InSTM { param($p) $p.Tenant = 'other-tenant'; Get-STMPlanHash -Plan $p } -ArgumentList $a
        $h | Should -Not -Be $a.Hash
    }

    It 'survives Export/Import, and an edited plan file is refused' {
        $a = New-STMChangePlan -Operations $ops
        $dir = Join-Path $TestDrive 'plans'
        $out = Export-STMChangePlan -Plan $a -Directory $dir
        Test-Path $out.Csv | Should -BeTrue
        (Import-STMChangePlan -Path $out.Json).Hash | Should -Be $a.Hash
        $text = (Get-Content $out.Json -Raw) -replace '"After":\s*\[\s*"1",\s*"8"\s*\]', '"After": ["1","5"]'
        $text | Should -Not -Be (Get-Content $out.Json -Raw)
        $edited = Join-Path $dir 'edited.json'
        Set-Content -LiteralPath $edited -Value $text
        { Import-STMChangePlan -Path $edited } | Should -Throw '*edited after it was created*'
    }

    It 'a plan from another tenant is refused on import' {
        $a = New-STMChangePlan -Operations $ops
        $out = Export-STMChangePlan -Plan $a -Directory (Join-Path $TestDrive 'plans2')
        InSTM { $script:STM.TenantId = 'aaaaaaaa-0000-0000-0000-000000000000' }
        { Import-STMChangePlan -Path $out.Json } | Should -Throw '*built for tenant*'
    }
}

Describe 'Protected tags and plan-level warnings' {
    BeforeEach { Mock -ModuleName IntuneScopeTagManager Start-Sleep { } }

    It 'blocks adding a protected tag to an object (the tool could not change or roll it back afterwards)' {
        Initialize-PlanTenant
        Set-MockTags -Type DeviceCategory -Id $cat[0] -Tags '1'
        $i = (New-STMChangePlan -Operations @(New-Op DeviceCategory $cat[0] Add @('PAW-Protected'))).Items[0]
        $i.State | Should -Be 'Blocked'
        $i.Issues -join ' ' | Should -Match 'Adds protected tag PAW-Protected'
    }

    It 'records an unresolvable protected tag as a plan warning under Warn' {
        Initialize-PlanTenant -Profile Lab
        InSTM { $script:STM.Settings.ProtectedScopeTagNames = @('PAW-Missing') }
        Set-MockTags -Type DeviceCategory -Id $cat[0] -Tags '1'
        $p = New-STMChangePlan -Operations @(New-Op DeviceCategory $cat[0] Add @('8'))
        $p.CanApply | Should -BeTrue
        $p.PlanWarnings -join ' ' | Should -Match 'missing \[PAW-Missing\].*Warn'
    }

    It 'the fingerprint changes when the plan verdict or an override is edited' {
        Initialize-PlanTenant
        Set-MockTags -Type DeviceCategory -Id $cat[0] -Tags '1'
        $p = New-STMChangePlan -Operations @(New-Op DeviceCategory $cat[0] Add @('8'))
        $h = $p.Hash
        foreach ($edit in @({ param($x) $x.CanApply = -not $x.CanApply }, { param($x) $x.OverrideCap = $true }, { param($x) $x.OverrideReason = 'edited' }, { param($x) $x.AllowNoExplicitTags = $true }, { param($x) $x.PlanIssues = @('x') })) {
            $c = $p | ConvertTo-Json -Depth 10 | ConvertFrom-Json
            & $edit $c
            (InSTM { param($pl) Get-STMPlanHash -Plan $pl } -ArgumentList $c) | Should -Not -Be $h
        }
        $same = $p | ConvertTo-Json -Depth 10 | ConvertFrom-Json
        (InSTM { param($pl) Get-STMPlanHash -Plan $pl } -ArgumentList $same) | Should -Be $h
    }
}