Private/Remove-365TuneElevation.ps1

function Remove-365TuneElevation {
    <#
    .SYNOPSIS
        Removes User Access Administrator elevation from root scope for the current user.
    #>


    $ctx         = Get-AzContext
    $currentUser = $ctx.Account.Id

    $uaaRoleId = "18d7d88d-d35e-4fb5-a5c3-7773c20a72d9"

    # Decode OID from the current JWT - works for both user and MSI/SP accounts
    $currentOid = $null
    $meTokenStr = $null
    try {
        $meToken    = Get-AzAccessToken -ResourceUrl "https://management.azure.com" -ErrorAction Stop
        $meTokenStr = if ($meToken.Token -is [System.Security.SecureString]) { [System.Net.NetworkCredential]::new("", $meToken.Token).Password } else { $meToken.Token }
    } catch {
        $meTokenStr = az account get-access-token --resource https://management.azure.com --query accessToken -o tsv 2>$null
    }

    if ($meTokenStr) {
        try {
            $jwtPayload = $meTokenStr.Split(".")[1]
            $pad        = 4 - ($jwtPayload.Length % 4)
            if ($pad -ne 4) { $jwtPayload += "=" * $pad }
            $claims     = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($jwtPayload)) | ConvertFrom-Json
            $currentOid = $claims.oid
        } catch {
            Write-Verbose "Could not decode token OID"
        }
    }

    # Primary: REST lookup by principalId - reliable for user AND MSI/SP (no SignInName dependency)
    $assignmentPath = $null
    if ($currentOid -and $meTokenStr) {
        try {
            $mgmtHeaders = @{ Authorization = "Bearer $meTokenStr" }
            $result      = Invoke-RestMethod -Uri "https://management.azure.com/providers/Microsoft.Authorization/roleAssignments?api-version=2022-04-01&`$filter=principalId eq '$currentOid'" -Headers $mgmtHeaders -Method GET -ErrorAction Stop -TimeoutSec 30
            $found       = $result.value | Where-Object { $_.properties.scope -eq "/" -and $_.properties.roleDefinitionId -like "*$uaaRoleId*" } | Select-Object -First 1
            if ($found) { $assignmentPath = $found.id.TrimStart('/') }
        } catch {
            Write-Verbose "REST OID lookup failed: $_"
        }
    }

    # Fallback: Az cmdlet - works when SignInName or ObjectId matches (user accounts at subscription scope)
    if (-not $assignmentPath) {
        $azAssignment = Get-AzRoleAssignment -RoleDefinitionId $uaaRoleId -Scope "/" -ErrorAction SilentlyContinue |
                        Where-Object { $_.SignInName -eq $currentUser -or ($currentOid -and $_.ObjectId -eq $currentOid) }
        if ($azAssignment) { $assignmentPath = $azAssignment.RoleAssignmentId.TrimStart('/') }
    }

    if (-not $assignmentPath) {
        Write-Host " Elevation already removed." -ForegroundColor Gray
        return
    }

    # DELETE with retry loop - RBAC propagation of the UAA assignment can take 30-120 seconds.
    # The assignment is readable immediately (GA can list root-scope assignments), but the
    # authorization service may not yet reflect UAA for write operations.
    $deleteUri  = "https://management.azure.com/$assignmentPath`?api-version=2018-07-01"
    $delHeaders = @{ Authorization = "Bearer $meTokenStr" }

    Write-Host " Waiting for propagation..." -ForegroundColor Gray
    Start-Sleep -Seconds 30

    $deleteStatus = $null
    for ($attempt = 1; $attempt -le 3; $attempt++) {
        try {
            $delResp      = Invoke-WebRequest -Uri $deleteUri -Method DELETE -Headers $delHeaders -UseBasicParsing
            $deleteStatus = [int]$delResp.StatusCode
        } catch {
            if ($_.Exception.Response) {
                $deleteStatus = [int]$_.Exception.Response.StatusCode
            } else { throw }
        }

        if ($deleteStatus -in @(200, 204)) {
            Write-Host " [OK] Elevation removed." -ForegroundColor Green
            return
        }

        if ($attempt -lt 3 -and $deleteStatus -eq 403) {
            Write-Host " Authorization not yet propagated; retrying in 30s (attempt $attempt/3)..." -ForegroundColor Gray
            # Re-fetch token in case a newer one is available
            try {
                $retryObj  = Get-AzAccessToken -ResourceUrl "https://management.azure.com" -ErrorAction Stop
                $newTok    = if ($retryObj.Token -is [System.Security.SecureString]) { [System.Net.NetworkCredential]::new("", $retryObj.Token).Password } else { $retryObj.Token }
                $delHeaders = @{ Authorization = "Bearer $newTok" }
            } catch {
                $newTok = az account get-access-token --resource https://management.azure.com --query accessToken -o tsv 2>$null
                if ($newTok) { $delHeaders = @{ Authorization = "Bearer $newTok" } }
            }
            Start-Sleep -Seconds 30
        } else {
            break
        }
    }

    Write-Warning " [WARN] Elevation removal returned status $deleteStatus -- remove manually: Azure Portal > Properties > Access management for Azure resources."
}