From 5017be480459490e304a78fcc1570ab673ffc9a7 Mon Sep 17 00:00:00 2001 From: Travis McDade Date: Sat, 31 Oct 2026 18:38:41 -0400 Subject: [PATCH 1/2] feat(github): add bounded evidence transport and rate limits --- .../Get-MtAffectedObjectFromCache.ps1 | 17 +- .../github/Get-MtGitHubErrorStatusCode.ps1 | 1 + .../services/github/Get-MtGitHubRateLimit.ps1 | 65 ++++++ .../github/Get-MtGitHubRateLimitMessage.ps1 | 77 +----- .../Get-MtGitHubRepositoryInventory.ps1 | 52 +++++ .../github/Invoke-MtGitHubGraphQLRequest.ps1 | 55 +++++ .../github/Invoke-MtGitHubRateLimitGuard.ps1 | 47 ++++ .../github/Invoke-MtGitHubRequest.ps1 | 165 ++++++++++--- .../internal/session/Clear-ModuleVariable.ps1 | 1 + .../public/connect/Connect-MtGitHub.ps1 | 27 ++- .../public/connect/Disconnect-MtGitHub.ps1 | 1 + .../Get-MtGitHubRepositoryInventory.Tests.ps1 | 85 +++++++ .../functions/GitHubAffectedObjects.Tests.ps1 | 51 ++++ .../tests/functions/GitHubRateLimit.Tests.ps1 | 221 ++++++++++++++++++ .../GitHubTransportTimeout.Tests.ps1 | 101 ++++++++ .../Invoke-MtGitHubGraphQLRequest.Tests.ps1 | 132 +++++++++++ .../Invoke-MtGitHubRequest.Tests.ps1 | 177 +++++++++++++- .../tests/general/GraphCacheUsage.Tests.ps1 | 1 + 18 files changed, 1159 insertions(+), 117 deletions(-) create mode 100644 powershell/internal/services/github/Get-MtGitHubRateLimit.ps1 create mode 100644 powershell/internal/services/github/Get-MtGitHubRepositoryInventory.ps1 create mode 100644 powershell/internal/services/github/Invoke-MtGitHubGraphQLRequest.ps1 create mode 100644 powershell/internal/services/github/Invoke-MtGitHubRateLimitGuard.ps1 create mode 100644 powershell/tests/functions/Get-MtGitHubRepositoryInventory.Tests.ps1 create mode 100644 powershell/tests/functions/GitHubAffectedObjects.Tests.ps1 create mode 100644 powershell/tests/functions/GitHubRateLimit.Tests.ps1 create mode 100644 powershell/tests/functions/GitHubTransportTimeout.Tests.ps1 create mode 100644 powershell/tests/functions/Invoke-MtGitHubGraphQLRequest.Tests.ps1 diff --git a/powershell/internal/report/affected-objects/Get-MtAffectedObjectFromCache.ps1 b/powershell/internal/report/affected-objects/Get-MtAffectedObjectFromCache.ps1 index b75bf35de1..57a6e2e102 100644 --- a/powershell/internal/report/affected-objects/Get-MtAffectedObjectFromCache.ps1 +++ b/powershell/internal/report/affected-objects/Get-MtAffectedObjectFromCache.ps1 @@ -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. @@ -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}\|(?[^|]+)\|Paginate=(?:True|False)(?:\|MaxPages=[1-9][0-9]*)?$' -or + $key -match '^\d{4}-\d{2}-\d{2}\|(?[^|]+)(?:\|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 diff --git a/powershell/internal/services/github/Get-MtGitHubErrorStatusCode.ps1 b/powershell/internal/services/github/Get-MtGitHubErrorStatusCode.ps1 index d1769dfc2a..32a3ade15a 100644 --- a/powershell/internal/services/github/Get-MtGitHubErrorStatusCode.ps1 +++ b/powershell/internal/services/github/Get-MtGitHubErrorStatusCode.ps1 @@ -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 diff --git a/powershell/internal/services/github/Get-MtGitHubRateLimit.ps1 b/powershell/internal/services/github/Get-MtGitHubRateLimit.ps1 new file mode 100644 index 0000000000..064823f1b3 --- /dev/null +++ b/powershell/internal/services/github/Get-MtGitHubRateLimit.ps1 @@ -0,0 +1,65 @@ +function Get-MtGitHubRateLimit { + <# + .SYNOPSIS + Internal: Classifies GitHub primary/secondary limits without parsing Maester diagnostic text. + .DESCRIPTION + Primary REST and GraphQL quotas are separate. Secondary limits can be shared across both APIs. + 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['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 -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.' } + } + $kind = if ($secondary -or -not $primary) { 'Secondary' } else { 'Primary' } + $scope = if ($kind -eq 'Secondary') { 'All' } else { $Api } + # Respect both server deadlines when both are present. A missing primary reset cannot be safely timed. + $resumeUtc = if ($primary -and $null -eq $resetUtc) { [DateTimeOffset]::MaxValue } + elseif ($primary -and $resetUtc -lt [DateTimeOffset]::MaxValue.AddSeconds(-1)) { $resetUtc.AddSeconds(1) } + elseif ($primary) { [DateTimeOffset]::MaxValue } + elseif ($retryUtc) { $retryUtc } + else { $now.AddSeconds(60) } + if ($retryUtc -and $retryUtc -gt $resumeUtc) { $resumeUtc = $retryUtc } + $resetText = if ($resetUtc) { $resetUtc.LocalDateTime } else { 'unknown' } + $diagnostic = if ($kind -eq 'Primary') { "GitHub API rate limit encountered (HTTP $StatusCode). Resets at: $resetText" } + elseif ($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 = $kind; Scope = $scope; HttpStatus = $StatusCode + Resource = Get-MtGitHubResponseHeaderValue -Headers $Headers -Name 'x-ratelimit-resource' + RetryAfterSeconds = $(if ($retryUtc) { $retrySeconds } else { $null }) + ResetUtc = $resetUtc; ResumeUtc = $resumeUtc; Message = $diagnostic + } +} diff --git a/powershell/internal/services/github/Get-MtGitHubRateLimitMessage.ps1 b/powershell/internal/services/github/Get-MtGitHubRateLimitMessage.ps1 index f55609689d..3ed875be55 100644 --- a/powershell/internal/services/github/Get-MtGitHubRateLimitMessage.ps1 +++ b/powershell/internal/services/github/Get-MtGitHubRateLimitMessage.ps1 @@ -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 ). Resets at: