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
@@ -0,0 +1,35 @@
function Invoke-MtGitHubConnectionProbe {
<#
.SYNOPSIS
Internal: Sends a GitHub connection probe with shared rate-limit tracking.
.DESCRIPTION
Checks the connection's cooldown before sending a GET request, then records rate-limit
state from the response or error. Returns the unparsed response and lets the caller
decide whether a probe failure blocks the connection. Both request timeouts are 30 seconds.
.PARAMETER Uri
The absolute GitHub API URI to probe.
.PARAMETER Headers
The authentication and API headers prepared by Connect-MtGitHub.
.PARAMETER Connection
The shared connection object used for rate-limit tracking throughout the probes.
.EXAMPLE
Invoke-MtGitHubConnectionProbe -Uri "$ApiBaseUri/user" -Headers $AuthHeaders -Connection $RateLimitConnection

Probes token identity using the supplied headers and connection's rate-limit state.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory)] [string] $Uri,
[Parameter(Mandatory)] [hashtable] $Headers,
[Parameter(Mandatory)] [object] $Connection
)
Invoke-MtGitHubRateLimitGuard -Api REST -Connection $Connection
try {
$Response = Invoke-WebRequest -Uri $Uri -Headers $Headers -Method GET -UseBasicParsing -ConnectionTimeoutSeconds 30 -OperationTimeoutSeconds 30 -ErrorAction Stop
Invoke-MtGitHubRateLimitGuard -Api REST -Connection $Connection -Headers $Response.Headers
return $Response
} catch {
Invoke-MtGitHubRateLimitGuard -Api REST -Connection $Connection -ErrorRecord $_
throw
}
}
19 changes: 4 additions & 15 deletions powershell/public/connect/Connect-MtGitHub.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -260,21 +260,10 @@
# Bootstrap probes use the same guard as assessment requests. Carry this connection's cooldown
# into the final session, including a non-blocking administration-probe limit.
$rateLimitConnection = [pscustomobject]@{ ApiBaseUri = $ApiBaseUri }
function Invoke-ConnectionProbe ([string] $Uri) {
Invoke-MtGitHubRateLimitGuard -Api REST -Connection $rateLimitConnection
try {
$response = Invoke-WebRequest -Uri $Uri -Headers $authHeaders -Method GET -UseBasicParsing -ConnectionTimeoutSeconds 30 -OperationTimeoutSeconds 30 -ErrorAction Stop
Invoke-MtGitHubRateLimitGuard -Api REST -Connection $rateLimitConnection -Headers $response.Headers
return $response
} catch {
Invoke-MtGitHubRateLimitGuard -Api REST -Connection $rateLimitConnection -ErrorRecord $_
throw
}
}

