Skip to content

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

@MariusStorhaug

Description

@MariusStorhaug
Member

Describe the change

Problem:

When multiple runspaces concurrently call functions utilizing Invoke-GitHubAPI, there's a risk of triggering multiple simultaneous refresh attempts of the same context's GitHub access token. This concurrency leads to race conditions, redundant token refreshes, and potential conflicts or errors.

Desired Behavior:

Only a single refresh operation per context should occur at a time. Subsequent calls needing the refreshed token should wait until the ongoing refresh completes, ensuring consistency and preventing conflicts.

Proposed Solution:

Implement synchronization using the System.Threading.Mutex class:

  • When a context initiates a token refresh, it creates and acquires a mutex lock specific to that context.
  • Other parallel runspaces attempting to refresh the same context should detect the mutex lock and wait until it's released.
  • Upon successful token refresh, release and remove the mutex.
  • Any waiting processes will then reload the updated context without attempting another redundant refresh.

Implementation Considerations:

  • Ensure mutex names are unique per context.
  • Use proper try/finally blocks to guarantee mutex release.
  • Dispose of mutex objects appropriately after use.

This solution will eliminate concurrent token refresh attempts and enhance stability and reliability for parallelized GitHub API calls.

Activity

MariusStorhaug

MariusStorhaug commented on Jun 22, 2025

@MariusStorhaug
MemberAuthor
> $modulesPath = $env:PSModulePath -Split [IO.Path]::PathSeparator | Select-Object -First 1
> Get-GitHubArtifact -Owner PSModule -Repository GitHub -Name module |
>     Save-GitHubArtifact -Path $modulesPath -Extract -Force
> 
⚠ Access token expired. Refreshing access token...
⚠ Access token expired. Refreshing access token...
Wait-GitHubAccessToken : The client_id and/or client_secret passed are incorrect.
At C:\Users\marst\OneDrive\Documents\PowerShell\Modules\GitHub\GitHub.psm1:4285 char:34
+ … nResponse = Wait-GitHubAccessToken -ClientID $ClientID -RefreshToken  …
+               ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Wait-GitHubAccessToken
added a commit that references this issue on Jul 3, 2025
bb97530
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

Status

Done

Milestone

No milestone

Relationships

None yet

    Participants

    @MariusStorhaug

    Issue actions

      🩹 [Patch]: Prevent Concurrent Access Token Refresh with Mutex Lock · Issue #392 · PSModule/GitHub