Private/Graph.ps1

# Graph transport: one place for every call, so retries, throttling, the mock tenant and logging behave the same everywhere.
# All scope tag reads and writes use Graph beta: v1.0 does not expose roleScopeTagIds on most Intune resources.

function Get-STMGraphBase { 'https://graph.microsoft.com/beta' }

function ConvertTo-STMAbsoluteUri {
    param([Parameter(Mandatory)][string]$Uri)
    if ($Uri -match '^https://') { return $Uri }
    return "$(Get-STMGraphBase)/$($Uri.TrimStart('/'))"
}

function Get-STMRetryDelay {
    # Intune 429s often have no Retry-After; fall back to capped exponential backoff with jitter.
    param([int]$Attempt, $RetryAfter)
    $seconds = 0
    if ($null -ne $RetryAfter -and "$RetryAfter" -ne '') {
        $parsed = 0
        if ([int]::TryParse("$RetryAfter", [ref]$parsed)) { $seconds = $parsed }
    }
    if ($seconds -le 0) { $seconds = [math]::Min([math]::Pow(2, $Attempt), 60) }
    $jitter = Get-Random -Minimum 0 -Maximum 1000
    return [int]($seconds * 1000 + $jitter)
}

function Assert-STMReadOnlySafe {
    # Defence in depth: a read-only session can only send GETs, a $batch made only of GETs, or the getByIds name lookup.
    # Anything else throws before it leaves the machine, whatever code path asked for it.
    param([string]$Method, [string]$AbsoluteUri, [string]$JsonBody)
    if ($Method -eq 'GET' -or $script:STM.Mode -eq 'ReadWrite') { return }
    $isBatch = $AbsoluteUri -match '/\$batch$'
    $batchIsReadOnly = $false
    if ($isBatch -and $JsonBody) {
        try {
            $reqs = @((ConvertFrom-STMJson $JsonBody).requests)
            $batchIsReadOnly = $reqs.Count -gt 0 -and -not @($reqs | Where-Object { -not $_ -or "$($_.method)".ToUpperInvariant() -ne 'GET' }).Count
        }
        catch { $batchIsReadOnly = $false }
    }
    $isLookup = $AbsoluteUri -match '/directoryObjects/getByIds$'
    if ($Method -eq 'POST' -and ($batchIsReadOnly -or $isLookup)) { return }
    $e = [System.Exception]::new("Blocked a $Method to $AbsoluteUri because this session is read-only. Nothing was sent.")
    $e.Data['Kind'] = 'ReadOnlyBlocked'; $e.Data['Status'] = 0
    throw $e
}

function Invoke-STMRawRequest {
    # Returns @{ Status = int; Body = string; RetryAfter = string } and never throws for HTTP errors.
    param(
        [Parameter(Mandatory)][ValidateSet('GET', 'PATCH', 'POST')][string]$Method,
        [Parameter(Mandatory)][string]$Uri,
        [string]$JsonBody
    )
    $abs = ConvertTo-STMAbsoluteUri -Uri $Uri
    Assert-STMReadOnlySafe -Method $Method -AbsoluteUri $abs -JsonBody $JsonBody
    if ($script:STM.Backend -eq 'Mock') {
        return & $script:STM.MockHandler $Method $abs $JsonBody
    }
    $params = @{ Method = $Method; Uri = $abs; OutputType = 'Json'; ErrorAction = 'Stop' }
    if ($JsonBody) { $params.Body = $JsonBody; $params.ContentType = 'application/json' }
    try {
        $json = Invoke-MgGraphRequest @params
        return @{ Status = 200; Body = [string]$json; RetryAfter = $null }
    }
    catch { return (Get-STMHttpErrorDetail -ErrorRecord $_) }
}

function Get-STMHeaderValue {
    param($Response, [string]$Name)
    $sets = @()
    try { $sets += $Response.Headers } catch { }
    try { if ($Response.Content) { $sets += $Response.Content.Headers } } catch { }
    foreach ($h in $sets) {
        if (-not $h) { continue }
        $vals = $null
        try { if ($h.TryGetValues($Name, [ref]$vals)) { return (@($vals) -join ', ') } } catch { try { $v = $h[$Name]; if ($v) { return (@($v) -join ', ') } } catch { } }
    }
    return ''
}

