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
[#53369] update usage of authorization state
Eric Schuberta77b1406b064
diff --git a/modules/storages/app/common/storages/peripherals/oauth_configurations/configuration_interface.rb b/modules/storages/app/common/storages/peripherals/oauth_configurations/configuration_interface.rbindex a4e457ff49e..78d22ce075a 100644--- a/modules/storages/app/common/storages/peripherals/oauth_configurations/configuration_interface.rb+++ b/modules/storages/app/common/storages/peripherals/oauth_configurations/configuration_interface.rb@@ -38,7 +38,7 @@ module Storagesdef to_httpx_oauth_config = raise ::Storages::Errors::SubclassResponsibility- def authorization_uri(state:)+ def authorization_uri(state: nil)basic_rack_oauth_client.authorization_uri(scope:, state:)endenddiff --git a/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/auth_check_query.rb b/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/auth_check_query.rbindex 16a58ee046d..a2d33060540 100644--- a/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/auth_check_query.rb+++ b/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/auth_check_query.rb@@ -47,7 +47,7 @@ module Storagesdef call(auth_strategy:)Auth[auth_strategy].call(storage: @storage, http_options: Util.ocs_api_request) do |http|- handle_response http.get(Util.join_uri_path(@storage.uri, '/ocs/v1.php/cloud/user'))+ handle_response http.get(Util.join_uri_path(@storage.uri, "/ocs/v1.php/cloud/user"))endend@@ -60,7 +60,7 @@ module Storagesin { status: 401 }ServiceResult.failure(result: :unauthorized, errors: ::Storages::StorageError.new(code: :unauthorized))else- data = ::Storages::StorageErrorData.new(source: self, payload: response)+ data = ::Storages::StorageErrorData.new(source: self.class, payload: response)ServiceResult.failure(result: :error, errors: ::Storages::StorageError.new(code: :error, data:))endenddiff --git a/modules/storages/app/common/storages/peripherals/storage_interaction/one_drive/auth_check_query.rb b/modules/storages/app/common/storages/peripherals/storage_interaction/one_drive/auth_check_query.rbindex 812525fb7f8..dec0178eb7b 100644--- a/modules/storages/app/common/storages/peripherals/storage_interaction/one_drive/auth_check_query.rb+++ b/modules/storages/app/common/storages/peripherals/storage_interaction/one_drive/auth_check_query.rb@@ -47,7 +47,7 @@ module Storagesdef call(auth_strategy:)Auth[auth_strategy].call(storage: @storage) do |http|- handle_response http.get(Util.join_uri_path(@storage.uri, '/v1.0/me'))+ handle_response http.get(Util.join_uri_path(@storage.uri, "/v1.0/me"))endend@@ -60,7 +60,7 @@ module Storagesin { status: 401 }ServiceResult.failure(result: :unauthorized, errors: ::Storages::StorageError.new(code: :unauthorized))else- data = ::Storages::StorageErrorData.new(source: self, payload: response)+ data = ::Storages::StorageErrorData.new(source: self.class, payload: response)ServiceResult.failure(result: :error, errors: ::Storages::StorageError.new(code: :error, data:))endenddiff --git a/modules/storages/app/controllers/storages/admin/project_storages_controller.rb b/modules/storages/app/controllers/storages/admin/project_storages_controller.rbindex 60dbbfe0841..890f7307b04 100644--- a/modules/storages/app/controllers/storages/admin/project_storages_controller.rb+++ b/modules/storages/app/controllers/storages/admin/project_storages_controller.rb@@ -95,12 +95,11 @@ class Storages::Admin::ProjectStoragesController < Projects::SettingsControllerdef oauth_access_grant # rubocop:disable Metrics/AbcSize@project_storage = @object- connection_manager = OAuthClients::ConnectionManager.new(- user: current_user,- configuration: @project_storage.storage.oauth_configuration- )+ storage = @project_storage.storage+ auth_state = ::Storages::Peripherals::StorageInteraction::Authentication+ .authorization_state(storage:, user: current_user)- if connection_manager.authorization_state_connected?+ if auth_state == :connectedredirect_to(project_settings_project_storages_path)elsenonce = SecureRandom.uuid@@ -110,11 +109,11 @@ class Storages::Admin::ProjectStoragesController < Projects::SettingsControllerexpires: 1.hour}session[:oauth_callback_flash_modal] = oauth_access_grant_nudge_modal(authorized: true)- redirect_to(connection_manager.get_authorization_uri(state: nonce))+ redirect_to(storage.oauth_configuration.authorization_uri(state: nonce))endend- # Edit page is very similar to new page, except that we don't need to set+ # Edit page is very similar to new page, except that we don"t need to set# default attribute values because the object already exists# Called by: Global app/config/routes.rb to serve Web pagedef edit@@ -150,7 +149,7 @@ class Storages::Admin::ProjectStoragesController < Projects::SettingsControllerend# Purpose: Destroy a ProjectStorage object- # Called by: By pressing a "Delete" icon in the Project's settings ProjectStorages page+ # Called by: By pressing a "Delete" icon in the Project"s settings ProjectStorages page# It redirects back to the list of ProjectStorages in the projectdef destroy# The complex logic for deleting associated objects was moved into a service:diff --git a/modules/storages/app/helpers/storage_login_helper.rb b/modules/storages/app/helpers/storage_login_helper.rbindex 7d0c5a0a785..db5f1e27b7f 100644--- a/modules/storages/app/helpers/storage_login_helper.rb+++ b/modules/storages/app/helpers/storage_login_helper.rb@@ -32,14 +32,11 @@ module StorageLoginHelperdef storage_login_input(storage)return {} if storage&.oauth_client.blank?- connection_manager = ::OAuthClients::ConnectionManager- .new(user: current_user, configuration: storage.oauth_configuration)-{storageId: storage.id,storageType: API::V3::Storages::STORAGE_TYPE_URN_MAP[storage.provider_type],authorizationLink: {- href: connection_manager.get_authorization_uri+ href: storage.oauth_configuration.authorization_uri}}enddiff --git a/modules/storages/lib/api/v3/storages/storage_representer.rb b/modules/storages/lib/api/v3/storages/storage_representer.rbindex 722a3913594..24c95803d08 100644--- a/modules/storages/lib/api/v3/storages/storage_representer.rb+++ b/modules/storages/lib/api/v3/storages/storage_representer.rb@@ -110,10 +110,10 @@ module API::V3::Storagesgetter: ->(*) {type = STORAGE_TYPE_URN_MAP[represented.provider_type] || represented.provider_type- { href: type, title: 'Nextcloud' }+ { href: type, title: "Nextcloud" }},setter: ->(fragment:, **) {- href = fragment['href']+ href = fragment["href"]break if href.blank?represented.provider_type = STORAGE_TYPE_MAP[href] || href@@ -122,9 +122,9 @@ module API::V3::Storageslink_without_resource :origin,getter: ->(*) { { href: represented.host } },setter: ->(fragment:, **) {- break if fragment['href'].blank?+ break if fragment["href"].blank?- represented.host = fragment['href'].gsub(/\/+$/, '')+ represented.host = fragment["href"].gsub(/\/+$/, "")}links :prepareUpload do@@ -135,8 +135,8 @@ module API::V3::Storagestitle: "Upload file",payload: {projectId: project_id,- fileName: '{fileName}',- parent: '{parent}'+ fileName: "{fileName}",+ parent: "{parent}"},templated: true}@@ -165,7 +165,7 @@ module API::V3::Storageslink :authorize donext unless authorization_state == :failed_authorization- { href: represented.oauth_configuration.authorization_uri(state: nil), title: 'Authorize' }+ { href: represented.oauth_configuration.authorization_uri, title: "Authorize" }endlink :projectStorages do@@ -204,7 +204,7 @@ module API::V3::Storages}def _type- 'Storage'+ "Storage"endprivatediff --git a/spec/requests/oauth_clients/ensure_connection_flow_spec.rb b/spec/requests/oauth_clients/ensure_connection_flow_spec.rbindex fcc3b3fc854..eced9e187b6 100644--- a/spec/requests/oauth_clients/ensure_connection_flow_spec.rb+++ b/spec/requests/oauth_clients/ensure_connection_flow_spec.rb@@ -27,13 +27,20 @@#++require "spec_helper"-require_module_spec_helper+require_relative "../../../modules/storages/spec/spec_helper"RSpec.describe "/oauth_clients/:oauth_client_id/ensure_connection endpoint", :webmock doshared_let(:user) { create(:user) }shared_let(:storage) { create(:nextcloud_storage, :with_oauth_client) }shared_let(:oauth_client) { storage.oauth_client }+ before do+ Storages::Peripherals::Registry.stub(+ "#{storage.short_provider_type}.queries.auth_check",+ ->(_) { ServiceResult.success }+ )+ end+describe "#ensure_connection" docontext "when user is not logged in" doit "requires login" do@@ -52,10 +59,15 @@ RSpec.describe "/oauth_clients/:oauth_client_id/ensure_connection endpoint", :weendcontext "when storage_id parameter is present" do- context 'when user is not "connected"' do+ context "when user is not 'connected'" dolet(:nonce) { "57a17c3f-b2ed-446e-9dd8-651ba3aec37d" }before do+ Storages::Peripherals::Registry.stub(+ "#{storage.short_provider_type}.queries.auth_check",+ ->(_) { ServiceResult.failure(errors: Storages::StorageError.new(code: :unauthorized)) }+ )+allow(SecureRandom).to receive(:uuid).and_call_original.orderedallow(SecureRandom).to receive(:uuid).and_return(nonce).orderedend@@ -72,7 +84,9 @@ RSpec.describe "/oauth_clients/:oauth_client_id/ensure_connection endpoint", :we"%2Foauth_clients%2F#{oauth_client.client_id}%2F" \"callback&response_type=code&state=#{nonce}")- expect(last_response.cookies["oauth_state_#{nonce}"]).to eq(["%7B%22href%22%3A%22http%3A%2F%2Fwww.example.com%2F%22%2C%22storageId%22%3A%22#{storage.id}%22%7D"])+ expect(last_response.cookies["oauth_state_#{nonce}"])+ .to eq(["%7B%22href%22%3A%22http%3A%2F%2Fwww.example.com" \+ "%2F%22%2C%22storageId%22%3A%22#{storage.id}%22%7D"])endend@@ -91,7 +105,9 @@ RSpec.describe "/oauth_clients/:oauth_client_id/ensure_connection endpoint", :we"%2Foauth_clients%2F#{oauth_client.client_id}%2F" \"callback&response_type=code&state=#{nonce}")- expect(last_response.cookies["oauth_state_#{nonce}"]).to eq(["%7B%22href%22%3A%22http%3A%2F%2Fwww.example.com%2F123%22%2C%22storageId%22%3A%22#{storage.id}%22%7D"])+ expect(last_response.cookies["oauth_state_#{nonce}"])+ .to eq(["%7B%22href%22%3A%22http%3A%2F%2Fwww.example.com" \+ "%2F123%22%2C%22storageId%22%3A%22#{storage.id}%22%7D"])endend@@ -109,13 +125,15 @@ RSpec.describe "/oauth_clients/:oauth_client_id/ensure_connection endpoint", :we"%2Foauth_clients%2F#{oauth_client.client_id}%2F" \"callback&response_type=code&state=#{nonce}")- expect(last_response.cookies["oauth_state_#{nonce}"]).to eq(["%7B%22href%22%3A%22http%3A%2F%2Fwww.example.com%2F%22%2C%22storageId%22%3A%22#{storage.id}%22%7D"])+ expect(last_response.cookies["oauth_state_#{nonce}"])+ .to eq(["%7B%22href%22%3A%22http%3A%2F%2Fwww.example.com" \+ "%2F%22%2C%22storageId%22%3A%22#{storage.id}%22%7D"])endendendend- context 'when user is "connected"' do+ context "when user is 'connected'" dolet!(:oauth_client_token) docreate(:oauth_client_token, oauth_client:, user:)enddiff --git a/spec/services/oauth_clients/connection_manager_spec.rb b/spec/services/oauth_clients/connection_manager_spec.rbindex fb464a3dfa5..a707b7ee3ef 100644--- a/spec/services/oauth_clients/connection_manager_spec.rb+++ b/spec/services/oauth_clients/connection_manager_spec.rb@@ -28,7 +28,7 @@# See COPYRIGHT and LICENSE files for more details.#++-require 'spec_helper'+require "spec_helper"RSpec.describe OAuthClients::ConnectionManager, :webmock, type: :model dousing Storages::Peripherals::ServiceResultRefinements@@ -45,78 +45,24 @@ RSpec.describe OAuthClients::ConnectionManager, :webmock, type: :model dolet(:instance) { described_class.new(user:, configuration:) }- # The get_authorization_uri method returns the OAuth2 authorization URI as a string. That URI is the starting point for- # a user to grant OpenProject access to Nextcloud.- describe '#get_authorization_uri' do- let(:scope) { nil }- let(:state) { nil }-- subject { instance.get_authorization_uri(state:) }-- context 'with empty state and scope' do- shared_examples_for 'returns the authorization URI relative to the host' do- it 'returns the authorization URI' do- expect(subject).to be_a String- expect(subject).to include oauth_client.integration.host- expect(subject).not_to include "scope"- expect(subject).not_to include "state"- end- end-- context 'when Nextcloud is installed in the server root' do- it_behaves_like 'returns the authorization URI relative to the host'- end-- context 'when Nextcloud is installed in a sub-directory' do- let(:host) { "https://example.org/nextcloud" }-- it_behaves_like 'returns the authorization URI relative to the host'- end- end-- context 'with state but empty scope' do- let(:state) { "https://example.com/page" }-- it 'returns the redirect URL' do- expect(subject).to be_a String- expect(subject).to include oauth_client.integration.host- expect(subject).not_to include "scope"- expect(subject).to include "&state=https"- end- end-- context 'with multiple scopes but empty state' do- let(:scope) { %i(email profile) }-- it 'returns the redirect URL' do- allow(configuration).to receive(:scope).and_return(scope)-- expect(subject).to be_a String- expect(subject).to include oauth_client.integration.host- expect(subject).not_to include "state"- expect(subject).to include "&scope=email%20profile"- end- end- end-# The first step in the OAuth2 flow is to produce a URL for the# user to authenticate and authorize access at the OAuth2 provider# (Nextcloud).- describe '#get_access_token' do+ describe "#get_access_token" dosubject { instance.get_access_token }- context 'with no OAuthClientToken present' do- it 'returns a redirection URL' do+ context "with no OAuthClientToken present" do+ it "returns a redirection URL" doexpect(subject.success).to be_falsyexpect(subject.result).to be_a String# Details of string are tested above in section #get_authorization_uriendend- context 'with no OAuthClientToken present and state parameters' do+ context "with no OAuthClientToken present and state parameters" dosubject { instance.get_access_token(state: "some_state") }- it 'returns the redirect URL' do+ it "returns the redirect URL" doallow(configuration).to receive(:scope).and_return(%w[email])expect(subject.success).to be_falsy@@ -127,12 +73,12 @@ RSpec.describe OAuthClients::ConnectionManager, :webmock, type: :model doendend- context 'with an OAuthClientToken present' do+ context "with an OAuthClientToken present" dobefore dooauth_client_tokenend- it 'returns the OAuthClientToken' do+ it "returns the OAuthClientToken" doexpect(subject).to be_truthyexpect(subject.result).to be_a OAuthClientToken # The one and only...expect(subject.result).to eql oauth_client_token@@ -147,12 +93,12 @@ RSpec.describe OAuthClients::ConnectionManager, :webmock, type: :model do# The callback endpoint calls `code_to_token(code)` with the code# received and exchanges the code for a bearer+refresh token# using a HTTP request.- describe '#code_to_token', :webmock do+ describe "#code_to_token", :webmock dolet(:code) { "7kRGJ...jG3KZ" }subject { instance.code_to_token(code) }- context 'with happy path' do+ context "with happy path" dobefore do# Simulate a successful authorization returning the tokensresponse_body = {@@ -162,11 +108,11 @@ RSpec.describe OAuthClients::ConnectionManager, :webmock, type: :model dorefresh_token: "UwFp...1FROJ",user_id: "admin"}.to_json- stub_request(:any, File.join(host, '/index.php/apps/oauth2/api/v1/token'))+ stub_request(:any, File.join(host, "/index.php/apps/oauth2/api/v1/token")).to_return(status: 200, body: response_body, headers: { "content-type" => "application/json; charset=utf-8" })end- it 'returns a valid ClientToken object and issues an appropriate event' do+ it "returns a valid ClientToken object and issues an appropriate event" doexpect(OpenProject::Notifications).to(receive(:send)).with(OpenProject::Events::OAUTH_CLIENT_TOKEN_CREATED, integration_type: "Storages::Storage")@@ -174,156 +120,156 @@ RSpec.describe OAuthClients::ConnectionManager, :webmock, type: :model doexpect(subject.result).to be_a OAuthClientTokenend- it 'fills in the origin_user_id' do+ it "fills in the origin_user_id" doexpect { subject }.to change(OAuthClientToken, :count).by(1)- last_token = OAuthClientToken.where(access_token: 'yjTDZ...RYvRH').last+ last_token = OAuthClientToken.where(access_token: "yjTDZ...RYvRH").last- expect(last_token.origin_user_id).to eq('admin')+ expect(last_token.origin_user_id).to eq("admin")endend- context 'with known error' do+ context "with known error" dobefore do- stub_request(:post, File.join(host, '/index.php/apps/oauth2/api/v1/token'))+ stub_request(:post, File.join(host, "/index.php/apps/oauth2/api/v1/token")).to_return(status: 400,body: { error: error_message }.to_json,headers: { "content-type" => "application/json; charset=utf-8" })end- shared_examples 'OAuth2 error response' do- it 'returns a specific error message' do+ shared_examples "OAuth2 error response" do+ it "returns a specific error message" doexpect(subject.success).to be_falsyexpect(subject.result).to eq(:bad_request)expect(subject.error_payload[:error]).to eq(error_message)endend- context 'when "invalid_request"' do- let(:error_message) { 'invalid_request' }+ context "when 'invalid_request'" do+ let(:error_message) { "invalid_request" }- it_behaves_like 'OAuth2 error response'+ it_behaves_like "OAuth2 error response"end- context 'when "invalid_grant"' do- let(:error_message) { 'invalid_grant' }+ context "when 'invalid_grant'" do+ let(:error_message) { "invalid_grant" }- it_behaves_like 'OAuth2 error response'+ it_behaves_like "OAuth2 error response"endend- context 'with unknown reply' do+ context "with unknown reply" dobefore do- stub_request(:post, File.join(host, '/index.php/apps/oauth2/api/v1/token'))+ stub_request(:post, File.join(host, "/index.php/apps/oauth2/api/v1/token")).to_return(status: 400,body: { error: "invalid_requesttt" }.to_json,headers: { "content-type" => "application/json; charset=utf-8" })end- it 'returns an error wrapping the unknown response' do+ it "returns an error wrapping the unknown response" doexpect(subject.success).to be_falsyexpect(subject.result).to eq(:bad_request)- expect(subject.error_payload[:error]).to eq('invalid_requesttt')+ expect(subject.error_payload[:error]).to eq("invalid_requesttt")expect(subject.error_source).to be_a(described_class)- expect(subject.errors.log_message).to include I18n.t('oauth_client.errors.oauth_returned_error')+ expect(subject.errors.log_message).to include I18n.t("oauth_client.errors.oauth_returned_error")endend- context 'with reply including JSON syntax error' do+ context "with reply including JSON syntax error" dobefore do- stub_request(:post, File.join(host, '/index.php/apps/oauth2/api/v1/token'))+ stub_request(:post, File.join(host, "/index.php/apps/oauth2/api/v1/token")).to_return(status: 400,- headers: { 'Content-Type' => 'application/json; charset=utf-8' },+ headers: { "Content-Type" => "application/json; charset=utf-8" },body: "some: very, invalid> <json}")end- it 'returns an error wrapping the parsing error' do+ it "returns an error wrapping the parsing error" doexpect(subject.success).to be_falsyexpect(subject.result).to eq(:internal_server_error)expect(subject.error_payload.class).to be(Faraday::ParsingError)expect(subject.error_source).to be_a(described_class)- expect(subject.errors.log_message).to include I18n.t('oauth_client.errors.oauth_returned_http_error')+ expect(subject.errors.log_message).to include I18n.t("oauth_client.errors.oauth_returned_http_error")endend- context 'with 500 reply without body' do+ context "with 500 reply without body" dobefore do- stub_request(:post, File.join(host, '/index.php/apps/oauth2/api/v1/token'))+ stub_request(:post, File.join(host, "/index.php/apps/oauth2/api/v1/token")).to_return(status: 500)end- it 'returns an error wrapping the empty error' do+ it "returns an error wrapping the empty error" doexpect(subject.success).to be_falsyexpect(subject.result).to eq(:bad_request)- expect(subject.error_payload[:error]).to eq('Unknown')+ expect(subject.error_payload[:error]).to eq("Unknown")endend- context 'when something is wrong with connection' do+ context "when something is wrong with connection" dobefore do- stub_request(:post, File.join(host, '/index.php/apps/oauth2/api/v1/token')).to_raise(Faraday::ConnectionFailed)+ stub_request(:post, File.join(host, "/index.php/apps/oauth2/api/v1/token")).to_raise(Faraday::ConnectionFailed)end- it 'returns an error wrapping the server error' do+ it "returns an error wrapping the server error" doexpect(subject.success).to be_falsyexpect(subject.result).to eq(:internal_server_error)expect(subject.error_payload.class).to be(Faraday::ConnectionFailed)expect(subject.error_source).to be_a(described_class)- expect(subject.errors.log_message).to include I18n.t('oauth_client.errors.oauth_returned_http_error')+ expect(subject.errors.log_message).to include I18n.t("oauth_client.errors.oauth_returned_http_error")endend- context 'when something is wrong with SSL' do+ context "when something is wrong with SSL" dobefore do- stub_request(:post, File.join(host, '/index.php/apps/oauth2/api/v1/token')).to_raise(Faraday::SSLError)+ stub_request(:post, File.join(host, "/index.php/apps/oauth2/api/v1/token")).to_raise(Faraday::SSLError)end- it 'returns an error wrapping the server error' do+ it "returns an error wrapping the server error" doexpect(subject.success).to be_falsyexpect(subject.result).to eq(:internal_server_error)expect(subject.error_payload.class).to be(Faraday::SSLError)expect(subject.error_source).to be_a(described_class)- expect(subject.errors.log_message).to include I18n.t('oauth_client.errors.oauth_returned_http_error')+ expect(subject.errors.log_message).to include I18n.t("oauth_client.errors.oauth_returned_http_error")endend- context 'with timeout returns internal error' do+ context "with timeout returns internal error" dobefore do- stub_request(:post, File.join(host, '/index.php/apps/oauth2/api/v1/token')).to_timeout+ stub_request(:post, File.join(host, "/index.php/apps/oauth2/api/v1/token")).to_timeoutend- it 'returns an error wrapping the server timeout' do+ it "returns an error wrapping the server timeout" doexpect(subject.success).to be_falsyexpect(subject.result).to eq(:internal_server_error)expect(subject.error_payload.class).to be(Faraday::ConnectionFailed)expect(subject.error_source).to be_a(described_class)- expect(subject.errors.log_message).to include I18n.t('oauth_client.errors.oauth_returned_http_error')+ expect(subject.errors.log_message).to include I18n.t("oauth_client.errors.oauth_returned_http_error")endendend- describe '#refresh_token' do+ describe "#refresh_token" dosubject { instance.refresh_token }- context 'without existing OAuthClientToken' do- it 'returns an error message' do+ context "without existing OAuthClientToken" do+ it "returns an error message" doexpect(subject.success).to be_falsyexpect(subject.result).to eq(:error)expect(subject.errors.log_message)- .to include I18n.t('oauth_client.errors.refresh_token_called_without_existing_token')+ .to include I18n.t("oauth_client.errors.refresh_token_called_without_existing_token")endend- context 'with existing OAuthClientToken' do+ context "with existing OAuthClientToken" dobefore { oauth_client_token }- context 'when token is stale' do+ context "when token is stale" dobefore dooauth_client_token.update_columns(updated_at: 1.day.ago)end- context 'with successful response from OAuth2 provider (happy path)' do+ context "with successful response from OAuth2 provider (happy path)" dobefore do# Simulate a successful authorization returning the tokensresponse_body = {@@ -333,11 +279,11 @@ RSpec.describe OAuthClients::ConnectionManager, :webmock, type: :model dorefresh_token: "xUwFp...1FROJ",user_id: "admin"}.to_json- stub_request(:any, File.join(host, '/index.php/apps/oauth2/api/v1/token'))+ stub_request(:any, File.join(host, "/index.php/apps/oauth2/api/v1/token")).to_return(status: 200, body: response_body, headers: { "content-type" => "application/json; charset=utf-8" })end- it 'returns a valid ClientToken object', :webmock do+ it "returns a valid ClientToken object", :webmock doexpect(subject.success).to be_truthyexpect(subject.result).to be_a OAuthClientTokenexpect(subject.result.access_token).to eq("xyjTDZ...RYvRH")@@ -346,7 +292,7 @@ RSpec.describe OAuthClients::ConnectionManager, :webmock, type: :model doendend- context 'with invalid access_token data' do+ context "with invalid access_token data" dobefore do# Simulate a token too longresponse_body = {@@ -356,11 +302,11 @@ RSpec.describe OAuthClients::ConnectionManager, :webmock, type: :model dorefresh_token: "xUwFp...1FROJ",user_id: "admin"}.to_json- stub_request(:any, File.join(host, '/index.php/apps/oauth2/api/v1/token'))+ stub_request(:any, File.join(host, "/index.php/apps/oauth2/api/v1/token")).to_return(status: 200, body: response_body, headers: { "content-type" => "application/json; charset=utf-8" })end- it 'returns dependent error from model validation', :webmock do+ it "returns dependent error from model validation", :webmock doexpect(subject.success).to be_falsyexpect(subject.result).to eq(:error)expect(subject.error_payload.class).to be(AttrRequired::AttrMissing)@@ -368,38 +314,38 @@ RSpec.describe OAuthClients::ConnectionManager, :webmock, type: :model doendend- context 'with server error from OAuth2 provider' do+ context "with server error from OAuth2 provider" dobefore do- stub_request(:any, File.join(host, '/index.php/apps/oauth2/api/v1/token'))+ stub_request(:any, File.join(host, "/index.php/apps/oauth2/api/v1/token")).to_return(status: 400,body: { error: "invalid_request" }.to_json,headers: { "content-type" => "application/json; charset=utf-8" })end- it 'returns a server error', :webmock do+ it "returns a server error", :webmock doexpect(subject.success).to be_falsyexpect(subject.result).to eq(:bad_request)- expect(subject.error_payload[:error]).to eq('invalid_request')+ expect(subject.error_payload[:error]).to eq("invalid_request")endend- context 'with successful response but invalid data' do+ context "with successful response but invalid data" dobefore do# Simulate timeout- stub_request(:any, File.join(host, '/index.php/apps/oauth2/api/v1/token'))+ stub_request(:any, File.join(host, "/index.php/apps/oauth2/api/v1/token")).to_timeoutend- it 'returns an error wrapping a timeout', :webmock do+ it "returns an error wrapping a timeout", :webmock doexpect(subject.success).to be_falsyexpect(subject.result).to eq(:internal_server_error)expect(subject.error_payload.class).to be(Faraday::ConnectionFailed)expect(subject.error_source).to be_a(described_class)- expect(subject.errors.log_message).to include('Faraday::ConnectionFailed: execution expired')+ expect(subject.errors.log_message).to include("Faraday::ConnectionFailed: execution expired")endend- context 'with parallel requests for refresh', :aggregate_failures do+ context "with parallel requests for refresh", :aggregate_failures doafter doStorages::Storage.destroy_allUser.destroy_all@@ -407,7 +353,7 @@ RSpec.describe OAuthClients::ConnectionManager, :webmock, type: :model doOAuthClient.destroy_allend- it 'requests token only once and other thread uses new token' do+ it "requests token only once and other thread uses new token" doresponse_body1 = {access_token: "xyjTDZ...RYvRH",token_type: "Bearer",@@ -417,7 +363,7 @@ RSpec.describe OAuthClients::ConnectionManager, :webmock, type: :model do}response_body2 = response_body1.dupresponse_body2[:access_token] = "differ...RYvRH"- request_url = File.join(host, '/index.php/apps/oauth2/api/v1/token')+ 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, headers: { "content-type" => "application/json; charset=utf-8" } },{ status: 200, body: response_body2.to_json, headers: { "content-type" => "application/json; charset=utf-8" } }@@ -443,7 +389,7 @@ RSpec.describe OAuthClients::ConnectionManager, :webmock, type: :model doexpect(WebMock).to have_requested(:any, request_url).onceend- it 'requests token refresh twice if enough time passes between requests' do+ it "requests token refresh twice if enough time passes between requests" dostub_const("OAuthClients::ConnectionManager::TOKEN_IS_FRESH_DURATION", 2.seconds)response_body1 = {access_token: "xyjTDZ...RYvRH",@@ -454,7 +400,7 @@ RSpec.describe OAuthClients::ConnectionManager, :webmock, type: :model do}response_body2 = response_body1.dupresponse_body2[:access_token] = "differ...RYvRH"- request_url = File.join(host, '/index.php/apps/oauth2/api/v1/token')+ request_url = File.join(host, "/index.php/apps/oauth2/api/v1/token")headers = { "content-type" => "application/json; charset=utf-8" }stub_request(:any, request_url).to_return(status: 200, body: response_body1.to_json, headers:).then@@ -483,8 +429,8 @@ RSpec.describe OAuthClients::ConnectionManager, :webmock, type: :model doendend- context 'when token is fresh' do- it 'does not send refresh request and respond with existing token', :webmock do+ context "when token is fresh" do+ it "does not send refresh request and respond with existing token", :webmock doexpect(subject.success).to be_truthyexpect(subject.result).to eq(oauth_client_token)expect { subject }.not_to change(oauth_client_token, :access_token)@@ -493,7 +439,7 @@ RSpec.describe OAuthClients::ConnectionManager, :webmock, type: :model doendend- describe '#request_with_token_refresh' do+ describe "#request_with_token_refresh" dolet(:yield_service_result) { ServiceResult.success }let(:refresh_service_result) { ServiceResult.success }@@ -506,18 +452,18 @@ RSpec.describe OAuthClients::ConnectionManager, :webmock, type: :model doallow(oauth_client_token).to receive(:reload)end- context 'with yield returning :success' do- it 'returns a ServiceResult with success, without refreshing the token' do+ context "with yield returning :success" do+ it "returns a ServiceResult with success, without refreshing the token" doexpect(subject.success).to be_truthyexpect(instance).not_to have_received(:refresh_token)expect(oauth_client_token).not_to have_received(:reload)endend- context 'with yield returning :error' do+ context "with yield returning :error" dolet(:yield_service_result) { ServiceResult.failure(result: :error) }- it 'returns a ServiceResult with success, without refreshing the token' do+ it "returns a ServiceResult with success, without refreshing the token" doexpect(subject.success).to be_falsyexpect(subject.result).to be :errorexpect(instance).not_to have_received(:refresh_token)@@ -525,10 +471,10 @@ RSpec.describe OAuthClients::ConnectionManager, :webmock, type: :model doendend- context 'with yield returning :unauthorized and the refresh returning a with a success' do+ context "with yield returning :unauthorized and the refresh returning a with a success" dolet(:yield_service_result) { ServiceResult.failure(result: :unauthorized) }- it 'returns a ServiceResult with success, without refresh' do+ it "returns a ServiceResult with success, without refresh" doexpect(subject.success).to be_falsyexpect(subject.result).to be :unauthorizedexpect(instance).to have_received(:refresh_token)@@ -536,15 +482,15 @@ RSpec.describe OAuthClients::ConnectionManager, :webmock, type: :model doendend- context 'with yield returning :unauthorized and the refresh returning with a :failure' do+ context "with yield returning :unauthorized and the refresh returning with a :failure" dolet(:yield_service_result) { ServiceResult.failure(result: :unauthorized) }let(:refresh_service_result) do- data = Storages::StorageErrorData.new(source: nil, payload: { error: 'invalid_request' })+ data = Storages::StorageErrorData.new(source: nil, payload: { error: "invalid_request" })ServiceResult.failure(result: :error,errors: Storages::StorageError.new(code: :error, data:))end- it 'returns a ServiceResult with success, without refresh' do+ it "returns a ServiceResult with success, without refresh" doexpect(subject.success).to be_falsyexpect(subject.result).to be :errorexpect(instance).to have_received(:refresh_token)@@ -552,7 +498,7 @@ RSpec.describe OAuthClients::ConnectionManager, :webmock, type: :model doendend- context 'with yield returning :unauthorized first time and :success the second time' do+ context "with yield returning :unauthorized first time and :success the second time" dolet(:yield_double_object) { Object.new }let(:yield_service_result1) { ServiceResult.failure(result: :unauthorized) }let(:yield_service_result2) { ServiceResult.success }@@ -572,7 +518,7 @@ RSpec.describe OAuthClients::ConnectionManager, :webmock, type: :model do)end- it 'returns a ServiceResult with success, without refresh' do+ it "returns a ServiceResult with success, without refresh" doexpect(subject.success).to be_truthyexpect(subject).to be yield_service_result2expect(instance).to have_received(:refresh_token)diff --git a/spec/services/oauth_clients/one_drive_connection_manager_spec.rb b/spec/services/oauth_clients/one_drive_connection_manager_spec.rbindex 76ddc524188..b04fa5de908 100644--- a/spec/services/oauth_clients/one_drive_connection_manager_spec.rb+++ b/spec/services/oauth_clients/one_drive_connection_manager_spec.rb@@ -28,19 +28,19 @@# See COPYRIGHT and LICENSE files for more details.#++-require 'spec_helper'+require "spec_helper"RSpec.describe OAuthClients::ConnectionManager, :webmock, type: :model dolet(:user) { create(:user) }- let(:storage) { create(:one_drive_storage, :with_oauth_client, tenant_id: 'consumers') }+ let(:storage) { create(:one_drive_storage, :with_oauth_client, tenant_id: "consumers") }let(:token) { create(:oauth_client_token, oauth_client: storage.oauth_client, user:) }subject(:connection_manager) dodescribed_class.new(user:, configuration: storage.oauth_configuration)end- describe '#code_to_token' do- let(:code) { 'wow.such.code.much.token' }+ describe "#code_to_token" do+ let(:code) { "wow.such.code.much.token" }let(:code_to_token_response) do{access_token: "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik5HVEZ2ZEstZnl0aEV1Q...",@@ -69,64 +69,51 @@ RSpec.describe OAuthClients::ConnectionManager, :webmock, type: :model doendbefore do- stub_request(:post, 'https://login.microsoftonline.com/consumers/oauth2/v2.0/token')- .to_return(status: 200, body: code_to_token_response, headers: { 'Content-Type' => 'application/json' })+ stub_request(:post, "https://login.microsoftonline.com/consumers/oauth2/v2.0/token")+ .to_return(status: 200, body: code_to_token_response, headers: { "Content-Type" => "application/json" })- stub_request(:get, 'https://graph.microsoft.com/v1.0/me')+ stub_request(:get, "https://graph.microsoft.com/v1.0/me").with(headers: { Authorization: "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik5HVEZ2ZEstZnl0aEV1Q..." })- .to_return(status: 200, body: me_response, headers: { 'Content-Type' => 'application/json' })+ .to_return(status: 200, body: me_response, headers: { "Content-Type" => "application/json" })end- it 'fills in the origin_user_id' do+ it "fills in the origin_user_id" doexpect { subject.code_to_token(code) }.to change(OAuthClientToken, :count).by(1)last_token = OAuthClientToken.where(access_token: "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik5HVEZ2ZEstZnl0aEV1Q...").last- expect(last_token.origin_user_id).to eq('87d349ed-44d7-43e1-9a83-5f2406dee5bd')+ expect(last_token.origin_user_id).to eq("87d349ed-44d7-43e1-9a83-5f2406dee5bd")end- context 'when the identification request fails' do+ context "when the identification request fails" dobefore do- stub_request(:get, 'https://graph.microsoft.com/v1.0/me')+ stub_request(:get, "https://graph.microsoft.com/v1.0/me").with(headers: { Authorization: "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik5HVEZ2ZEstZnl0aEV1Q..." }).to_return(status: 404)end- it 'raises an error' do+ it "raises an error" doexpect { subject.code_to_token(code) }.to raise_error(HTTPX::HTTPError)endendend- describe '#get_authorization_uri' do- it 'always add the necessary scopes' do- uri = connection_manager.get_authorization_uri(state: nil)-- expect(uri).to include CGI.escape(storage.oauth_configuration.scope.join(' '))- end-- it 'adds the state if present' do- uri = connection_manager.get_authorization_uri(state: 'https://some.site.com')- expect(uri).to include "&state=https"- end- end-- describe '#get_access_token' do+ describe "#get_access_token" dosubject(:access_token_result) { connection_manager.get_access_token }- context 'with no OAuthClientToken present' do- it 'returns a redirection URL' do+ context "with no OAuthClientToken present" do+ it "returns a redirection URL" doexpect(access_token_result).to be_failure- expect(access_token_result.result).to eq(connection_manager.get_authorization_uri)+ expect(access_token_result.result).to eq(storage.oauth_configuration.authorization_uri)endend- context 'with an OAuthClientToken present' do+ context "with an OAuthClientToken present" dobefore { token }- it 'returns the OAuthClientToken' do+ it "returns the OAuthClientToken" doexpect(access_token_result).to be_truthyexpect(access_token_result.result).to be_a OAuthClientToken # The one and only...expect(access_token_result.result).to eql token