Tests/Graph.Tests.ps1

#Requires -Modules Pester
# Graph transport: retries, error kinds, $batch chunking and per-request retry, read-only guard.

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

Describe 'Invoke-STMGraph retries' {
    BeforeEach {
        Mock -ModuleName IntuneScopeTagManager Start-Sleep { }
        [void](Connect-TestTenant -Mode ReadOnly)
        Reset-MockLog
    }

    It 'retries a 429 that carries Retry-After and waits that long' {
        InSTM { $script:STMMock.Options.ThrottleNext = 2; $script:STMMock.Options.ThrottleRetryAfter = 7 }
        $r = InSTM { Invoke-STMGraph -Method GET -Uri 'deviceManagement/roleScopeTags' }
        @($r.value).Count | Should -Be 9
        @(Get-MockRequests).Count | Should -Be 3
        Should -Invoke Start-Sleep -ModuleName IntuneScopeTagManager -Times 2 -Exactly -ParameterFilter { $Milliseconds -ge 7000 -and $Milliseconds -lt 8000 }
        (Get-STMState).Stats.Retries | Should -Be 2
    }

    It 'retries a 429 without Retry-After using exponential backoff' {
        InSTM { $script:STMMock.Options.ThrottleNext = 3; $script:STMMock.Options.ThrottleRetryAfter = $null }
        $r = InSTM { Invoke-STMGraph -Method GET -Uri 'deviceManagement/roleScopeTags' }
        @($r.value).Count | Should -Be 9
        @(Get-MockRequests).Count | Should -Be 4
        # attempt 1 -> 2 s, attempt 2 -> 4 s, attempt 3 -> 8 s (plus < 1 s jitter)
        Should -Invoke Start-Sleep -ModuleName IntuneScopeTagManager -Times 1 -Exactly -ParameterFilter { $Milliseconds -ge 2000 -and $Milliseconds -lt 3000 }
        Should -Invoke Start-Sleep -ModuleName IntuneScopeTagManager -Times 1 -Exactly -ParameterFilter { $Milliseconds -ge 4000 -and $Milliseconds -lt 5000 }
        Should -Invoke Start-Sleep -ModuleName IntuneScopeTagManager -Times 1 -Exactly -ParameterFilter { $Milliseconds -ge 8000 -and $Milliseconds -lt 9000 }
    }

    It 'caps the backoff at 60 seconds' {
        $d = InSTM { Get-STMRetryDelay -Attempt 10 -RetryAfter $null }
        $d | Should -BeGreaterOrEqual 60000
        $d | Should -BeLessThan 61000
    }

    It 'retries 5xx responses (<_>)' -ForEach @(500, 502, 503, 504) {
        $status = $_
        InSTM {
            param($s)
            $script:FailCount = 2; $script:FailStatus = $s
            $script:STM.MockHandler = {
                param($m, $u, $b)
                if ($script:FailCount -gt 0) { $script:FailCount--; return @{ Status = $script:FailStatus; Body = '{"error":{"code":"x","message":"Service unavailable"}}'; RetryAfter = $null } }
                Invoke-STMMockRequest -Method $m -Uri $u -Body $b
            }
        } -ArgumentList $status
        $r = InSTM { Invoke-STMGraph -Method GET -Uri 'deviceManagement/roleScopeTags' }
        @($r.value).Count | Should -Be 9
        Should -Invoke Start-Sleep -ModuleName IntuneScopeTagManager -Times 2 -Exactly
    }

    It 'throws with Data[Kind] = Throttled once retries run out' {
        InSTM { $script:STMMock.Options.ThrottleNext = 100 }
        $err = $null
        try { InSTM { Invoke-STMGraph -Method GET -Uri 'deviceManagement/roleScopeTags' -MaxRetries 3 } } catch { $err = $_.Exception }
        $err | Should -Not -BeNullOrEmpty
        $err.Data['Kind'] | Should -Be 'Throttled'
        $err.Data['Status'] | Should -Be 429
        @(Get-MockRequests).Count | Should -Be 3
    }

    It 'throws with Data[Kind] = ServiceError after persistent 5xx' {
        InSTM { $script:STM.MockHandler = { param($m, $u, $b) @{ Status = 503; Body = '{"error":{"code":"x","message":"down"}}'; RetryAfter = $null } } }
        $err = $null
        try { InSTM { Invoke-STMGraph -Method GET -Uri 'deviceManagement/roleScopeTags' -MaxRetries 4 } } catch { $err = $_.Exception }
        $err.Data['Kind'] | Should -Be 'ServiceError'
        Should -Invoke Start-Sleep -ModuleName IntuneScopeTagManager -Times 3 -Exactly
    }

    It 'does not retry a 403 and reports Kind Forbidden' {
        InSTM { $script:STMMock.Options.ForbiddenPaths = @('deviceManagement/intents') }
        $err = $null
        try { InSTM { Invoke-STMGraph -Method GET -Uri 'deviceManagement/intents' } } catch { $err = $_.Exception }
        $err.Data['Kind'] | Should -Be 'Forbidden'
        @(Get-MockRequests).Count | Should -Be 1
        Should -Invoke Start-Sleep -ModuleName IntuneScopeTagManager -Times 0 -Exactly
    }

    It 'maps <Status> to <Kind>' -ForEach @(
        @{ Status = 400; Message = 'bad'; Kind = 'BadRequest' }
        @{ Status = 401; Message = 'x'; Kind = 'NotSignedIn' }
        @{ Status = 403; Message = 'denied'; Kind = 'Forbidden' }
        @{ Status = 403; Message = 'Multi Admin Approval is enabled'; Kind = 'MultiAdminApprovalRequired' }
        @{ Status = 404; Message = 'x'; Kind = 'NotFound' }
        @{ Status = 409; Message = 'x'; Kind = 'Conflict' }
        @{ Status = 429; Message = 'x'; Kind = 'Throttled' }
        @{ Status = 503; Message = 'x'; Kind = 'ServiceError' }
    ) {
        InSTM { param($s, $m) Get-STMErrorKind -Status $s -Message $m } -ArgumentList $Status, $Message | Should -Be $Kind
    }
}