function Get-STMHttpErrorDetail {
    # Everything Microsoft Graph said about a failed call: status, the JSON error body (Graph puts it in ErrorDetails, not in
    # the exception message), and the request-id and date Microsoft support asks for. Never the token.
    param($ErrorRecord)
    $ex = $ErrorRecord.Exception
    $d = @{ Status = 0; Body = ''; RetryAfter = $null; RequestId = ''; ClientRequestId = ''; Date = ''; WwwAuthenticate = ''; Raw = [string]$ex.Message; ExceptionType = $ex.GetType().FullName }
    try { if ($ErrorRecord.ErrorDetails -and $ErrorRecord.ErrorDetails.Message) { $d.Body = [string]$ErrorRecord.ErrorDetails.Message } } catch { }
    $resp = $null
    try { $resp = $ex.Response } catch { }
    if ($resp) {
        try { if ($resp.StatusCode) { $d.Status = [int]$resp.StatusCode } } catch { }
        if (-not $d.Body) { try { $d.Body = [string]$resp.Content.ReadAsStringAsync().GetAwaiter().GetResult() } catch { } }
        $d.RequestId = Get-STMHeaderValue $resp 'request-id'
        $d.ClientRequestId = Get-STMHeaderValue $resp 'client-request-id'
        $d.Date = Get-STMHeaderValue $resp 'Date'
        $d.WwwAuthenticate = Get-STMHeaderValue $resp 'WWW-Authenticate'
        try { $h = $resp.Headers; if ($h -and $h.RetryAfter -and $h.RetryAfter.Delta) { $d.RetryAfter = [int][math]::Ceiling($h.RetryAfter.Delta.TotalSeconds) } } catch { }
    }
    if ($d.Status -eq 0) { try { if ($ex.StatusCode) { $d.Status = [int]$ex.StatusCode } } catch { } }
    if ($d.Status -eq 0 -and $d.Raw -match '\b(4\d\d|5\d\d)\b') { $d.Status = [int]$Matches[1] }
    if ($d.Status -eq 0) { $d.Status = 599 }
    if (-not $d.Body) { $d.Body = $d.Raw }
    return $d
}

function Invoke-STMGraph {
    # JSON in, PSCustomObject out. Retries 429/5xx. Throws STMGraphException on final failure.
    param(
        [Parameter(Mandatory)][ValidateSet('GET', 'PATCH', 'POST')][string]$Method,
        [Parameter(Mandatory)][string]$Uri,
        $Body,
        [int]$MaxRetries = 6
    )
    $json = $null
    if ($null -ne $Body) { $json = if ($Body -is [string]) { $Body } else { $Body | ConvertTo-Json -Depth 20 -Compress } }
    for ($attempt = 1; $attempt -le $MaxRetries; $attempt++) {
        if ($Method -eq 'PATCH') { Wait-STMWriteBudget -Count 1 }
        $r = Invoke-STMRawRequest -Method $Method -Uri $Uri -JsonBody $json
        if ($r.Status -ge 200 -and $r.Status -lt 300) {
            if ([string]::IsNullOrWhiteSpace($r.Body)) { return $null }
            return ($r.Body | ConvertFrom-STMJson)
        }
        if ($r.Status -in 429, 500, 502, 503, 504 -and $attempt -lt $MaxRetries) {
            $script:STM.Stats.Retries++
            Start-Sleep -Milliseconds (Get-STMRetryDelay -Attempt $attempt -RetryAfter $r.RetryAfter)
            continue
        }
        throw (New-STMGraphError -Status $r.Status -Body $r.Body -Uri $Uri -Method $Method -Detail $r)
    }
}

