ScopeGap.psm1

Set-StrictMode -Version Latest

function Get-ScopeGap {
<#
.SYNOPSIS
Compare the scopes your API key holds with the scopes a list of endpoints needs.
.DESCRIPTION
-EndpointsPath is a CSV with the columns endpoint (a label such as "GET /items") and required_scope (one scope text).
-GrantedPath is a CSV with one column, scope: the scopes your key has. Header matching is trimmed and
case-insensitive; extra columns are ignored.

A required scope is covered when a granted scope equals it (trimmed, case-insensitive), or a granted scope is "*"
(covers everything), or a granted scope ends in ":*" and the required scope starts with the same text before that colon
plus a colon ("items:*" covers "items:read" but not "itemsx:read" or "reports:read"). These rules are generic; they
are not any vendor's scope scheme.

Returns one object per endpoint (Endpoint, RequiredScope, Callable, CoveredBy) and each object also carries Summary
(Endpoints, Callable, Blocked, BlockedShare as a number with 1 decimal, BlockedShareText, GrantedScopes,
RepeatedGrantedRows), MissingScopes (Scope, Unlocks; count descending then scope), UnusedGranted (granted scopes that
cover no listed endpoint, sorted) and Report. The text report is also written to the console unless -Quiet is given.
Throws on a missing file, a missing column, no data rows in either file, an empty required_scope or endpoint (the data
row number is named) or a duplicate endpoint label. Empty cells in the granted file are ignored.
.EXAMPLE
Get-ScopeGap -EndpointsPath endpoints.csv -GrantedPath granted.csv
#>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory)][string]$EndpointsPath,
        [Parameter(Mandatory)][string]$GrantedPath,
        [switch]$Quiet
    )

    $inv = [System.Globalization.CultureInfo]::InvariantCulture
    $readCsv = {
        param([string]$path, [string[]]$cols, [string]$label)
        if (-not (Test-Path -LiteralPath $path -PathType Leaf)) { throw "file not found: $path" }
        $rows = @(Import-Csv -LiteralPath $path)
        if ($rows.Count -eq 0) { throw "$label has no data rows" }
        $names = @{}
        foreach ($p in $rows[0].PSObject.Properties.Name) { $names[$p.Trim([char]0xFEFF).Trim().ToLowerInvariant()] = $p }
        foreach ($need in $cols) {
            if (-not $names.ContainsKey($need)) { throw "missing column: $need ($label)" }
        }
        $out = New-Object System.Collections.Generic.List[object]
        foreach ($r in $rows) {
            $o = [ordered]@{}
            foreach ($c in $cols) {
                $v = $r.PSObject.Properties[$names[$c]].Value
                $o[$c] = if ($null -eq $v) { '' } else { ([string]$v).Trim() }
            }
            $out.Add([pscustomobject]$o)
        }
        , $out.ToArray()
    }
    $ordinal = [System.Comparison[object]] { param($a, $b) [string]::CompareOrdinal($a, $b) }

    $ep = & $readCsv $EndpointsPath @('endpoint', 'required_scope') 'endpoints file'
    $gr = & $readCsv $GrantedPath @('scope') 'granted file'

    # Granted scopes: unique (trimmed, case-insensitive), first spelling kept, repeats counted.
    $granted = New-Object System.Collections.Generic.List[string]
    $grantedSeen = New-Object 'System.Collections.Generic.HashSet[string]'
    $repeated = 0
    foreach ($g in $gr) {
        if ($g.scope -eq '') { continue }
        if ($grantedSeen.Add($g.scope.ToLowerInvariant())) { $granted.Add($g.scope) } else { $repeated++ }
    }

    $covers = {
        param([string]$g, [string]$req)
        $gl = $g.ToLowerInvariant(); $rl = $req.ToLowerInvariant()
        if ($gl -eq $rl -or $gl -eq '*') { return $true }
        if ($gl.EndsWith(':*')) {
            $prefix = $gl.Substring(0, $gl.Length - 2) + ':'
            return $rl.StartsWith($prefix, [System.StringComparison]::Ordinal)
        }
        return $false
    }

    $labels = New-Object 'System.Collections.Generic.HashSet[string]'
    $objs = New-Object System.Collections.Generic.List[object]
    $usedGranted = New-Object 'System.Collections.Generic.HashSet[string]'
    $missing = @{}      # lowercased scope -> @{ Scope; Unlocks }
    $n = 0
    foreach ($e in $ep) {
        $n++
        if ($e.endpoint -eq '') { throw "row ${n}: empty endpoint" }
        if ($e.required_scope -eq '') { throw "row ${n}: empty required_scope for endpoint '$($e.endpoint)'" }
        if (-not $labels.Add($e.endpoint.ToLowerInvariant())) { throw "row ${n}: duplicate endpoint '$($e.endpoint)'" }
        $by = ''
        foreach ($g in $granted) {
            if (& $covers $g $e.required_scope) {
                if ($by -eq '') { $by = $g }
                [void]$usedGranted.Add($g.ToLowerInvariant())
            }
        }
        $ok = ($by -ne '')
        if (-not $ok) {
            $k = $e.required_scope.ToLowerInvariant()
            if (-not $missing.ContainsKey($k)) { $missing[$k] = @{ Scope = $e.required_scope; Unlocks = 0 } }
            $missing[$k].Unlocks++
        }
        $objs.Add([pscustomobject]@{ Endpoint = $e.endpoint; RequiredScope = $e.required_scope; Callable = $ok; CoveredBy = $by })
    }

    $total = $objs.Count
    $callable = @($objs | Where-Object { $_.Callable }).Count
    $blocked = $total - $callable
    $share = [math]::Round([decimal]100 * $blocked / $total, 1, [System.MidpointRounding]::AwayFromZero)
    $shareText = $share.ToString('0.0', $inv) + '%'

    $miss = New-Object System.Collections.Generic.List[object]
    foreach ($k in $missing.Keys) { $miss.Add([pscustomobject]@{ Scope = $missing[$k].Scope; Unlocks = $missing[$k].Unlocks }) }
    $miss.Sort([System.Comparison[object]] {
        param($a, $b)
        if ($a.Unlocks -ne $b.Unlocks) { return $b.Unlocks - $a.Unlocks }
        [string]::CompareOrdinal($a.Scope.ToLowerInvariant(), $b.Scope.ToLowerInvariant())
    })
    $unused = New-Object System.Collections.Generic.List[string]
    foreach ($g in $granted) { if (-not $usedGranted.Contains($g.ToLowerInvariant())) { $unused.Add($g) } }
    $unused.Sort([System.Comparison[string]] { param($a, $b) [string]::CompareOrdinal($a.ToLowerInvariant(), $b.ToLowerInvariant()) })

    $summary = [pscustomobject]@{
        Endpoints = $total; Callable = $callable; Blocked = $blocked; BlockedShare = [double]$share; BlockedShareText = $shareText
        GrantedScopes = $granted.Count; RepeatedGrantedRows = $repeated
    }

    $lines = New-Object System.Collections.Generic.List[string]
    $lines.Add("Endpoints: $total")
    $lines.Add("Callable: $callable")
    $lines.Add("Blocked: $blocked ($shareText)")
    $lines.Add("Granted scopes: $($granted.Count) (repeated rows ignored: $repeated)")
    $lines.Add('')
    if ($blocked -eq 0) { $lines.Add('Blocked endpoints: none') }
    else {
        $lines.Add('Blocked endpoints:')
        foreach ($o in $objs) { if (-not $o.Callable) { $lines.Add((' {0} needs {1}' -f $o.Endpoint, $o.RequiredScope)) } }
    }
    $lines.Add('')
    if ($miss.Count -eq 0) { $lines.Add('Missing scopes: none') }
    else {
        $lines.Add('Missing scopes (endpoints each would unlock):')
        foreach ($m in $miss) { $lines.Add((' {0} {1}' -f $m.Scope, $m.Unlocks)) }
    }
    $lines.Add('')
    if ($unused.Count -eq 0) { $lines.Add('Granted scopes no listed endpoint needs: none') }
    else {
        $lines.Add('Granted scopes no listed endpoint needs:')
        foreach ($u in $unused) { $lines.Add(" $u") }
    }
    $report = $lines -join [Environment]::NewLine
    if (-not $Quiet) { Write-Host $report }

    $missArr = $miss.ToArray(); $unusedArr = $unused.ToArray()
    foreach ($o in $objs) {
        $o | Add-Member -NotePropertyName Summary -NotePropertyValue $summary
        $o | Add-Member -NotePropertyName MissingScopes -NotePropertyValue $missArr
        $o | Add-Member -NotePropertyName UnusedGranted -NotePropertyValue $unusedArr
        $o | Add-Member -NotePropertyName Report -NotePropertyValue $report
    }
    $objs.ToArray()
}

Export-ModuleMember -Function Get-ScopeGap