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
[#53993] Use authentication in delete_folder_command
Eric Schubertb997557df6ea
diff --git a/modules/storages/app/common/storages/peripherals/storage_interaction/authentication_strategies/failures.rb b/modules/storages/app/common/storages/peripherals/storage_interaction/authentication_strategies/failures.rbindex 575a5db3410..ad2740f842b 100644--- a/modules/storages/app/common/storages/peripherals/storage_interaction/authentication_strategies/failures.rb+++ b/modules/storages/app/common/storages/peripherals/storage_interaction/authentication_strategies/failures.rb@@ -37,6 +37,20 @@ module Storagesstorage_error = ::Storages::StorageError.new(code:, log_message:, data:)ServiceResult.failure(result: code, errors: storage_error)end++ ErrorData = ->(response:, source:) do+ payload =+ case response+ in { content_type: { mime_type: "application/json" } }+ response.json+ in { content_type: { mime_type: "text/xml" } }+ response.xml+ else+ response.body.to_s+ end++ ::Storages::StorageErrorData.new(source:, payload:)+ endendendenddiff --git a/modules/storages/app/common/storages/peripherals/storage_interaction/authentication_strategies/oauth_client_credentials.rb b/modules/storages/app/common/storages/peripherals/storage_interaction/authentication_strategies/oauth_client_credentials.rbindex ed482c92d75..15d47ffd091 100644--- a/modules/storages/app/common/storages/peripherals/storage_interaction/authentication_strategies/oauth_client_credentials.rb+++ b/modules/storages/app/common/storages/peripherals/storage_interaction/authentication_strategies/oauth_client_credentials.rb@@ -37,41 +37,57 @@ module StoragesStrategy.new(:oauth_client_credentials)end- def call(storage:, http_options: {}, &)+ def call(storage:, http_options: {})config = storage.oauth_configuration.to_httpx_oauth_configreturn build_failure(storage) unless config.valid?- create_http_and_yield(issuer: config.issuer,- client_id: config.client_id,- client_secret: config.client_secret,- scope: config.scope,- http_options:,- &)- end+ access_token = Rails.cache.read("storage.#{storage.id}.access_token")- private+ http_result = if access_token.present?+ http_with_current_token(access_token: access_token, http_options: http_options)+ else+ http_with_new_token(issuer: config.issuer,+ client_id: config.client_id,+ client_secret: config.client_secret,+ scope: config.scope,+ http_options:)+ end++ return http_result if http_result.failure?+ http = http_result.result- def create_http_and_yield(issuer:, client_id:, client_secret:, scope:, http_options:)- begin- http = OpenProject.httpx- .oauth_auth(issuer:,- client_id:,- client_secret:,- scope:,- token_endpoint_auth_method: "client_secret_post")- .with_access_token- .with(http_options)- rescue HTTPX::HTTPError => e- data = ::Storages::StorageErrorData.new(source: self.class, payload: e.response.json)- return Failures::Builder.call(code: :unauthorized,- log_message: "Error while fetching OAuth access token.",- data:)+ if access_token.nil?+ token = http.instance_variable_get(:@options).oauth_session.access_token+ Rails.cache.write("storage.#{storage.id}.access_token", token, expires_in: 50.minutes)endyield httpend+ private++ def http_with_current_token(access_token:, http_options:)+ opts = http_options.deep_merge({ headers: { "Authorization" => "Bearer #{access_token}" } })+ ServiceResult.success(result: OpenProject.httpx.with(opts))+ end++ def http_with_new_token(issuer:, client_id:, client_secret:, scope:, http_options:)+ http = OpenProject.httpx+ .oauth_auth(issuer:,+ client_id:,+ client_secret:,+ scope:,+ token_endpoint_auth_method: "client_secret_post")+ .with_access_token+ .with(http_options)+ ServiceResult.success(result: http)+ rescue HTTPX::HTTPError => e+ return Failures::Builder.call(code: :unauthorized,+ log_message: "Error while fetching OAuth access token.",+ data: Failures::ErrorData.new(response: e.response, source: self.class))+ end+def build_failure(storage)log_message = "Cannot authenticate storage with client credential oauth flow. Storage not configured."data = ::Storages::StorageErrorData.new(source: self.class, payload: storage)diff --git a/modules/storages/app/common/storages/peripherals/storage_interaction/authentication_strategies/oauth_user_token.rb b/modules/storages/app/common/storages/peripherals/storage_interaction/authentication_strategies/oauth_user_token.rbindex 5f5e2943c5e..9404f28ebcf 100644--- a/modules/storages/app/common/storages/peripherals/storage_interaction/authentication_strategies/oauth_user_token.rb+++ b/modules/storages/app/common/storages/peripherals/storage_interaction/authentication_strategies/oauth_user_token.rb@@ -84,7 +84,7 @@ module Storagesrescue HTTPX::HTTPError => ereturn Failures::Builder.call(code: :unauthorized,log_message: "Error while refreshing OAuth token.",- data: error_data_from_response(e.response))+ data: Failures::ErrorData.new(response: e.response, source: self.class))endresponse = yield http_session@@ -104,20 +104,6 @@ module Storages# rubocop:enable Metrics/AbcSize- def error_data_from_response(response)- payload =- case response- in { content_type: { mime_type: "application/json" } }- response.json- in { content_type: { mime_type: "text/xml" } }- response.xml- else- response.body.to_s- end-- ::Storages::StorageErrorData.new(source: self.class, payload:)- end-def update_refreshed_token(token, http_session)oauth = http_session.instance_variable_get(:@options).oauth_sessionaccess_token = oauth.access_tokendiff --git a/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/delete_folder_command.rb b/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/delete_folder_command.rbindex 80258309c1f..30718b93897 100644--- a/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/delete_folder_command.rb+++ b/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/delete_folder_command.rb@@ -28,16 +28,16 @@module Storages::Peripherals::StorageInteraction::Nextcloudclass DeleteFolderCommand- def initialize(storage)- @delegate = Internal::DeleteEntityCommand.new(storage)+ def self.call(storage:, auth_strategy:, location:)+ new(storage).call(auth_strategy:, location:)end- def self.call(storage:, location:)- new(storage).call(location:)+ def initialize(storage)+ @delegate = Internal::DeleteEntityCommand.new(storage)end- def call(location:)- @delegate.call(location:)+ def call(auth_strategy:, location:)+ @delegate.call(auth_strategy:, location:)endendenddiff --git a/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/internal/delete_entity_command.rb b/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/internal/delete_entity_command.rbindex 161db81f78e..08d63fd83af 100644--- a/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/internal/delete_entity_command.rb+++ b/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/internal/delete_entity_command.rb@@ -28,37 +28,76 @@module Storages::Peripherals::StorageInteraction::Nextcloud::Internalclass DeleteEntityCommand- UTIL = ::Storages::Peripherals::StorageInteraction::Nextcloud::Util+ Util = ::Storages::Peripherals::StorageInteraction::Nextcloud::Util+ Auth = ::Storages::Peripherals::StorageInteraction::Authentication- def initialize(storage)- @uri = storage.uri- @username = storage.username- @password = storage.password+ def self.call(storage:, auth_strategy:, location:)+ new(storage).call(auth_strategy:, location:)end- def self.call(storage:, location:)- new(storage).call(location:)+ def initialize(storage)+ @storage = storageend- def call(location:)- response = OpenProject- .httpx- .basic_auth(@username, @password)- .delete(UTIL.join_uri_path(@uri,- "remote.php/dav/files",- CGI.escapeURIComponent(@username),- UTIL.escape_path(location)))+ def call(auth_strategy:, location:)+ origin_user_id = origin_user_id(auth_strategy)+ if origin_user_id.failure?+ return origin_user_id+ end++ response = Auth[auth_strategy].call(storage: @storage) do |http|+ http.delete(Util.join_uri_path(@storage.uri,+ "remote.php/dav/files",+ CGI.escapeURIComponent(origin_user_id.result),+ Util.escape_path(location)))+ endcase responsein { status: 200..299 }ServiceResult.successin { status: 404 }- UTIL.error(:not_found)+ failure(code: :not_found,+ payload: response.json(symbolize_keys: true),+ log_message: "Outbound request destination not found!")in { status: 401 }- UTIL.error(:unauthorized)+ failure(code: :unauthorized,+ payload: response.json(symbolize_keys: true),+ log_message: "Outbound request not authorized!")+ else+ failure(code: :error,+ payload: response.json(symbolize_keys: true),+ log_message: "Outbound request failed with unknown error!")+ end+ end++ private++ def origin_user_id(auth_strategy)+ case auth_strategy.key+ when :basic_auth+ ServiceResult.success(result: @storage.username)+ when :oauth_user_token+ origin_user_id = OAuthClientToken.find_by(user_id: user, oauth_client_id: @storage.oauth_client.id)&.origin_user_id+ origin_user_id.present? ?+ ServiceResult.success(result: origin_user_id) :+ failure(code: :error,+ payload: nil,+ log_message: "No origin user ID or user token found. Cannot execute query without user context.")else- UTIL.error(:error)+ failure(code: :error,+ payload: nil,+ log_message: "No authentication strategy with user context found. " \+ "Cannot execute query without user context.")endend++ def failure(code:, payload:, log_message:)+ ServiceResult.failure(+ result: code,+ errors: ::Storages::StorageError.new(code:,+ data: ::Storages::StorageErrorData.new(source: self.class, payload:),+ log_message:)+ )+ endendenddiff --git a/modules/storages/app/common/storages/peripherals/storage_interaction/one_drive/delete_folder_command.rb b/modules/storages/app/common/storages/peripherals/storage_interaction/one_drive/delete_folder_command.rbindex d56e475c06c..787ad49efac 100644--- a/modules/storages/app/common/storages/peripherals/storage_interaction/one_drive/delete_folder_command.rb+++ b/modules/storages/app/common/storages/peripherals/storage_interaction/one_drive/delete_folder_command.rb@@ -33,18 +33,20 @@ module Storagesmodule StorageInteractionmodule OneDriveclass DeleteFolderCommand- def self.call(storage:, location:)- new(storage).call(location:)+ Auth = ::Storages::Peripherals::StorageInteraction::Authentication++ def self.call(storage:, auth_strategy:, location:)+ new(storage).call(auth_strategy:, location:)enddef initialize(storage)@storage = storage- @uri = storage.uriend- def call(location:)- Util.using_admin_token(@storage) do |http|- response = http.delete("/v1.0/drives/#{@storage.drive_id}/items/#{location}")+ def call(auth_strategy:, location:)+ Auth[auth_strategy].call(storage: @storage) do |http|+ response = http.delete(+ Util.join_uri_path(@storage.uri, "/v1.0/drives/#{@storage.drive_id}/items/#{location}"))data = ::Storages::StorageErrorData.new(source: self.class, payload: response)diff --git a/modules/storages/app/common/storages/peripherals/storage_interaction/one_drive/files_query.rb b/modules/storages/app/common/storages/peripherals/storage_interaction/one_drive/files_query.rbindex 5aad9c64927..91088a4cda2 100644--- a/modules/storages/app/common/storages/peripherals/storage_interaction/one_drive/files_query.rb+++ b/modules/storages/app/common/storages/peripherals/storage_interaction/one_drive/files_query.rb@@ -48,7 +48,7 @@ module Storagesenddef call(auth_strategy:, folder:)- Auth[auth_strategy].call(storage: @storage) do |http|+ Auth[auth_strategy].call(storage: @storage, http_options: { headers: { "OCS-APIRequest" => "true" } }) do |http|call = http.get(Util.join_uri_path(@uri, children_uri_path_for(folder) + FIELDS))response = handle_response(call, :value)diff --git a/modules/storages/app/services/storages/project_storages/delete_service.rb b/modules/storages/app/services/storages/project_storages/delete_service.rbindex f00e06b890c..c1de8da7c70 100644--- a/modules/storages/app/services/storages/project_storages/delete_service.rb+++ b/modules/storages/app/services/storages/project_storages/delete_service.rb@@ -58,9 +58,16 @@ module Storages::ProjectStoragesprivate+ def auth_strategy+ ::Storages::Peripherals::Registry+ .resolve("#{model.storage.short_provider_type}.authentication.userless")+ .call+ end+def delete_project_folder- ::Storages::Peripherals::Registry.resolve("#{model.storage.short_provider_type}.commands.delete_folder")- .call(storage: model.storage, location: model.project_folder_location)+ ::Storages::Peripherals::Registry+ .resolve("#{model.storage.short_provider_type}.commands.delete_folder")+ .call(storage: model.storage, auth_strategy:, location: model.project_folder_location)end# Delete FileLinks with the same Storage as the ProjectStorage.diff --git a/modules/storages/spec/common/storages/peripherals/registry_spec.rb b/modules/storages/spec/common/storages/peripherals/registry_spec.rbindex 5fff3d2f780..f2422a3748b 100644--- a/modules/storages/spec/common/storages/peripherals/registry_spec.rb+++ b/modules/storages/spec/common/storages/peripherals/registry_spec.rb@@ -209,10 +209,9 @@ RSpec.describe Storages::Peripherals::Registry, :webmock doit "responds with a failure and parses message from the xml response" doresult = registry.resolve("nextcloud.commands.remove_user_from_group").call(storage:, user: origin_user_id)expect(result).to be_failure- expect(result.errors.log_message).to eq(- "Failed to remove user #{origin_user_id} from group OpenProject: " \- "Not viable to remove user from the last group you are SubAdmin of"- )+ expect(result.errors.log_message)+ .to eq("Failed to remove user #{origin_user_id} from group OpenProject: " \+ "Not viable to remove user from the last group you are SubAdmin of")endendend@@ -568,8 +567,9 @@ RSpec.describe Storages::Peripherals::Registry, :webmock doshared_examples "a file_ids_query response" doit "responds with a list of paths and attributes for each of them" do- result = registry.resolve("nextcloud.queries.file_ids").call(storage:, path: "OpenProject")- .result+ result = registry.resolve("nextcloud.queries.file_ids")+ .call(storage:, path: "OpenProject")+ .resultexpect(result).to eq({ "OpenProject/" => { "fileid" => "349" },"OpenProject/Project #2/" => { "fileid" => "381" },"OpenProject/Project#1/" => { "fileid" => "773" },@@ -610,6 +610,8 @@ RSpec.describe Storages::Peripherals::Registry, :webmock doenddescribe "#delete_folder_command" do+ let(:auth_strategy) { ::Storages::Peripherals::StorageInteraction::AuthenticationStrategies::BasicAuth.strategy }+before dostub_request(:delete, "https://example.com/remote.php/dav/files/OpenProject/OpenProject/Folder%201").with(headers: { "Authorization" => "Basic T3BlblByb2plY3Q6T3BlblByb2plY3RTZWN1cmVQYXNzd29yZA==" })@@ -618,7 +620,8 @@ RSpec.describe Storages::Peripherals::Registry, :webmock dodescribe "with Nextcloud storage type selected" doit "deletes the folder" do- result = registry.resolve("nextcloud.commands.delete_folder").call(storage:, location: "OpenProject/Folder 1")+ result = registry.resolve("nextcloud.commands.delete_folder")+ .call(storage:, auth_strategy:, location: "OpenProject/Folder 1")expect(result).to be_successendenddiff --git a/modules/storages/spec/common/storages/peripherals/storage_interaction/one_drive/delete_folder_command_spec.rb b/modules/storages/spec/common/storages/peripherals/storage_interaction/one_drive/delete_folder_command_spec.rbindex d03e471382e..c5fe1d4d048 100644--- a/modules/storages/spec/common/storages/peripherals/storage_interaction/one_drive/delete_folder_command_spec.rb+++ b/modules/storages/spec/common/storages/peripherals/storage_interaction/one_drive/delete_folder_command_spec.rb@@ -33,6 +33,9 @@ require_module_spec_helperRSpec.describe Storages::Peripherals::StorageInteraction::OneDrive::DeleteFolderCommand, :vcr, :webmock dolet(:storage) { create(:sharepoint_dev_drive_storage) }+ let(:auth_strategy) do+ Storages::Peripherals::StorageInteraction::AuthenticationStrategies::OAuthClientCredentials.strategy+ endit "is registered as commands.one_drive.delete_folder" doexpect(Storages::Peripherals::Registry.resolve("one_drive.commands.delete_folder")).to eq(described_class)@@ -42,21 +45,21 @@ RSpec.describe Storages::Peripherals::StorageInteraction::OneDrive::DeleteFolderexpect(described_class).to respond_to(:call)method = described_class.method(:call)- expect(method.parameters).to contain_exactly(%i[keyreq storage], %i[keyreq location])+ expect(method.parameters).to contain_exactly(%i[keyreq storage], %i[keyreq auth_strategy], %i[keyreq location])endit "deletes a folder", vcr: "one_drive/delete_folder" docreate_result = Storages::Peripherals::Registry- .resolve("one_drive.commands.create_folder")- .call(storage:, folder_path: "To Be Deleted Soon")+ .resolve("one_drive.commands.create_folder")+ .call(storage:, folder_path: "To Be Deleted Soon")folder = create_result.result- expect(described_class.call(storage:, location: folder.id)).to be_success+ expect(described_class.call(storage:, auth_strategy:, location: folder.id)).to be_successendit "when the folder is not found, returns a failure", vcr: "one_drive/delete_folder_not_found" do- result = described_class.call(storage:, location: "NOT_HERE")+ result = described_class.call(storage:, auth_strategy:, location: "NOT_HERE")expect(result).to be_failureexpect(result.result).to eq(:not_found)end