function ConvertFrom-STMGraphErrorBody {
    # Graph SDK 2.x puts a whole HTTP dump (request line, headers, HTML-encoded JSON) in the error. Intune nests its own JSON
    # error inside error.message. Returns @{ Code; Message; RequestId; Date; Json } with the innermost readable text.
    param([string]$Body)
    $r = @{ Code = ''; Message = ''; RequestId = ''; Date = ''; Json = '' }
    if (-not $Body) { return $r }
    $t = [System.Net.WebUtility]::HtmlDecode($Body)
    $i = $t.IndexOf('{"error"')
    if ($i -lt 0) { $i = $t.IndexOf('{') }
    $json = if ($i -ge 0) { $t.Substring($i).Trim() } else { '' }
    $o = $null
    if ($json) { try { $o = $json | ConvertFrom-Json -ErrorAction Stop; $r.Json = $json } catch { $o = $null } }
    if (-not $o -or -not $o.error) {
        $r.Message = (($t -split "`r?`n") | Where-Object { $_ -and $_ -notmatch '^(GET|POST|PATCH|HTTP/|[A-Za-z\-]+: )' } | Select-Object -First 3) -join ' '
        if (-not $r.Message) { $r.Message = $t }
        return $r
    }
    $r.Code = [string]$o.error.code
    $msg = [string]$o.error.message
    if ($o.error.innerError) { $r.RequestId = [string]$o.error.innerError.'request-id'; $r.Date = [string]$o.error.innerError.date }
    for ($n = 0; $n -lt 3 -and $msg.TrimStart().StartsWith('{'); $n++) {
        try { $m = $msg | ConvertFrom-Json -ErrorAction Stop } catch { break }
        if ($m.ErrorCode) { $r.Code = [string]$m.ErrorCode }
        $next = if ($m.Message) { [string]$m.Message } elseif ($m.message) { [string]$m.message } else { '' }
        if (-not $next) { break }
        $msg = $next
    }
    $r.Message = ($msg -replace '\s+', ' ').Trim()
    return $r
}

function New-STMGraphError {
    param([int]$Status, [string]$Body, [string]$Uri, [string]$Method = 'GET', [hashtable]$Detail)
    $pe = ConvertFrom-STMGraphErrorBody -Body $Body
    $msg = if ($pe.Message) { $pe.Message } else { $Body }
    $code = $pe.Code; $reqId = $pe.RequestId; $date = $pe.Date
    if ($Detail) {
        if (-not $reqId -and $Detail.RequestId) { $reqId = [string]$Detail.RequestId }
        if (-not $date -and $Detail.Date) { $date = [string]$Detail.Date }
    }
    if (-not $msg) { $msg = 'No error text came back from Microsoft Graph.' }
    $kind = Get-STMErrorKind -Status $Status -Message $msg
    $label = if ($Status -eq 401) { 'Unauthorized' } else { $kind }
    $text = "HTTP $Status ($label): $msg"
    if ($code -and $msg -notmatch [regex]::Escape($code)) { $text += " [$code]" }
    $hint = Get-STMErrorHint -Status $Status -Message $msg -Code $code
    if ($hint) { $text += " $hint" }
    $e = [System.Exception]::new($text)
    $e.Data['Status'] = $Status
    $e.Data['Kind'] = $kind
    $e.Data['Uri'] = $Uri
    $e.Data['Method'] = $Method
    $e.Data['GraphCode'] = $code
    $e.Data['RequestId'] = $reqId
    $e.Data['Date'] = $date
    if ($Detail) {
        $e.Data['ClientRequestId'] = [string]$Detail.ClientRequestId
        $e.Data['WwwAuthenticate'] = [string]$Detail.WwwAuthenticate
        $e.Data['RawMessage'] = [string]$Detail.Raw
        $e.Data['ExceptionType'] = [string]$Detail.ExceptionType
    }
    $e.Data['Body'] = if ($Body.Length -gt 4000) { $Body.Substring(0, 4000) } else { $Body }
    try { $e.Data['ErrorId'] = Write-STMErrorLog -Exception $e -Source 'Graph' } catch { }
    return $e
}

function Get-STMErrorHint {
    param([int]$Status, [string]$Message, [string]$Code)
    if ($Status -in 401, 403 -and $script:STM.AppOnly -and $script:STM.TokenCheck -and $script:STM.TokenCheck.claims -and -not @($script:STM.TokenCheck.claims.applicationPermissions).Count) {
        return 'The app''s token carries no application permissions at all, so Intune refuses it. An Entra admin adds the Intune Read.All permissions as Application permissions on this app registration and grants admin consent; then sign out and sign in again.'
    }
    if ($Status -in 401, 403 -and $script:STM.AppOnly -and (($script:STM.TokenCheck -and $script:STM.TokenCheck.ok) -or ($script:STM.Tags -and @($script:STM.Tags).Count))) {
        return 'Other Intune areas accepted the app''s sign-in, so the app''s permissions are fine; this one area does not accept app-only access. Sign in with your own account to include it.'
    }
    if ($Status -eq 401 -and $script:STM.AppOnly) {
        return 'Microsoft Graph did not accept the app''s sign-in for Intune. Usually the app registration lacks Intune application permissions with admin consent (DeviceManagementConfiguration.Read.All, DeviceManagementApps.Read.All, DeviceManagementRBAC.Read.All, DeviceManagementManagedDevices.Read.All). Press Details: it shows which permissions the token carries.'
    }
    if ($Status -eq 401) { return 'The sign-in was not accepted or has expired. Sign out and sign in again; press Details if it keeps happening.' }
    if ($Status -eq 403 -and $script:STM.AppOnly) { return 'The app registration is missing an application permission for this object type. Press Details to see what the token carries.' }
    return ''
}

function Get-STMErrorKind {
    param([int]$Status, [string]$Message)
    if ($Status -eq 403 -and $Message -match '(?i)multi.?admin|approval') { return 'MultiAdminApprovalRequired' }
    switch ($Status) {
        400 { 'BadRequest' }
        401 { 'NotSignedIn' }
        403 { 'Forbidden' }
        404 { 'NotFound' }
        409 { 'Conflict' }
        429 { 'Throttled' }
        default { if ($Status -ge 500) { 'ServiceError' } else { 'Error' } }
    }
}

function Get-STMCollection {
    # Follows @odata.nextLink. Calls $OnPage with each page so large lists (devices) can stream.
    param([Parameter(Mandatory)][string]$Uri, [scriptblock]$OnPage, [int]$MaxItems = 0)
    $items = [System.Collections.Generic.List[object]]::new()
    $next = $Uri
    while ($next) {
        $resp = Invoke-STMGraph -Method GET -Uri $next
        $page = @()
        if ($null -ne $resp -and $resp.PSObject.Properties['value']) { $page = @($resp.value) }
        foreach ($i in $page) { $items.Add($i) }
        if ($OnPage) { & $OnPage $page }
        $next = $null
        if ($resp.PSObject.Properties['@odata.nextLink']) { $next = [string]$resp.'@odata.nextLink' }
        if ($MaxItems -gt 0 -and $items.Count -ge $MaxItems) { break }
    }
    return , $items
}

# ---- $batch (20 sub-requests). Each sub-request counts against throttling and can 429 on its own. ----

function Invoke-STMBatch {
    # $Requests: list of @{ id; method; url (relative to beta, leading /); body (object or $null) }
    # Returns hashtable id -> @{ status; body (PSCustomObject or $null); error }
    param([Parameter(Mandatory)][object[]]$Requests, [int]$MaxRetries = 6)
    $results = @{}
    # Graph batch ids are mapped to short numeric ids internally; callers keep their own ids.
    $pending = [System.Collections.Generic.List[object]]::new()
    $n = 0
    foreach ($r in $Requests) { $n++; $pending.Add([pscustomobject]@{ id = [string]$n; callerId = [string]$r.id; method = $r.method; url = $r.url; body = $r.body; attempts = 0 }) }
    while ($pending.Count -gt 0) {
        $chunk = @($pending | Select-Object -First 20)
        $writes = @($chunk | Where-Object { $_.method -ne 'GET' }).Count
        if ($writes -gt 0) { Wait-STMWriteBudget -Count $writes }
        $payload = @{ requests = @(foreach ($r in $chunk) {
            $sub = [ordered]@{ id = [string]$r.id; method = $r.method; url = $r.url }
            if ($null -ne $r.body) { $sub.body = $r.body; $sub.headers = @{ 'Content-Type' = 'application/json' } }
            $sub
        }) }
        foreach ($r in $chunk) { $r.attempts++ }
        $resp = $null
        try { $resp = Invoke-STMGraph -Method POST -Uri '$batch' -Body ($payload | ConvertTo-Json -Depth 30 -Compress) }
        catch {
            foreach ($r in $chunk) { $results[$r.callerId] = @{ status = [int]$_.Exception.Data['Status']; body = $null; error = $_.Exception.Message } }
            foreach ($r in $chunk) { [void]$pending.Remove($r) }
            continue
        }
        $retryLater = [System.Collections.Generic.List[object]]::new()
        $maxRetryAfter = 0
        foreach ($sub in @($resp.responses)) {
            $id = [string]$sub.id
            $req = $chunk | Where-Object { [string]$_.id -eq $id } | Select-Object -First 1
            $status = [int]$sub.status
            if ($req -and $status -in 429, 500, 502, 503, 504 -and $req.attempts -lt $MaxRetries) {
                $retryLater.Add($req)
                $ra = $null
                if ($sub.headers -and $sub.headers.PSObject.Properties['Retry-After']) { $ra = $sub.headers.'Retry-After' }
                $d = Get-STMRetryDelay -Attempt $req.attempts -RetryAfter $ra
                if ($d -gt $maxRetryAfter) { $maxRetryAfter = $d }
                continue
            }
            $err = $null
            if ($status -ge 400) {
                $m = ''
                try { $m = [string]$sub.body.error.message } catch { }
                $err = "HTTP $status ($(Get-STMErrorKind -Status $status -Message $m)): $m"
            }
            if ($req) { $results[$req.callerId] = @{ status = $status; body = $sub.body; error = $err } }
        }
        foreach ($r in $chunk) { [void]$pending.Remove($r) }
        if ($retryLater.Count -gt 0) {
            $script:STM.Stats.Retries += $retryLater.Count
            Start-Sleep -Milliseconds $maxRetryAfter
            foreach ($r in $retryLater) { $pending.Insert(0, $r) }
        }
    }
    return $results
}

