Private/Access.ps1

# Read-only access check: what this sign-in (or app) is allowed to read, and whether scope tags come back for every object type.
# Sends only GET requests (and GET-only $batch). The session is forced to read-only for the duration of the check.

$script:STMPermissionCatalog = @(
    [pscustomobject]@{ Permission = 'DeviceManagementRBAC.Read.All'; Need = 'Required'; For = 'Scope tags, role definitions and role assignments' }
    [pscustomobject]@{ Permission = 'DeviceManagementConfiguration.Read.All'; Need = 'Required'; For = 'Configuration, compliance, endpoint security, settings catalog, filters, scripts (legacy), updates' }
    [pscustomobject]@{ Permission = 'DeviceManagementApps.Read.All'; Need = 'Required'; For = 'Apps, app configuration, app protection, policy sets' }
    [pscustomobject]@{ Permission = 'DeviceManagementManagedDevices.Read.All'; Need = 'Required'; For = 'Managed devices and device scripts' }
    [pscustomobject]@{ Permission = 'DeviceManagementServiceConfig.Read.All'; Need = 'Required'; For = 'Enrollment configurations, ADE and Autopilot profiles, terms and conditions' }
    [pscustomobject]@{ Permission = 'DeviceManagementScripts.Read.All'; Need = 'Recommended'; For = 'Platform scripts and remediations (newer permission; older tenants use Configuration)' }
    [pscustomobject]@{ Permission = 'Group.Read.All'; Need = 'Optional'; For = 'Show group names instead of ids' }
)

function Test-STMScopeGranted {
    param([string[]]$Granted, [string]$Permission)
    if (@($Granted) -contains $Permission) { return 'Granted' }
    $rw = $Permission -replace '\.Read\.All$', '.ReadWrite.All'
    if (@($Granted) -contains $rw) { return 'Granted (ReadWrite)' }
    if ($Permission -eq 'Group.Read.All' -and (@($Granted) -match '^(Directory\.Read\.All|Directory\.ReadWrite\.All|Group\.ReadWrite\.All)$')) { return 'Granted (via Directory or Group write)' }
    return 'Missing'
}

function Get-STMGrantedScopes {
    if ($script:STM.Backend -eq 'Mock') {
        if ($script:STM.MockGrantedScopes) { return @($script:STM.MockGrantedScopes) }
        return @($script:STMReadScopes + 'Group.Read.All')
    }
    $ctx = Get-MgContext
    if (-not $ctx) { return @() }
    return @($ctx.Scopes)
}

