Tests/Access.Tests.ps1

#Requires -Modules Pester
# Read-only access check: verdicts, report files, privacy of the report, mode restore, GET-only traffic.

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

    function Start-WatchedCheck {
        # Wraps the mock handler to record the session mode and every method/sub-method sent during the check.
        InSTM {
            $script:Seen = [System.Collections.Generic.List[object]]::new()
            $script:STM.MockHandler = {
                param($m, $u, $b)
                $subs = @()
                if ($u -match '\$batch$') { $subs = @(($b | ConvertFrom-Json).requests | ForEach-Object method) }
                $script:Seen.Add([pscustomobject]@{ Method = $m; Uri = $u; SubMethods = $subs; Mode = $script:STM.Mode })
                Invoke-STMMockRequest -Method $m -Uri $u -Body $b
            }
        }
    }
    function Get-Seen { InSTM { $script:Seen.ToArray() } }

    # Object names from the mock tenant (type labels such as "Company Portal branding profile" are fine in the report).
    $script:secretNames = @('WIN - Device restrictions', 'Microsoft Outlook', 'Zoom Workplace', 'ADMX - Chrome', 'Acceptable use', 'Compliance - iOS BYOD', 'WKS-0', 'IPH-0', 'SN0000007', 'user1@contoso')
}

Describe 'Test-STMAccess on the demo tenant' {
    BeforeAll {
        Mock -ModuleName IntuneScopeTagManager Start-Sleep { }
        Mock -ModuleName IntuneScopeTagManager Write-Host { }
        $script:root = Connect-TestTenant -Mode ReadWrite -Name access
        Start-WatchedCheck
        $script:out = Join-Path $TestDrive 'check1'
        $script:report = Test-STMAccess -OutputDirectory $out -DeviceSampleSize 10
    }

    It 'returns ReadyForReadOnlyUse' {
        $report.Verdict | Should -Be 'ReadyForReadOnlyUse'
        $report.Demo | Should -BeTrue
        @($report.Summary.MissingRequiredPermissions | Where-Object { $_ }).Count | Should -Be 0
        $report.Summary.NotInTenant | Should -Be 2
        $report.Summary.ObjectTypesReadable | Should -Be ($report.Summary.ObjectTypesTotal - 2)
        $report.DeviceSample.Result | Should -Be 'OK'
        $report.DeviceSample.Sampled | Should -Be 10
        $report.DeviceSample.MorePages | Should -BeTrue
    }

    It 'writes access-check.md, access-check.json and access-check-types.csv (and no inventory)' {
        foreach ($f in 'access-check.md', 'access-check.json', 'access-check-types.csv') { Test-Path (Join-Path $out $f) | Should -BeTrue -Because $f }
        Test-Path (Join-Path $out 'inventory.csv') | Should -BeFalse
        (Get-Content (Join-Path $out 'access-check.json') -Raw | ConvertFrom-Json).Verdict | Should -Be 'ReadyForReadOnlyUse'
        @(Import-Csv (Join-Path $out 'access-check-types.csv')).Count | Should -Be $report.Summary.ObjectTypesTotal
        Get-Content (Join-Path $out 'access-check.md') -Raw | Should -Match 'Ready for read-only use'
    }

    It 'contains no object names' {
        $text = (Get-ChildItem $out -File | ForEach-Object { Get-Content $_.FullName -Raw }) -join "`n"
        foreach ($n in $secretNames) { $text | Should -Not -Match ([regex]::Escape($n)) -Because "'$n' is an object name" }
    }

    It 'sends GET only (including GET-only $batch and the getByIds lookup) and changes nothing' {
        $seen = @(Get-Seen)
        $seen.Count | Should -BeGreaterThan 30
        foreach ($s in $seen) {
            if ($s.Method -eq 'POST') { $s.Uri | Should -Match '(\$batch|/directoryObjects/getByIds)$' }
            else { $s.Method | Should -Be 'GET' }
            foreach ($sm in $s.SubMethods) { $sm | Should -Be 'GET' }
        }
        @((Get-MockState).Writes).Count | Should -Be 0
        @((Get-MockState).Requests | Where-Object Method -eq 'PATCH').Count | Should -Be 0
    }

    It 'holds the session read-only while it runs and restores the previous mode afterwards' {
        @(Get-Seen | ForEach-Object Mode | Sort-Object -Unique) | Should -Be @('ReadOnly')
        (Get-STMState).Mode | Should -Be 'ReadWrite'
    }

    It 'Regression: MissingRequiredPermissions is an empty list when nothing is missing' {
        @($report.Summary.MissingRequiredPermissions).Count | Should -Be 0
        (Get-Content (Join-Path $out 'access-check.json') -Raw) | Should -Match '"MissingRequiredPermissions":\s*\[\s*\]'
    }

    It 'notes the write permissions it did not use' {
        InSTM { $script:STM.MockGrantedScopes = @($script:STMWriteScopes + 'Group.Read.All') }
        $r = Test-STMAccess -OutputDirectory (Join-Path $TestDrive 'check-rw') -SkipDeviceSample
        $r.Verdict | Should -Be 'ReadyForReadOnlyUse'
        @($r.Summary.GrantedWritePermissions).Count | Should -BeGreaterThan 0
        ($r.Permissions | Where-Object Permission -eq 'DeviceManagementApps.Read.All').Status | Should -Be 'Granted (ReadWrite)'
        Get-Content (Join-Path $TestDrive 'check-rw/access-check.md') -Raw | Should -Match 'The check did not use them'
        $r.DeviceSample | Should -BeNullOrEmpty
    }

    It 'logs an AccessCheck audit entry' {
        $a = @(Get-Content (Join-Path $root 'audit.log') | ForEach-Object { $_ | ConvertFrom-Json } | Where-Object event -eq 'AccessCheck')
        $a.Count | Should -BeGreaterOrEqual 1
        $a[0].verdict | Should -Be 'ReadyForReadOnlyUse'
        $a[0].inventoryCsv | Should -BeFalse
    }
}

