Tests/Tools.Tests.ps1

#Requires -Modules Pester
# Page-driven tools: starting signed out, sign-in from the page, saved sign-in details, the access check and the lab test
# started from the page, and the guards that keep the lab test away from the Production tenant. Uses the built-in sample tenant.

BeforeAll {
    . (Join-Path $PSScriptRoot 'TestHelpers.ps1')
    $script:oldUserConfig = $env:STM_USERCONFIG
    $env:STM_USERCONFIG = Join-Path $TestDrive 'userconfig'
    function Invoke-Route { param([string]$Method, [string]$Path, $Body) InSTM { param($m, $p, $b) Invoke-STMApiRoute -Method $m -Path $p -Query @{} -Body $b } -ArgumentList $Method, $Path, $Body }
    function New-Body { param([hashtable]$H) [pscustomobject]$H }
    $script:graphInstalled = [bool](Get-Module -ListAvailable -Name Microsoft.Graph.Authentication)
}
AfterAll { $env:STM_USERCONFIG = $script:oldUserConfig }

Describe 'Starting signed out' {
    BeforeAll { InSTM { Disconnect-STMTenant; $script:STM.Settings = @{ DataRoot = (Join-Path $TestDrive 'signedout') } } }
    It 'state says not signed in and lists the shipped profiles' {
        $st = Invoke-Route GET '/api/state'
        $st.signedIn | Should -BeFalse
        $st.profileNames | Should -Contain 'Production'
        $st.profileNames | Should -Contain 'Lab'
        $st.profiles['Production'].protectedTagNames | Should -Contain 'PAW-Protected'
        $st.profiles['Production'].protectedTagMissingBehavior | Should -Be 'Block'
    }
    It 'refuses data routes until someone signs in: <_>' -ForEach @('POST /api/refresh/meta', 'GET /api/inventory', 'POST /api/plan', 'POST /api/apply/start', 'POST /api/access', 'POST /api/import/csv') {
        $m, $p = $_.Split(' ')
        { Invoke-Route $m $p (New-Body @{}) } | Should -Throw '*Sign in first*'
    }
    It 'Start-ScopeTagManager with no sign-in parameters does not try to sign in' {
        $src = (Get-Command Start-ScopeTagManager).Definition
        $src | Should -Match '-not \$Launcher -and \(\$TenantId -or \$ClientId'
    }
}

Describe 'Sign-in from the page' {
    It 'opens the sample tenant' {
        $st = Invoke-Route POST '/api/connect' (New-Body @{ kind = 'demo'; profile = 'Production' })
        $st.signedIn | Should -BeTrue
        $st.backend | Should -Be 'Mock'
        $st.profile | Should -Be 'Production'
        $st.mode | Should -Be 'ReadOnly'
    }
    It 'refuses an unknown profile' {
        { Invoke-Route POST '/api/connect' (New-Body @{ kind = 'demo'; profile = '..\x' }) } | Should -Throw '*Unknown profile*'
    }
    It 'refuses an unknown sign-in kind' {
        { Invoke-Route POST '/api/connect' (New-Body @{ kind = 'password'; profile = 'Lab'; tenantId = 'contoso.onmicrosoft.com' }) } | Should -Throw '*Unknown sign-in kind*'
    }
    It 'reports a missing Microsoft Graph module with a kind the page can act on' -Skip:$script:graphInstalled {
        $err = $null
        try { Invoke-Route POST '/api/connect' (New-Body @{ kind = 'delegated'; profile = 'Lab'; tenantId = 'contoso.onmicrosoft.com' }) } catch { $err = $_ }
        $err | Should -Not -BeNullOrEmpty
        $err.Exception.Data['Kind'] | Should -Be 'GraphModuleMissing'
    }
    It 'never writes a client secret anywhere' {
        $secret = 'Zz9~NotARealSecret-' + [guid]::NewGuid().ToString('N')
        try { Invoke-Route POST '/api/connect' (New-Body @{ kind = 'appSecret'; profile = 'Lab'; tenantId = '00000000-0000-4000-8000-000000000001'; clientId = '00000000-0000-4000-8000-000000000002'; secret = $secret; remember = $true }) } catch { }
        $hits = @(Get-ChildItem -LiteralPath $TestDrive -Recurse -File | Where-Object { (Get-Content -LiteralPath $_.FullName -Raw -ErrorAction SilentlyContinue) -like "*$secret*" })
        $hits.Count | Should -Be 0
    }
}