function Invoke-STMAccessCheck {
    param([string]$OutputDirectory, [switch]$SkipDeviceSample, [int]$DeviceSampleSize = 100, [switch]$IncludeInventoryCsv)
    $started = [DateTime]::UtcNow
    $prevMode = $script:STM.Mode
    $script:STM.Mode = 'ReadOnly'   # every non-GET is refused by Assert-STMReadOnlySafe while the check runs
    try {
        $granted = Get-STMGrantedScopes
        $writeLike = @($granted | Where-Object { $_ -match 'ReadWrite' })
        $perms = @(foreach ($p in $script:STMPermissionCatalog) {
            [pscustomobject]@{ Permission = $p.Permission; Need = $p.Need; Status = (Test-STMScopeGranted -Granted $granted -Permission $p.Permission); For = $p.For }
        })

        $checks = [System.Collections.Generic.List[object]]::new()
        $addCheck = {
            param($Area, $State, $Count, $Detail)
            $checks.Add([pscustomobject][ordered]@{ Area = $Area; Result = $State; Count = $Count; Detail = $Detail })
        }

        try { $tags = @(Update-STMScopeTags); & $addCheck 'Scope tags' 'OK' $tags.Count '' }
        catch { & $addCheck 'Scope tags' 'Failed' 0 $_.Exception.Message }
        try {
            $ra = @(Update-STMRoleAssignments)
            $unreadable = @($ra | Where-Object { $_.ReadError }).Count
            & $addCheck 'Role assignments' $(if ($unreadable) { 'Partial' } else { 'OK' }) $ra.Count $(if ($unreadable) { "$unreadable could not be read" } else { '' })
        }
        catch { & $addCheck 'Role assignments' 'Failed' 0 $_.Exception.Message }
        & $addCheck 'Group names' $(if ($script:STM.GroupNameStatus -eq 'Resolved' -or -not $script:STM.GroupNameStatus) { 'OK' } else { 'Not available' }) $script:STM.GroupNames.Count ([string]$script:STM.GroupNameStatus)

        $types = [System.Collections.Generic.List[object]]::new()
        foreach ($t in @(Get-STMTypeRegistry | Where-Object { -not ($_.PSObject.Properties['onDemand'] -and $_.onDemand) })) {
            $st = Update-STMTypeInventory -TypeKey $t.key
            $types.Add([pscustomobject][ordered]@{
                Type = $t.key; Label = $t.label; Category = $t.category; WritePath = $t.status
                Result = $st.State; Objects = $st.Count; ObjectsWithoutTags = $st.TagsMissing; SelectFallback = $st.SelectFallback; Error = $st.Error
            })
        }

        $device = $null
        if (-not $SkipDeviceSample) {
            $def = Get-STMTypeDef -Key 'ManagedDevice'
            $size = [math]::Max(1, [math]::Min($DeviceSampleSize, 999))
            try {
                $r = Invoke-STMGraph -Method GET -Uri "$($def.path)?`$select=$($def.select)&`$top=$size"
                $rows = @(@($r.value) | ForEach-Object { ConvertTo-STMRow -TypeDef $def -Object $_ })
                $device = [pscustomobject][ordered]@{ Result = 'OK'; Sampled = $rows.Count; WithoutTags = @($rows | Where-Object { -not $_.TagsKnown }).Count; MorePages = [bool]($r.PSObject.Properties['@odata.nextLink']); Error = '' }
            }
            catch {
                $kind = $_.Exception.Data['Kind']
                $device = [pscustomobject][ordered]@{ Result = $(if ($kind -eq 'Forbidden') { 'NoPermission' } else { 'Failed' }); Sampled = 0; WithoutTags = 0; MorePages = $false; Error = $_.Exception.Message }
            }
        }

        $readable = @($types | Where-Object { $_.Result -eq 'Loaded' }).Count
        $denied = @($types | Where-Object { $_.Result -eq 'NoPermission' })
        $failed = @($types | Where-Object { $_.Result -eq 'Failed' })
        $notInTenant = @($types | Where-Object { $_.Result -eq 'NotAvailable' }).Count
        $needsUser = @($types | Where-Object { $_.Result -eq 'AppSignInNotSupported' }).Count
        $noTags = @($types | Where-Object { $_.ObjectsWithoutTags -gt 0 })
        $missingRequired = @($perms | Where-Object { $_.Need -eq 'Required' -and $_.Status -eq 'Missing' })
        $verdict = if ($missingRequired.Count -or $denied.Count -or $failed.Count -or @($checks | Where-Object { $_.Area -eq 'Scope tags' -and $_.Result -ne 'OK' }).Count) { 'Incomplete' } else { 'ReadyForReadOnlyUse' }

        $report = [pscustomobject][ordered]@{
            Tool = "Intune Scope Tag Manager $($script:STM.Version)"
            CheckedAtUtc = $started.ToString('o'); FinishedAtUtc = [DateTime]::UtcNow.ToString('o')
            TenantId = $script:STM.TenantId; SignedInAs = $script:STM.Account; AppOnly = [bool]$script:STM.AppOnly; AppWritePermissions = @(Get-STMAppWritePermissions); Demo = ($script:STM.Backend -eq 'Mock')
            RequestsSent = 'GET only (including GET-only $batch and the group-name lookup). No changes were made.'
            Verdict = $verdict
            Summary = [pscustomobject][ordered]@{
                ObjectTypesReadable = $readable; ObjectTypesTotal = $types.Count; NoPermission = $denied.Count; Failed = $failed.Count; NotInTenant = $notInTenant; NeedsUserSignIn = $needsUser
                TypesWithObjectsMissingTags = $noTags.Count; MissingRequiredPermissions = @($missingRequired | ForEach-Object { $_.Permission })
                GrantedWritePermissions = $writeLike
            }
            Permissions = $perms; GrantedScopes = @($granted)
            Checks = @($checks); ObjectTypes = @($types); DeviceSample = $device
        }

        if (-not $OutputDirectory) { $OutputDirectory = Join-Path (Get-STMDataRoot) ("AccessChecks/" + $started.ToString('yyyyMMdd-HHmmss')) }
        if (-not (Test-Path -LiteralPath $OutputDirectory)) { New-Item -ItemType Directory -Path $OutputDirectory -Force | Out-Null }
        $report | ConvertTo-Json -Depth 8 | Set-Content -LiteralPath (Join-Path $OutputDirectory 'access-check.json') -Encoding utf8
        $types | Export-Csv -LiteralPath (Join-Path $OutputDirectory 'access-check-types.csv') -NoTypeInformation -Encoding utf8
        ConvertTo-STMAccessMarkdown -Report $report | Set-Content -LiteralPath (Join-Path $OutputDirectory 'access-check.md') -Encoding utf8
        if ($IncludeInventoryCsv) { [void](Export-STMInventoryCsv -Path (Join-Path $OutputDirectory 'inventory.csv')) }
        Write-STMAudit -Event 'AccessCheck' -Data @{ verdict = $verdict; readable = $readable; total = $types.Count; output = $OutputDirectory; inventoryCsv = [bool]$IncludeInventoryCsv }
        $report | Add-Member -NotePropertyName OutputDirectory -NotePropertyValue $OutputDirectory
        return $report
    }
    finally { $script:STM.Mode = $prevMode }
}