# ---- Write pacing. Intune allows 200 writes / 20 s per tenant and 100 per app; stay under the per-app limit. ----

function Wait-STMWriteBudget {
    param([int]$Count = 1)
    $limit = [int]$script:STM.Settings.MaxWritesPer20Seconds
    if ($limit -le 0) { return }
    $window = [TimeSpan]::FromSeconds(20)
    while ($true) {
        $now = [DateTime]::UtcNow
        while ($script:STM.WriteLog.Count -gt 0 -and ($now - $script:STM.WriteLog.Peek()) -gt $window) { [void]$script:STM.WriteLog.Dequeue() }
        if ($script:STM.WriteLog.Count + $Count -le $limit) {
            for ($i = 0; $i -lt $Count; $i++) { $script:STM.WriteLog.Enqueue($now) }
            return
        }
        $wait = $window - ($now - $script:STM.WriteLog.Peek())
        Start-Sleep -Milliseconds ([math]::Max(50, [int]$wait.TotalMilliseconds + 50))
    }
}

# ---- Who is signed in. Reads Entra role template ids from the token's wids claim; the token itself is never stored or logged. ----

function Get-STMSignedInRoleInfo {
    $info = [ordered]@{ Detected = $false; IsTenantWideAdmin = $false; Roles = @() }
    if ($script:STM.Backend -eq 'Mock') { return [pscustomobject](& $script:STM.MockRoleInfo) }
    $known = @{
        '62e90394-69f5-4237-9190-012177145e10' = 'Global Administrator'
        '3a2c62db-5318-420d-8d74-23affee5d9d5' = 'Intune Administrator'
        'f2ef992c-3afb-46b9-b7cf-a126ee74c451' = 'Global Reader'
    }
    try {
        $resp = Invoke-MgGraphRequest -Method GET -Uri "$(Get-STMGraphBase)/deviceManagement/roleScopeTags?`$top=1" -OutputType HttpResponseMessage -ErrorAction Stop
        $token = $resp.RequestMessage.Headers.Authorization.Parameter
        $payload = $token.Split('.')[1].Replace('-', '+').Replace('_', '/')
        switch ($payload.Length % 4) { 2 { $payload += '==' } 3 { $payload += '=' } }
        $claims = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($payload)) | ConvertFrom-Json
        $token = $null
        $wids = @($claims.wids)
        $info.Detected = $true
        $info.Roles = @($wids | Where-Object { $known.ContainsKey($_) } | ForEach-Object { $known[$_] })
        $info.IsTenantWideAdmin = [bool](@($info.Roles) -match 'Global Administrator|Intune Administrator|Global Reader')
    } catch { }
    return [pscustomobject]$info
}