fix(mcp): coordinate OAuth token refresh and authorization polling

Prevent concurrent refresh-token rotation across instances, distinguish
expired-but-refreshable tokens from active authorization, and bind OAuth
popup polling to a per-attempt ID so stale tokens cannot satisfy new consent.
This commit is contained in:
wizardchen
2026-07-23 15:33:20 +08:00
committed by lyingbug
parent c74b0caa35
commit 8ae82573ab
31 changed files with 1418 additions and 109 deletions
@@ -140,3 +140,51 @@ func (r *mcpOAuthRepository) DeleteTokenForPrincipal(
).
Delete(&types.MCPOAuthToken{}).Error
}
func (r *mcpOAuthRepository) TryAcquireTokenRefreshLease(
ctx context.Context,
tenantID uint64,
principal types.Principal,
serviceID, leaseID string,
leaseUntil time.Time,
) (bool, error) {
principal = principal.Normalize()
if !principal.Valid() || leaseID == "" {
return false, nil
}
now := time.Now()
result := r.db.WithContext(ctx).
Model(&types.MCPOAuthToken{}).
Where(
"tenant_id = ? AND principal_type = ? AND principal_id = ? AND service_id = ?",
tenantID, principal.Type, principal.ID, serviceID,
).
Where("refresh_lease_until IS NULL OR refresh_lease_until < ?", now).
Updates(map[string]interface{}{
"refresh_lease_id": leaseID,
"refresh_lease_until": leaseUntil,
})
return result.RowsAffected == 1, result.Error
}
func (r *mcpOAuthRepository) ReleaseTokenRefreshLease(
ctx context.Context,
tenantID uint64,
principal types.Principal,
serviceID, leaseID string,
) error {
principal = principal.Normalize()
if !principal.Valid() || leaseID == "" {
return nil
}
return r.db.WithContext(ctx).
Model(&types.MCPOAuthToken{}).
Where(
"tenant_id = ? AND principal_type = ? AND principal_id = ? AND service_id = ? AND refresh_lease_id = ?",
tenantID, principal.Type, principal.ID, serviceID, leaseID,
).
Updates(map[string]interface{}{
"refresh_lease_id": "",
"refresh_lease_until": nil,
}).Error
}