Describe 'Invoke-STMBatch' {
    BeforeEach {
        Mock -ModuleName IntuneScopeTagManager Start-Sleep { }
        [void](Connect-TestTenant -Mode ReadOnly)
        Reset-MockLog
    }

    It 'splits 45 requests into $batch calls of 20, 20 and 5 and maps results back to caller ids' {
        $ids = @(Get-MockObjects -Type MobileApp | Select-Object -First 45 | ForEach-Object { $_.id })
        $ids.Count | Should -Be 45
        $res = InSTM {
            param($ids)
            $reqs = @(foreach ($i in $ids) { @{ id = "app:$i"; method = 'GET'; url = "/deviceAppManagement/mobileApps/$i"; body = $null } })
            Invoke-STMBatch -Requests $reqs
        } -ArgumentList (, $ids)
        $batches = Get-BatchSubRequests
        $batches.Count | Should -Be 3
        @($batches | ForEach-Object { @($_).Count }) | Should -Be @(20, 20, 5)
        $res.Count | Should -Be 45
        foreach ($i in $ids) { $res["app:$i"].status | Should -Be 200; $res["app:$i"].body.id | Should -Be $i }
    }

    It 'retries only the sub-request that was throttled (with its Retry-After)' {
        $ids = @(Get-MockObjects -Type MobileApp | Select-Object -First 5 | ForEach-Object { $_.id })
        InSTM { $script:STMMock.Options.ThrottleNext = 1; $script:STMMock.Options.ThrottleRetryAfter = 3 }
        $res = InSTM {
            param($ids)
            Invoke-STMBatch -Requests @(foreach ($i in $ids) { @{ id = $i; method = 'GET'; url = "/deviceAppManagement/mobileApps/$i"; body = $null } })
        } -ArgumentList (, $ids)
        $batches = Get-BatchSubRequests
        $batches.Count | Should -Be 2
        @($batches[0]).Count | Should -Be 5
        @($batches[1]).Count | Should -Be 1
        $batches[1][0].url | Should -Be "/deviceAppManagement/mobileApps/$($ids[0])"
        # Every object was fetched once, except the throttled one (twice).
        $subs = @(Get-MockRequests | Where-Object { $_.Uri -notmatch '\$batch$' })
        @($subs | Where-Object { $_.Uri -like "*$($ids[0])" }).Count | Should -Be 2
        foreach ($i in $ids[1..4]) { @($subs | Where-Object { $_.Uri -like "*$i" }).Count | Should -Be 1 }
        foreach ($i in $ids) { $res[$i].status | Should -Be 200 }
        Should -Invoke Start-Sleep -ModuleName IntuneScopeTagManager -Times 1 -Exactly -ParameterFilter { $Milliseconds -ge 3000 -and $Milliseconds -lt 4000 }
    }

    It 'gives up on a sub-request after MaxRetries and reports its last status' {
        $ids = @(Get-MockObjects -Type MobileApp | Select-Object -First 2 | ForEach-Object { $_.id })
        InSTM {
            # Throttle every sub-request for the first object only.
            $script:BatchCalls = 0
            $script:STM.MockHandler = {
                param($m, $u, $b)
                if ($u -match '\$batch$') {
                    $script:BatchCalls++
                    $req = $b | ConvertFrom-Json
                    $responses = foreach ($r in $req.requests) {
                        if ($r.url -like "*$($script:ThrottleId)") { [ordered]@{ id = $r.id; status = 429; body = @{ error = @{ message = 'slow down' } } } }
                        else { $x = Invoke-STMMockRequest -Method $r.method -Uri ('https://graph.microsoft.com/beta' + $r.url) -Body $null; [ordered]@{ id = $r.id; status = $x.Status; body = ($x.Body | ConvertFrom-Json) } }
                    }
                    return @{ Status = 200; Body = (@{ responses = @($responses) } | ConvertTo-Json -Depth 10 -Compress); RetryAfter = $null }
                }
                Invoke-STMMockRequest -Method $m -Uri $u -Body $b
            }
        }
        InSTM { param($i) $script:ThrottleId = $i } -ArgumentList $ids[0]
        $res = InSTM {
            param($ids)
            Invoke-STMBatch -MaxRetries 3 -Requests @(foreach ($i in $ids) { @{ id = $i; method = 'GET'; url = "/deviceAppManagement/mobileApps/$i"; body = $null } })
        } -ArgumentList (, $ids)
        $res[$ids[0]].status | Should -Be 429
        $res[$ids[0]].error | Should -Match 'Throttled'
        $res[$ids[1]].status | Should -Be 200
        InSTM { $script:BatchCalls } | Should -Be 3
    }

    It 'reports an outer $batch failure on every sub-request instead of throwing' {
        InSTM { $script:STM.MockHandler = { param($m, $u, $b) @{ Status = 400; Body = '{"error":{"message":"bad batch"}}'; RetryAfter = $null } } }
        $res = InSTM { Invoke-STMBatch -Requests @(@{ id = 'a'; method = 'GET'; url = '/x'; body = $null }, @{ id = 'b'; method = 'GET'; url = '/y'; body = $null }) }
        $res['a'].status | Should -Be 400
        $res['b'].error | Should -Match 'bad batch'
    }
}

