Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
- Singleton records for tenant-level config resources (e.g. policies/authorizationPolicy)
- Collection records for plain collection reads (e.g. users, servicePrincipals)

GitHub cache keys ({ApiVersion}|{AbsoluteUri}) yield External records for the
Legacy and metadata GitHub REST cache keys yield External records for the
organization or repository addressed by the request.

This is a run-level view (what data the run touched), not per-test attribution.
Expand Down Expand Up @@ -164,10 +164,17 @@

if ($__MtSession.GitHubCache) {
foreach ($key in $__MtSession.GitHubCache.Keys) {
# Key format: {ApiVersion}|{AbsoluteUri}
$uri = ($key -split '\|', 2)[-1]
if ($uri -notmatch '^https://[^/]+/(.+)$') { continue }
$path = (($Matches[1]) -split '\?', 2)[0].TrimEnd('/')
# Recognize only the REST namespaces; GraphQL keys contain opaque request data.
# Pagination options belong to the cache key, never to the resource URI.
if ($key -match '^Metadata\|GET\|\d{4}-\d{2}-\d{2}\|(?<uri>[^|]+)\|Paginate=(?:True|False)(?:\|MaxPages=[1-9][0-9]*)?$' -or
$key -match '^\d{4}-\d{2}-\d{2}\|(?<uri>[^|]+)(?:\|MaxPages=[1-9][0-9]*)?$') {
$uri = $Matches.uri
} else { continue }
$parsedUri = $null
if ($uri -match '\s' -or -not [uri]::TryCreate($uri, [UriKind]::Absolute, [ref]$parsedUri) -or
$parsedUri.Scheme -ne 'https' -or -not $parsedUri.Host -or $parsedUri.UserInfo -or $parsedUri.Fragment) { continue }
$path = $parsedUri.AbsolutePath.Trim('/')
if (-not $path) { continue }
$segments = $path -split '/'

$type = $null
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
$null for transport failures where no HTTP response was produced.
#>
param([Parameter(Mandatory)] $ErrorRecord)
if ($ErrorRecord.Exception.Data['GitHubRateLimit']) { return $ErrorRecord.Exception.Data['GitHubRateLimit'].HttpStatus }
try {
if ($ErrorRecord.Exception.Response -and $ErrorRecord.Exception.Response.StatusCode) {
return [int]$ErrorRecord.Exception.Response.StatusCode
Expand Down
71 changes: 71 additions & 0 deletions powershell/internal/services/github/Get-MtGitHubRateLimit.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
function Get-MtGitHubRateLimit {
<#
.SYNOPSIS
Internal: Classifies GitHub primary/secondary limits without parsing Maester diagnostic text.
.DESCRIPTION
Returns a separate record for each observed limit. Primary REST and GraphQL quotas are separate;
secondary limits can be shared across both APIs, with their own deadline.
Uses response headers, documented API error messages and GraphQL RATE_LIMITED errors.
An unknown primary reset requires a new connection; no retry time is invented for it.
#>
[CmdletBinding()]
param(
[object] $ErrorRecord,
[AllowNull()] [object] $Headers,
[int] $StatusCode = 200,
[ValidateSet('REST', 'GraphQL')] [string] $Api = 'REST',
[switch] $GraphQLRateLimited,
[string] $Message
)
if ($ErrorRecord) {
if ($ErrorRecord.Exception.Data['GitHubRateLimits']) { return $ErrorRecord.Exception.Data['GitHubRateLimits'] }
if ($ErrorRecord.Exception.Data['GitHubRateLimit']) { return $ErrorRecord.Exception.Data['GitHubRateLimit'] }
$StatusCode = Get-MtGitHubErrorStatusCode -ErrorRecord $ErrorRecord
if ($StatusCode -notin 403, 429) { return $null }
$Headers = $ErrorRecord.Exception.Response.Headers
$Message = Get-MtGitHubErrorMessage -ErrorRecord $ErrorRecord
}
$remaining = Get-MtGitHubResponseHeaderValue -Headers $Headers -Name 'x-ratelimit-remaining'
$remainingValue = 0
$primary = $null -ne $remaining -and [int]::TryParse([string]$remaining, [ref]$remainingValue) -and $remainingValue -eq 0
$retryAfter = Get-MtGitHubResponseHeaderValue -Headers $Headers -Name 'retry-after'
$secondary = $Message -match '(?i)secondary\s+rate\s+limit|abuse\s+detection' -or (($StatusCode -in 403, 429 -or $GraphQLRateLimited) -and $null -ne $retryAfter)
if (-not $primary -and -not $secondary -and $StatusCode -ne 429 -and -not $GraphQLRateLimited) { return $null }
if ($StatusCode -notin 200, 403, 429) { return $null }

$now = [DateTimeOffset]::UtcNow
$reset = Get-MtGitHubResponseHeaderValue -Headers $Headers -Name 'x-ratelimit-reset'
$resetSeconds = 0L
$resetUtc = $null
if ($null -ne $reset -and [long]::TryParse([string]$reset, [ref]$resetSeconds)) {
try { $resetUtc = [DateTimeOffset]::FromUnixTimeSeconds($resetSeconds) } catch { Write-Debug 'GitHub returned an out-of-range reset epoch.' }
}
$retrySeconds = 0L
$retryUtc = $null
if ($null -ne $retryAfter -and [long]::TryParse([string]$retryAfter, [ref]$retrySeconds) -and $retrySeconds -ge 0) {
try { $retryUtc = $now.AddSeconds($retrySeconds) } catch { Write-Debug 'GitHub returned an out-of-range retry interval.' }
}
$resource = Get-MtGitHubResponseHeaderValue -Headers $Headers -Name 'x-ratelimit-resource'
if ($primary) {
# An unknown reset blocks only the exhausted API, not the other primary quota.
$resumeUtc = if ($null -eq $resetUtc -or $resetUtc -ge [DateTimeOffset]::MaxValue.AddSeconds(-1)) { [DateTimeOffset]::MaxValue }
else { $resetUtc.AddSeconds(1) }
$resetText = if ($resetUtc) { $resetUtc.LocalDateTime } else { 'unknown' }
[pscustomobject]@{
Kind = 'Primary'; Scope = $Api; HttpStatus = $StatusCode; Resource = $resource
RetryAfterSeconds = $null; ResetUtc = $resetUtc; ResumeUtc = $resumeUtc
Message = "GitHub API rate limit encountered (HTTP $StatusCode). Resets at: $resetText"
}
}
if ($secondary -or -not $primary) {
# A simultaneous primary reset must neither extend nor shorten the shared cooldown.
$resumeUtc = if ($retryUtc) { $retryUtc } else { $now.AddSeconds(60) }
$diagnostic = if ($retryUtc) { "GitHub secondary rate limit encountered (HTTP $StatusCode). Retry after: ${retrySeconds}s" }
else { "GitHub secondary rate limit encountered (HTTP $StatusCode). Retry after at least 60s." }
[pscustomobject]@{
Kind = 'Secondary'; Scope = 'All'; HttpStatus = $StatusCode; Resource = $resource
RetryAfterSeconds = $(if ($retryUtc) { $retrySeconds } else { $null })
ResetUtc = $null; ResumeUtc = $resumeUtc; Message = $diagnostic
}
}
}
Original file line number Diff line number Diff line change
@@ -1,75 +1,12 @@
function Get-MtGitHubRateLimitMessage {
function Get-MtGitHubRateLimitMessage {
<#
.SYNOPSIS
Internal: Returns a GitHub rate-limit message for an ErrorRecord, or $null when the
error is not a rate-limit response.

Internal: Returns a GitHub rate-limit diagnostic, or null for ordinary HTTP errors.
.DESCRIPTION
Mirrors the rate-limit detection in Invoke-MtGitHubRequest so that bootstrap callers
(Connect-MtGitHub) can distinguish HTTP 403/429 caused by rate limiting from
permission, token, or org-access failures.

Returns:
- "GitHub API rate limit encountered (HTTP <code>). Resets at: <time>" when the
response carries x-ratelimit-remaining = 0 (primary rate limit).
- "GitHub secondary rate limit encountered (HTTP <code>). Retry after: <n>s" when
the response carries retry-after (secondary rate limit / abuse detection).
- "GitHub secondary rate limit encountered (HTTP <code>). Retry after at least 60s."
when the response body indicates secondary-limit / abuse-detection wording but
no retry-after header is present.
- $null for any other error, including 403/429 without rate-limit headers.
Retains the bootstrap diagnostic contract. Classification is shared with the transport guard;
consumers should use structured GitHubRateLimit exception data rather than parse this text.
#>
param(
[Parameter(Mandatory)] $ErrorRecord
)

$code = Get-MtGitHubErrorStatusCode -ErrorRecord $ErrorRecord
if ($code -notin 403, 429) { return $null }

$response = $null
try {
if ($null -ne $ErrorRecord.Exception) { $response = $ErrorRecord.Exception.Response }
} catch {
Write-Debug "Get-MtGitHubRateLimitMessage: $($_.Exception.Message)"
}
if ($null -eq $response) { return $null }

$headers = $null
try { $headers = $response.Headers } catch {
Write-Debug "Get-MtGitHubRateLimitMessage headers: $($_.Exception.Message)"
}
if ($null -eq $headers) { return $null }

$remaining = Get-MtGitHubResponseHeaderValue -Headers $headers -Name 'x-ratelimit-remaining'
$remainingValue = 0
$remainingParsed = $null -ne $remaining -and [int]::TryParse([string]$remaining, [ref]$remainingValue)
if ($remainingParsed -and $remainingValue -eq 0) {
$reset = Get-MtGitHubResponseHeaderValue -Headers $headers -Name 'x-ratelimit-reset'
$resetSeconds = 0L
$resetTime = 'unknown'
if ($null -ne $reset -and [long]::TryParse([string]$reset, [ref]$resetSeconds)) {
try { $resetTime = [DateTimeOffset]::FromUnixTimeSeconds($resetSeconds).LocalDateTime } catch {
Write-Debug "Get-MtGitHubRateLimitMessage reset conversion: $($_.Exception.Message)"
}
}
return "GitHub API rate limit encountered (HTTP $code). Resets at: $resetTime"
}

$retryAfter = Get-MtGitHubResponseHeaderValue -Headers $headers -Name 'retry-after'
if ($null -ne $retryAfter) {
return "GitHub secondary rate limit encountered (HTTP $code). Retry after: ${retryAfter}s"
}

# Some secondary-limit responses omit retry-after entirely (e.g. older abuse-detection
# responses, or responses where the proxy strips the header). Fall back to body wording -
# GitHub's documented messages include phrases like "secondary rate limit" and
# "abuse detection mechanism". When matched, recommend the 60-second minimum backoff
# documented at https://docs.github.com/en/rest/using-the-rest-api/rate-limits-for-the-rest-api.
$bodyMessage = Get-MtGitHubErrorMessage -ErrorRecord $ErrorRecord
if (-not [string]::IsNullOrEmpty($bodyMessage) -and
$bodyMessage -match '(?i)secondary\s+rate\s+limit|abuse\s+detection') {
return "GitHub secondary rate limit encountered (HTTP $code). Retry after at least 60s."
}

return $null
param([Parameter(Mandatory)] $ErrorRecord)
$limit = Get-MtGitHubRateLimit -ErrorRecord $ErrorRecord | Sort-Object ResumeUtc -Descending | Select-Object -First 1
if ($limit) { $limit.Message }
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
function Get-MtGitHubRepositoryInventory {
<#
.SYNOPSIS
Internal: Enumerates organization repositories without visibility or archived-state filtering.
#>
[CmdletBinding()]
param()
$organization = $__MtSession.GitHubConnection.Organization
$encoded = [uri]::EscapeDataString($organization)
$evidence = Invoke-MtGitHubRequest -RelativeUri "/orgs/$encoded/repos?type=all" -Paginate -ApiVersion '2026-03-10' -IncludeMetadata -MaxPages 100
$issues = [System.Collections.Generic.List[string]]::new()
foreach ($issue in $evidence.Issues) { $issues.Add($issue) }
if (-not $evidence.CollectionIntegrityValid -or $evidence.ContentKind -ne 'Array' -or $evidence.Data -isnot [array]) { $issues.Add('Repository inventory is incomplete or has an unexpected API shape.') }
if (-not $evidence.PaginationComplete) { $issues.Add('Repository pagination is incomplete.') }
$repositories = [System.Collections.Generic.List[object]]::new()
$seenIds = @{}
$seenPaths = @{}
$conflictingIds = [System.Collections.Generic.HashSet[string]]::new()
$items = @()
if ($evidence.Data -is [array]) { $items = $evidence.Data }
foreach ($repository in $items) {
$id = $repository.id
$numeric = $id -is [int] -or $id -is [long] -or $id -is [bigint]
if (($null -eq $repository -or $repository.GetType() -ne [System.Management.Automation.PSCustomObject]) -or -not $numeric -or $id -le 0 -or $repository.name -isnot [string] -or [string]::IsNullOrWhiteSpace($repository.name) -or $null -eq $repository.owner -or $repository.owner.GetType() -ne [System.Management.Automation.PSCustomObject] -or $repository.owner.login -isnot [string] -or $repository.owner.login -ne $organization -or $repository.full_name -isnot [string] -or $repository.full_name -ne "$organization/$($repository.name)") {
$issues.Add('Repository inventory contains an unusable identity.')
# A usable companion must not win by arriving first when the same numeric ID
# has an invalid or foreign owner/path association elsewhere in the inventory.
if ($numeric -and $id -gt 0) { $null = $conflictingIds.Add([string]$id) }
continue
}
$key = [string]$id
$path = $repository.full_name
# Paths are case-insensitive on GitHub. Register every valid association, even
# for a duplicate ID, so all IDs sharing an ambiguous path are excluded.
if ($seenPaths.ContainsKey($path) -and $seenPaths[$path] -cne $key) {
$issues.Add('Repository inventory maps the same repository path to different IDs.')
$null = $conflictingIds.Add($seenPaths[$path])
$null = $conflictingIds.Add($key)
} else { $seenPaths[$path] = $key }
if ($seenIds.ContainsKey($key)) {
$issues.Add('Repository inventory contains a duplicate ID.')
if ($seenIds[$key] -ne $path) {
$issues.Add('Repository inventory maps the same ID to different repository paths.')
$null = $conflictingIds.Add($key)
}
continue
}
$seenIds[$key] = $path
$repositories.Add($repository)
}
return [pscustomobject]@{ Repositories = @($repositories | Where-Object { [string]$_.id -cnotin $conflictingIds }); Issues = @($issues | Select-Object -Unique); StartedUtc = $evidence.StartedUtc; CompletedUtc = $evidence.CompletedUtc }
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
function Invoke-MtGitHubGraphQLRequest {
<#
.SYNOPSIS
Internal: Runs a static GitHub GraphQL read query with session-isolated evidence caching.
.DESCRIPTION
GraphQL is not versioned by X-GitHub-Api-Version. Error and partial responses are never cached.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory)] [string] $Query,
[Parameter(Mandatory)] [hashtable] $Variables,
[Parameter(Mandatory)] [string] $OperationName,
[switch] $DisableCache
)
if (-not $__MtSession.GitHubConnection -or $__MtSession.GitHubConnection.Connected -ne $true) {
throw 'Not connected to GitHub. Call Connect-MtGitHub first.'
}
if ($Query -notmatch '^\s*query\s' -or $Query -match '\bmutation\b') { throw 'Only static read queries are supported.' }
$uri = "$($__MtSession.GitHubConnection.ApiBaseUri.TrimEnd('/'))/graphql"
$payload = @{ query = $Query; variables = $Variables; operationName = $OperationName } | ConvertTo-Json -Depth 20 -Compress
$digest = [Convert]::ToHexString([System.Security.Cryptography.SHA256]::HashData([Text.Encoding]::UTF8.GetBytes($payload)))
$key = "GraphQL|$uri|$digest"
if (-not $DisableCache -and $__MtSession.GitHubCache.ContainsKey($key)) {
return $__MtSession.GitHubCache[$key]
}
$headers = @{} + $__MtSession.GitHubAuthHeader
$headers.Remove('X-GitHub-Api-Version')
$started = [DateTimeOffset]::UtcNow
Invoke-MtGitHubRateLimitGuard -Api GraphQL
try {
# Match connection probes: bound header waiting and each stalled body read.
$response = Invoke-WebRequest -Uri $uri -Method POST -Headers $headers -ContentType 'application/json' -Body $payload -ConnectionTimeoutSeconds 30 -OperationTimeoutSeconds 30 -ErrorAction Stop
Invoke-MtGitHubRateLimitGuard -Api GraphQL -Headers $response.Headers
} catch {
Invoke-MtGitHubRateLimitGuard -Api GraphQL -ErrorRecord $_
throw
}
$parsed = ConvertFrom-Json -InputObject $response.Content -NoEnumerate -ErrorAction Stop
$codes = [System.Collections.Generic.List[string]]::new()
if (($null -ne $parsed -and $parsed.GetType() -eq [System.Management.Automation.PSCustomObject]) -and (Test-MtGitHubObjectProperty -InputObject $parsed -PropertyName errors)) {
if ($parsed.errors -isnot [array]) { throw 'GitHub GraphQL error collection is unusable.' }
foreach ($errorItem in $parsed.errors) {
if ($null -eq $errorItem -or $errorItem.GetType() -ne [System.Management.Automation.PSCustomObject]) { throw 'GitHub GraphQL error collection is unusable.' }
$code = if ($errorItem.type) { $errorItem.type } elseif ($errorItem.extensions.code) { $errorItem.extensions.code } else { 'UNKNOWN' }
if ($code -ceq 'RATE_LIMITED') { Invoke-MtGitHubRateLimitGuard -Api GraphQL -Headers $response.Headers -GraphQLRateLimited -Message $errorItem.message }
if ($code -cnotin 'FORBIDDEN', 'NOT_FOUND', 'INSUFFICIENT_SCOPES') { throw 'GitHub GraphQL execution failed; no configuration verdict was produced.' }
$codes.Add($code)
}
}
$data = $null
if ($null -ne $parsed -and $parsed.GetType() -eq [System.Management.Automation.PSCustomObject] -and $null -ne $parsed.data -and $parsed.data.GetType() -eq [System.Management.Automation.PSCustomObject]) { $data = $parsed.data }
$result = [pscustomobject]@{ Data = $data; Errors = $codes.ToArray(); StartedUtc = $started; CompletedUtc = [DateTimeOffset]::UtcNow }
if (-not $DisableCache -and $codes.Count -eq 0 -and ($null -ne $data -and $data.GetType() -eq [System.Management.Automation.PSCustomObject])) { $__MtSession.GitHubCache[$key] = $result }
return $result
}
Loading
Loading