Skip to content

Commit 54337bc

Browse files
authored
Merge pull request #3 from obot-platform/lock
Fix: add properly lock when refresh access token
2 parents 4943c8c + 5f43be1 commit 54337bc

File tree

1 file changed

+11
-0
lines changed

1 file changed

+11
-0
lines changed

main.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import (
1414
"net/url"
1515
"os"
1616
"strings"
17+
"sync"
1718
"time"
1819

1920
"github.com/gin-contrib/cors"
@@ -429,6 +430,7 @@ type OAuthProxy struct {
429430
provider string
430431
encryptionKey string
431432
resourceName string
433+
lock sync.Mutex
432434
}
433435

434436
func NewOAuthProxy() (*OAuthProxy, error) {
@@ -1016,6 +1018,9 @@ func (p *OAuthProxy) mcpProxyHandler(c *gin.Context) {
10161018
expiresAt, ok := tokenInfo.Props["expires_at"].(float64)
10171019
if ok && expiresAt > 0 {
10181020
if time.Now().Add(5 * time.Minute).After(time.Unix(int64(expiresAt), 0)) {
1021+
// when refreshing token, we need to lock the database to avoid race conditions
1022+
// otherwise we could get save the old access token into the database when another refresh process is running
1023+
p.lock.Lock()
10191024
log.Printf("Access token is expired or will expire soon, attempting to refresh")
10201025

10211026
// Get the refresh token
@@ -1026,6 +1031,7 @@ func (p *OAuthProxy) mcpProxyHandler(c *gin.Context) {
10261031
"error": "invalid_token",
10271032
"error_description": "Access token expired and no refresh token available",
10281033
})
1034+
p.lock.Unlock()
10291035
return
10301036
}
10311037

@@ -1037,6 +1043,7 @@ func (p *OAuthProxy) mcpProxyHandler(c *gin.Context) {
10371043
"error": "server_error",
10381044
"error_description": "Failed to refresh token",
10391045
})
1046+
p.lock.Unlock()
10401047
return
10411048
}
10421049

@@ -1049,6 +1056,7 @@ func (p *OAuthProxy) mcpProxyHandler(c *gin.Context) {
10491056
"error": "server_error",
10501057
"error_description": "OAuth credentials not configured",
10511058
})
1059+
p.lock.Unlock()
10521060
return
10531061
}
10541062

@@ -1060,6 +1068,7 @@ func (p *OAuthProxy) mcpProxyHandler(c *gin.Context) {
10601068
"error": "invalid_token",
10611069
"error_description": "Failed to refresh access token",
10621070
})
1071+
p.lock.Unlock()
10631072
return
10641073
}
10651074

@@ -1070,11 +1079,13 @@ func (p *OAuthProxy) mcpProxyHandler(c *gin.Context) {
10701079
"error": "server_error",
10711080
"error_description": "Failed to update grant with new token",
10721081
})
1082+
p.lock.Unlock()
10731083
return
10741084
}
10751085

10761086
// Update the token info with the new access token for the current request
10771087
tokenInfo.Props["access_token"] = newTokenInfo.AccessToken
1088+
p.lock.Unlock()
10781089

10791090
log.Printf("Successfully refreshed access token")
10801091
}

0 commit comments

Comments
 (0)