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
Ruby agile-developmentangularbcfboardsbug-trackerganttgantt-chartifcissue-trackerjira-alternativekanbanopenprojectproduct-managementproject-managementproject-planningroadmaprubyscrumtimelineworkflows
[#46195] Prevent OAuth refresh token race condition. (#12059)
Pavel Balashou2de999ea40f3
diff --git a/Gemfile b/Gemfileindex 6c001c77a43..88f4b53399a 100644--- a/Gemfile+++ b/Gemfile@@ -254,6 +254,7 @@ group :test dogem 'shoulda-matchers', '~> 5.0', require: nilgem 'parallel_tests', '~> 4.0'+ gem 'database_cleaner-active_record'endgroup :ldap dodiff --git a/Gemfile.lock b/Gemfile.lockindex 8bf35d3a286..5653f50232d 100644--- a/Gemfile.lock+++ b/Gemfile.lock@@ -391,6 +391,10 @@ GEMdanger-plugin-api (~> 1.0)danger-plugin-api (1.0.0)danger (> 2.0)+ database_cleaner-active_record (2.0.1)+ activerecord (>= 5.a)+ database_cleaner-core (~> 2.0.0)+ database_cleaner-core (2.0.1)date (3.3.3)date_validator (0.12.0)activemodel (>= 3)@@ -1033,6 +1037,7 @@ DEPENDENCIESdalli (~> 3.2.0)danger-brakemandashboards!+ database_cleaner-active_recorddate_validator (~> 0.12.0)deckar01-task_list (~> 2.3.1)delayed_cron_job (~> 0.9.0)diff --git a/app/services/oauth_clients/connection_manager.rb b/app/services/oauth_clients/connection_manager.rbindex bb21b6b9493..15a7a30ae5f 100644--- a/app/services/oauth_clients/connection_manager.rb+++ b/app/services/oauth_clients/connection_manager.rb@@ -33,6 +33,7 @@ module OAuthClientsclass ConnectionManager# Nextcloud API endpoint to check if Bearer token is validAUTHORIZATION_CHECK_PATH = '/ocs/v1.php/cloud/user'.freeze+ TOKEN_IS_FRESH_DURATION = 10.seconds.freezeattr_reader :user, :oauth_client@@ -61,19 +62,25 @@ module OAuthClients# The bearer/access token has expired or is due for renew for other reasons.# Talk to OAuth2 Authorization Server to exchange the renew_token for a new bearer token.def refresh_token- # There should already be an existing token,- # otherwise this method has been called too early (internal flow error).- oauth_client_token = get_existing_token- if oauth_client_token.nil?- return service_result_with_error(I18n.t('oauth_client.errors.refresh_token_called_without_existing_token'))+ OAuthClientToken.transaction do+ oauth_client_token = OAuthClientToken.lock('FOR UPDATE').find_by(user_id: @user, oauth_client_id: @oauth_client.id)++ if oauth_client_token.present?+ if (Time.current - oauth_client_token.updated_at) > TOKEN_IS_FRESH_DURATION+ service_result = request_new_token(refresh_token: oauth_client_token.refresh_token)++ if service_result.success?+ update_oauth_client_token(oauth_client_token, service_result.result)+ else+ service_result+ end+ else+ ServiceResult.success(result: oauth_client_token)+ end+ else+ service_result_with_error(I18n.t('oauth_client.errors.refresh_token_called_without_existing_token'))+ endend-- # Get the Rack::OAuth2::Client and call access_token!, then return a ServiceResult.- service_result = request_new_token(refresh_token: oauth_client_token.refresh_token)- return service_result unless service_result.success?-- # Updated tokens, handle model checking errors and return a ServiceResult- update_oauth_client_token(oauth_client_token, service_result.result)end# Returns the URI of the "authorize" endpoint of the OAuth2 Authorization Server.@@ -99,7 +106,18 @@ module OAuthClientsif oauth_client_token.present?update_oauth_client_token(oauth_client_token, service_result.result)else- oauth_client_token = create_new_oauth_client_token(service_result.result)+ rack_access_token = service_result.result+ oauth_client_token =+ OAuthClientToken.create(+ user: @user,+ oauth_client: @oauth_client,+ origin_user_id: rack_access_token.raw_attributes[:user_id], # ID of user at OAuth2 Authorization Server+ access_token: rack_access_token.access_token,+ token_type: rack_access_token.token_type, # :bearer+ refresh_token: rack_access_token.refresh_token,+ expires_in: rack_access_token.raw_attributes[:expires_in],+ scope: rack_access_token.scope+ )endServiceResult.success(result: oauth_client_token)@@ -237,21 +255,6 @@ module OAuthClients)end- # Create a new OpenProject token object based on the return values- # from a Rack::OAuth2::AccessToken::Bearer token- def create_new_oauth_client_token(rack_access_token)- OAuthClientToken.create(- user: @user,- oauth_client: @oauth_client,- origin_user_id: rack_access_token.raw_attributes[:user_id], # ID of user at OAuth2 Authorization Server- access_token: rack_access_token.access_token,- token_type: rack_access_token.token_type, # :bearer- refresh_token: rack_access_token.refresh_token,- expires_in: rack_access_token.raw_attributes[:expires_in],- scope: rack_access_token.scope- )- end-# Update an OpenProject token based on updated values from a# Rack::OAuth2::AccessToken::Bearer after a OAuth2 refresh operationdef update_oauth_client_token(oauth_client_token, rack_oauth2_access_token)diff --git a/spec/services/oauth_clients/connection_manager_spec.rb b/spec/services/oauth_clients/connection_manager_spec.rbindex 194536ae4a6..da0ea114ef2 100644--- a/spec/services/oauth_clients/connection_manager_spec.rb+++ b/spec/services/oauth_clients/connection_manager_spec.rb@@ -28,9 +28,12 @@require 'spec_helper'require 'webmock/rspec'+require 'database_cleaner/active_record'-describe ::OAuthClients::ConnectionManager, type: :model do- let(:user) { create :user }+DatabaseCleaner.strategy = :truncation++describe OAuthClients::ConnectionManager, type: :model do+ let(:user) { create(:user) }let(:host) { "https://example.org" }let(:provider_type) { ::Storages::Storage::PROVIDER_TYPE_NEXTCLOUD }let(:storage) { create(:storage, provider_type:, host: "#{host}/") }@@ -285,7 +288,7 @@ describe ::OAuthClients::ConnectionManager, type: :model dodescribe '#refresh_token' dosubject { instance.refresh_token }- context 'without preexisting OAuthClientToken' do+ context 'without existing OAuthClientToken' doit 'returns an error message' doexpect(subject.success).to be_falseyexpect(subject.errors[:base].first)@@ -293,80 +296,175 @@ describe ::OAuthClients::ConnectionManager, type: :model doendend- context 'with successful response from OAuth2 provider (happy path)' do- before do- # Simulate a successful authorization returning the tokens- response_body = {- access_token: "xyjTDZ...RYvRH",- token_type: "Bearer",- expires_in: 3601,- refresh_token: "xUwFp...1FROJ",- user_id: "admin"- }.to_json- stub_request(:any, File.join(host, '/index.php/apps/oauth2/api/v1/token'))- .to_return(status: 200, body: response_body)- oauth_client_token- end+ context 'with existing OAuthClientToken' do+ before { oauth_client_token }- it 'returns a valid ClientToken object', webmock: true do- expect(subject.success).to be_truthy- expect(subject.result).to be_a OAuthClientToken- expect(subject.result.access_token).to eq("xyjTDZ...RYvRH")- expect(subject.result.refresh_token).to eq("xUwFp...1FROJ")- expect(subject.result.expires_in).to be(3601)- end- end+ context 'when token is stale' do+ before do+ oauth_client_token.update_columns(updated_at: 1.day.ago)+ end- context 'with invalid access_token data' do- before do- # Simulate a token too long- response_body = {- access_token: "x" * 257, # will fail model validation- token_type: "Bearer",- expires_in: 3601,- refresh_token: "xUwFp...1FROJ",- user_id: "admin"- }.to_json- stub_request(:any, File.join(host, '/index.php/apps/oauth2/api/v1/token'))- .to_return(status: 200, body: response_body)+ context 'with successful response from OAuth2 provider (happy path)' do+ before do+ # Simulate a successful authorization returning the tokens+ response_body = {+ access_token: "xyjTDZ...RYvRH",+ token_type: "Bearer",+ expires_in: 3601,+ refresh_token: "xUwFp...1FROJ",+ user_id: "admin"+ }.to_json+ stub_request(:any, File.join(host, '/index.php/apps/oauth2/api/v1/token'))+ .to_return(status: 200, body: response_body)+ end- oauth_client_token- end+ it 'returns a valid ClientToken object', webmock: true do+ expect(subject.success).to be_truthy+ expect(subject.result).to be_a OAuthClientToken+ expect(subject.result.access_token).to eq("xyjTDZ...RYvRH")- it 'returns dependent error from model validation', webmock: true do- expect(subject.success).to be_falsey- expect(subject.result).to be_nil- expect(subject.errors.size).to be(1)- puts subject.errors- end- end+ expect(subject.result.expires_in).to be(3601)+ end+ end- context 'with server error from OAuth2 provider' do- before do- stub_request(:any, File.join(host, '/index.php/apps/oauth2/api/v1/token'))- .to_return(status: 400, body: { error: "invalid_request" }.to_json)- oauth_client_token- end+ context 'with invalid access_token data' do+ before do+ # Simulate a token too long+ response_body = {+ access_token: "x" * 257, # will fail model validation+ token_type: "Bearer",+ expires_in: 3601,+ refresh_token: "xUwFp...1FROJ",+ user_id: "admin"+ }.to_json+ stub_request(:any, File.join(host, '/index.php/apps/oauth2/api/v1/token'))+ .to_return(status: 200, body: response_body)+ end- it 'returns a server error', webmock: true do- expect(subject.success).to be_falsey- expect(subject.errors.size).to be(1)- puts subject.errors- end- end+ it 'returns dependent error from model validation', webmock: true do+ expect(subject.success).to be_falsey+ expect(subject.result).to be_nil+ expect(subject.errors.size).to be(1)+ puts subject.errors+ end+ end- context 'with successful response but invalid data' do- before do- # Simulate timeout- stub_request(:any, File.join(host, '/index.php/apps/oauth2/api/v1/token'))- .to_timeout- oauth_client_token+ context 'with server error from OAuth2 provider' do+ before do+ stub_request(:any, File.join(host, '/index.php/apps/oauth2/api/v1/token'))+ .to_return(status: 400, body: { error: "invalid_request" }.to_json)+ end++ it 'returns a server error', webmock: true do+ expect(subject.success).to be_falsey+ expect(subject.errors.size).to be(1)+ puts subject.errors+ end+ end++ context 'with successful response but invalid data' do+ before do+ # Simulate timeout+ stub_request(:any, File.join(host, '/index.php/apps/oauth2/api/v1/token'))+ .to_timeout+ end++ it 'returns a valid ClientToken object', webmock: true do+ expect(subject.success).to be_falsey+ expect(subject.result).to be_nil+ expect(subject.errors.size).to be(1)+ end+ end++ context 'with parrallel requests for refresh',+ :aggregate_failures,+ use_transactional_fixtures: false,+ webmock: true do+ after do+ DatabaseCleaner.clean+ end++ it 'requests token only once and other thread uses new token' do+ response_body1 = {+ access_token: "xyjTDZ...RYvRH",+ token_type: "Bearer",+ expires_in: 3601,+ refresh_token: "xUwFp...1FROJ",+ user_id: "admin"+ }+ response_body2 = response_body1.dup+ response_body2[:access_token] = "differ...RYvRH"+ request_url = File.join(host, '/index.php/apps/oauth2/api/v1/token')+ stub_request(:any, request_url).to_return(+ { status: 200, body: response_body1.to_json },+ { status: 200, body: response_body2.to_json }+ )++ result1 = nil+ result2 = nil+ thread1 = Thread.new do+ ApplicationRecord.connection_pool.with_connection do+ result1 = described_class.new(user:, oauth_client:).refresh_token.result+ end+ end+ thread2 = Thread.new do+ ApplicationRecord.connection_pool.with_connection do+ result2 = described_class.new(user:, oauth_client:).refresh_token.result+ end+ end+ thread1.join+ thread2.join++ expect(result1.access_token).to eq(response_body1[:access_token])+ expect(result2.access_token).to eq(response_body1[:access_token])+ expect(WebMock).to have_requested(:any, request_url).once+ end++ it 'requests token refresh twice if enough time passes between requests' do+ stub_const("OAuthClients::ConnectionManager::TOKEN_IS_FRESH_DURATION", 2.seconds)+ response_body1 = {+ access_token: "xyjTDZ...RYvRH",+ token_type: "Bearer",+ expires_in: 3601,+ refresh_token: "xUwFp...1FROJ",+ user_id: "admin"+ }+ response_body2 = response_body1.dup+ response_body2[:access_token] = "differ...RYvRH"+ request_url = File.join(host, '/index.php/apps/oauth2/api/v1/token')+ stub_request(:any, request_url)+ .to_return(status: 200, body: response_body1.to_json).then+ .to_return(status: 200, body: response_body2.to_json)++ result1 = nil+ result2 = nil+ thread1 = Thread.new do+ ApplicationRecord.connection_pool.with_connection do+ sleep(3)+ result1 = described_class.new(user:, oauth_client:).refresh_token.result+ end+ end+ thread2 = Thread.new do+ ApplicationRecord.connection_pool.with_connection do+ result2 = described_class.new(user:, oauth_client:).refresh_token.result+ end+ end+ thread1.join+ thread2.join++ expect([result1.access_token,+ result2.access_token]).to match_array([response_body1[:access_token], response_body2[:access_token]])+ expect(WebMock).to have_requested(:any, request_url).twice+ end+ endend- it 'returns a valid ClientToken object', webmock: true do- expect(subject.success).to be_falsey- expect(subject.result).to be_nil- expect(subject.errors.size).to be(1)+ context 'when token is fresh' do+ it 'does not send refresh request and respond with existing token', webmock: true do+ expect(subject.success).to be_truthy+ expect(subject.result).to eq(oauth_client_token)+ expect { subject }.not_to change(oauth_client_token, :access_token)+ endendendend@@ -410,7 +508,7 @@ describe ::OAuthClients::ConnectionManager, type: :model doendcontext 'with outdated access token' do- let(:new_oauth_client_token) { create :oauth_client_token }+ let(:new_oauth_client_token) { create(:oauth_client_token) }let(:refresh_service_result) { ServiceResult.success }before dodiff --git a/spec/support/transactional_tests.rb b/spec/support/transactional_tests.rbindex be21c10e652..ad96e2c12a0 100644--- a/spec/support/transactional_tests.rb+++ b/spec/support/transactional_tests.rb@@ -6,4 +6,9 @@ RSpec.configure do |config|# Run every test method within a transactionconfig.use_transactional_fixtures = true+ config.around(:each, use_transactional_fixtures: false) do |example|+ self.use_transactional_tests = false+ example.run+ self.use_transactional_tests = true+ endend