Tests/Server.Tests.ps1

#Requires -Modules Pester
# Local web UI host: one-time key, session header, Host/Origin checks, Content-Type, CSP and loopback-only binding.
# The server runs in its own runspace on the demo tenant and is shut down through /api/shutdown at the end.

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

    $script:serverRoot = Join-Path $TestDrive 'server-data'
    $script:ps = [powershell]::Create()
    [void]$ps.AddScript({
            param($Manifest, $DataRoot)
            Import-Module $Manifest -Force
            [void](Connect-STMDemo -DeviceCount 15 -DataRoot $DataRoot)
            # MaxRequests is a safety net so the runspace always ends even if shutdown is never sent.
            # Start-STMServer is private; Start-ScopeTagManager -Demo has no -DataRoot, so call it in module scope.
            & (Get-Module IntuneScopeTagManager) { Start-STMServer -NoBrowser -MaxRequests 200 6>$null }
        }).AddArgument($script:ModuleManifest).AddArgument($script:serverRoot)
    $script:output = [System.Management.Automation.PSDataCollection[psobject]]::new()
    $script:async = $ps.BeginInvoke([System.Management.Automation.PSDataCollection[psobject]]::new(), $script:output)

    $deadline = [DateTime]::UtcNow.AddSeconds(60)
    $script:url = $null
    while (-not $script:url -and [DateTime]::UtcNow -lt $deadline -and -not $async.IsCompleted) {
        # Index access: enumerating an open PSDataCollection blocks until the pipeline ends.
        for ($i = 0; $i -lt $output.Count; $i++) { if ("$($output[$i])" -like 'STM_URL=*') { $script:url = "$($output[$i])".Substring(8) } }
        if (-not $script:url) { Start-Sleep -Milliseconds 100 }
    }
    if (-not $script:url) { throw "Server did not start: $(@($ps.Streams.Error) -join '; ')" }
    $u = [uri]$script:url
    $script:port = $u.Port
    $script:token = [uri]::UnescapeDataString(($u.Query.TrimStart('?').Split('&') | Where-Object { $_ -like 't=*' }).Substring(2))
    $script:base = "http://127.0.0.1:$port"

    $handler = [System.Net.Http.HttpClientHandler]::new()
    $handler.UseProxy = $false
    $handler.AllowAutoRedirect = $false
    $script:http = [System.Net.Http.HttpClient]::new($handler)
    $script:http.Timeout = [TimeSpan]::FromSeconds(20)

    function Send-Req {
        param([string]$Method = 'GET', [string]$Path, [hashtable]$Headers = @{}, [string]$Body, [string]$ContentType, [string]$HostHeader)
        $req = [System.Net.Http.HttpRequestMessage]::new([System.Net.Http.HttpMethod]::new($Method), "$base$Path")
        if ($HostHeader) { $req.Headers.Host = $HostHeader }
        foreach ($k in $Headers.Keys) { [void]$req.Headers.TryAddWithoutValidation($k, [string]$Headers[$k]) }
        if ($PSBoundParameters.ContainsKey('Body')) {
            $req.Content = [System.Net.Http.StringContent]::new($Body, [Text.Encoding]::UTF8)
            $req.Content.Headers.Remove('Content-Type') | Out-Null
            if ($ContentType) { [void]$req.Content.Headers.TryAddWithoutValidation('Content-Type', $ContentType) }
        }
        $resp = $script:http.SendAsync($req).GetAwaiter().GetResult()
        $csp = $null
        if ($resp.Headers.Contains('Content-Security-Policy')) { $csp = @($resp.Headers.GetValues('Content-Security-Policy')) -join '' }
        [pscustomobject]@{
            Status = [int]$resp.StatusCode
            Body = $resp.Content.ReadAsStringAsync().GetAwaiter().GetResult()
            Csp = $csp
            Headers = $resp.Headers
            ContentType = [string]$resp.Content.Headers.ContentType
        }
    }
}

AfterAll {
    if ($script:token -and $script:async -and -not $script:async.IsCompleted) {
        try { [void](Send-Req -Method POST -Path '/api/shutdown' -Headers @{ 'X-STM-Token' = $token } -Body '{}' -ContentType 'application/json') } catch { }
        [void]$script:async.AsyncWaitHandle.WaitOne(15000)
    }
    if ($script:async -and -not $script:async.IsCompleted) { $script:ps.Stop() }
    if ($script:ps) { $script:ps.Dispose() }
    if ($script:http) { $script:http.Dispose() }
}

Describe 'Start-STMServer' {
    It 'prints STM_URL with a loopback address and a one-time key' {
        $url | Should -Match '^http://127\.0\.0\.1:\d+/\?t=[A-Za-z0-9_-]{40,}$'
    }

    It 'listens on 127.0.0.1 only' {
        $listeners = @([System.Net.NetworkInformation.IPGlobalProperties]::GetIPGlobalProperties().GetActiveTcpListeners() | Where-Object Port -eq $port)
        $listeners.Count | Should -BeGreaterThan 0
        foreach ($l in $listeners) { $l.Address.ToString() | Should -Be '127.0.0.1' }
    }

    It 'cannot be reached on a non-loopback address of this machine' {
        $addrs = @([System.Net.NetworkInformation.NetworkInterface]::GetAllNetworkInterfaces() |
            ForEach-Object { $_.GetIPProperties().UnicastAddresses } | ForEach-Object Address |
            Where-Object { $_.AddressFamily -eq 'InterNetwork' -and -not [System.Net.IPAddress]::IsLoopback($_) })
        if (-not $addrs.Count) { Set-ItResult -Skipped -Because 'this machine has no non-loopback IPv4 address' ; return }
        $c = [System.Net.Sockets.TcpClient]::new()
        try {
            $ok = $false
            try { $ok = $c.ConnectAsync($addrs[0], $port).Wait(2000) -and $c.Connected } catch { $ok = $false }
            $ok | Should -BeFalse
        } finally { $c.Dispose() }
    }
}