# Probe 1: token identity
try {
$userResponse = Invoke-ConnectionProbe -Uri "$ApiBaseUri/user"
$userResponse = Invoke-MtGitHubConnectionProbe -Uri "$ApiBaseUri/user" -Headers $authHeaders -Connection $rateLimitConnection
$user = $userResponse.Content | ConvertFrom-Json
Write-Verbose "GitHub token identity: $($user.login)"
} catch {
Expand Down Expand Up @@ -342,7 +331,7 @@
$roleWarning = $null

try {
$orgResponse = Invoke-ConnectionProbe -Uri "$ApiBaseUri/orgs/$encodedOrg"
$orgResponse = Invoke-MtGitHubConnectionProbe -Uri "$ApiBaseUri/orgs/$encodedOrg" -Headers $authHeaders -Connection $rateLimitConnection
try {
$orgData = $orgResponse.Content | ConvertFrom-Json -ErrorAction Stop
} catch {
Expand Down Expand Up @@ -401,7 +390,7 @@
# Use /user/memberships/orgs/{org} so the token only has to prove its own membership,
# not read an arbitrary /orgs/{org}/memberships/{username} record.
try {
$membershipResponse = Invoke-ConnectionProbe -Uri "$ApiBaseUri/user/memberships/orgs/$encodedOrg"
$membershipResponse = Invoke-MtGitHubConnectionProbe -Uri "$ApiBaseUri/user/memberships/orgs/$encodedOrg" -Headers $authHeaders -Connection $rateLimitConnection

$membershipData = $null
try {
Expand Down Expand Up @@ -486,7 +475,7 @@
$adminAcceptedPermissions = $null
$adminWarning = $null
try {
$adminResponse = Invoke-ConnectionProbe -Uri "$ApiBaseUri/orgs/$encodedOrg/actions/permissions"
$adminResponse = Invoke-MtGitHubConnectionProbe -Uri "$ApiBaseUri/orgs/$encodedOrg/actions/permissions" -Headers $authHeaders -Connection $rateLimitConnection
$adminVerified = $true
$adminStatusCode = 200
if ($adminResponse.PSObject.Properties.Name -contains 'StatusCode' -and $null -ne $adminResponse.StatusCode) {
Expand Down
96 changes: 96 additions & 0 deletions powershell/tests/functions/Connect-MtGitHub.Tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -380,6 +380,42 @@ Describe 'Connect-MtGitHub' {
}
}

It 'Passes explicit headers and the same connection object to all four probes' {
$script:ProbeCalls = [System.Collections.Generic.List[object]]::new()
Mock Invoke-MtGitHubConnectionProbe -ModuleName Maester {
$script:ProbeCalls.Add([pscustomobject]@{ Uri = $Uri; Headers = $Headers; Connection = $Connection })
$Content = switch ($Uri) {
'https://api.myco.ghe.com/user' { '{"login":"testuser"}' }
'https://api.myco.ghe.com/orgs/myorg' { '{"login":"myorg"}' }
'https://api.myco.ghe.com/user/memberships/orgs/myorg' { '{"state":"active","role":"admin"}' }
'https://api.myco.ghe.com/orgs/myorg/actions/permissions' { '{}' }
default { throw "Unexpected probe URI: $Uri" }
}
[pscustomobject]@{ Content = $Content; StatusCode = 200 }
}

Connect-MtGitHub -Organization 'myorg' -ApiBaseUri 'https://api.myco.ghe.com' -ApiVersion '2024-01-01' 3>$null

Should -Invoke Invoke-MtGitHubConnectionProbe -ModuleName Maester -Exactly -Times 4
Should -Invoke Invoke-WebRequest -ModuleName Maester -Exactly -Times 0
$script:ProbeCalls.Uri | Should -Be @(
'https://api.myco.ghe.com/user'
'https://api.myco.ghe.com/orgs/myorg'
'https://api.myco.ghe.com/user/memberships/orgs/myorg'
'https://api.myco.ghe.com/orgs/myorg/actions/permissions'
)
InModuleScope Maester -Parameters @{ ProbeCalls = $script:ProbeCalls } {
$__MtSession.GitHubConnection.Connected | Should -BeTrue
foreach ($Call in $ProbeCalls) {
[object]::ReferenceEquals($Call.Connection, $ProbeCalls[0].Connection) | Should -BeTrue
$Call.Connection.ApiBaseUri | Should -Be 'https://api.myco.ghe.com'
[object]::ReferenceEquals($Call.Headers, $__MtSession.GitHubAuthHeader) | Should -BeTrue
$Call.Headers.Authorization | Should -Be 'Bearer valid-token'
$Call.Headers['X-GitHub-Api-Version'] | Should -Be '2024-01-01'
}
}
}

It 'All four probes use the configured ApiBaseUri and X-GitHub-Api-Version header' {
Connect-MtGitHub -Organization 'myorg' -ApiBaseUri 'https://api.myco.ghe.com' -ApiVersion '2024-01-01' 3>$null

Expand Down Expand Up @@ -1591,3 +1627,63 @@ Describe 'Connect-MtGitHub' {
}
}
}

Describe 'Invoke-MtGitHubConnectionProbe' {
It 'Checks the supplied connection before GET and records headers before returning the original response' {
InModuleScope Maester {
$ProbeConnection = [pscustomobject]@{ ApiBaseUri = 'https://api.fixture.ghe.com' }
$RequestHeaders = @{ Authorization = 'Bearer synthetic-probe'; Accept = 'application/vnd.github+json' }
$Response = [pscustomobject]@{ Content = 'unparsed response'; Headers = @{ 'x-ratelimit-remaining' = '1' }; StatusCode = 200 }
$Events = [System.Collections.Generic.List[string]]::new()
Mock Invoke-MtGitHubRateLimitGuard {
$Events.Add($(if ($null -ne $Headers) { 'Response' } else { 'Preflight' }))
}
Mock Invoke-WebRequest { $Events.Add('Request'); return $Response }

$Actual = Invoke-MtGitHubConnectionProbe -Uri 'https://api.fixture.ghe.com/user' -Headers $RequestHeaders -Connection $ProbeConnection

[object]::ReferenceEquals($Actual, $Response) | Should -BeTrue
$Events | Should -Be @('Preflight', 'Request', 'Response')
Should -Invoke Invoke-WebRequest -Exactly -Times 1 -ParameterFilter {
$Uri -eq 'https://api.fixture.ghe.com/user' -and [object]::ReferenceEquals($Headers, $RequestHeaders) -and
$Method -eq 'GET' -and $UseBasicParsing -and $ConnectionTimeoutSeconds -eq 30 -and
$OperationTimeoutSeconds -eq 30 -and $ErrorAction -eq 'Stop'
}
Should -Invoke Invoke-MtGitHubRateLimitGuard -Exactly -Times 2 -ParameterFilter {
$Api -eq 'REST' -and [object]::ReferenceEquals($Connection, $ProbeConnection)
}
Should -Invoke Invoke-MtGitHubRateLimitGuard -Exactly -Times 1 -ParameterFilter {
[object]::ReferenceEquals($Headers, $Response.Headers)
}
}
}

It 'Records an ordinary request error on the supplied connection and rethrows it' {
InModuleScope Maester {
$ProbeConnection = [pscustomobject]@{ ApiBaseUri = 'https://api.github.com' }
$Response = [System.Net.Http.HttpResponseMessage]::new([System.Net.HttpStatusCode]::Forbidden)
$Failure = [System.Management.Automation.ErrorRecord]::new(
[Microsoft.PowerShell.Commands.HttpResponseException]::new('Synthetic forbidden probe', $Response),
'FixtureProbe', 'InvalidOperation', $null
)
$Failure.ErrorDetails = [System.Management.Automation.ErrorDetails]::new('{"message":"Forbidden"}')
Mock Invoke-MtGitHubRateLimitGuard {}
Mock Invoke-WebRequest { throw $Failure }

$Caught = $null
try {
Invoke-MtGitHubConnectionProbe -Uri 'https://api.github.com/user' -Headers @{ Authorization = 'Bearer synthetic-probe' } -Connection $ProbeConnection
} catch { $Caught = $_ }

$Caught | Should -Not -BeNullOrEmpty
[object]::ReferenceEquals($Caught.Exception, $Failure.Exception) | Should -BeTrue
$Caught.ErrorDetails.Message | Should -Be $Failure.ErrorDetails.Message
Should -Invoke Invoke-MtGitHubRateLimitGuard -Exactly -Times 2 -ParameterFilter {
$Api -eq 'REST' -and [object]::ReferenceEquals($Connection, $ProbeConnection)
}
Should -Invoke Invoke-MtGitHubRateLimitGuard -Exactly -Times 1 -ParameterFilter {
$null -ne $ErrorRecord -and [object]::ReferenceEquals($ErrorRecord.Exception, $Failure.Exception)
}
}
}
}
63 changes: 45 additions & 18 deletions powershell/tests/functions/GitHubRateLimit.Tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -193,30 +193,57 @@ Describe 'GraphQL and bootstrap rate-limit boundaries' {
Should -Invoke Invoke-WebRequest -ModuleName Maester -Exactly -Times 1
}

It 'Stops bootstrap after successful primary exhaustion and carries a final permission-probe limit into assessments (early=<Early>)' -ForEach @(@{ Early = $true }, @{ Early = $false }) {
$script:early = $Early
It 'Preserves bootstrap cooldowns at <Probe> after <Outcome>' -ForEach @(
@{ Probe = 'user'; Outcome = 'Success'; ExpectedRequests = 1 }
@{ Probe = 'orgs/fixture-org'; Outcome = 'Success'; ExpectedRequests = 2 }
@{ Probe = 'user/memberships/orgs/fixture-org'; Outcome = 'Success'; ExpectedRequests = 3 }
@{ Probe = 'orgs/fixture-org/actions/permissions'; Outcome = 'Success'; ExpectedRequests = 4 }
@{ Probe = 'user'; Outcome = 'Error'; ExpectedRequests = 1 }
@{ Probe = 'orgs/fixture-org'; Outcome = 'Error'; ExpectedRequests = 2 }
@{ Probe = 'user/memberships/orgs/fixture-org'; Outcome = 'Error'; ExpectedRequests = 3 }
@{ Probe = 'orgs/fixture-org/actions/permissions'; Outcome = 'Error'; ExpectedRequests = 4 }
) {
$script:LimitedProbe = "https://api.github.com/$Probe"
$script:ProbeOutcome = $Outcome
Mock Invoke-WebRequest -ModuleName Maester {
if ($Uri -match '/user$') {
$headers = if ($script:early) { @{ 'x-ratelimit-remaining' = '0'; 'x-ratelimit-reset' = [DateTimeOffset]::UtcNow.AddMinutes(10).ToUnixTimeSeconds() } } else { @{} }
return [pscustomobject]@{ Content = '{"login":"fixture-user"}'; Headers = $headers }
$Headers = @{}
if ($Uri -eq $script:LimitedProbe) {
if ($script:ProbeOutcome -eq 'Error') {
$Response = [System.Net.Http.HttpResponseMessage]::new([System.Net.HttpStatusCode]::TooManyRequests)
$null = $Response.Headers.TryAddWithoutValidation('retry-after', '120')
throw [Microsoft.PowerShell.Commands.HttpResponseException]::new('Synthetic rate limit', $Response)
}
$Headers = @{ 'x-ratelimit-remaining' = '0'; 'x-ratelimit-reset' = [DateTimeOffset]::UtcNow.AddMinutes(10).ToUnixTimeSeconds() }
}
if ($Uri -match '/memberships/') { return [pscustomobject]@{ Content = '{"state":"active","role":"admin"}'; Headers = @{} } }
if ($Uri -match '/orgs/fixture-org$') { return [pscustomobject]@{ Content = '{"login":"fixture-org","plan":{"name":"enterprise"}}'; Headers = @{} } }
$response = [System.Net.Http.HttpResponseMessage]::new([System.Net.HttpStatusCode]::TooManyRequests)
$null = $response.Headers.TryAddWithoutValidation('retry-after', '120')
throw [Microsoft.PowerShell.Commands.HttpResponseException]::new('Synthetic rate limit', $response)
$Content = switch ($Uri) {
'https://api.github.com/user' { '{"login":"fixture-user"}' }
'https://api.github.com/orgs/fixture-org' { '{"login":"fixture-org","plan":{"name":"enterprise"}}' }
'https://api.github.com/user/memberships/orgs/fixture-org' { '{"state":"active","role":"admin"}' }
'https://api.github.com/orgs/fixture-org/actions/permissions' { '{}' }
default { throw "Unexpected request: $Uri" }
}
[pscustomobject]@{ Content = $Content; Headers = $Headers; StatusCode = 200 }
}
InModuleScope Maester -Parameters @{ Early = $Early } {
$token = [System.Security.SecureString]::new()
$token.AppendChar('x')
Connect-MtGitHub -Organization fixture-org -Token $token -ApiBaseUri https://api.github.com -ApiVersion '2022-11-28' -WarningAction SilentlyContinue
if ($Early) { $__MtSession.GitHubConnection.FailureReason | Should -Be 'RateLimited' }
else {
$__MtSession.GitHubConnection.Connected | Should -BeTrue
InModuleScope Maester -Parameters @{ Probe = $Probe; Outcome = $Outcome } {
$Token = [System.Security.SecureString]::new()
$Token.AppendChar('x')
Connect-MtGitHub -Organization fixture-org -Token $Token -ApiBaseUri https://api.github.com -ApiVersion '2022-11-28' -WarningVariable Warnings -WarningAction SilentlyContinue
# Exhausting the membership response blocks only the non-blocking administration probe.
$Connected = $Probe -eq 'orgs/fixture-org/actions/permissions' -or ($Outcome -eq 'Success' -and $Probe -eq 'user/memberships/orgs/fixture-org')
$__MtSession.GitHubConnection.Connected | Should -Be $Connected
if (-not $Connected) {
$__MtSession.GitHubConnection.FailureReason | Should -Be 'RateLimited'
$__MtSession.GitHubAuthHeader | Should -BeNullOrEmpty
} else {
[object]::ReferenceEquals($__MtSession.GitHubRateLimits.Connection, $__MtSession.GitHubConnection) | Should -BeTrue
$AdminVerified = $Outcome -eq 'Success' -and $Probe -eq 'orgs/fixture-org/actions/permissions'
$__MtSession.GitHubConnection.AdministrationPermissionVerified | Should -Be $AdminVerified
if (-not $AdminVerified) { $Warnings -join ' ' | Should -Match 'administration.*rate limit' }
{ Invoke-MtGitHubRequest '/repository' } | Should -Throw '*rate limit*'
}
$__MtSession.GitHubRateLimits.Limits.Count | Should -Be 1
}
Should -Invoke Invoke-WebRequest -ModuleName Maester -Exactly -Times $(if ($Early) { 1 } else { 4 })
Should -Invoke Invoke-WebRequest -ModuleName Maester -Exactly -Times $ExpectedRequests
}
}

Expand Down
Loading