Describe 'Read-only guard (Assert-STMReadOnlySafe)' {
    BeforeEach {
        Mock -ModuleName IntuneScopeTagManager Start-Sleep { }
        [void](Connect-TestTenant -Mode ReadOnly)
        Reset-MockLog
        $script:obj = Get-MockObjects -Type DeviceCategory | Select-Object -First 1
    }

    It 'blocks a PATCH before it reaches the mock' {
        $err = $null
        try { InSTM { param($id) Invoke-STMGraph -Method PATCH -Uri "deviceManagement/deviceCategories/$id" -Body @{ roleScopeTagIds = @('1') } } -ArgumentList $obj.id } catch { $err = $_.Exception }
        $err.Data['Kind'] | Should -Be 'ReadOnlyBlocked'
        @(Get-MockRequests).Count | Should -Be 0
        @((Get-MockState).Writes).Count | Should -Be 0
    }

    It 'blocks a POST that is not $batch or getByIds' {
        { InSTM { Invoke-STMGraph -Method POST -Uri 'deviceManagement/deviceCategories' -Body @{ displayName = 'x' } } } | Should -Throw '*read-only*'
        @(Get-MockRequests).Count | Should -Be 0
    }

    It 'blocks a $batch that contains a PATCH (Invoke-STMGraph throws)' {
        $body = @{ requests = @(
                @{ id = '1'; method = 'GET'; url = '/deviceManagement/roleScopeTags' }
                @{ id = '2'; method = 'PATCH'; url = "/deviceManagement/deviceCategories/$($obj.id)"; body = @{ roleScopeTagIds = @('1') }; headers = @{ 'Content-Type' = 'application/json' } }
            ) } | ConvertTo-Json -Depth 10 -Compress
        $err = $null
        try { InSTM { param($b) Invoke-STMGraph -Method POST -Uri '$batch' -Body $b } -ArgumentList $body } catch { $err = $_.Exception }
        $err.Data['Kind'] | Should -Be 'ReadOnlyBlocked'
        @(Get-MockRequests).Count | Should -Be 0
    }

    It 'blocks a $batch whose method key is written with a JSON escape' {
        $body = '{"requests":[{"id":"1","\u006dethod":"PATCH","url":"/deviceManagement/deviceCategories/x","body":{"roleScopeTagIds":["1"]}}]}'
        { InSTM { param($b) Invoke-STMRawRequest -Method POST -Uri '$batch' -JsonBody $b } -ArgumentList $body } | Should -Throw '*read-only*'
        @(Get-MockRequests).Count | Should -Be 0
    }

    It 'blocks a $batch body that is not valid JSON' {
        { InSTM { Invoke-STMRawRequest -Method POST -Uri '$batch' -JsonBody '{"requests":[' } } | Should -Throw '*read-only*'
    }

    It 'blocks a $batch with a pretty-printed or non-GET method (<_>)' -ForEach @('POST', 'DELETE', 'PUT', 'patch') {
        $method = $_
        $body = "{ `"requests`": [ { `"id`": `"1`", `"method`" : `"$method`", `"url`": `"/deviceManagement/deviceCategories`" } ] }"
        { InSTM { param($b) Invoke-STMRawRequest -Method POST -Uri '$batch' -JsonBody $b } -ArgumentList $body } | Should -Throw '*read-only*'
        @(Get-MockRequests).Count | Should -Be 0
    }

    It 'Invoke-STMBatch with a PATCH returns errors and sends nothing' {
        $res = InSTM { param($id) Invoke-STMBatch -Requests @(@{ id = 'w'; method = 'PATCH'; url = "/deviceManagement/deviceCategories/$id"; body = @{ roleScopeTagIds = @('1') } }) } -ArgumentList $obj.id
        $res['w'].error | Should -Match 'read-only'
        @(Get-MockRequests).Count | Should -Be 0
        @((Get-MockState).Writes).Count | Should -Be 0
    }

    It 'allows a GET-only $batch' {
        $res = InSTM { param($id) Invoke-STMBatch -Requests @(@{ id = 'r'; method = 'GET'; url = "/deviceManagement/deviceCategories/$id"; body = $null }) } -ArgumentList $obj.id
        $res['r'].status | Should -Be 200
        @(Get-MockRequests | Where-Object { $_.Uri -match '\$batch$' }).Count | Should -Be 1
    }

    It 'allows the directoryObjects/getByIds POST' {
        $r = InSTM { Invoke-STMGraph -Method POST -Uri 'https://graph.microsoft.com/v1.0/directoryObjects/getByIds' -Body @{ ids = @('a1111111-0000-4000-8000-000000000001'); types = @('group') } }
        @($r.value)[0].displayName | Should -Be 'SG-Intune-Helpdesk-East'
    }

    It 'lets a PATCH through in ReadWrite mode' {
        Set-STMMode -Mode ReadWrite | Out-Null
        InSTM { param($id) Invoke-STMGraph -Method PATCH -Uri "deviceManagement/deviceCategories/$id" -Body @{ roleScopeTagIds = @('1') } } -ArgumentList $obj.id
        Get-MockTags -Type DeviceCategory -Id $obj.id | Should -Be '1'
    }
}