Describe 'Saved sign-in details' {
    It 'saves tenant and client id for the current user and fills them into the profile' {
        [void](Invoke-Route POST '/api/settings/save' (New-Body @{ profile = 'Lab'; tenantId = 'aaaaaaaa-1111-4222-8333-444444444444'; clientId = 'bbbbbbbb-1111-4222-8333-444444444444' }))
        $s = InSTM { Get-STMSettings -Profile 'Lab' }
        $s.TenantId | Should -Be 'aaaaaaaa-1111-4222-8333-444444444444'
        $s.ClientId | Should -Be 'bbbbbbbb-1111-4222-8333-444444444444'
        Test-Path (Join-Path $env:STM_USERCONFIG 'Profiles/Lab.json') | Should -BeTrue
    }
    It 'refuses a client id that is not a GUID' {
        { Invoke-Route POST '/api/settings/save' (New-Body @{ profile = 'Lab'; tenantId = 'contoso.onmicrosoft.com'; clientId = 'not-a-guid' }) } | Should -Throw '*GUID*'
    }
    It 'never takes guardrails from the saved file' {
        $f = Join-Path $env:STM_USERCONFIG 'Profiles/Production.json'
        @{ TenantId = 'cccccccc-1111-4222-8333-444444444444'; ProtectedScopeTagNames = @(); ProtectedTagMissingBehavior = 'Warn'; MaxChangesPerRun = 99999 } | ConvertTo-Json | Set-Content -LiteralPath $f
        $s = InSTM { Get-STMSettings -Profile 'Production' }
        $s.ProtectedScopeTagNames | Should -Contain 'PAW-Protected'
        $s.ProtectedTagMissingBehavior | Should -Be 'Block'
        $s.MaxChangesPerRun | Should -Be 250
        $s.TenantId | Should -Be 'cccccccc-1111-4222-8333-444444444444'
    }
}

Describe 'Lab test guards' {
    BeforeAll {
        [void](Invoke-Route POST '/api/connect' (New-Body @{ kind = 'demo'; profile = 'Lab' }))
        # TestDrive files from earlier blocks are gone, so save the Production tenant id for this user again.
        $script:productionTenant = 'cccccccc-1111-4222-8333-444444444444'
        [void](Invoke-Route POST '/api/settings/save' (New-Body @{ profile = 'Production'; tenantId = $script:productionTenant }))
    }
    It 'refuses when the two tenant ids differ' {
        { Invoke-Route POST '/api/labtest/start' (New-Body @{ tenantId = 'dddddddd-1111-4222-8333-444444444444'; confirmTenantId = 'eeeeeeee-1111-4222-8333-444444444444'; clientId = 'bbbbbbbb-1111-4222-8333-444444444444' }) } | Should -Throw '*differ*'
    }
    It 'refuses a domain name instead of a tenant id' {
        { Invoke-Route POST '/api/labtest/start' (New-Body @{ tenantId = 'contoso.onmicrosoft.com'; confirmTenantId = 'contoso.onmicrosoft.com'; clientId = 'bbbbbbbb-1111-4222-8333-444444444444' }) } | Should -Throw '*GUID*'
    }
    It 'refuses the Production tenant, also in other letter case' {
        { Invoke-Route POST '/api/labtest/start' (New-Body @{ tenantId = $script:productionTenant.ToUpper(); confirmTenantId = $script:productionTenant.ToUpper(); clientId = 'bbbbbbbb-1111-4222-8333-444444444444' }) } | Should -Throw '*Production*'
    }
    It 'the lab script itself also refuses the Production tenant' {
        $out = & (InSTM { Get-STMPowerShellExe }) -NoProfile -NonInteractive -File (Join-Path $script:ModuleRoot 'LabTest/Invoke-STMLabTest.ps1') -TenantId $script:productionTenant -ConfirmLabTenant $script:productionTenant -ClientId 'bbbbbbbb-1111-4222-8333-444444444444' -NoPrompt -OutputDirectory (Join-Path $TestDrive 'labrefused') 2>&1
        ($out | Out-String) | Should -Match 'Production profile'
        Test-Path (Join-Path $TestDrive 'labrefused/lab-results.json') | Should -BeFalse
    }
    It 'offers the sample run only while the sample tenant is open' {
        InSTM { $script:STM.Backend = 'Graph' }
        try { { Invoke-Route POST '/api/labtest/start' (New-Body @{ demo = $true }) } | Should -Throw '*sample tenant*' }
        finally { InSTM { $script:STM.Backend = 'Mock' } }
    }
}

