@@ -14,6 +14,7 @@ import (
14
14
"net/url"
15
15
"os"
16
16
"strings"
17
+ "sync"
17
18
"time"
18
19
19
20
"github.com/gin-contrib/cors"
@@ -429,6 +430,7 @@ type OAuthProxy struct {
429
430
provider string
430
431
encryptionKey string
431
432
resourceName string
433
+ lock sync.Mutex
432
434
}
433
435
434
436
func NewOAuthProxy () (* OAuthProxy , error ) {
@@ -1016,6 +1018,9 @@ func (p *OAuthProxy) mcpProxyHandler(c *gin.Context) {
1016
1018
expiresAt , ok := tokenInfo .Props ["expires_at" ].(float64 )
1017
1019
if ok && expiresAt > 0 {
1018
1020
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 ()
1019
1024
log .Printf ("Access token is expired or will expire soon, attempting to refresh" )
1020
1025
1021
1026
// Get the refresh token
@@ -1026,6 +1031,7 @@ func (p *OAuthProxy) mcpProxyHandler(c *gin.Context) {
1026
1031
"error" : "invalid_token" ,
1027
1032
"error_description" : "Access token expired and no refresh token available" ,
1028
1033
})
1034
+ p .lock .Unlock ()
1029
1035
return
1030
1036
}
1031
1037
@@ -1037,6 +1043,7 @@ func (p *OAuthProxy) mcpProxyHandler(c *gin.Context) {
1037
1043
"error" : "server_error" ,
1038
1044
"error_description" : "Failed to refresh token" ,
1039
1045
})
1046
+ p .lock .Unlock ()
1040
1047
return
1041
1048
}
1042
1049
@@ -1049,6 +1056,7 @@ func (p *OAuthProxy) mcpProxyHandler(c *gin.Context) {
1049
1056
"error" : "server_error" ,
1050
1057
"error_description" : "OAuth credentials not configured" ,
1051
1058
})
1059
+ p .lock .Unlock ()
1052
1060
return
1053
1061
}
1054
1062
@@ -1060,6 +1068,7 @@ func (p *OAuthProxy) mcpProxyHandler(c *gin.Context) {
1060
1068
"error" : "invalid_token" ,
1061
1069
"error_description" : "Failed to refresh access token" ,
1062
1070
})
1071
+ p .lock .Unlock ()
1063
1072
return
1064
1073
}
1065
1074
@@ -1070,11 +1079,13 @@ func (p *OAuthProxy) mcpProxyHandler(c *gin.Context) {
1070
1079
"error" : "server_error" ,
1071
1080
"error_description" : "Failed to update grant with new token" ,
1072
1081
})
1082
+ p .lock .Unlock ()
1073
1083
return
1074
1084
}
1075
1085
1076
1086
// Update the token info with the new access token for the current request
1077
1087
tokenInfo .Props ["access_token" ] = newTokenInfo .AccessToken
1088
+ p .lock .Unlock ()
1078
1089
1079
1090
log .Printf ("Successfully refreshed access token" )
1080
1091
}
0 commit comments