function ConvertTo-STMAccessMarkdown {
    param([Parameter(Mandatory)]$Report)
    $s = $Report.Summary
    $lines = [System.Collections.Generic.List[string]]::new()
    $lines.Add('# Intune Scope Tag Manager: read-only access check')
    $lines.Add('')
    $lines.Add("- Checked: $($Report.CheckedAtUtc) (UTC)")
    $lines.Add("- Tenant: $($Report.TenantId)")
    $lines.Add("- Signed in as: $($Report.SignedInAs)$(if ($Report.AppOnly) { ' (app-only, Intune RBAC not applied)' })")
    if ($Report.AppOnly) { $lines.Add("- App write permissions: $(if (@($Report.AppWritePermissions).Count) { @($Report.AppWritePermissions) -join ', ' } else { 'none (the app can only read)' })") }
    $lines.Add("- Requests sent: $($Report.RequestsSent)")
    $lines.Add("- Result: **$(if ($Report.Verdict -eq 'ReadyForReadOnlyUse') { 'Ready for read-only use' } else { 'Incomplete, see below' })**")
    $lines.Add("- Object types readable: $($s.ObjectTypesReadable) of $($s.ObjectTypesTotal) (no permission: $($s.NoPermission), failed: $($s.Failed), not in this tenant: $($s.NotInTenant)$(if ($s.NeedsUserSignIn) { ", need your own sign-in: $($s.NeedsUserSignIn)" }))")
    if (@($s.GrantedWritePermissions).Count) { $lines.Add("- Note: this sign-in also holds write permissions ($(@($s.GrantedWritePermissions) -join ', ')). The check did not use them.") }
    $lines.Add('')
    $lines.Add('## Permissions')
    $lines.Add('')
    $lines.Add('| Permission | Need | Status | Used for |')
    $lines.Add('|---|---|---|---|')
    foreach ($p in $Report.Permissions) { $lines.Add("| $($p.Permission) | $($p.Need) | $($p.Status) | $($p.For) |") }
    $lines.Add('')
    $lines.Add('## Checks')
    $lines.Add('')
    $lines.Add('| Area | Result | Count | Detail |')
    $lines.Add('|---|---|---|---|')
    foreach ($c in $Report.Checks) { $lines.Add("| $($c.Area) | $($c.Result) | $($c.Count) | $(([string]$c.Detail) -replace '\|', '/') |") }
    if ($Report.DeviceSample) {
        $d = $Report.DeviceSample
        $lines.Add("| Managed devices (sample) | $($d.Result) | $($d.Sampled) | $(if ($d.WithoutTags) { "$($d.WithoutTags) came back without scope tags" }) $(([string]$d.Error) -replace '\|', '/') |")
    }
    $lines.Add('')
    $lines.Add('## Object types')
    $lines.Add('')
    $lines.Add('| Object type | Result | Objects | Without tags | Write path |')
    $lines.Add('|---|---|---|---|---|')
    foreach ($t in $Report.ObjectTypes) {
        $res = $t.Result; if ($t.Error -and $t.Result -ne 'Loaded') { $res = "${res}: $(([string]$t.Error) -replace '\|', '/')" }
        $lines.Add("| $($t.Label) | $res | $($t.Objects) | $($t.ObjectsWithoutTags) | $(if ($t.WritePath -eq 'Supported') { 'Supported' } else { 'Verify in lab first' }) |")
    }
    $lines.Add('')
    $lines.Add('Object names are not included in this report. Use -IncludeInventoryCsv to also save the full inventory (names and tags) next to it.')
    return ($lines -join [Environment]::NewLine)
}