Describe 'Lab test started from the page (sample tenant)' {
    BeforeAll {
        [void](Invoke-Route POST '/api/connect' (New-Body @{ kind = 'demo'; profile = 'Lab' }))
        $script:start = Invoke-Route POST '/api/labtest/start' (New-Body @{ demo = $true; includeDevice = $true })
        $deadline = [DateTime]::UtcNow.AddMinutes(8)
        $script:final = $script:start
        while ($script:final.state -eq 'Running' -and [DateTime]::UtcNow -lt $deadline) { Start-Sleep -Seconds 2; $script:final = Invoke-Route POST '/api/labtest/status' (New-Body @{ id = $script:start.id }) }
    }
    It 'runs as its own process and reports Running first' { $script:start.state | Should -Be 'Running' }
    It 'finishes with results' { $script:final.state | Should -Be 'Finished' }
    It 'verifies object types and fails none' {
        $res = @($script:final.results)
        @($res | Where-Object Verdict -eq 'Verified').Count | Should -BeGreaterThan 20
        @($res | Where-Object Verdict -eq 'Failed').Count | Should -Be 0
    }
    It 'keeps its log and results in its own folder' {
        Test-Path (Join-Path $script:final.folder 'lab-results.md') | Should -BeTrue
        @($script:final.log).Count | Should -BeGreaterThan 5
    }
    It 'opens only folders the tool knows about' {
        (Invoke-Route POST '/api/folder/open' (New-Body @{ which = 'lab'; id = $script:start.id })).folder | Should -Be (Resolve-Path $script:final.folder).ProviderPath
        { Invoke-Route POST '/api/folder/open' (New-Body @{ which = 'C:\Windows' }) } | Should -Throw '*Nothing to open*'
    }
}

Describe 'Access check from the page' {
    BeforeAll { [void](Invoke-Route POST '/api/connect' (New-Body @{ kind = 'demo'; profile = 'Production' })) }
    It 'runs read-only, saves the report in the chosen folder and remembers the folder' {
        $dir = Join-Path $TestDrive 'client-folder'
        Reset-MockLog
        $r = Invoke-Route POST '/api/access' (New-Body @{ folder = $dir; rememberFolder = $true; includeInventory = $true })
        $r.Verdict | Should -Be 'ReadyForReadOnlyUse'
        $r.OutputDirectory | Should -BeLike "$dir*ScopeTag_AccessCheck_*"
        Test-Path (Join-Path $r.OutputDirectory 'access-check.md') | Should -BeTrue
        Test-Path (Join-Path $r.OutputDirectory 'inventory.csv') | Should -BeTrue
        @((Get-MockState).Writes).Count | Should -Be 0
        (InSTM { Get-STMSettings -Profile 'Production' }).AccessCheckFolder | Should -Be $dir
    }
    It 'refuses a folder path that climbs out with ..' {
        { Invoke-Route POST '/api/access' (New-Body @{ folder = (Join-Path $TestDrive '..\..\x') }) } | Should -Throw '*not valid*'
    }
    It 'signing out clears the session' {
        $st = Invoke-Route POST '/api/signout' (New-Body @{})
        $st.signedIn | Should -BeFalse
        $st.tags.Count | Should -Be 0
    }
}