Skip to content

Commit

Permalink
Fix concurrency issues
Browse files Browse the repository at this point in the history
  • Loading branch information
pierluc-codes committed Aug 28, 2024
1 parent 816652c commit 9d41927
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .changelog/267.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
```release-note:bug
Fixes concurrency issues while using a browser based token.
```
13 changes: 13 additions & 0 deletions auth/tokencache/tokensource.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"context"
"fmt"
"log"
"sync"
"time"

"golang.org/x/oauth2"
Expand All @@ -22,6 +23,10 @@ const (
minTTL = 15 * time.Second
)

var (
mutex sync.Mutex
)

// sourceType identities the type of token source.
type sourceType = string

Expand All @@ -37,6 +42,14 @@ type cachingTokenSource struct {
// Token implements the oauth2.TokenSource interface. It will read cached tokens from a file and based on their validity
// return, refresh or replace them.
func (source *cachingTokenSource) Token() (*oauth2.Token, error) {
// According to https://cs.opensource.google/go/x/oauth2/+/refs/tags/v0.22.0:oauth2.go;l=68-73
// Token must be safe for concurrent use by multiple goroutines.
// Additionally, terraform invoke the provider in a parallel manner. Without this synchronization,
// multiple Token exchange will happen. This also means that if user uses browser based token,
// it will opens the browser multiple times.
mutex.Lock()
defer mutex.Unlock()

// Read the cache information from the file, if it exists
cachedTokens, err := readCache(source.cacheFile)
if err != nil {
Expand Down

0 comments on commit 9d41927

Please sign in to comment.