Skip to content

Commit 35c355c

Browse files
committed
fix concurrent refresh race
closes #1
1 parent 7cdd436 commit 35c355c

File tree

1 file changed

+9
-8
lines changed

1 file changed

+9
-8
lines changed

auth/token.go

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -152,11 +152,10 @@ func (c *CachingTokenSource) tokenFromDisk() (*identityToken, error) {
152152

153153
func (c *CachingTokenSource) tokenToDisk(tok *identityToken) error {
154154
cacheKey := c.cacheKey()
155-
156155
jsonCachePath := path.Join(c.cacheDir, fmt.Sprintf("%s.json", cacheKey))
157-
jsonCachePathTmp := jsonCachePath + ".tmp"
158156

159-
jsonCacheFile, err := os.OpenFile(jsonCachePathTmp, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0600)
157+
jsonTmpPattern := fmt.Sprintf("%s.json.tmp.*", cacheKey)
158+
jsonCacheFile, err := os.CreateTemp(c.cacheDir, jsonTmpPattern)
160159
if err != nil {
161160
return fmt.Errorf("unable to open cache file: %w", err)
162161
}
@@ -167,16 +166,18 @@ func (c *CachingTokenSource) tokenToDisk(tok *identityToken) error {
167166
return fmt.Errorf("unable to encode token: %w", err)
168167
}
169168
jsonCacheFile.Close()
170-
err = os.Rename(jsonCachePathTmp, jsonCachePath)
169+
err = os.Rename(jsonCacheFile.Name(), jsonCachePath)
171170
if err != nil {
172171
return fmt.Errorf("unable to rename tmpfile: %w", err)
173172
}
174173

175174
// also write out the raw token for use in fallback
176175
rawCachePath := c.GetAccessTokenPath()
177-
rawCachePathTmp := rawCachePath + ".tmp"
178-
179-
rawCacheFile, err := os.OpenFile(rawCachePathTmp, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0600)
176+
rawTmpPattern := fmt.Sprintf("%s.tmp.*", cacheKey)
177+
rawCacheFile, err := os.CreateTemp(c.cacheDir, rawTmpPattern)
178+
if err != nil {
179+
return fmt.Errorf("unable to open cache file: %w", err)
180+
}
180181
if err != nil {
181182
return fmt.Errorf("unable to open cache file: %w", err)
182183
}
@@ -186,7 +187,7 @@ func (c *CachingTokenSource) tokenToDisk(tok *identityToken) error {
186187
return fmt.Errorf("unable to write token to cache file: %w", err)
187188
}
188189
rawCacheFile.Close()
189-
err = os.Rename(rawCachePathTmp, rawCachePath)
190+
err = os.Rename(rawCacheFile.Name(), rawCachePath)
190191
if err != nil {
191192
return fmt.Errorf("unable to rename tmpfile: %w", err)
192193
}

0 commit comments

Comments
 (0)