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

Introduces the UploadLinkService

Marcello Rochaac08605ef6a5
diff --git a/lib/api/errors/outbound_request_forbidden.rb b/lib/api/errors/outbound_request_forbidden.rb
index 941a4a09a24..b146f250554 100644
--- a/lib/api/errors/outbound_request_forbidden.rb
+++ b/lib/api/errors/outbound_request_forbidden.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) the OpenProject GmbH
@@ -29,11 +31,11 @@
module API
module Errors
class OutboundRequestForbidden < ErrorBase
- identifier "OutboundRequest:Forbidden".freeze
+ identifier "OutboundRequest:Forbidden"
code 500
- def initialize
- super(I18n.t("api_v3.errors.code_500_outbound_request_failure", status_code: 403))
+ def initialize(message = I18n.t("api_v3.errors.code_500_outbound_request_failure", status_code: 403))
+ super
end
end
end
diff --git a/lib/api/errors/outbound_request_not_found.rb b/lib/api/errors/outbound_request_not_found.rb
index adf5d0bc31e..3f4ba15952c 100644
--- a/lib/api/errors/outbound_request_not_found.rb
+++ b/lib/api/errors/outbound_request_not_found.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) the OpenProject GmbH
@@ -29,11 +31,11 @@
module API
module Errors
class OutboundRequestNotFound < ErrorBase
- identifier "OutboundRequest:NotFound".freeze
+ identifier "OutboundRequest:NotFound"
code 500
- def initialize
- super(I18n.t("api_v3.errors.code_500_outbound_request_failure", status_code: 404))
+ def initialize(message = I18n.t("api_v3.errors.code_500_outbound_request_failure", status_code: 404))
+ super
end
end
end
diff --git a/modules/storages/app/common/storages/peripherals/storage_error_helper.rb b/modules/storages/app/common/storages/peripherals/storage_error_helper.rb
index d12e46b365d..ae5d8788d88 100644
--- a/modules/storages/app/common/storages/peripherals/storage_error_helper.rb
+++ b/modules/storages/app/common/storages/peripherals/storage_error_helper.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) the OpenProject GmbH
@@ -28,6 +30,30 @@
module Storages::Peripherals
module StorageErrorHelper
+ def raise_service_result_error(errors)
+ handle_base_errors(errors) if errors.has_key?(:base)
+
+ api_errors = ::API::Errors::ErrorBase.create_errors(errors)
+ fail ::API::Errors::MultipleErrors.create_if_many(api_errors)
+ end
+
+ # rubocop:disable Metrics/AbcSize
+ def handle_base_errors(errors)
+ base_errors = errors.symbols_for(:base)
+ if base_errors.include? :not_found
+ fail API::Errors::OutboundRequestNotFound.new(errors.full_messages_for(:base).first)
+ elsif base_errors.include? :unauthorized
+ fail ::API::Errors::Unauthenticated.new(errors.full_messages_for(:base).first)
+ elsif base_errors.include? :forbidden
+ fail API::Errors::OutboundRequestForbidden.new(errors.full_messages_for(:base).first)
+ elsif base_errors.include? :error
+ fail API::Errors::InternalError.new(errors.full_messages)
+ else
+ base_errors
+ end
+ end
+ # rubocop:enable Metrics/AbcSize
+
def raise_error(error)
Rails.logger.error(error)
diff --git a/modules/storages/app/models/storages/upload_data.rb b/modules/storages/app/common/storages/peripherals/storage_interaction/inputs/upload_data.rb
similarity index 70%
rename from modules/storages/app/models/storages/upload_data.rb
rename to modules/storages/app/common/storages/peripherals/storage_interaction/inputs/upload_data.rb
index 58e4f30be9e..c08f2e47d57 100644
--- a/modules/storages/app/models/storages/upload_data.rb
+++ b/modules/storages/app/common/storages/peripherals/storage_interaction/inputs/upload_data.rb
@@ -1,3 +1,5 @@
+# frozen_string_literal: true
+
#-- copyright
# OpenProject is an open source project management software.
# Copyright (C) the OpenProject GmbH
@@ -27,5 +29,19 @@
#++
module Storages
- UploadData = Data.define(:folder_id, :file_name)
+ module Peripherals
+ module StorageInteraction
+ module Inputs
+ UploadData = Data.define(:folder_id, :file_name) do
+ private_class_method :new
+
+ def self.build(folder_id:, file_name:, contract: UploadDataContract.new)
+ contract.call(folder_id:, file_name:).to_monad.fmap do |result|
+ new(file_name: result[:file_name], folder_id: ParentFolder.new(result[:folder_id]))
+ end
+ end
+ end
+ end
+ end
+ end
end
diff --git a/modules/storages/app/common/storages/peripherals/storage_interaction/inputs/upload_data_contract.rb b/modules/storages/app/common/storages/peripherals/storage_interaction/inputs/upload_data_contract.rb
new file mode 100644
index 00000000000..8fceaa7a084
--- /dev/null
+++ b/modules/storages/app/common/storages/peripherals/storage_interaction/inputs/upload_data_contract.rb
@@ -0,0 +1,19 @@
+# frozen_string_literal: true
+
+#-- copyright
+#++
+
+module Storages
+ module Peripherals
+ module StorageInteraction
+ module Inputs
+ class UploadDataContract < Dry::Validation::Contract
+ params do
+ required(:folder_id).filled(:string)
+ required(:file_name).filled(:string)
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/upload_link_query.rb b/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/upload_link_query.rb
index 474a1283c18..3137d17683c 100644
--- a/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/upload_link_query.rb
+++ b/modules/storages/app/common/storages/peripherals/storage_interaction/nextcloud/upload_link_query.rb
@@ -33,6 +33,8 @@ module Storages
module StorageInteraction
module Nextcloud
class UploadLinkQuery
+ include TaggedLogging
+
using ServiceResultRefinements
def self.call(storage:, auth_strategy:, upload_data:)
@@ -44,13 +46,13 @@ module Storages
end
def call(auth_strategy:, upload_data:)
- return upload_data_failure if invalid?(upload_data:)
-
- Authentication[auth_strategy].call(storage: @storage) do |http|
- response = http.post(base_uri, json: payload_from(upload_data:))
+ with_tagged_logger do
+ Authentication[auth_strategy].call(storage: @storage) do |http|
+ response = http.post(base_uri, json: payload_from(upload_data:))
- handle_response(response).map do |rsp|
- UploadLink.new(URI("#{upload_base_uri}/#{rsp[:token]}"), :post)
+ handle_response(response).map do |rsp|
+ UploadLink.new(URI("#{upload_base_uri}/#{rsp[:token]}"), :post)
+ end
end
end
end
@@ -65,12 +67,6 @@ module Storages
UrlBuilder.url(@storage.uri, "index.php/apps/integration_openproject/direct-upload")
end
- def upload_data_failure
- Util.failure(code: :error,
- data: StorageErrorData.new(source: self.class),
- log_message: "Invalid upload data!")
- end
-
def invalid?(upload_data:)
upload_data.folder_id.blank? || upload_data.file_name.blank?
end
@@ -82,16 +78,20 @@ module Storages
def handle_response(response)
case response
in { status: 200..299 }
+ info "Request successful"
ServiceResult.success(result: response.json(symbolize_keys: true))
in { status: 404 }
+ info "The parent folder was not found."
Util.failure(code: :not_found,
data: Util.error_data_from_response(caller: self.class, response:),
log_message: "Outbound request destination not found!")
in { status: 401 }
+ info "User authorization failed."
Util.failure(code: :unauthorized,
data: Util.error_data_from_response(caller: self.class, response:),
log_message: "Outbound request not authorized!")
else
+ info "Unknown error happened."
Util.failure(code: :error,
data: Util.error_data_from_response(caller: self.class, response:),
log_message: "Outbound request failed with unknown error!")
diff --git a/modules/storages/app/common/storages/peripherals/storage_interaction/one_drive/upload_link_query.rb b/modules/storages/app/common/storages/peripherals/storage_interaction/one_drive/upload_link_query.rb
index 67a980a8e48..a64753fb3a8 100644
--- a/modules/storages/app/common/storages/peripherals/storage_interaction/one_drive/upload_link_query.rb
+++ b/modules/storages/app/common/storages/peripherals/storage_interaction/one_drive/upload_link_query.rb
@@ -33,6 +33,8 @@ module Storages
module StorageInteraction
module OneDrive
class UploadLinkQuery
+ include TaggedLogging
+
def self.call(storage:, auth_strategy:, upload_data:)
new(storage).call(auth_strategy:, upload_data:)
end
@@ -42,23 +44,16 @@ module Storages
end
def call(auth_strategy:, upload_data:)
- return upload_data_failure if invalid?(upload_data:)
-
- Authentication[auth_strategy].call(storage: @storage) do |http|
- handle_response http.post(url(upload_data.folder_id, upload_data.file_name),
- json: payload(upload_data.file_name))
+ with_tagged_logger do
+ Authentication[auth_strategy].call(storage: @storage) do |http|
+ handle_response http.post(url(upload_data.folder_id, upload_data.file_name),
+ json: payload(upload_data.file_name))
+ end
end
end
private
- def upload_data_failure
- ServiceResult.failure(result: :error,
- errors: StorageError.new(code: :error,
- data: StorageErrorData.new(source: self.class),
- log_message: "Invalid upload data!"))
- end
-
def invalid?(upload_data:)
upload_data.folder_id.blank? || upload_data.file_name.blank?
end
@@ -74,15 +69,19 @@ module Storages
upload_url = response.json(symbolize_keys: true)[:uploadUrl]
ServiceResult.success(result: UploadLink.new(URI(upload_url), :put))
in { status: 404 | 400 } # not existent parent folder in request url is responded with 400
+ info "The parent folder was not found."
ServiceResult.failure(result: :not_found,
errors: Util.storage_error(code: :not_found, response:, source: self.class))
in { status: 401 }
+ info "User authorization failed."
ServiceResult.failure(result: :unauthorized,
errors: Util.storage_error(code: :unauthorized, response:, source: self.class))
in { status: 403 }
+ info "User authorization failed."
ServiceResult.failure(result: :forbidden,
errors: Util.storage_error(code: :forbidden, response:, source: self.class))
else
+ info "Unknown error happened."
ServiceResult.failure(result: :error,
errors: Util.storage_error(code: :error, response:, source: self.class))
end
diff --git a/modules/storages/app/common/storages/peripherals/storage_interaction/types.rb b/modules/storages/app/common/storages/peripherals/storage_interaction/types.rb
new file mode 100644
index 00000000000..1d7408901ea
--- /dev/null
+++ b/modules/storages/app/common/storages/peripherals/storage_interaction/types.rb
@@ -0,0 +1,16 @@
+# frozen_string_literal: true
+
+#-- copyright
+#++
+
+module Storages
+ module Peripherals
+ module StorageInteraction
+ module Types
+ include Dry::Types()
+
+ ParentFolderType = Constructor(ParentFolder, ParentFolder.method(:build))
+ end
+ end
+ end
+end
diff --git a/modules/storages/app/services/storages/file_link_sync_service.rb b/modules/storages/app/services/storages/file_link_sync_service.rb
index 7a7da04c88e..f644170fcf7 100644
--- a/modules/storages/app/services/storages/file_link_sync_service.rb
+++ b/modules/storages/app/services/storages/file_link_sync_service.rb
@@ -28,92 +28,97 @@
# See COPYRIGHT and LICENSE files for more details.
#++
-class Storages::FileLinkSyncService
- using Storages::Peripherals::ServiceResultRefinements
+module Storages
+ class FileLinkSyncService < BaseService
+ using Peripherals::ServiceResultRefinements
- def initialize(user:)
- @user = user
- end
+ def initialize(user:)
+ super()
+ @user = user
+ end
- def call(file_links)
- resulting_file_links = file_links
- .group_by(&:storage_id)
- .map { |storage_id, storage_file_links| sync_storage_data(storage_id, storage_file_links) }
- .reduce([]) do |state, sync_result|
- sync_result.match(
- on_success: ->(sr) { state + sr },
- on_failure: ->(_) { state }
- )
+ def call(file_links)
+ with_tagged_logger do
+ resulting_file_links = file_links
+ .group_by(&:storage_id)
+ .map { |storage_id, storage_file_links| sync_storage_data(storage_id, storage_file_links) }
+ .reduce([]) do |state, sync_result|
+ sync_result.match(
+ on_success: ->(sr) { state + sr },
+ on_failure: ->(_) { state }
+ )
+ end
+
+ ServiceResult.success(result: resulting_file_links)
end
+ end
- ServiceResult.success(result: resulting_file_links)
- end
+ private
+
+ def sync_storage_data(storage_id, file_links)
+ storage = ::Storages::Storage.find(storage_id)
+ ::Storages::Peripherals::Registry
+ .resolve("#{storage.short_provider_type}.queries.files_info")
+ .call(storage:, auth_strategy:, file_ids: file_links.map(&:origin_id))
+ .map { |file_infos| to_hash(file_infos) }
+ .match(
+ on_success: set_file_link_status(file_links),
+ on_failure: lambda { |_|
+ ServiceResult.success(result: file_links.map do |file_link|
+ file_link.origin_status = :error
+ file_link
+ end)
+ }
+ )
+ end
- private
-
- def sync_storage_data(storage_id, file_links)
- storage = ::Storages::Storage.find(storage_id)
- ::Storages::Peripherals::Registry
- .resolve("#{storage.short_provider_type}.queries.files_info")
- .call(storage:, auth_strategy:, file_ids: file_links.map(&:origin_id))
- .map { |file_infos| to_hash(file_infos) }
- .match(
- on_success: set_file_link_status(file_links),
- on_failure: ->(_) {
- ServiceResult.success(result: file_links.map do |file_link|
- file_link.origin_status = :error
- file_link
- end)
- }
- )
- end
+ def auth_strategy
+ Storages::Peripherals::StorageInteraction::AuthenticationStrategies::OAuthUserToken
+ .strategy
+ .with_user(@user)
+ end
- def auth_strategy
- Storages::Peripherals::StorageInteraction::AuthenticationStrategies::OAuthUserToken
- .strategy
- .with_user(@user)
- end
+ def to_hash(file_infos)
+ file_infos.index_by { |file_info| file_info.id.to_s }.to_h
+ end
- def to_hash(file_infos)
- file_infos.index_by { |file_info| file_info.id.to_s }.to_h
- end
+ def set_file_link_status(file_links)
+ lambda do |file_infos|
+ resulting_file_links = []
- def set_file_link_status(file_links)
- ->(file_infos) do
- resulting_file_links = []
+ file_links.each do |file_link|
+ file_info = file_infos[file_link.origin_id]
- file_links.each do |file_link|
- file_info = file_infos[file_link.origin_id]
+ case file_info.status_code
+ when 200
+ update_file_link(file_link, file_info)
- case file_info.status_code
- when 200
- update_file_link(file_link, file_info)
+ file_link.origin_status = :view_allowed
+ when 403
+ file_link.origin_status = :view_not_allowed
+ when 404
+ file_link.origin_status = :not_found
+ else
+ file_link.origin_status = :error
+ end
- file_link.origin_status = :view_allowed
- when 403
- file_link.origin_status = :view_not_allowed
- when 404
- file_link.origin_status = :not_found
- else
- file_link.origin_status = :error
+ resulting_file_links << file_link
+ file_link.save
end
- resulting_file_links << file_link
- file_link.save
+ ServiceResult.success(result: resulting_file_links)
end
-
- ServiceResult.success(result: resulting_file_links)
end
- end
- def update_file_link(file_link, file_info)
- file_link.origin_mime_type = file_info.mime_type
- file_link.origin_created_by_name = file_info.owner_name
- file_link.origin_last_modified_by_name = file_info.last_modified_by_name
- file_link.origin_name = file_info.name
- file_link.origin_created_at = file_info.created_at
- file_link.origin_updated_at = file_info.last_modified_at
+ def update_file_link(file_link, file_info)
+ file_link.origin_mime_type = file_info.mime_type
+ file_link.origin_created_by_name = file_info.owner_name
+ file_link.origin_last_modified_by_name = file_info.last_modified_by_name
+ file_link.origin_name = file_info.name
+ file_link.origin_created_at = file_info.created_at
+ file_link.origin_updated_at = file_info.last_modified_at
- file_link
+ file_link
+ end
end
end
diff --git a/modules/storages/app/services/storages/upload_link_service.rb b/modules/storages/app/services/storages/upload_link_service.rb
new file mode 100644
index 00000000000..fd0bff61f8c
--- /dev/null
+++ b/modules/storages/app/services/storages/upload_link_service.rb
@@ -0,0 +1,56 @@
+# frozen_string_literal: true
+
+#-- copyright
+#++
+
+module Storages
+ class UploadLinkService < BaseService
+ def self.call(user:, storage:, upload_data:)
+ new(storage).call(user:, upload_data:)
+ end
+
+ def initialize(storage)
+ super()
+ @storage = storage
+ end
+
+ def call(user:, upload_data:)
+ with_tagged_logger do
+ info "Validating upload information"
+ input = validate_input(**upload_data).value_or { return @result }
+
+ info "Upload data validated..."
+ info "Requesting an upload link to #{@storage.name}"
+ upload_link = request_upload_link(auth_strategy(user), input).on_failure { return @result }.result
+
+ @result.result = upload_link
+ @result
+ end
+ end
+
+ private
+
+ def request_upload_link(auth_strategy, upload_data)
+ Peripherals::Registry
+ .resolve("#{@storage.short_provider_type}.queries.upload_link")
+ .call(storage: @storage, auth_strategy:, upload_data:)
+ .on_failure do |error|
+ add_error(:base, error.errors, options: { storage_name: @storage.name, folder: upload_data.folder_id })
+ log_storage_error(error.errors)
+ @result.success = false
+ end
+ end
+
+ def validate_input(...)
+ Peripherals::StorageInteraction::Inputs::UploadData.build(...).alt_map do |failure|
+ error failure.inspect
+ @result.add_error(:base, :invalid, options: failure.to_h)
+ @result.success = false
+ end
+ end
+
+ def auth_strategy(user)
+ Peripherals::Registry.resolve("#{@storage.short_provider_type}.authentication.userbound").call(user:)
+ end
+ end
+end
diff --git a/modules/storages/config/locales/en.yml b/modules/storages/config/locales/en.yml
index 130c171126b..a78f6dca199 100644
--- a/modules/storages/config/locales/en.yml
+++ b/modules/storages/config/locales/en.yml
@@ -91,10 +91,14 @@ en:
remote_folders: 'Read contents of the group folder:'
rename_project_folder: 'Rename managed project Folder:'
errors:
+ messages:
+ error: An unexpected error occurred. Please check OpenProject logs for more information or contact an administrator
+ unauthorized: OpenProject could not authenticate with the Storage Provider. Please ensure that you have access to it.
models:
+ upload_link_service:
+ not_found: The destination folder %{folder} could not be found on %{storage_name}.
copy_project_folders_service:
conflict: The folder %{destination_path} already exists. Interrupting process to avoid overwrites.
- error: An unexpected error occurred. Please check OpenProject logs for more information or contact an administrator
forbidden: OpenProject could not access the source folder. Please check your permissions configuration on the Storage Provider
not_found: The source template location %{source_path} wasn't found.
unauthorized: OpenProject could not authenticate with the Storage Provider. Please check your storage configuration
diff --git a/modules/storages/lib/api/v3/storage_files/storage_files_api.rb b/modules/storages/lib/api/v3/storage_files/storage_files_api.rb
index 2ff326bd339..44278291ebf 100644
--- a/modules/storages/lib/api/v3/storage_files/storage_files_api.rb
+++ b/modules/storages/lib/api/v3/storage_files/storage_files_api.rb
@@ -38,25 +38,22 @@ module API::V3::StorageFiles
helpers do
def validate_upload_request(body)
if Storages::Storage::one_drive_without_ee_token?(@storage.provider_type)
- log_message = "The request can not be handled due to invalid or missing Enterprise token."
- return ServiceResult.failure(errors: Storages::StorageError.new(code: :missing_ee_token_for_one_drive, log_message:))
+ raise API::Errors::EnterpriseTokenMissing.new
end
case body.transform_keys(&:to_sym)
in { projectId: project_id, fileName: file_name, parent: parent }
authorize_in_project(:manage_file_links, project: Project.find(project_id))
- ServiceResult.success(result: Storages::UploadData.new(folder_id: parent, file_name:))
+ ServiceResult.success(result: { folder_id: parent, file_name: })
else
- ServiceResult.failure(errors: Storages::StorageError.new(code: :bad_request,
- log_message: "Request body malformed!"))
+ raise API::Errors::BadRequest.new("Request body malformed!")
end
end
def fetch_upload_link
- ->(upload_data) do
- Storages::Peripherals::Registry
- .resolve("#{@storage.short_provider_type}.queries.upload_link")
- .call(storage: @storage, auth_strategy:, upload_data:)
+ lambda do |upload_data|
+ Rails.logger.error "UploadLink #{upload_data.inspect}"
+ Storages::UploadLinkService.call(storage: @storage, upload_data:, user: current_user)
end
end
@@ -85,7 +82,7 @@ module API::V3::StorageFiles
.call(storage: @storage, auth_strategy:, file_id: params[:file_id])
.map { |file_info| to_storage_file(file_info) }
.match(
- on_success: ->(storage_file) {
+ on_success: lambda { |storage_file|
API::V3::StorageFiles::StorageFileRepresenter.new(storage_file, @storage, current_user:)
},
on_failure: ->(error) { raise_error(error) }
@@ -97,7 +94,7 @@ module API::V3::StorageFiles
result = validate_upload_request(request_body) >> fetch_upload_link
result.match(
on_success: ->(link) { API::V3::StorageFiles::StorageUploadLinkRepresenter.new(link, current_user:) },
- on_failure: ->(error) { raise_error(error) }
+ on_failure: ->(error) { raise_service_result_error(error) }
)
end
end
diff --git a/modules/storages/spec/requests/api/v3/storages/storage_files_api_spec.rb b/modules/storages/spec/requests/api/v3/storages/storage_files_api_spec.rb
index d7a2f06912d..5998e090502 100644
--- a/modules/storages/spec/requests/api/v3/storages/storage_files_api_spec.rb
+++ b/modules/storages/spec/requests/api/v3/storages/storage_files_api_spec.rb
@@ -257,10 +257,8 @@ RSpec.describe "API v3 storage files", :webmock, content_type: :json do
describe "with successful response" do
before do
- Storages::Peripherals::Registry.stub(
- "nextcloud.queries.upload_link",
- ->(_) { ServiceResult.success(result: upload_link) }
- )
+ Storages::Peripherals::Registry
+ .stub("nextcloud.queries.upload_link", ->(_) { ServiceResult.success(result: upload_link) })
end
subject { last_response.body }
@@ -287,7 +285,7 @@ RSpec.describe "API v3 storage files", :webmock, content_type: :json do
describe "due to authorization failure" do
let(:error) { :unauthorized }
- it { expect(last_response).to have_http_status(:internal_server_error) }
+ it { expect(last_response).to have_http_status(:unauthorized) }
end
describe "due to internal error" do
@@ -303,7 +301,8 @@ RSpec.describe "API v3 storage files", :webmock, content_type: :json do
expect(last_response).to have_http_status(:internal_server_error)
body = JSON.parse(last_response.body)
- expect(body["message"]).to eq(I18n.t("api_v3.errors.code_500_outbound_request_failure", status_code: 404))
+ expect(body["message"]).to eq(I18n.t("services.errors.models.upload_link_service.not_found",
+ folder: "/Pictures", storage_name: storage.name))
expect(body["errorIdentifier"]).to eq("urn:openproject-org:api:v3:errors:OutboundRequest:NotFound")
end
end