Describe 'Page and one-time key' {
    It 'GET / without the key is refused' {
        $r = Send-Req -Path '/'
        $r.Status | Should -Be 403
        $r.Body | Should -Not -Match ([regex]::Escape($token))
    }

    It 'GET / with a wrong key is refused' {
        (Send-Req -Path '/?t=wrong-key').Status | Should -Be 403
        (Send-Req -Path "/?t=$($token.ToUpperInvariant())").Status | Should -Be 403
    }

    It 'GET / with the key serves the page with a nonce-based CSP' {
        $r = Send-Req -Path "/?t=$token"
        $r.Status | Should -Be 200
        $r.ContentType | Should -Match 'text/html'
        $r.Csp | Should -Not -BeNullOrEmpty
        $directives = @{}
        foreach ($d in $r.Csp -split ';') { $d = $d.Trim(); if ($d) { $n, $v = $d -split '\s+', 2; $directives[$n] = $v } }
        $directives['script-src'] | Should -Match "^'nonce-[A-Za-z0-9_-]{20,}'$"
        $directives['script-src'] | Should -Not -Match 'unsafe-inline|unsafe-eval|\*|http'
        $directives['default-src'] | Should -Be "'none'"
        $directives['frame-ancestors'] | Should -Be "'none'"
        $directives['connect-src'] | Should -Be "'self'"
        $nonce = ([regex]::Match($directives['script-src'], "'nonce-([^']+)'")).Groups[1].Value
        $r.Body | Should -Match ([regex]::Escape("<script nonce=`"$nonce`">"))
        $r.Body | Should -Not -Match '__STM_NONCE__|__STM_TOKEN__'
        # Every script tag carries the nonce.
        foreach ($m in [regex]::Matches($r.Body, '<script\b[^>]*>')) { $m.Value | Should -Match ([regex]::Escape("nonce=`"$nonce`"")) }
    }

    It 'uses a fresh nonce per page load' {
        $a = (Send-Req -Path "/?t=$token").Csp
        $b = (Send-Req -Path "/?t=$token").Csp
        $a | Should -Not -Be $b
    }

    It 'sends hardening headers' {
        $r = Send-Req -Path "/?t=$token"
        @($r.Headers.GetValues('X-Frame-Options')) | Should -Be @('DENY')
        @($r.Headers.GetValues('X-Content-Type-Options')) | Should -Be @('nosniff')
        @($r.Headers.GetValues('Referrer-Policy')) | Should -Be @('no-referrer')
        $r.Headers.CacheControl.NoStore | Should -BeTrue
    }

    It 'unknown non-API paths are 404' {
        (Send-Req -Path '/etc/passwd').Status | Should -Be 404
    }
}

Describe 'API protection' {
    It 'an API call without X-STM-Token is refused' {
        $r = Send-Req -Path '/api/state'
        $r.Status | Should -BeIn 401, 403
        $r.Body | Should -Match 'session key'
    }

    It 'an API call with the key only in the query string is refused' {
        (Send-Req -Path "/api/state?t=$token").Status | Should -BeIn 401, 403
    }

    It 'an API call with a wrong X-STM-Token is refused' {
        (Send-Req -Path '/api/state' -Headers @{ 'X-STM-Token' = 'nope' }).Status | Should -BeIn 401, 403
    }

    It 'an API call with the right token works' {
        $r = Send-Req -Path '/api/state' -Headers @{ 'X-STM-Token' = $token }
        $r.Status | Should -Be 200
        $s = $r.Body | ConvertFrom-Json
        $s.backend | Should -Be 'Mock'
        $s.mode | Should -Be 'ReadOnly'
    }

    It 'a wrong Host header is refused (DNS rebinding), even with the token' -ForEach @('evil.example', 'evil.example:{0}', '127.0.0.1:1', 'localhost') {
        $h = $_ -f $port
        $r = Send-Req -Path '/api/state' -Headers @{ 'X-STM-Token' = $token } -HostHeader $h
        $r.Status | Should -Be 403
        $r.Body | Should -Match 'Host not allowed'
        (Send-Req -Path "/?t=$token" -HostHeader $h).Status | Should -Be 403
    }

    It 'localhost:<port> is an allowed Host' {
        (Send-Req -Path '/api/state' -Headers @{ 'X-STM-Token' = $token } -HostHeader "localhost:$port").Status | Should -Be 200
    }

    It 'a foreign Origin is refused, even with the token' -ForEach @('http://evil.example', 'null', 'http://127.0.0.1:1', 'https://127.0.0.1:{0}') {
        $o = $_ -f $port
        $r = Send-Req -Method POST -Path '/api/refresh/meta' -Headers @{ 'X-STM-Token' = $token; 'Origin' = $o } -Body '{}' -ContentType 'application/json'
        $r.Status | Should -Be 403
        $r.Body | Should -Match 'Origin not allowed'
    }

    It 'the page''s own Origin is allowed' {
        (Send-Req -Path '/api/state' -Headers @{ 'X-STM-Token' = $token; 'Origin' = "http://127.0.0.1:$port" }).Status | Should -Be 200
    }

    It 'a POST without Content-Type application/json is refused (<_>)' -ForEach @('text/plain', 'application/x-www-form-urlencoded', 'multipart/form-data; boundary=x', '') {
        $ct = $_
        $r = Send-Req -Method POST -Path '/api/mode' -Headers @{ 'X-STM-Token' = $token } -Body '{"mode":"ReadWrite"}' -ContentType $ct
        $r.Status | Should -Be 400
        $r.Body | Should -Match 'Content-Type must be application/json'
        ((Send-Req -Path '/api/state' -Headers @{ 'X-STM-Token' = $token }).Body | ConvertFrom-Json).mode | Should -Be 'ReadOnly'
    }

    It 'other methods are refused' {
        (Send-Req -Method PUT -Path '/api/state' -Headers @{ 'X-STM-Token' = $token } -Body '{}' -ContentType 'application/json').Status | Should -Be 405
        (Send-Req -Method DELETE -Path '/api/state' -Headers @{ 'X-STM-Token' = $token }).Status | Should -Be 405
    }

    It 'an unknown API route is 404 and errors come back as JSON' {
        $r = Send-Req -Path '/api/nope' -Headers @{ 'X-STM-Token' = $token }
        $r.Status | Should -Be 404
        ($r.Body | ConvertFrom-Json).error | Should -Match 'No route'
    }

    It 'a read-only session refuses to apply through the API' {
        $tags = Send-Req -Method POST -Path '/api/refresh/meta' -Headers @{ 'X-STM-Token' = $token } -Body '{}' -ContentType 'application/json'
        $tags.Status | Should -Be 200
        $r = Send-Req -Method POST -Path '/api/apply/start' -Headers @{ 'X-STM-Token' = $token } -Body '{"planId":"none","confirmation":"APPLY 1"}' -ContentType 'application/json'
        $r.Status | Should -Be 400
    }
}

Describe 'Shutdown' {
    It 'POST /api/shutdown without the token does not stop the server' {
        (Send-Req -Method POST -Path '/api/shutdown' -Body '{}' -ContentType 'application/json').Status | Should -BeIn 401, 403
        Start-Sleep -Milliseconds 200
        $async.IsCompleted | Should -BeFalse
    }

    It 'POST /api/shutdown with the token stops the server and closes the port' {
        $r = Send-Req -Method POST -Path '/api/shutdown' -Headers @{ 'X-STM-Token' = $token } -Body '{}' -ContentType 'application/json'
        $r.Status | Should -Be 200
        $async.AsyncWaitHandle.WaitOne(15000) | Should -BeTrue
        $ps.EndInvoke($async) | Out-Null
        @([System.Net.NetworkInformation.IPGlobalProperties]::GetIPGlobalProperties().GetActiveTcpListeners() | Where-Object Port -eq $port).Count | Should -Be 0
        $audit = @(Get-Content (Join-Path $serverRoot 'audit.log') | ForEach-Object { $_ | ConvertFrom-Json })
        @($audit | Where-Object event -eq 'UiStarted').Count | Should -Be 1
        @($audit | Where-Object event -eq 'UiStopped').Count | Should -Be 1
    }
}