Describe 'Test-STMAccess when something is missing' {
    BeforeEach {
        Mock -ModuleName IntuneScopeTagManager Start-Sleep { }
        Mock -ModuleName IntuneScopeTagManager Write-Host { }
        [void](Connect-TestTenant -Mode ReadOnly)
    }

    It 'ForbiddenPaths -> Incomplete with the type reported as NoPermission' {
        InSTM { $script:STMMock.Options.ForbiddenPaths = @('deviceManagement/intents', 'deviceManagement/managedDevices') }
        $r = Test-STMAccess -OutputDirectory (Join-Path $TestDrive 'forbidden')
        $r.Verdict | Should -Be 'Incomplete'
        $r.Summary.NoPermission | Should -Be 1
        ($r.ObjectTypes | Where-Object Type -eq 'Intent').Result | Should -Be 'NoPermission'
        $r.DeviceSample.Result | Should -Be 'NoPermission'
        Get-Content (Join-Path $TestDrive 'forbidden/access-check.md') -Raw | Should -Match 'Incomplete'
    }

    It 'a missing required permission is reported and makes it Incomplete' {
        InSTM { $script:STM.MockGrantedScopes = @($script:STMReadScopes | Where-Object { $_ -ne 'DeviceManagementApps.Read.All' }) }
        $r = Test-STMAccess -OutputDirectory (Join-Path $TestDrive 'perm') -SkipDeviceSample
        $r.Verdict | Should -Be 'Incomplete'
        $r.Summary.MissingRequiredPermissions | Should -Be @('DeviceManagementApps.Read.All')
        ($r.Permissions | Where-Object Permission -eq 'DeviceManagementApps.Read.All').Status | Should -Be 'Missing'
        ($r.Permissions | Where-Object Permission -eq 'Group.Read.All').Status | Should -Be 'Missing'
    }

    It 'a missing optional permission alone does not make it Incomplete' {
        InSTM { $script:STM.MockGrantedScopes = @($script:STMReadScopes) }
        (Test-STMAccess -OutputDirectory (Join-Path $TestDrive 'opt') -SkipDeviceSample).Verdict | Should -Be 'ReadyForReadOnlyUse'
    }

    It 'Directory.Read.All counts for Group.Read.All' {
        InSTM { $script:STM.MockGrantedScopes = @($script:STMReadScopes + 'Directory.Read.All') }
        $r = Test-STMAccess -OutputDirectory (Join-Path $TestDrive 'dir') -SkipDeviceSample
        ($r.Permissions | Where-Object Permission -eq 'Group.Read.All').Status | Should -Match '^Granted'
    }

    It 'scope tags that cannot be read make it Incomplete' {
        InSTM { $script:STMMock.Options.ForbiddenPaths = @('deviceManagement/roleScopeTags') }
        $r = Test-STMAccess -OutputDirectory (Join-Path $TestDrive 'tags') -SkipDeviceSample
        $r.Verdict | Should -Be 'Incomplete'
        ($r.Checks | Where-Object Area -eq 'Scope tags').Result | Should -Be 'Failed'
    }

    It 'restores the session mode even when the check throws' {
        Set-STMMode -Mode ReadWrite | Out-Null
        Mock -ModuleName IntuneScopeTagManager ConvertTo-STMAccessMarkdown { throw 'report writer failed' }
        { Test-STMAccess -OutputDirectory (Join-Path $TestDrive 'throws') -SkipDeviceSample } | Should -Throw '*report writer failed*'
        (Get-STMState).Mode | Should -Be 'ReadWrite'
    }

    It '-IncludeInventoryCsv adds inventory.csv with object names' {
        $dir = Join-Path $TestDrive 'withinv'
        $r = Test-STMAccess -OutputDirectory $dir -SkipDeviceSample -IncludeInventoryCsv
        $inv = Join-Path $dir 'inventory.csv'
        Test-Path $inv | Should -BeTrue
        Get-Content $inv -Raw | Should -Match 'Microsoft Outlook'
        # The report files themselves still hold no names.
        Get-Content (Join-Path $dir 'access-check.json') -Raw | Should -Not -Match 'Microsoft Outlook'
        (Get-Content (Join-Path $dir 'access-check.json') -Raw | ConvertFrom-Json).Verdict | Should -Be 'ReadyForReadOnlyUse'
    }
}