Private/Compliance/Get-GovernancePreflightAccess.ps1

# Security namespaces and the bits preflight reads to say what a person can do.
$script:PreflightCssNamespace = '83e28ad4-2d72-4ceb-97b0-c7726d5502c3'   # area paths (CSS)
$script:PreflightGitNamespace = '2e9eb7ed-3c0a-47d4-87c1-0ffdd275fd87'   # Git repositories

function ConvertTo-GovernanceAccessLevel {
    <# The highest named level an effective allow mask gives, or '' for none. #>
    param([ValidateSet('area', 'repo')][string]$Kind, [long]$Allow)
    if ($Kind -eq 'area') {
        if ($Allow -band 32) { return 'edit work items' }
        if ($Allow -band 16) { return 'read work items' }
        return ''
    }
    if ($Allow -band 1) { return 'administer' }
    if ($Allow -band 4) { return 'contribute' }
    if ($Allow -band 2) { return 'read' }
    return ''
}

function Get-GovernanceAreaSecurityToken {
    <# The CSS token of an area path: the chain of node identifiers from the
       project root, 'vstfs:///Classification/Node/<id>:…'. Throws if any
       segment is missing — a token built on a guess reads someone else's ACL. #>

    [CmdletBinding()]
    param([Parameter(Mandatory)][string]$OrgUrl, [Parameter(Mandatory)][string]$Project, [Parameter(Mandatory)][string]$AreaPath)
    $segments = @(([string]$AreaPath).Trim('\') -split '\\')
    if ($segments[0] -ne $Project) { throw "area path '$AreaPath' is not under project '$Project'" }
    $enc  = { param($s) [Uri]::EscapeDataString($s) }
    $root = Invoke-AdoRest -OrgUrl $OrgUrl -Path "$(& $enc $Project)/_apis/wit/classificationnodes/Areas"
    $ids  = [System.Collections.Generic.List[string]]::new()
    $ids.Add([string]$root.identifier)
    for ($i = 1; $i -lt $segments.Count; $i++) {
        $rel  = ($segments[1..$i] | ForEach-Object { & $enc $_ }) -join '/'
        $node = Invoke-AdoRest -OrgUrl $OrgUrl -Path "$(& $enc $Project)/_apis/wit/classificationnodes/Areas/$rel"
        if (-not $node.identifier) { throw "area path segment '$($segments[$i])' of '$AreaPath' not found" }
        $ids.Add([string]$node.identifier)
    }
    return (($ids | ForEach-Object { "vstfs:///Classification/Node/$_" }) -join ':')
}

function Get-GovernanceEffectiveAccess {
    <# Identities with access on a token -> level.
       -ExplicitOnly (with -WriteOnly, Martin 2026-12-01: "only people that have
       explicit write access, not inherited"): only the entries set ON the token
       itself, judged by their own allow and deny bits — nothing inherited from
       a parent path or a project-wide grant.
       Otherwise: every identity with an entry on the token or an ancestor,
       judged by its EFFECTIVE allow on the token (inheritance included). #>

    [CmdletBinding()]
    param([string]$OrgUrl, [string]$NamespaceId, [string]$Token, [string[]]$AncestorTokens, [ValidateSet('area', 'repo')][string]$Kind,
          [switch]$WriteOnly, [switch]$ExplicitOnly)
    $keep = { param($level) $level -and (-not $WriteOnly -or $level -in 'edit work items', 'contribute', 'administer') }
    $out = @{}
    if ($ExplicitOnly) {
        $r = Invoke-AdoRest -OrgUrl $OrgUrl -Path "_apis/accesscontrollists/$NamespaceId`?token=$([Uri]::EscapeDataString($Token))&includeExtendedInfo=false&recurse=false"
        foreach ($l in @($r.value)) {
            if ([string]$l.token -ne $Token) { continue }
            foreach ($p in $l.acesDictionary.PSObject.Properties) {
                $level = ConvertTo-GovernanceAccessLevel -Kind $Kind -Allow ([long]$p.Value.allow -band (-bnot [long]$p.Value.deny))
                if (& $keep $level) { $out[$p.Name] = $level }
            }
        }
        return $out
    }
    $descs = [System.Collections.Generic.HashSet[string]]::new()
    foreach ($t in @($AncestorTokens) + @($Token)) {
        $r = Invoke-AdoRest -OrgUrl $OrgUrl -Path "_apis/accesscontrollists/$NamespaceId`?token=$([Uri]::EscapeDataString($t))&includeExtendedInfo=false&recurse=false"
        foreach ($l in @($r.value)) { foreach ($p in $l.acesDictionary.PSObject.Properties) { [void]$descs.Add($p.Name) } }
    }
    $all = @($descs)
    for ($i = 0; $i -lt $all.Count; $i += 50) {
        $batch = $all[$i..([Math]::Min($i + 49, $all.Count - 1))]
        $r = Invoke-AdoRest -OrgUrl $OrgUrl -Path ("_apis/accesscontrollists/$NamespaceId`?token=$([Uri]::EscapeDataString($Token))&descriptors=" +
            [Uri]::EscapeDataString($batch -join ',') + '&includeExtendedInfo=true&recurse=false')
        foreach ($l in @($r.value)) {
            foreach ($p in $l.acesDictionary.PSObject.Properties) {
                $level = ConvertTo-GovernanceAccessLevel -Kind $Kind -Allow ([long]$p.Value.extendedInfo.effectiveAllow -band (-bnot [long]$p.Value.extendedInfo.effectiveDeny))
                if (& $keep $level) { $out[$p.Name] = $level }
            }
        }
    }
    return $out
}
function Get-GovernancePreflightAccess {
    <#
        .SYNOPSIS
        Who can reach one team's source area and claimed repositories today,
        and at what level — the "today" half of the access review. Read-only.

        Every identity with an effective level is resolved. A user is listed
        by UPN. A group is expanded to its users (nested groups included)
        unless it holds more than -BroadThreshold users: project-wide groups
        such as Contributors reach hundreds of people, so they are listed as a
        group with a member count instead of hundreds of rows. Throws on any
        read failure: a partial list of who has access is worse than none.
    #>

    [CmdletBinding()]
    param(
        [Parameter(Mandatory)][string]$OrgUrl,
        [Parameter(Mandatory)][string]$Project,
        [Parameter(Mandatory)][string]$AreaPath,            # '\Project\Node'
        [object[]]$Repos = @(),                             # claimed repos: @{ name; id }
        [int]$BroadThreshold = 50,
        [switch]$WriteOnly,           # list only people who can change things: edit work items, contribute or administer
        [switch]$ExplicitOnly         # only access set on the area or repo itself, never inherited
    )

    $vssps = ($OrgUrl.TrimEnd('/') -replace '^https://dev\.azure\.com/', 'https://vssps.dev.azure.com/')
    $proj  = Invoke-AdoRest -OrgUrl $OrgUrl -Path "_apis/projects/$([Uri]::EscapeDataString($Project))"

    # identity cache: security descriptor -> @{ name; upn; isGroup; subject }
    $idCache = @{}
    $resolveIds = {
        param([string[]]$descriptors)
        $need = @($descriptors | Where-Object { -not $idCache.ContainsKey($_) })
        for ($i = 0; $i -lt $need.Count; $i += 50) {
            $batch = $need[$i..([Math]::Min($i + 49, $need.Count - 1))]
            $r = Invoke-AdoRest -OrgUrl $vssps -Path "_apis/identities?descriptors=$([Uri]::EscapeDataString($batch -join ','))"
            $j = 0
            foreach ($id in @($r.value)) {
                $d = $batch[$j]; $j++
                if ($null -eq $id) { $idCache[$d] = $null; continue }
                $acct = if ($id.properties.Account) { [string]$id.properties.Account.'$value' } else { '' }
                $idCache[$d] = @{
                    name    = [string]$id.providerDisplayName
                    upn     = if ($acct -match '@') { $acct } else { '' }
                    isGroup = [bool]$id.isContainer
                    subject = [string]$id.subjectDescriptor
                }
            }
        }
    }

    # Group expansion, cheap first: walk memberships only (one call per group,
    # nested groups included) to get every user descriptor, so a large group's
    # count is exact. Names are looked up only for groups small enough to list,
    # in batches; a group over the threshold is reported by count alone.
    # (The first version looked every user up one call at a time before it
    # knew the group was too big to list: over an hour on one Visage area.)
    $memberCache = @{}   # group subject -> @{ users = @(descriptors); broad = bool }
    $collect = {
        param([string]$subject)
        if ($memberCache.ContainsKey($subject)) { return $memberCache[$subject] }
        $users  = [System.Collections.Generic.HashSet[string]]::new()
        $seenG  = [System.Collections.Generic.HashSet[string]]::new()
        $queue  = [System.Collections.Generic.Queue[string]]::new()
        $queue.Enqueue($subject)
        $broad = $false
        while ($queue.Count) {
            $g = $queue.Dequeue()
            if (-not $seenG.Add($g)) { continue }
            $m = Invoke-AdoRest -OrgUrl $vssps -Path "_apis/graph/memberships/$([Uri]::EscapeDataString($g))?direction=Down" -ApiVersion '7.1-preview.1'
            foreach ($x in @($m.value)) {
                $md = [string]$x.memberDescriptor
                if ($md -match '^(aad|msa)\.') { [void]$users.Add($md) }
                elseif ($md -match '^(vssgp|aadgp)\.') { $queue.Enqueue($md) }
            }
        }
        $broad = $users.Count -gt $BroadThreshold
        $memberCache[$subject] = @{ users = @($users); broad = $broad }
        return $memberCache[$subject]
    }
    $userCache = @{}   # user subject descriptor -> @{ upn; name } or $null (deleted)
    $resolveUsers = {
        param([string[]]$subjects)
        $need = @($subjects | Where-Object { -not $userCache.ContainsKey($_) })
        for ($i = 0; $i -lt $need.Count; $i += 50) {
            $batch = $need[$i..([Math]::Min($i + 49, $need.Count - 1))]
            $r = Invoke-AdoRest -OrgUrl $vssps -Path "_apis/identities?subjectDescriptors=$([Uri]::EscapeDataString($batch -join ','))"
            $j = 0
            foreach ($id in @($r.value)) {
                $d = $batch[$j]; $j++
                $acct = if ($id -and $id.properties.Account) { [string]$id.properties.Account.'$value' } else { '' }
                # A member the organisation no longer knows comes back empty: it
                # is not a person anyone can keep, so it is counted, not listed.
                $userCache[$d] = if ($acct -match '@') { @{ upn = $acct; name = [string]$id.providerDisplayName } } else { $null }
                if (-not $userCache[$d]) { [void]$gone.Add($d) }
            }
        }
    }
    $people = [ordered]@{}   # upn -> @{ name; grants = list of @{ on; level; via } }
    $groups = [System.Collections.Generic.List[object]]::new()
    $record = {
        param([string]$on, [hashtable]$levels)
        & $resolveIds @($levels.Keys)
        foreach ($d in @($levels.Keys | Sort-Object)) {
            $id = $idCache[$d]
            if (-not $id) { continue }
            $level = $levels[$d]
            if (-not $id.isGroup) {
                if (-not $id.upn) { continue }   # service identities are not people
                if (-not $people.Contains($id.upn)) { $people[$id.upn] = [ordered]@{ name = $id.name; grants = [System.Collections.Generic.List[object]]::new() } }
                $people[$id.upn].grants.Add([ordered]@{ on = $on; level = $level; via = 'direct grant' })
                continue
            }
            $c = & $collect $id.subject
            if ($c.broad) {
                $groups.Add([ordered]@{ on = $on; group = $id.name; level = $level; members = @($c.users).Count })
                continue
            }
            & $resolveUsers $c.users
            $members = @($c.users | ForEach-Object { $userCache[$_] } | Where-Object { $_ })
            foreach ($u in $members) {
                if (-not $people.Contains($u.upn)) { $people[$u.upn] = [ordered]@{ name = $u.name; grants = [System.Collections.Generic.List[object]]::new() } }
                if (@($people[$u.upn].grants | Where-Object { $_.on -eq $on -and $_.via -eq $id.name }).Count -eq 0) {
                    $people[$u.upn].grants.Add([ordered]@{ on = $on; level = $level; via = $id.name })
                }
            }
        }
    }

    # ── the area: its own token, read with every ancestor's entries ──────────
    $areaToken = Get-GovernanceAreaSecurityToken -OrgUrl $OrgUrl -Project $Project -AreaPath $AreaPath
    $parts     = $areaToken -split ':(?=vstfs)'
    $ancestors = @(for ($i = 1; $i -lt $parts.Count; $i++) { ($parts[0..($i - 1)]) -join ':' })
    & $record "area $AreaPath" (Get-GovernanceEffectiveAccess -OrgUrl $OrgUrl -NamespaceId $script:PreflightCssNamespace `
        -Token $areaToken -AncestorTokens $ancestors -Kind 'area' -WriteOnly:$WriteOnly -ExplicitOnly:$ExplicitOnly)

    # ── each claimed repository ───────────────────────────────────────────────
    foreach ($repo in @($Repos | Where-Object { $_ -and $_.id })) {
        $projToken = "repoV2/$($proj.id)"
        & $record "repo $($repo.name)" (Get-GovernanceEffectiveAccess -OrgUrl $OrgUrl -NamespaceId $script:PreflightGitNamespace `
            -Token "$projToken/$($repo.id)" -AncestorTokens @('repoV2', $projToken) -Kind 'repo' -WriteOnly:$WriteOnly -ExplicitOnly:$ExplicitOnly)
    }

    $peopleOut = foreach ($upn in @($people.Keys | Sort-Object)) {
        [ordered]@{ upn = $upn; name = $people[$upn].name; grants = @($people[$upn].grants | Sort-Object { $_.on }, { $_.via }) }
    }
    return [ordered]@{
        broadThreshold = $BroadThreshold
        writeOnly      = [bool]$WriteOnly
        explicitOnly   = [bool]$ExplicitOnly
        goneMembers    = $gone.Count
        people         = @($peopleOut)
        groups         = @($groups | Sort-Object { $_.on }, { -[long]$_.members }, { $_.group })
    }
}

function Get-GovernanceRepoInventory {
    <# Every repository in the source project: name, id, size, disabled, and
       the date of its latest commit on the default branch. Read-only. #>

    [CmdletBinding()]
    param([Parameter(Mandatory)][string]$OrgUrl, [Parameter(Mandatory)][string]$Project)
    $enc = [Uri]::EscapeDataString($Project)
    $r = Invoke-AdoRest -OrgUrl $OrgUrl -Path "$enc/_apis/git/repositories?includeHidden=true"
    foreach ($repo in @($r.value | Sort-Object name)) {
        $last = ''
        if (-not $repo.isDisabled -and $repo.defaultBranch) {
            $c = Invoke-AdoRest -OrgUrl $OrgUrl -Path "$enc/_apis/git/repositories/$($repo.id)/commits?`$top=1&searchCriteria.itemVersion.version=$([Uri]::EscapeDataString(($repo.defaultBranch -replace '^refs/heads/', '')))"
            if (@($c.value).Count) { $last = ([datetime]$c.value[0].committer.date).ToUniversalTime().ToString('yyyy-MM-dd') }
        }
        [ordered]@{ name = [string]$repo.name; id = [string]$repo.id; size = [long]$repo.size; disabled = [bool]$repo.isDisabled; lastCommit = $last }
    }
}