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

[#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.rb
index 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 Storages
def 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:)
end
end
diff --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.rb
index 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 Storages
def 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"))
end
end
@@ -60,7 +60,7 @@ module Storages
in { 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:))
end
end
diff --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.rb
index 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 Storages
def 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"))
end
end
@@ -60,7 +60,7 @@ module Storages
in { 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:))
end
end
diff --git a/modules/storages/app/controllers/storages/admin/project_storages_controller.rb b/modules/storages/app/controllers/storages/admin/project_storages_controller.rb
index 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::SettingsController
def 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 == :connected
redirect_to(project_settings_project_storages_path)
else
nonce = SecureRandom.uuid
@@ -110,11 +109,11 @@ class Storages::Admin::ProjectStoragesController < Projects::SettingsController
expires: 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))
end
end
- # 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 page
def edit
@@ -150,7 +149,7 @@ class Storages::Admin::ProjectStoragesController < Projects::SettingsController
end
# 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 project
def 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.rb
index 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 StorageLoginHelper
def 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
}
}
end
diff --git a/modules/storages/lib/api/v3/storages/storage_representer.rb b/modules/storages/lib/api/v3/storages/storage_representer.rb
index 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::Storages
getter: ->(*) {
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::Storages
link_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::Storages
title: "Upload file",
payload: {
projectId: project_id,
- fileName: '{fileName}',
- parent: '{parent}'
+ fileName: "{fileName}",
+ parent: "{parent}"
},
templated: true
}
@@ -165,7 +165,7 @@ module API::V3::Storages
link :authorize do
next unless authorization_state == :failed_authorization
- { href: represented.oauth_configuration.authorization_uri(state: nil), title: 'Authorize' }
+ { href: represented.oauth_configuration.authorization_uri, title: "Authorize" }
end
link :projectStorages do
@@ -204,7 +204,7 @@ module API::V3::Storages
}
def _type
- 'Storage'
+ "Storage"
end
private
diff --git a/spec/requests/oauth_clients/ensure_connection_flow_spec.rb b/spec/requests/oauth_clients/ensure_connection_flow_spec.rb
index 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 do
shared_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" do
context "when user is not logged in" do
it "requires login" do
@@ -52,10 +59,15 @@ RSpec.describe "/oauth_clients/:oauth_client_id/ensure_connection endpoint", :we
end
context "when storage_id parameter is present" do
- context 'when user is not "connected"' do
+ context "when user is not 'connected'" do
let(: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.ordered
allow(SecureRandom).to receive(:uuid).and_return(nonce).ordered
end
@@ -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"])
end
end
@@ -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"])
end
end
@@ -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"])
end
end
end
end
- context 'when user is "connected"' do
+ context "when user is 'connected'" do
let!(:oauth_client_token) do
create(:oauth_client_token, oauth_client:, user:)
end
diff --git a/spec/services/oauth_clients/connection_manager_spec.rb b/spec/services/oauth_clients/connection_manager_spec.rb
index 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 do
using Storages::Peripherals::ServiceResultRefinements
@@ -45,78 +45,24 @@ RSpec.describe OAuthClients::ConnectionManager, :webmock, type: :model do
let(: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" do
subject { 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" do
expect(subject.success).to be_falsy
expect(subject.result).to be_a String
# Details of string are tested above in section #get_authorization_uri
end
end
- context 'with no OAuthClientToken present and state parameters' do
+ context "with no OAuthClientToken present and state parameters" do
subject { instance.get_access_token(state: "some_state") }
- it 'returns the redirect URL' do
+ it "returns the redirect URL" do
allow(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 do
end
end
- context 'with an OAuthClientToken present' do
+ context "with an OAuthClientToken present" do
before do
oauth_client_token
end
- it 'returns the OAuthClientToken' do
+ it "returns the OAuthClientToken" do
expect(subject).to be_truthy
expect(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 do
let(:code) { "7kRGJ...jG3KZ" }
subject { instance.code_to_token(code) }
- context 'with happy path' do
+ context "with happy path" do
before do
# Simulate a successful authorization returning the tokens
response_body = {
@@ -162,11 +108,11 @@ RSpec.describe OAuthClients::ConnectionManager, :webmock, type: :model do
refresh_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" do
expect(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 do
expect(subject.result).to be_a OAuthClientToken
end
- it 'fills in the origin_user_id' do
+ it "fills in the origin_user_id" do
expect { 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")
end
end
- context 'with known error' do
+ context "with known error" do
before 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" do
expect(subject.success).to be_falsy
expect(subject.result).to eq(:bad_request)
expect(subject.error_payload[:error]).to eq(error_message)
end
end
- 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"
end
end
- context 'with unknown reply' do
+ context "with unknown reply" do
before 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" do
expect(subject.success).to be_falsy
expect(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")
end
end
- context 'with reply including JSON syntax error' do
+ context "with reply including JSON syntax error" do
before 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" do
expect(subject.success).to be_falsy
expect(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")
end
end
- context 'with 500 reply without body' do
+ context "with 500 reply without body" do
before 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" do
expect(subject.success).to be_falsy
expect(subject.result).to eq(:bad_request)
- expect(subject.error_payload[:error]).to eq('Unknown')
+ expect(subject.error_payload[:error]).to eq("Unknown")
end
end
- context 'when something is wrong with connection' do
+ context "when something is wrong with connection" do
before 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" do
expect(subject.success).to be_falsy
expect(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")
end
end
- context 'when something is wrong with SSL' do
+ context "when something is wrong with SSL" do
before 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" do
expect(subject.success).to be_falsy
expect(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")
end
end
- context 'with timeout returns internal error' do
+ context "with timeout returns internal error" do
before 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_timeout
end
- it 'returns an error wrapping the server timeout' do
+ it "returns an error wrapping the server timeout" do
expect(subject.success).to be_falsy
expect(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")
end
end
end
- describe '#refresh_token' do
+ describe "#refresh_token" do
subject { instance.refresh_token }
- context 'without existing OAuthClientToken' do
- it 'returns an error message' do
+ context "without existing OAuthClientToken" do
+ it "returns an error message" do
expect(subject.success).to be_falsy
expect(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")
end
end
- context 'with existing OAuthClientToken' do
+ context "with existing OAuthClientToken" do
before { oauth_client_token }
- context 'when token is stale' do
+ context "when token is stale" do
before do
oauth_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)" do
before do
# Simulate a successful authorization returning the tokens
response_body = {
@@ -333,11 +279,11 @@ RSpec.describe OAuthClients::ConnectionManager, :webmock, type: :model do
refresh_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 do
expect(subject.success).to be_truthy
expect(subject.result).to be_a OAuthClientToken
expect(subject.result.access_token).to eq("xyjTDZ...RYvRH")
@@ -346,7 +292,7 @@ RSpec.describe OAuthClients::ConnectionManager, :webmock, type: :model do
end
end
- context 'with invalid access_token data' do
+ context "with invalid access_token data" do
before do
# Simulate a token too long
response_body = {
@@ -356,11 +302,11 @@ RSpec.describe OAuthClients::ConnectionManager, :webmock, type: :model do
refresh_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 do
expect(subject.success).to be_falsy
expect(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 do
end
end
- context 'with server error from OAuth2 provider' do
+ context "with server error from OAuth2 provider" do
before 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 do
expect(subject.success).to be_falsy
expect(subject.result).to eq(:bad_request)
- expect(subject.error_payload[:error]).to eq('invalid_request')
+ expect(subject.error_payload[:error]).to eq("invalid_request")
end
end
- context 'with successful response but invalid data' do
+ 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'))
+ stub_request(:any, File.join(host, "/index.php/apps/oauth2/api/v1/token"))
.to_timeout
end
- it 'returns an error wrapping a timeout', :webmock do
+ it "returns an error wrapping a timeout", :webmock do
expect(subject.success).to be_falsy
expect(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")
end
end
- context 'with parallel requests for refresh', :aggregate_failures do
+ context "with parallel requests for refresh", :aggregate_failures do
after do
Storages::Storage.destroy_all
User.destroy_all
@@ -407,7 +353,7 @@ RSpec.describe OAuthClients::ConnectionManager, :webmock, type: :model do
OAuthClient.destroy_all
end
- it 'requests token only once and other thread uses new token' do
+ it "requests token only once and other thread uses new token" do
response_body1 = {
access_token: "xyjTDZ...RYvRH",
token_type: "Bearer",
@@ -417,7 +363,7 @@ RSpec.describe OAuthClients::ConnectionManager, :webmock, type: :model do
}
response_body2 = response_body1.dup
response_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 do
expect(WebMock).to have_requested(:any, request_url).once
end
- it 'requests token refresh twice if enough time passes between requests' do
+ 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",
@@ -454,7 +400,7 @@ RSpec.describe OAuthClients::ConnectionManager, :webmock, type: :model do
}
response_body2 = response_body1.dup
response_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 do
end
end
- 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 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)
@@ -493,7 +439,7 @@ RSpec.describe OAuthClients::ConnectionManager, :webmock, type: :model do
end
end
- describe '#request_with_token_refresh' do
+ describe "#request_with_token_refresh" do
let(:yield_service_result) { ServiceResult.success }
let(:refresh_service_result) { ServiceResult.success }
@@ -506,18 +452,18 @@ RSpec.describe OAuthClients::ConnectionManager, :webmock, type: :model do
allow(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" do
expect(subject.success).to be_truthy
expect(instance).not_to have_received(:refresh_token)
expect(oauth_client_token).not_to have_received(:reload)
end
end
- context 'with yield returning :error' do
+ context "with yield returning :error" do
let(: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" do
expect(subject.success).to be_falsy
expect(subject.result).to be :error
expect(instance).not_to have_received(:refresh_token)
@@ -525,10 +471,10 @@ RSpec.describe OAuthClients::ConnectionManager, :webmock, type: :model do
end
end
- 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" do
let(:yield_service_result) { ServiceResult.failure(result: :unauthorized) }
- it 'returns a ServiceResult with success, without refresh' do
+ it "returns a ServiceResult with success, without refresh" do
expect(subject.success).to be_falsy
expect(subject.result).to be :unauthorized
expect(instance).to have_received(:refresh_token)
@@ -536,15 +482,15 @@ RSpec.describe OAuthClients::ConnectionManager, :webmock, type: :model do
end
end
- 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" do
let(: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" do
expect(subject.success).to be_falsy
expect(subject.result).to be :error
expect(instance).to have_received(:refresh_token)
@@ -552,7 +498,7 @@ RSpec.describe OAuthClients::ConnectionManager, :webmock, type: :model do
end
end
- 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" do
let(: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" do
expect(subject.success).to be_truthy
expect(subject).to be yield_service_result2
expect(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.rb
index 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 do
let(: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) do
described_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 do
end
before 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" do
expect { 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" do
before 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" do
expect { subject.code_to_token(code) }.to raise_error(HTTPX::HTTPError)
end
end
end
- 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" do
subject(: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" do
expect(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)
end
end
- context 'with an OAuthClientToken present' do
+ context "with an OAuthClientToken present" do
before { token }
- it 'returns the OAuthClientToken' do
+ it "returns the OAuthClientToken" do
expect(access_token_result).to be_truthy
expect(access_token_result.result).to be_a OAuthClientToken # The one and only...
expect(access_token_result.result).to eql token