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
[#42843] Add authorization state to storages API endpoint
Wieland Lindenthal16c3ebecd2e3
diff --git a/app/services/oauth_clients/connection_manager.rb b/app/services/oauth_clients/connection_manager.rbindex 8e1c7379842..1571dd5cef5 100644--- a/app/services/oauth_clients/connection_manager.rb+++ b/app/services/oauth_clients/connection_manager.rb@@ -31,6 +31,8 @@ require "uri/http"module OAuthClientsclass ConnectionManager+ AUTHORIZATION_CHECK_PATH = '/ocs/v2.php/cloud/capabilities'.freeze+attr_reader :user, :oauth_clientdef initialize(user:, oauth_client:)@@ -105,6 +107,33 @@ module OAuthClients)end+ def authorization_state+ oauth_client_token = get_existing_token+ return :failed_authentication unless oauth_client_token++ RestClient.get(+ File.join(oauth_client.integration.host, AUTHORIZATION_CHECK_PATH),+ { :Authorization => "Bearer #{oauth_client_token.access_token}" }+ )+ :connected+ rescue RestClient::Unauthorized, RestClient::Forbidden => _e+ service_result = refresh_token # `refresh_token` already has exception handling+ return :connected if service_result.success?++ if service_result.result == 'invalid_grant'+ # This can happen if the Authorization Server invalidated all tokens.+ # Then the user would ideally be asked to reauthorize.+ :failed_authentication+ else+ # It could also be that some other error happened, i.e. firewall badly configured.+ # Then the user needs to know that something is technically off. The user could try+ # to reload the page or contact an admin.+ :error+ end+ rescue StandardError => _e+ :error+ end+private# Check if a OAuthClientToken already exists and return nil otherwise.@@ -123,7 +152,7 @@ module OAuthClientsServiceResult.new(success: true,result: rack_access_token)rescue Rack::OAuth2::Client::Error => e # Handle Rack::OAuth2 specific errors- service_result_with_error(i18n_rack_oauth2_error_message(e))+ service_result_with_error(i18n_rack_oauth2_error_message(e), e.message)rescue Timeout::Error, EOFError, Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError, Net::ProtocolError,Errno::EINVAL, Errno::ENETUNREACH, Errno::ECONNRESET, Errno::ECONNREFUSED, JSON::ParserError => eservice_result_with_error(@@ -205,9 +234,9 @@ module OAuthClients# Shortcut method to convert an error message into an unsuccessful# ServiceResult with that error message- def service_result_with_error(message)- ServiceResult.new(success: false).tap do |result|- result.errors.add(:base, message)+ def service_result_with_error(message, res = nil)+ ServiceResult.new(success: false, result: res).tap do |service_result|+ service_result.errors.add(:base, message)endendenddiff --git a/config/locales/en.yml b/config/locales/en.ymlindex fa8f2d25b72..5ac6f2568d5 100644--- a/config/locales/en.yml+++ b/config/locales/en.yml@@ -3214,6 +3214,10 @@ en:my_registered_applications: "Registered OAuth applications"oauth_client:+ urn_connection_status:+ connected: "Connected"+ error: "Error"+ auth_failed: "Authentication failed"labels:label_oauth_integration: "OAuth2 integration"label_redirect_uri: "Redirect URI"@@ -3248,9 +3252,8 @@ en:rack_oauth2:client_secret_invalid: "Client secret is invalid"invalid_request: >- OAuth2 server responded with 'invalid_request'.+ OAuth2 Authorization Server responded with 'invalid_request'.This error appears if you try to authorize multiple times.- invalid_response: "OAuth2 server provided an invalid response"--+ invalid_response: "OAuth2 Authorization Server provided an invalid response"+ invalid_grant: "The OAuth2 Authorization Server asks you to reauthorize."you: youdiff --git a/modules/storages/lib/api/v3/storages/storage_representer.rb b/modules/storages/lib/api/v3/storages/storage_representer.rbindex a96dd5a2822..a96ff6cc7a1 100644--- a/modules/storages/lib/api/v3/storages/storage_representer.rb+++ b/modules/storages/lib/api/v3/storages/storage_representer.rb@@ -34,9 +34,9 @@ module APImodule V3module StoragesURN_TYPE_NEXTCLOUD = "#{::API::V3::URN_PREFIX}storages:Nextcloud".freeze- URN_CONNECTION_CONNECTED = "#{::API::V3::URN_PREFIX}storages:connection:Connected".freeze- URN_CONNECTION_AUTH_FAILED = "#{::API::V3::URN_PREFIX}storages:connection:FailedAuthentication".freeze- URN_CONNECTION_ERROR = "#{::API::V3::URN_PREFIX}storages:connection:Error".freeze+ URN_CONNECTION_CONNECTED = "#{::API::V3::URN_PREFIX}storages:authorization:Connected".freeze+ URN_CONNECTION_AUTH_FAILED = "#{::API::V3::URN_PREFIX}storages:authorization:FailedAuthentication".freeze+ URN_CONNECTION_ERROR = "#{::API::V3::URN_PREFIX}storages:authorization:Error".freezeclass StorageRepresenter < ::API::Decorators::Single# LinkedResource module defines helper methods to describe attributes@@ -67,17 +67,49 @@ module API}end- link :connectionState do- # TODO: replace with service to check real connection state+ link :authorizationState do+ oauth_client = represented.oauth_client+ connection_manager = ::OAuthClients::ConnectionManager.new(user: User.current, oauth_client:)+ status_urn = urn_authorization_state(connection_manager.authorization_state){- href: URN_CONNECTION_CONNECTED,- title: 'Connected'+ href: status_urn,+ title: urn_authorization_state_title(status_urn)}enddef _type'Storage'end++ private++ # Check the ConnectionManager for the OAuth2 status+ def urn_authorization_state(authorization_state)+ case authorization_state+ when :error+ URN_CONNECTION_ERROR+ when :connected+ URN_CONNECTION_CONNECTED+ when :failed_authentication+ URN_CONNECTION_AUTH_FAILED+ else+ # This should never happen+ raise StandardError+ end+ end++ # Provide a human readable title for the connection status+ def urn_authorization_state_title(token_status)+ case token_status+ when URN_CONNECTION_CONNECTED+ I18n.t(:"urn_authorization_state")+ when URN_CONNECTION_AUTH_FAILED+ I18n.t(:"urn_authorization_state")+ else+ # Mainly covers URN_CONNECTION_ERROR+ I18n.t(:"urn_authorization_state")+ end+ endendendenddiff --git a/modules/storages/spec/requests/api/v3/storages/storages_spec.rb b/modules/storages/spec/requests/api/v3/storages/storages_spec.rbindex d91a785d4a5..013bf8a3e99 100644--- a/modules/storages/spec/requests/api/v3/storages/storages_spec.rb+++ b/modules/storages/spec/requests/api/v3/storages/storages_spec.rb@@ -98,5 +98,16 @@ describe 'API v3 storages resource', :enable_storages, type: :request, content_tcontext 'when storages module is inactive', :disable_storages doit_behaves_like 'not found'end++ context 'when Storage connected to a OAuth2 Authorization Server' do+ subject { last_response.body }++ let(:current_user) { create(:admin) }++ it 'returns an error authorization state' do+ is_expected.to be_json_eql("urn:openproject-org:api:v3:storages:authorization:Error".to_json)+ .at_path('_links/authorizationState/href')+ end+ endendenddiff --git a/spec/services/oauth_clients/connection_manager_spec.rb b/spec/services/oauth_clients/connection_manager_spec.rbindex f40b29c94d6..7f4b59ca26a 100644--- a/spec/services/oauth_clients/connection_manager_spec.rb+++ b/spec/services/oauth_clients/connection_manager_spec.rb@@ -44,6 +44,7 @@ describe ::OAuthClients::ConnectionManager, type: :model dolet(:oauth_client_token) { create(:oauth_client_token, oauth_client:, user:) }let(:instance) { described_class.new(user:, oauth_client:) }+# Test the redirect_to_oauth_authorize function that puts together# the OAuth2 provider URL (Nextcloud) according to RFC specs.describe '#redirect_to_oauth_authorize' do@@ -155,18 +156,45 @@ describe ::OAuthClients::ConnectionManager, type: :model doendend- context 'with known reply invalid_request', webmock: true do+ context 'with known error', webmock: true dobefore dostub_request(:post, File.join(host, '/apps/oauth2/api/v1/token'))- .to_return(status: 400, body: { error: "invalid_request" }.to_json)+ .to_return(status: 400, body: { error: error_message }.to_json)+ end++ shared_examples 'OAuth2 error response' do+ it 'returns a specific error message' do+ expect(subject.success).to be_falsey+ expect(subject.result).to eq error_message+ expect(subject.errors[:base].count).to be(1)+ expect(subject.errors[:base].first).to include I18n.t("oauth_client.errors.rack_oauth2.#{error_message}")+ end+ end++ context 'when "invalid_request"' do+ let(:error_message) { 'invalid_request' }++ it_behaves_like 'OAuth2 error response'+ end++ context 'when "invalid_grant"' do+ let(:error_message) { 'invalid_grant' }++ it_behaves_like 'OAuth2 error response'+ end+ end++ context 'with known reply invalid_grant', webmock: true do+ before do+ stub_request(:post, File.join(host, '/apps/oauth2/api/v1/token'))+ .to_return(status: 400, body: { error: "invalid_grant" }.to_json)endit 'returns a specific error message' doexpect(subject.success).to be_falsey- expect(subject.result).to be_nil+ expect(subject.result).to eq 'invalid_grant'expect(subject.errors[:base].count).to be(1)- expect(subject.errors[:base].first).to include I18n.t('oauth_client.errors.rack_oauth2.invalid_request')- expect(subject.errors[:base].first).not_to include I18n.t('oauth_client.errors.oauth_returned_error')+ expect(subject.errors[:base].first).to include I18n.t('oauth_client.errors.rack_oauth2.invalid_grant')endend@@ -178,7 +206,7 @@ describe ::OAuthClients::ConnectionManager, type: :model doit 'returns an unspecific error message' doexpect(subject.success).to be_falsey- expect(subject.result).to be_nil+ expect(subject.result).to eq 'invalid_requesttt'expect(subject.errors[:base].count).to be(1)expect(subject.errors[:base].first).to include I18n.t('oauth_client.errors.oauth_returned_error')end@@ -196,7 +224,7 @@ describe ::OAuthClients::ConnectionManager, type: :model doit 'returns an unspecific error message' doexpect(subject.success).to be_falsey- expect(subject.result).to be_nil+ expect(subject.result).to eq 'Unknown :: some: very, invalid> <json}'expect(subject.errors[:base].count).to be(1)expect(subject.errors[:base].first).to include I18n.t('oauth_client.errors.oauth_returned_error')end@@ -210,7 +238,7 @@ describe ::OAuthClients::ConnectionManager, type: :model doit 'returns an unspecific error message' doexpect(subject.success).to be_falsey- expect(subject.result).to be_nil+ expect(subject.result).to eq 'Unknown :: 'expect(subject.errors[:base].count).to be(1)expect(subject.errors[:base].first).to include I18n.t('oauth_client.errors.oauth_returned_error')end@@ -331,4 +359,86 @@ describe ::OAuthClients::ConnectionManager, type: :model doendendend++ describe '#authorization_state' do+ subject { instance.authorization_state }++ context 'without access token present' do+ it 'returns :failed_authentication' do+ expect(subject).to eq :failed_authentication+ end+ end++ context 'with access token present', webmock: true do+ before do+ oauth_client_token+ end++ context 'with access token valid' do+ context 'without other errors or exceptions' do+ before do+ stub_request(:get, File.join(host, ::OAuthClients::ConnectionManager::AUTHORIZATION_CHECK_PATH))+ .to_return(status: 200)+ end++ it 'returns :connected' do+ expect(subject).to eq :connected+ end+ end++ context 'with some other error or exception' do+ before do+ stub_request(:get, File.join(host, ::OAuthClients::ConnectionManager::AUTHORIZATION_CHECK_PATH))+ .to_timeout+ end++ it 'returns :error' do+ expect(subject).to eq :error+ end+ end+ end++ context 'with outdated access token' do+ let(:new_oauth_client_token) { create :oauth_client_token }+ let(:refresh_service_result) { ServiceResult.new(success: true) }++ before do+ stub_request(:get, File.join(host, ::OAuthClients::ConnectionManager::AUTHORIZATION_CHECK_PATH))+ .to_return(status: 401) # 401 unauthorized+ allow(instance).to receive(:refresh_token).and_return(refresh_service_result)+ end++ context 'with valid refresh token' do+ it 'refreshes the access token and returns :connected' do+ expect(subject).to eq :connected+ expect(instance).to have_received(:refresh_token)+ end+ end++ context 'with invalid refresh token' do+ let(:refresh_service_result) { ServiceResult.new(success: false, result: 'invalid_grant') }++ it 'refreshes the access token and returns :failed_authentication' do+ expect(subject).to eq :failed_authentication+ expect(instance).to have_received(:refresh_token)+ end+ end++ context 'with some other error while refreshing access token' do+ let(:refresh_service_result) { ServiceResult.new(success: false, result: nil) }++ it 'returns :error' do+ expect(subject).to eq :error+ expect(instance).to have_received(:refresh_token)+ end+ end+ end+ end++ context 'with both invalid access token and refresh token', webmock: true do+ it 'returns :failed_authentication' do+ expect(subject).to eq :failed_authentication+ end+ end+ endend