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)
    $assignmentId = $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) { $assignmentId = $found.id }   # preserve raw id (e.g. "//providers/.../roleAssignments/{guid}")
        } catch {
            Write-Verbose "REST OID lookup failed: $_"
        }
    }

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

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

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

    # Build DELETE URI preserving the raw id path (double-slash for root scope is intentional)
    # e.g. "//providers/Microsoft.Authorization/roleAssignments/{guid}" -> correct root-scope URL
    $deleteUri = "https://management.azure.com$assignmentId`?api-version=2022-04-01"

    # Force-refresh the ARM token before DELETE so Azure's auth cache sees a new token and re-evaluates
    # the caller's roles (important: the cached pre-elevation token may get a stale 403 from the auth cache)
    $deleteToken = $meTokenStr
    if (Get-Command az -ErrorAction SilentlyContinue) {
        $refreshed = az account get-access-token --resource https://management.azure.com --force-refresh --query accessToken -o tsv 2>$null
        if ($refreshed) { $deleteToken = $refreshed }
    }

    # Method 1: Invoke-WebRequest with force-refreshed ARM token
    $deleteStatus = $null
    if ($deleteToken) {
        $delHeaders = @{ Authorization = "Bearer $deleteToken" }
        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
        }
    }

    # Method 2: az role assignment delete - dedicated CLI sub-command, different auth code path
    if ($currentOid -and (Get-Command az -ErrorAction SilentlyContinue)) {
        Write-Verbose "Trying az role assignment delete..."
        $null = az role assignment delete --assignee-object-id $currentOid --role $uaaRoleId --scope / 2>&1
        if ($LASTEXITCODE -eq 0) {
            Write-Host " [OK] Elevation removed." -ForegroundColor Green
            return
        }
    }

    # Method 3: az rest DELETE
    if (Get-Command az -ErrorAction SilentlyContinue) {
        Write-Verbose "Trying az rest DELETE..."
        $null = az rest --method DELETE --url $deleteUri 2>&1
        if ($LASTEXITCODE -eq 0) {
            Write-Host " [OK] Elevation removed." -ForegroundColor Green
            return
        }
    }

    # Method 4: Remove-AzRoleAssignment cmdlet
    if ($currentOid) {
        try {
            Remove-AzRoleAssignment -ObjectId $currentOid -RoleDefinitionId $uaaRoleId -Scope "/" -SkipClientSideScopeValidation -ErrorAction Stop | Out-Null
            Write-Host " [OK] Elevation removed." -ForegroundColor Green
            return
        } catch {
            Write-Verbose "Remove-AzRoleAssignment failed: $_"
        }
    }

    Write-Warning " [WARN] Could not remove elevation (status $deleteStatus) -- remove manually: Azure Portal > Properties > Access management for Azure resources."
}