Skip to content

OpenProject is the leading open source project management software for product, project and portfolio management. A powerful Jira alternative with agile planning, issue tracking, roadmaps, Gantt charts, time tracking, collaboration features, and more. Available on premises or in the cloud. ⭐ Star us on GitHub

[#57835] Use advisory lock to synchronize token refresh process.

Pavel Balashou32843020ad7e
diff --git a/app/models/user.rb b/app/models/user.rb
index 23e85c02b3b..577ee760618 100644
--- a/app/models/user.rb
+++ b/app/models/user.rb
@@ -55,6 +55,7 @@ class User < Principal
inverse_of: :user
has_one :rss_token, class_name: "::Token::RSS", dependent: :destroy
has_many :api_tokens, class_name: "::Token::API", dependent: :destroy
+ has_many :oauth_client_tokens, dependent: :destroy
# The user might have one invitation token
has_one :invitation_token, class_name: "::Token::Invitation", dependent: :destroy
diff --git a/modules/storages/app/common/storages/peripherals/storage_interaction/authentication_strategies/oauth_user_token.rb b/modules/storages/app/common/storages/peripherals/storage_interaction/authentication_strategies/oauth_user_token.rb
index ac17b430704..267dbe75dea 100644
--- a/modules/storages/app/common/storages/peripherals/storage_interaction/authentication_strategies/oauth_user_token.rb
+++ b/modules/storages/app/common/storages/peripherals/storage_interaction/authentication_strategies/oauth_user_token.rb
@@ -33,6 +33,12 @@ module Storages
module StorageInteraction
module AuthenticationStrategies
class OAuthUserToken
+ REFRESH_TOKEN_TIMEOUT_SECONDS = 4
+
+ def self.mutex_refresh_token_key(token)
+ "Refreshing OAuth token stored in #{token.class}##{token.id}"
+ end
+
def self.strategy
Strategy.new(:oauth_user_token)
end
@@ -78,7 +84,7 @@ module Storages
end
# Uncached block is used here because in case of concurrent update on the second try we need a fresh token.
- # Otherwise token ends up in an invalid state which leads to an undesired token deletion.
+ # Otherwise token ends up in an invalid state which could lead to an undesired token deletion.
current_token = OAuthClientToken.uncached do
OAuthClientToken.find_by(user: @user, oauth_client: storage.oauth_configuration.oauth_client)
end
@@ -93,35 +99,40 @@ module Storages
# rubocop:disable Metrics/AbcSize
def refresh_and_retry(config, http_options, token, &)
- begin
+ http_session = nil
+ lock_was_acquired = OpenProject::Mutex.with_advisory_lock(OAuthClientToken,
+ self.class.mutex_refresh_token_key(token),
+ timeout_seconds: REFRESH_TOKEN_TIMEOUT_SECONDS) do
http_session = OpenProject.httpx
- .oauth_auth(issuer: config.issuer,
- client_id: config.client_id,
- client_secret: config.client_secret,
- scope: config.scope,
- refresh_token: token.refresh_token,
- token_endpoint_auth_method: "client_secret_post")
- .with_access_token
- .with(http_options)
+ .oauth_auth(issuer: config.issuer,
+ client_id: config.client_id,
+ client_secret: config.client_secret,
+ scope: config.scope,
+ refresh_token: token.refresh_token,
+ token_endpoint_auth_method: "client_secret_post")
+ .with_access_token
+ .with(http_options)
+ if update_refreshed_token(token, http_session)
+ true
+ else
+ return Failures::Builder.call(code: :error,
+ log_message: "Error while persisting updated access token.",
+ data: ::Storages::StorageErrorData.new(source: self.class))
+ end
rescue HTTPX::HTTPError => e
return handle_http_error_on_refresh(token, e)
rescue HTTPX::TimeoutError => e
return handle_timeout_on_refresh(token, e)
end
- response = yield http_session
-
- if response.success?
- success = update_refreshed_token(token, http_session)
- unless success
- data = ::Storages::StorageErrorData.new(source: self.class)
- return Failures::Builder.call(code: :error,
- log_message: "Error while persisting updated access token.",
- data:)
- end
+ if lock_was_acquired
+ yield http_session
+ else
+ Failures::Builder.call(code: :error,
+ log_message: "Lock has not been acquired in #{REFRESH_TOKEN_TIMEOUT_SECONDS} seconds. " \
+ "Refresh token is being updated at the moment by another thread.",
+ data: ::Storages::StorageErrorData.new(source: self.class))
end
-
- response
end
# rubocop:enable Metrics/AbcSize
diff --git a/modules/storages/spec/common/storages/peripherals/storage_interaction/authentication_spec.rb b/modules/storages/spec/common/storages/peripherals/storage_interaction/authentication_spec.rb
index d144895cfec..6aa0dd5e471 100644
--- a/modules/storages/spec/common/storages/peripherals/storage_interaction/authentication_spec.rb
+++ b/modules/storages/spec/common/storages/peripherals/storage_interaction/authentication_spec.rb
@@ -143,8 +143,22 @@ RSpec.describe Storages::Peripherals::StorageInteraction::Authentication, :webmo
.to be(Storages::Peripherals::StorageInteraction::AuthenticationStrategies::OAuthUserToken)
end
+ it "responds with error when lock could not be obtained timely" do
+ strategy = described_class[auth_strategy]
+
+ allow(OpenProject::Mutex).to receive(:with_advisory_lock).and_return(false)
+
+ result = strategy.call(storage:, http_options:) { |http| make_request(http) }
+ expect(result).to be_failure
+
+ error = result.errors
+ expect(error.code).to eq(:error)
+ expect(error.data.source).to be(Storages::Peripherals::StorageInteraction::AuthenticationStrategies::OAuthUserToken)
+ expect(error.log_message).to eq("Lock has not been acquired in 4 seconds. Refresh token is being updated at the moment by another thread.")
+ end
+
it "logs, retries once, raises exception if race condition happens" do
- token = OAuthClientToken.last
+ token = user.oauth_client_tokens.first
strategy = described_class[auth_strategy]
allow(Rails.logger).to receive(:error)
@@ -163,6 +177,22 @@ RSpec.describe Storages::Peripherals::StorageInteraction::Authentication, :webmo
context "with invalid oauth access token", vcr: "auth/nextcloud/user_token_access_token_invalid" do
it_behaves_like "successful response", refreshed: true
+
+ context "when updating token in openproject database fails" do
+ it "responds with error" do
+ storage
+ token = user.oauth_client_tokens.first
+ strategy = described_class[auth_strategy]
+ allow(strategy).to receive(:current_token).and_return(ServiceResult.success(result: token))
+ allow(token).to receive(:update).and_return(false)
+
+ result = strategy.call(storage:, http_options:) { |http| make_request(http) }
+ expect(result).to be_failure
+ expect(result.result).to eq(:error)
+ expect(result.errors.code).to eq(:error)
+ expect(result.errors.log_message).to eq("Error while persisting updated access token.")
+ end
+ end
end
end
end