Skip to content

🩹 [Patch]: Prevent Concurrent Access Token Refresh with Mutex Lock #393

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
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 @@ -44,52 +44,93 @@
process {
Write-Verbose "Reusing previously stored ClientID: [$($Context.AuthClientID)]"
$authClientID = $Context.AuthClientID
$accessTokenValidity = [datetime]($Context.TokenExpirationDate) - (Get-Date)
$accessTokenIsValid = $accessTokenValidity.Seconds -gt 0
$hours = $accessTokenValidity.Hours.ToString().PadLeft(2, '0')
$minutes = $accessTokenValidity.Minutes.ToString().PadLeft(2, '0')
$seconds = $accessTokenValidity.Seconds.ToString().PadLeft(2, '0')
$accessTokenValidityText = "$hours`:$minutes`:$seconds"
if ($accessTokenIsValid) {
if ($accessTokenValidity.TotalHours -gt $script:GitHub.Config.AccessTokenGracePeriodInHours) {
if (-not $Silent) {
Write-Host '✓ ' -ForegroundColor Green -NoNewline
Write-Host "Access token is still valid for $accessTokenValidityText ..."

# Create a unique mutex name for this context to prevent concurrent token refresh
$mutexName = "GitHubTokenRefresh_$($Context.ID -replace '[\\/:*?"<>|]', '_')"
$mutex = $null
$mutexAcquired = $false

try {
# Try to create and acquire the mutex with a reasonable timeout
$mutex = New-Object System.Threading.Mutex($false, $mutexName)
$mutexAcquired = $mutex.WaitOne(30000) # 30 second timeout

if (-not $mutexAcquired) {
Write-Warning "Timeout waiting for token refresh mutex. Proceeding without synchronization."
}

# Double-check if we still need to refresh after acquiring the mutex
# Another process might have already refreshed the token
$accessTokenValidity = [datetime]($Context.TokenExpirationDate) - (Get-Date)
$accessTokenIsValid = $accessTokenValidity.Seconds -gt 0
$hours = $accessTokenValidity.Hours.ToString().PadLeft(2, '0')
$minutes = $accessTokenValidity.Minutes.ToString().PadLeft(2, '0')
$seconds = $accessTokenValidity.Seconds.ToString().PadLeft(2, '0')
$accessTokenValidityText = "$hours`:$minutes`:$seconds"

if ($accessTokenIsValid) {
if ($accessTokenValidity.TotalHours -gt $script:GitHub.Config.AccessTokenGracePeriodInHours) {
if (-not $Silent) {
Write-Host '✓ ' -ForegroundColor Green -NoNewline
Write-Host "Access token is still valid for $accessTokenValidityText ..."
}
return
} else {
if (-not $Silent) {
Write-Host 'âš  ' -ForegroundColor Yellow -NoNewline
Write-Host "Access token remaining validity $accessTokenValidityText. Refreshing access token..."
}
$tokenResponse = Invoke-GitHubDeviceFlowLogin -ClientID $authClientID -RefreshToken ($Context.RefreshToken) -HostName $Context.HostName
}
return
} else {
if (-not $Silent) {
Write-Host 'âš  ' -ForegroundColor Yellow -NoNewline
Write-Host "Access token remaining validity $accessTokenValidityText. Refreshing access token..."
$refreshTokenValidity = [datetime]($Context.RefreshTokenExpirationDate) - (Get-Date)
$refreshTokenIsValid = $refreshTokenValidity.Seconds -gt 0
if ($refreshTokenIsValid) {
if (-not $Silent) {
Write-Host 'âš  ' -ForegroundColor Yellow -NoNewline
Write-Host 'Access token expired. Refreshing access token...'
}
$tokenResponse = Invoke-GitHubDeviceFlowLogin -ClientID $authClientID -RefreshToken ($Context.RefreshToken) -HostName $Context.HostName
} else {
Write-Verbose "Using $Mode authentication..."
$tokenResponse = Invoke-GitHubDeviceFlowLogin -ClientID $authClientID -Scope $Scope -HostName $Context.HostName
}
$tokenResponse = Invoke-GitHubDeviceFlowLogin -ClientID $authClientID -RefreshToken ($Context.RefreshToken) -HostName $Context.HostName
}
} else {
$refreshTokenValidity = [datetime]($Context.RefreshTokenExpirationDate) - (Get-Date)
$refreshTokenIsValid = $refreshTokenValidity.Seconds -gt 0
if ($refreshTokenIsValid) {
if (-not $Silent) {
Write-Host 'âš  ' -ForegroundColor Yellow -NoNewline
Write-Host 'Access token expired. Refreshing access token...'

# Only update the context if we actually got a token response
if ($tokenResponse) {
$Context.Token = ConvertTo-SecureString -AsPlainText $tokenResponse.access_token
$Context.TokenExpirationDate = (Get-Date).AddSeconds($tokenResponse.expires_in)
$Context.TokenType = $tokenResponse.access_token -replace $script:GitHub.TokenPrefixPattern
$Context.RefreshToken = ConvertTo-SecureString -AsPlainText $tokenResponse.refresh_token
$Context.RefreshTokenExpirationDate = (Get-Date).AddSeconds($tokenResponse.refresh_token_expires_in)

if ($PSCmdlet.ShouldProcess('Access token', 'Update/refresh')) {
Set-Context -Context $Context -ID $Context.ID
}
$tokenResponse = Invoke-GitHubDeviceFlowLogin -ClientID $authClientID -RefreshToken ($Context.RefreshToken) -HostName $Context.HostName
} else {
Write-Verbose "Using $Mode authentication..."
$tokenResponse = Invoke-GitHubDeviceFlowLogin -ClientID $authClientID -Scope $Scope -HostName $Context.HostName
}
}
$Context.Token = ConvertTo-SecureString -AsPlainText $tokenResponse.access_token
$Context.TokenExpirationDate = (Get-Date).AddSeconds($tokenResponse.expires_in)
$Context.TokenType = $tokenResponse.access_token -replace $script:GitHub.TokenPrefixPattern
$Context.RefreshToken = ConvertTo-SecureString -AsPlainText $tokenResponse.refresh_token
$Context.RefreshTokenExpirationDate = (Get-Date).AddSeconds($tokenResponse.refresh_token_expires_in)

if ($PSCmdlet.ShouldProcess('Access token', 'Update/refresh')) {
Set-Context -Context $Context -ID $Context.ID
}

if ($PassThru) {
$Context.Token
if ($PassThru) {
$Context.Token
}

} finally {
# Always release the mutex and dispose of it properly
if ($mutexAcquired -and $mutex) {
try {
$mutex.ReleaseMutex()
Write-Debug "Released mutex '$mutexName'"
} catch {
Write-Warning "Failed to release mutex '$mutexName': $($_.Exception.Message)"
}
}
if ($mutex) {
try {
$mutex.Dispose()
} catch {
Write-Warning "Failed to dispose mutex '$mutexName': $($_.Exception.Message)"
}
}
}

}
Expand Down
96 changes: 96 additions & 0 deletions tests/ConcurrentTokenRefresh.Tests.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
#Requires -Modules @{ ModuleName = 'Pester'; RequiredVersion = '5.7.1' }

[Diagnostics.CodeAnalysis.SuppressMessageAttribute(
'PSUseDeclaredVarsMoreThanAssignments', '',
Justification = 'Pester grouping syntax: known issue.'
)]
[CmdletBinding()]
param()

Describe 'Concurrent Token Refresh Prevention - Unit Tests' {

Context 'Mutex Implementation' {
It 'Should create and dispose mutex objects without throwing' {
# Test that the mutex can be created and disposed properly
$mutexName = "TestMutex_$(Get-Random)"
$mutex = $null
$acquired = $false

try {
# Create mutex object
$mutex = New-Object System.Threading.Mutex($false, $mutexName)
$mutex | Should -Not -BeNullOrEmpty

# Should be able to acquire
$acquired = $mutex.WaitOne(1000)
$acquired | Should -Be $true

} finally {
if ($acquired -and $mutex) { $mutex.ReleaseMutex() }
if ($mutex) { $mutex.Dispose() }
}
}

It 'Should handle mutex name sanitization' {
# Test that problematic characters in context ID are handled
$contextId = 'test/context:with*invalid?chars<>|'
$sanitizedName = "GitHubTokenRefresh_$($contextId -replace '[\\/:*?"<>|]', '_')"

# Should not contain any invalid characters
$sanitizedName | Should -Not -Match '[\\/:*?"<>|]'
$sanitizedName | Should -BeLike 'GitHubTokenRefresh_test_context_with_invalid_chars___'
}

It 'Should handle mutex timeout gracefully' {
$mutexName = "TestTimeoutMutex_$(Get-Random)"
$mutex = $null
$acquired = $false

try {
$mutex = New-Object System.Threading.Mutex($false, $mutexName)

# Should be able to acquire
$acquired = $mutex.WaitOne(1000)
$acquired | Should -Be $true

# Test timeout behavior - this should not throw
{ $mutex.WaitOne(50) } | Should -Not -Throw

} finally {
if ($acquired -and $mutex) { $mutex.ReleaseMutex() }
if ($mutex) { $mutex.Dispose() }
}
}
}

Context 'Code Structure Verification' {
It 'Should have mutex implementation in Update-GitHubUserAccessToken.ps1' {
$functionPath = '/home/runner/work/GitHub/GitHub/src/functions/private/Auth/DeviceFlow/Update-GitHubUserAccessToken.ps1'
$content = Get-Content $functionPath -Raw

# Verify mutex-related code is present
$content | Should -Match 'System\.Threading\.Mutex'
$content | Should -Match 'WaitOne'
$content | Should -Match 'ReleaseMutex'
$content | Should -Match 'finally'
$content | Should -Match 'Dispose'
}

It 'Should have proper try-finally structure' {
$functionPath = '/home/runner/work/GitHub/GitHub/src/functions/private/Auth/DeviceFlow/Update-GitHubUserAccessToken.ps1'
$content = Get-Content $functionPath -Raw

# Check for proper structure
$content | Should -Match 'try\s*\{'
$content | Should -Match '\}\s*finally\s*\{'
}

It 'Should implement double-check pattern' {
$functionPath = '/home/runner/work/GitHub/GitHub/src/functions/private/Auth/DeviceFlow/Update-GitHubUserAccessToken.ps1'
$content = Get-Content $functionPath -Raw

# Should check token validity after acquiring mutex
$content | Should -Match 'Double-check if we still need to refresh'
}
}
}
Loading