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
[37868] Whitelist for attachment mime types and extensions on upload (#9431)
Oliver Günthere9d7c374ccc5
diff --git a/app/contracts/attachments/create_contract.rb b/app/contracts/attachments/create_contract.rbnew file mode 100644index 00000000000..6c7c36078ce--- /dev/null+++ b/app/contracts/attachments/create_contract.rb@@ -0,0 +1,98 @@+#-- encoding: UTF-8++#-- copyright+# OpenProject is an open source project management software.+# Copyright (C) 2012-2021 the OpenProject GmbH+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License version 3.+#+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:+# Copyright (C) 2006-2013 Jean-Philippe Lang+# Copyright (C) 2010-2013 the ChiliProject Team+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License+# as published by the Free Software Foundation; either version 2+# of the License, or (at your option) any later version.+#+# This program is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU General Public License+# along with this program; if not, write to the Free Software+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.+#+# See docs/COPYRIGHT.rdoc for more details.+#++++module Attachments+ class CreateContract < ::ModelContract+ attribute :file+ attribute :filename+ attribute :filesize+ attribute :digest+ attribute :description+ attribute :content_type+ attribute :container+ attribute :container_type+ attribute :author++ validates :filename, presence: true++ validate :validate_attachments_addable+ validate :validate_container_addable+ validate :validate_author+ validate :validate_content_type++ private++ def validate_attachments_addable+ return if model.container++ if Redmine::Acts::Attachable.attachables.none?(&:attachments_addable?)+ errors.add(:base, :error_unauthorized)+ end+ end++ def validate_author+ unless model.author == user+ errors.add(:author, :invalid)+ end+ end++ def validate_container_addable+ return unless model.container++ errors.add(:base, :error_unauthorized) unless model.container.attachments_addable?(user)+ end++ ##+ # Validates the content type, if a whitelist is set+ def validate_content_type+ # If the whitelist is empty, assume all files are allowed+ # as before+ unless matches_whitelist?(attachment_whitelist)+ Rails.logger.info { "Uploaded file #{model.filename} with type #{model.content_type} does not match whitelist" }+ errors.add :content_type, :not_whitelisted, value: model.content_type+ end+ end++ ##+ # Get the user-defined whitelist or a custom whitelist+ # defined for this invocation+ def attachment_whitelist+ Array(options.fetch(:whitelist, Setting.attachment_whitelist))+ end++ ##+ # Returns whether the attachment matches the whitelist+ def matches_whitelist?(whitelist)+ return true if whitelist.empty?++ whitelist.include?(model.content_type) || whitelist.include?("*#{model.extension}")+ end+ end+enddiff --git a/app/contracts/attachments/prepare_upload_contract.rb b/app/contracts/attachments/prepare_upload_contract.rbnew file mode 100644index 00000000000..91f6a717dee--- /dev/null+++ b/app/contracts/attachments/prepare_upload_contract.rb@@ -0,0 +1,41 @@+#-- encoding: UTF-8++#-- copyright+# OpenProject is an open source project management software.+# Copyright (C) 2012-2021 the OpenProject GmbH+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License version 3.+#+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:+# Copyright (C) 2006-2013 Jean-Philippe Lang+# Copyright (C) 2010-2013 the ChiliProject Team+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License+# as published by the Free Software Foundation; either version 2+# of the License, or (at your option) any later version.+#+# This program is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU General Public License+# along with this program; if not, write to the Free Software+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.+#+# See docs/COPYRIGHT.rdoc for more details.+#++++module Attachments+ class PrepareUploadContract < CreateContract+ validate :validate_direct_uploads_active++ private++ def validate_direct_uploads_active+ errors.add :base, :not_available unless OpenProject::Configuration.direct_uploads?+ end+ end+enddiff --git a/app/contracts/base_contract.rb b/app/contracts/base_contract.rbindex be5bbe32ef2..ed2c12951fe 100644--- a/app/contracts/base_contract.rb+++ b/app/contracts/base_contract.rb@@ -82,7 +82,7 @@ class BaseContract < Disposable::Twinenddef attribute(attribute, options = {}, &block)- property attribute+ property attribute, options.slice(:readable)add_writable(attribute, options[:writeable])attribute_permission(attribute, options[:permission])diff --git a/app/contracts/wiki_pages/update_contract.rb b/app/contracts/wiki_pages/update_contract.rbnew file mode 100644index 00000000000..3aa737381de--- /dev/null+++ b/app/contracts/wiki_pages/update_contract.rb@@ -0,0 +1,32 @@+#-- copyright+# OpenProject is an open source project management software.+# Copyright (C) 2012-2021 the OpenProject GmbH+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License version 3.+#+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:+# Copyright (C) 2006-2013 Jean-Philippe Lang+# Copyright (C) 2010-2013 the ChiliProject Team+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License+# as published by the Free Software Foundation; either version 2+# of the License, or (at your option) any later version.+#+# This program is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU General Public License+# along with this program; if not, write to the Free Software+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.+#+# See docs/COPYRIGHT.rdoc for more details.+#++++module WikiPages+ class UpdateContract < BaseContract+ end+enddiff --git a/lib/api/v3/attachments/attachment_metadata_representer.rb b/app/controllers/admin/settings/attachments_settings_controller.rbsimilarity index 63%rename from lib/api/v3/attachments/attachment_metadata_representer.rbrename to app/controllers/admin/settings/attachments_settings_controller.rbindex 323bf60e69f..fcd768575d0 100644--- a/lib/api/v3/attachments/attachment_metadata_representer.rb+++ b/app/controllers/admin/settings/attachments_settings_controller.rb@@ -28,28 +28,19 @@# See docs/COPYRIGHT.rdoc for more details.#++-require 'roar/decorator'-require 'roar/json/hal'+module Admin::Settings+ class AttachmentsSettingsController < ::Admin::SettingsController+ menu_item :settings_attachments-module API- module V3- module Attachments- class AttachmentMetadataRepresenter < ::API::Decorators::Single- def initialize(attachment)- super(attachment, current_user: nil)- end+ def default_breadcrumb+ t(:'attributes.attachments')+ end- property :file_name- property :description,- getter: ->(*) {- ::API::Decorators::Formattable.new(description, plain: true)- },- setter: ->(fragment:, **) { self.description = fragment['raw'] },- render_nil: true+ private- property :content_type, render_nil: false- property :file_size, render_nil: false- property :digest, render_nil: false+ def settings_params+ super.tap do |settings|+ settings["attachment_whitelist"] = settings["attachment_whitelist"].split(/\r?\n/)endendenddiff --git a/app/controllers/concerns/attachable_service_call.rb b/app/controllers/concerns/attachable_service_call.rbnew file mode 100644index 00000000000..5803a95b191--- /dev/null+++ b/app/controllers/concerns/attachable_service_call.rb@@ -0,0 +1,66 @@+#-- copyright+# OpenProject is an open source project management software.+# Copyright (C) 2012-2021 the OpenProject GmbH+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License version 3.+#+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:+# Copyright (C) 2006-2013 Jean-Philippe Lang+# Copyright (C) 2010-2013 the ChiliProject Team+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License+# as published by the Free Software Foundation; either version 2+# of the License, or (at your option) any later version.+#+# This program is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU General Public License+# along with this program; if not, write to the Free Software+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.+#+# See docs/COPYRIGHT.rdoc for more details.+#++++module AttachableServiceCall+ ##+ # Call the presented CreateContract service+ # with the given params, merging in any attachment params+ #+ # @param service_cls the service class instance+ # @param args permitted args for the service call+ def attachable_create_call(service_cls, args:)+ service_cls+ .new(user: current_user)+ .call(args.merge(attachment_params))+ end++ ##+ # Call the presented UpdateContract service+ # with the given params, merging in any attachment params+ #+ # @param service_cls the service class instance+ # @param args permitted args for the service call+ def attachable_update_call(service_cls, model:, args:)+ service_cls+ .new(user: current_user, model: model)+ .call(args.merge(attachment_params))+ end++ ##+ # Attachable parameters mapped to a format the+ # SetReplacements service concern+ def attachment_params+ attachment_params = permitted_params.attachments.to_h++ if attachment_params.any?+ { attachment_ids: attachment_params.values.map(&:values).flatten }+ else+ {}+ end+ end+enddiff --git a/app/controllers/wiki_controller.rb b/app/controllers/wiki_controller.rbindex 03ffe95dec5..3ddfd161774 100644--- a/app/controllers/wiki_controller.rb+++ b/app/controllers/wiki_controller.rb@@ -57,6 +57,7 @@ class WikiController < ApplicationControllerbefore_action :handle_new_wiki_page, only: %i[show]before_action :build_wiki_page_and_content, only: %i[new create]+ include AttachableServiceCallinclude AttachmentsHelperinclude PaginationHelperinclude Redmine::MenuManager::WikiMenuHelper@@ -105,17 +106,18 @@ class WikiController < ApplicationControllerenddef create- @page.attributes = permitted_params.wiki_page+ call = attachable_create_call ::WikiPages::CreateService,+ args: permitted_params.wiki_page_with_content.to_h.merge(wiki: @wiki)- @content.attributes = permitted_params.wiki_content- @content.author = User.current- @page.attach_files(permitted_params.attachments.to_h)+ @page = call.result+ @content = @page.content- if @page.save+ if call.success?call_hook(:controller_wiki_edit_after_save, params: params, page: @page)flash[:notice] = I18n.t(:notice_successful_create)redirect_to_showelse+ @errors = call.errorsrender action: 'new'endend@@ -165,22 +167,21 @@ class WikiController < ApplicationControllerreturnend- @content = @page.content || @page.build_contentreturn if locked?- @page.attach_files(permitted_params.attachments.to_h)+ call = attachable_update_call ::WikiPages::UpdateService,+ model: @page,+ args: permitted_params.wiki_page_with_content.to_h- @page.title = permitted_params.wiki_page[:title]- @page.parent_id = permitted_params.wiki_page[:parent_id].presence- @content.attributes = permitted_params.wiki_content- @content.author = User.current- @content.add_journal User.current, params['content']['comments']+ @page = call.result+ @content = @page.content- if @page.save_with_content+ if call.success?call_hook(:controller_wiki_edit_after_save, params: params, page: @page)flash[:notice] = I18n.t(:notice_successful_update)redirect_to_showelse+ @errors = call.errorsrender action: 'edit'endrescue ActiveRecord::StaleObjectErrordiff --git a/app/helpers/settings_helper.rb b/app/helpers/settings_helper.rbindex 94cca1dbbdb..ff50fb10352 100644--- a/app/helpers/settings_helper.rb+++ b/app/helpers/settings_helper.rb@@ -51,6 +51,11 @@ module SettingsHelpercontroller: '/admin/settings/projects_settings',label: :label_project_plural},+ {+ name: 'attachments',+ controller: '/admin/settings/attachments_settings',+ label: :'attributes.attachments'+ },{name: 'api',controller: '/admin/settings/api_settings',diff --git a/app/models/attachment.rb b/app/models/attachment.rbindex 15f32c7810e..3ad52806285 100644--- a/app/models/attachment.rb+++ b/app/models/attachment.rb@@ -47,8 +47,8 @@ class Attachment < ApplicationRecordacts_as_journalizedacts_as_event title: -> { file.name },url: (Proc.new do |o|- { controller: '/attachments', action: 'download', id: o.id, filename: o.filename }- end)+ { controller: '/attachments', action: 'download', id: o.id, filename: o.filename }+ end)mount_uploader :file, OpenProject::Configuration.file_uploader@@ -148,7 +148,7 @@ class Attachment < ApplicationRecordenddef filename- attributes['file']+ attributes['file'] || superend##@@ -175,9 +175,7 @@ class Attachment < ApplicationRecordenddef set_content_type(file)- return if content_type.present?-- self.content_type = file.try(:content_type) || self.class.content_type_for(file.path)+ self.content_type = self.class.content_type_for(file.path)enddef set_digest(file)@@ -255,37 +253,6 @@ class Attachment < ApplicationRecordwhere(digest: "", downloads: -1)end- def self.create_pending_direct_upload(file_name:, author:, container: nil, content_type: nil, file_size: 0)- a = create(- container: container,- author: author,- content_type: content_type.presence || "application/octet-stream",- filesize: file_size,- digest: "",- downloads: -1- )-- # We need to do it like this because `file` is an uploader which expects a File (not a string)- # to upload usually. But in this case the data has already been uploaded and we just point to it.- a[:file] = pending_direct_upload_filename(file_name)-- a.save!- a.reload # necessary so that the fog file uploader path is correct-- a- end-- class << self- private-- # The name has to be in the same format as what Carrierwave will produce later on. If they are different,- # Carrierwave will alter the name (both local and remote) whenever the attachment is saved with the remote- # file loaded.- def pending_direct_upload_filename(file_name)- CarrierWave::SanitizedFile.new(nil).send(:sanitize, file_name)- end- end-def pending_direct_upload?digest == "" && downloads == -1end@@ -293,7 +260,7 @@ class Attachment < ApplicationRecordprivatedef filesize_below_allowed_maximum- if filesize > Setting.attachment_max_size.to_i.kilobytes+ if filesize.to_i > Setting.attachment_max_size.to_i.kilobyteserrors.add(:file, :file_too_large, count: Setting.attachment_max_size.to_i.kilobytes)endenddiff --git a/app/models/mail_handler.rb b/app/models/mail_handler.rbindex d421d6cc1fc..085ab296b39 100644--- a/app/models/mail_handler.rb+++ b/app/models/mail_handler.rb@@ -272,9 +272,15 @@ class MailHandler < ActionMailer::Basebinary: true)- ::Attachments::CreateService- .new(container, author: user)- .call(uploaded_file: file, description: nil)+ call = ::Attachments::CreateService+ .new(user: user)+ .call(container: container, filename: attachment.filename, file: file)++ call.on_failure do+ log "Failed to add attachment #{attachment.filename} for [#{sender_email}]: #{call.message}"+ end++ call.resultend# Adds To and Cc as watchers of the given object if the sender has thediff --git a/app/models/permitted_params.rb b/app/models/permitted_params.rbindex caf3fcf9275..0adf15b41b9 100644--- a/app/models/permitted_params.rb+++ b/app/models/permitted_params.rb@@ -252,6 +252,10 @@ class PermittedParamsparams.require(:content).permit(*self.class.permitted_attributes[:wiki_content])end+ def wiki_page_with_content+ wiki_page.merge(wiki_content)+ end+def prefparams.fetch(:pref, {}).permit(:hide_mail, :time_zone, :theme,:comments_sorting, :warn_on_leaving_unsaved,diff --git a/app/services/attachments/build_service.rb b/app/services/attachments/build_service.rbnew file mode 100644index 00000000000..9a725f571bf--- /dev/null+++ b/app/services/attachments/build_service.rb@@ -0,0 +1,51 @@+#-- copyright+# OpenProject is an open source project management software.+# Copyright (C) 2012-2021 the OpenProject GmbH+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License version 3.+#+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:+# Copyright (C) 2006-2013 Jean-Philippe Lang+# Copyright (C) 2010-2013 the ChiliProject Team+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License+# as published by the Free Software Foundation; either version 2+# of the License, or (at your option) any later version.+#+# This program is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU General Public License+# along with this program; if not, write to the Free Software+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.+#+# See docs/COPYRIGHT.rdoc for more details.+#++++module Attachments+ class BuildService < ::BaseServices::Create+ private++ def persist(service_result)+ attachment = service_result.result+ add_to_association(attachment)++ unless attachment.valid?+ service_result.errors = attachment.errors+ service_result.success = false+ end++ service_result+ end++ def add_to_association(attachment)+ return unless attachment.container++ attachment.container.association(:attachments).add_to_target(attachment)+ end+ end+enddiff --git a/app/services/attachments/create_service.rb b/app/services/attachments/create_service.rbindex 0671dc65a22..850f6c13e0e 100644--- a/app/services/attachments/create_service.rb+++ b/app/services/attachments/create_service.rb@@ -26,78 +26,74 @@# See docs/COPYRIGHT.rdoc for more details.#++-class Attachments::CreateService+class Attachments::CreateService < ::BaseServices::Createinclude Attachments::TouchContainer- attr_reader :container, :author-- def initialize(container, author:)- @container = container- @author = author- end+ around_call :error_wrapped_call##- # Adds and saves the uploaded file as attachment of the given container.- # In case the container supports it, a journal will be written.+ # Create an attachment service bypassing the user-provided whitelist+ # for internal purposes such as exporting data.+ #+ # @param user The user to call the service with+ # @param whitelist A custom whitelist to validate with, or empty to disable validation#- # An ActiveRecord::RecordInvalid error is raised if any record can't be saved.- def call(uploaded_file:, description:)- create_attachment(uploaded_file, description)- .tap(&method(:created_event))+ # Warning: When passing an empty whitelist, this results in no validations on the content type taking place.+ def self.bypass_whitelist(user:, whitelist: [])+ new(user: user, contract_options: { whitelist: whitelist.map(&:to_s) })end- private-- def create_attachment(uploaded_file, description)- if container.nil?- save_attachment(uploaded_file, description)- elsif container.class.journaled?- create_journalized(uploaded_file, description)+ def persist(call)+ attachment = call.result+ if attachment.container+ in_container_mutex(attachment.container) { super }else- create_unjournalized(uploaded_file, description)+ superendend- def create_journalized(uploaded_file, description)+ def in_container_mutex(container)OpenProject::Mutex.with_advisory_lock_transaction(container) do- save_attachment(uploaded_file, description).tap do+ yield.tap do# Get the latest attachments to ensure having them all for journalization.# We just created an attachment and a different worker might have added attachments# in the meantime, e.g when bulk uploading.container.attachments.reload-- touch(container)endendend- def create_unjournalized(uploaded_file, description)- save_attachment(uploaded_file, description).tap do- touch(container)- end- end+ def after_perform(call)+ attachment = call.result+ container = attachment.container- def save_attachment(uploaded_file, description)- attachment = Attachment.new(file: uploaded_file,- container: container,- description: description,- author: author)+ touch(container) unless container.nil?- attachment.save!- attachment- end-- def build_attachment(uploaded_file, description)- container.attachments.build(file: uploaded_file,- description: description,- content_type: uploaded_file.content_type,- author: author)- end-- def created_event(attachment)OpenProject::Notifications.send(OpenProject::Events::ATTACHMENT_CREATED,attachment: attachment)++ call+ end++ def error_wrapped_call+ yield+ rescue StandardError => e+ log_attachment_saving_error(e)++ message =+ if e&.class&.to_s == 'Errno::EACCES'+ I18n.t('api_v3.errors.unable_to_create_attachment_permissions')+ else+ I18n.t('api_v3.errors.unable_to_create_attachment')+ end+ raise message+ end++ def log_attachment_saving_error(error)+ message = "Failed to save attachment: #{error&.class} - #{error&.message || 'Unknown error'}"++ OpenProject.logger.error messageendenddiff --git a/app/services/attachments/prepare_upload_service.rb b/app/services/attachments/prepare_upload_service.rbnew file mode 100644index 00000000000..abc1a55c5b6--- /dev/null+++ b/app/services/attachments/prepare_upload_service.rb@@ -0,0 +1,48 @@+#-- copyright+# OpenProject is an open source project management software.+# Copyright (C) 2012-2021 the OpenProject GmbH+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License version 3.+#+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:+# Copyright (C) 2006-2013 Jean-Philippe Lang+# Copyright (C) 2010-2013 the ChiliProject Team+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License+# as published by the Free Software Foundation; either version 2+# of the License, or (at your option) any later version.+#+# This program is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU General Public License+# along with this program; if not, write to the Free Software+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.+#+# See docs/COPYRIGHT.rdoc for more details.+#++++module Attachments+ class PrepareUploadService < ::BaseServices::Create+ def persist(call)+ attachment = call.result++ if attachment.save+ attachment.reload # necessary so that the fog file uploader path is correct+ ServiceResult.new success: true, result: attachment+ else+ ServiceResult.new success: false, result: attachment+ end+ end++ private++ def attributes_service_class+ SetPreparedAttributesService+ end+ end+enddiff --git a/app/services/attachments/set_attributes_service.rb b/app/services/attachments/set_attributes_service.rbnew file mode 100644index 00000000000..3f7e5c5b522--- /dev/null+++ b/app/services/attachments/set_attributes_service.rb@@ -0,0 +1,43 @@+#-- encoding: UTF-8++#-- copyright+# OpenProject is an open source project management software.+# Copyright (C) 2012-2021 the OpenProject GmbH+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License version 3.+#+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:+# Copyright (C) 2006-2013 Jean-Philippe Lang+# Copyright (C) 2010-2013 the ChiliProject Team+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License+# as published by the Free Software Foundation; either version 2+# of the License, or (at your option) any later version.+#+# This program is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU General Public License+# along with this program; if not, write to the Free Software+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.+#+# See docs/COPYRIGHT.rdoc for more details.+#++++module Attachments+ class SetAttributesService < ::BaseServices::SetAttributes+ def set_attributes(params)+ # Don't set the content type manually,+ # we always want to infer it+ super params.except :content_type+ end++ def set_default_attributes(params)+ model.author = user if model.author.nil?+ end+ end+enddiff --git a/app/services/attachments/set_prepared_attributes_service.rb b/app/services/attachments/set_prepared_attributes_service.rbnew file mode 100644index 00000000000..f46d99334cc--- /dev/null+++ b/app/services/attachments/set_prepared_attributes_service.rb@@ -0,0 +1,66 @@+#-- encoding: UTF-8++#-- copyright+# OpenProject is an open source project management software.+# Copyright (C) 2012-2021 the OpenProject GmbH+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License version 3.+#+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:+# Copyright (C) 2006-2013 Jean-Philippe Lang+# Copyright (C) 2010-2013 the ChiliProject Team+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License+# as published by the Free Software Foundation; either version 2+# of the License, or (at your option) any later version.+#+# This program is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU General Public License+# along with this program; if not, write to the Free Software+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.+#+# See docs/COPYRIGHT.rdoc for more details.+#++++module Attachments+ class SetPreparedAttributesService < SetAttributesService+ private++ def set_attributes(params)+ super++ set_prepared_attributes params+ end++ def set_prepared_attributes(params)+ # We need to do it like this because `file` is an uploader which expects a File (not a string)+ # to upload usually. But in this case the data has already been uploaded and we just point to it.+ model[:file] = pending_direct_upload_filename(params[:filename])++ # Explicitly set the filesize from metadata+ # as the provided file is not actually uploaded+ model.filesize = params[:filesize]++ model.extend(OpenProject::ChangedBySystem)+ model.change_by_system do+ model.downloads = -1+ # Set a content type as the file is not present+ # The real content type will be set by FinishDirectUploadJob+ model.content_type = params[:content_type] || OpenProject::ContentTypeDetector::SENSIBLE_DEFAULT+ end+ end++ # The name has to be in the same format as what Carrierwave will produce later on. If they are different,+ # Carrierwave will alter the name (both local and remote) whenever the attachment is saved with the remote+ # file loaded.+ def pending_direct_upload_filename(filename)+ CarrierWave::SanitizedFile.new(nil).send(:sanitize, filename)+ end+ end+enddiff --git a/app/services/base_services/base_contracted.rb b/app/services/base_services/base_contracted.rbindex a2d688a2ced..25dbc8bf12a 100644--- a/app/services/base_services/base_contracted.rb+++ b/app/services/base_services/base_contracted.rb@@ -92,6 +92,7 @@ module BaseServices# nothing for now but subclasses can overridecallend+alias_method :after_save, :after_performdef persist(call)diff --git a/app/services/wiki_pages/create_service.rb b/app/services/wiki_pages/create_service.rbindex 6c138267d6e..8fd4e802d5b 100644--- a/app/services/wiki_pages/create_service.rb+++ b/app/services/wiki_pages/create_service.rb@@ -29,4 +29,5 @@#++class WikiPages::CreateService < ::BaseServices::Create+ include Attachments::ReplaceAttachmentsenddiff --git a/app/services/wiki_pages/set_attributes_service.rb b/app/services/wiki_pages/set_attributes_service.rbindex c3b89e7c115..64fd698d346 100644--- a/app/services/wiki_pages/set_attributes_service.rb+++ b/app/services/wiki_pages/set_attributes_service.rb@@ -36,6 +36,8 @@## Attributes for both the page as well as for the content are accepted.class WikiPages::SetAttributesService < ::BaseServices::SetAttributes+ include Attachments::SetReplacements+privatedef set_attributes(params)@@ -53,7 +55,7 @@ class WikiPages::SetAttributesService < ::BaseServices::SetAttributesenddef set_default_attributes(_params)- model.build_content+ model.build_content page: modelmodel.content.extend(OpenProject::ChangedBySystem)model.content.change_by_system do@@ -66,6 +68,10 @@ class WikiPages::SetAttributesService < ::BaseServices::SetAttributesenddef split_page_and_content_params(params)- params.partition { |p, _| WikiContent.column_names.include?(p) }.map(&:to_h)+ params.partition { |p, _| content_attribute?(p) }.map(&:to_h)+ end++ def content_attribute?(name)+ WikiContent.column_names.include?(name) || name.to_s == 'comments'endenddiff --git a/app/services/wiki_pages/update_service.rb b/app/services/wiki_pages/update_service.rbnew file mode 100644index 00000000000..c76009f09ad--- /dev/null+++ b/app/services/wiki_pages/update_service.rb@@ -0,0 +1,50 @@+#-- encoding: UTF-8++#-- copyright+# OpenProject is an open source project management software.+# Copyright (C) 2012-2021 the OpenProject GmbH+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License version 3.+#+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:+# Copyright (C) 2006-2013 Jean-Philippe Lang+# Copyright (C) 2010-2013 the ChiliProject Team+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License+# as published by the Free Software Foundation; either version 2+# of the License, or (at your option) any later version.+#+# This program is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU General Public License+# along with this program; if not, write to the Free Software+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.+#+# See docs/COPYRIGHT.rdoc for more details.+#++++class WikiPages::UpdateService < ::BaseServices::Update+ include Attachments::ReplaceAttachments++ private++ def persist(service_result)+ service_result = super(service_result)++ page = service_result.result+ content = page.content++ unless page.save && content.save+ service_result.errors = page.errors+ service_result.errors.merge! content.errors+ service_result.success = false+ end++ service_result+ end+enddiff --git a/app/views/admin/settings/attachments_settings/show.html.erb b/app/views/admin/settings/attachments_settings/show.html.erbnew file mode 100644index 00000000000..f31ac9d4994--- /dev/null+++ b/app/views/admin/settings/attachments_settings/show.html.erb@@ -0,0 +1,48 @@+<%#-- copyright+OpenProject is an open source project management software.+Copyright (C) 2012-2021 the OpenProject GmbH++This program is free software; you can redistribute it and/or+modify it under the terms of the GNU General Public License version 3.++OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:+Copyright (C) 2006-2013 Jean-Philippe Lang+Copyright (C) 2010-2013 the ChiliProject Team++This program is free software; you can redistribute it and/or+modify it under the terms of the GNU General Public License+as published by the Free Software Foundation; either version 2+of the License, or (at your option) any later version.++This program is distributed in the hope that it will be useful,+but WITHOUT ANY WARRANTY; without even the implied warranty of+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+GNU General Public License for more details.++You should have received a copy of the GNU General Public License+along with this program; if not, write to the Free Software+Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.++See docs/COPYRIGHT.rdoc for more details.++++#%>+<%= toolbar title: t(:'attributes.attachments') %>++<%= styled_form_tag(admin_settings_update_attachments_path, method: :patch) do %>+ <section class="form--section">+ <div class="form--field">+ <%= setting_text_field :attachment_max_size, size: 6, unit: t(:"number.human.storage_units.units.kb"), container_class: '-slim' %>+ </div>+ <div class="form--field">+ <%= setting_text_area :attachment_whitelist, rows: 5, container_class: '-wide' %>+ <div class="form--field-instructions">+ <%= t('settings.attachments.whitelist_text_html',+ ext_example: '*.jpg',+ mime_example: 'image/jpeg',+ ) %>+ </div>+ </div>+ </section>++ <%= styled_button_tag t(:button_save), class: '-highlight -with-icon icon-checkmark' %>+<% end %>diff --git a/app/views/admin/settings/general_settings/show.html.erb b/app/views/admin/settings/general_settings/show.html.erbindex 22fbf8d682c..2ab2f7c1e51 100644--- a/app/views/admin/settings/general_settings/show.html.erb+++ b/app/views/admin/settings/general_settings/show.html.erb@@ -31,9 +31,6 @@ See docs/COPYRIGHT.rdoc for more details.<%= styled_form_tag(admin_settings_update_general_path, method: :patch) do %><section class="form--section"><div class="form--field"><%= setting_text_field :app_title, size: 30, container_class: '-middle' %></div>- <div class="form--field">- <%= setting_text_field :attachment_max_size, size: 6, unit: t(:"number.human.storage_units.units.kb"), container_class: '-slim' %>- </div><div class="form--field"><%= setting_text_field :per_page_options, size: 20, container_class: '-slim' %><span class="form--field-instructions">diff --git a/app/views/wiki/_page_form.html.erb b/app/views/wiki/_page_form.html.erbindex 41b39cd47b6..d5f8c8c369d 100644--- a/app/views/wiki/_page_form.html.erb+++ b/app/views/wiki/_page_form.html.erb@@ -1,4 +1,4 @@-<%= error_messages_for 'page' %>+<%= error_messages_for_contract @page, @errors %><% resource = ::API::V3::WikiPages::WikiPageRepresenter.new(@page, current_user: current_user, embed_links: true) %>diff --git a/app/workers/attachments/finish_direct_upload_job.rb b/app/workers/attachments/finish_direct_upload_job.rbindex f1893f00e5a..0b319208d16 100644--- a/app/workers/attachments/finish_direct_upload_job.rb+++ b/app/workers/attachments/finish_direct_upload_job.rb@@ -55,9 +55,9 @@ class Attachments::FinishDirectUploadJob < ApplicationJobdef set_attributes_from_file(attachment, local_file)attachment.downloads = 0- attachment.set_file_size local_file unless attachment.filesize && attachment.filesize > 0- attachment.set_content_type local_file unless attachment.content_type.present?- attachment.set_digest local_file unless attachment.digest.present?+ attachment.set_file_size local_file+ attachment.set_content_type local_file+ attachment.set_digest local_fileenddef save_attachment(attachment)diff --git a/app/workers/backup_job.rb b/app/workers/backup_job.rbindex b5e76b448ba..9d951833398 100644--- a/app/workers/backup_job.rb+++ b/app/workers/backup_job.rb@@ -120,17 +120,24 @@ class BackupJob < ::ApplicationJobdef store_backup(file_name, backup:, user:)File.open(file_name) do |file|- attachment = Attachments::CreateService- .new(backup, author: user)- .call(uploaded_file: file, description: 'OpenProject backup')-- download_url = ::API::V3::Utilities::PathHelper::ApiV3Path.attachment_content(attachment.id)+ call = Attachments::CreateService+ .bypass_whitelist(user: user)+ .call(container: backup, filename: file_name, file: file, description: 'OpenProject backup')++ call.on_success do+ download_url = ::API::V3::Utilities::PathHelper::ApiV3Path.attachment_content(call.result.id)++ upsert_status(+ status: :success,+ message: I18n.t('export.succeeded'),+ payload: download_payload(download_url)+ )+ end- upsert_status(- status: :success,- message: I18n.t('export.succeeded'),- payload: download_payload(download_url)- )+ call.on_failure do+ upsert_status status: :failure,+ message: I18n.t('export.failed', message: call.message)+ endendenddiff --git a/app/workers/extract_fulltext_job.rb b/app/workers/extract_fulltext_job.rbindex 7fbbb7f0932..975cac15bf9 100644--- a/app/workers/extract_fulltext_job.rb+++ b/app/workers/extract_fulltext_job.rb@@ -81,7 +81,7 @@ class ExtractFulltextJob < ApplicationJobenddef find_attachment(id)- Attachment.find_by_id id+ Attachment.find_by(id: id)enddef remote_file?diff --git a/app/workers/work_packages/exports/export_job.rb b/app/workers/work_packages/exports/export_job.rbindex f98f10ef079..ea09c48680d 100644--- a/app/workers/work_packages/exports/export_job.rb+++ b/app/workers/work_packages/exports/export_job.rb@@ -88,16 +88,23 @@ module WorkPackagesendend- def store_attachment(storage, file)- attachment = Attachments::CreateService- .new(storage, author: User.current)- .call(uploaded_file: file, description: '')+ def store_attachment(container, file)+ call = Attachments::CreateService+ .bypass_whitelist(user: User.current)+ .call(container: container, file: file, filename: File.basename(file), description: '')- download_url = ::API::V3::Utilities::PathHelper::ApiV3Path.attachment_content(attachment.id)+ call.on_success do+ download_url = ::API::V3::Utilities::PathHelper::ApiV3Path.attachment_content(call.result.id)- upsert_status status: :success,- message: I18n.t('export.succeeded'),- payload: download_payload(download_url)+ upsert_status status: :success,+ message: I18n.t('export.succeeded'),+ payload: download_payload(download_url)+ end++ call.on_failure do+ upsert_status status: :failure,+ message: I18n.t('export.failed', message: call.message)+ endendendenddiff --git a/config/locales/en.yml b/config/locales/en.ymlindex 12013d038f4..3fe202a7d98 100644--- a/config/locales/en.yml+++ b/config/locales/en.yml@@ -613,6 +613,7 @@ en:invalid_url: 'is not a valid URL.'invalid_url_scheme: 'is not a supported protocol (allowed: %{allowed_schemes}).'less_than_or_equal_to: "must be less than or equal to %{count}."+ not_available: "is not available due to a system configuration."not_deletable: "cannot be deleted."not_current_user: "is not the current user."not_a_date: "is not a valid date."@@ -632,6 +633,10 @@ en:unremovable: "cannot be removed."wrong_length: "is the wrong length (should be %{count} characters)."models:+ attachment:+ attributes:+ content_type:+ not_whitelisted: "is set to '%{value}', which is not whitelisted for uploading."capability:context:global: 'Global'@@ -1271,6 +1276,7 @@ en:export:your_work_packages_export: "Your work packages export"succeeded: "The export has completed successfully."+ failed: "The export has failed: %{message}"format:atom: "Atom"csv: "CSV"@@ -2351,6 +2357,7 @@ en:setting_apiv3_docs_enabled_instructions_html: >If the docs page is enabled you can get an interactive view of the APIv3 documentation under<a href="%{link}" target="_blank">%{link}</a>.+ setting_attachment_whitelist: "Attachment upload whitelist"setting_email_delivery_method: "Email delivery method"setting_sendmail_location: "Location of the sendmail executable"setting_smtp_enable_starttls_auto: "Automatically use STARTTLS if available"@@ -2467,6 +2474,14 @@ en:passwords: "Passwords"session: "Session"brute_force_prevention: "Automated user blocking"+ attachments:+ whitelist_text_html: >+ Define a list of valid file extensions and/or mime types for uploaded files.+ <br/>+ Enter file extensions (e.g., <code>%{ext_example}</code>) or mime types (e.g., <code>%{mime_example}</code>).+ <br/>+ Leave empty to allow any file type to be uploaded.+ Multiple values allowed (one line for each value).notifications:retention_text: >Set the number of days notification events for users (the source for in-app notifications)diff --git a/config/settings.yml b/config/settings.ymlindex 462ba83b956..d4394789621 100644--- a/config/settings.yml+++ b/config/settings.yml@@ -388,3 +388,6 @@ notification_retention_period_days:notification_email_delay_minutes:default: 15format: int+attachment_whitelist:+ serialized: true+ default: []diff --git a/lib/api/utilities/endpoints/bodied.rb b/lib/api/utilities/endpoints/bodied.rbindex c5e2ca2697c..6e207559ea3 100644--- a/lib/api/utilities/endpoints/bodied.rb+++ b/lib/api/utilities/endpoints/bodied.rb@@ -46,11 +46,19 @@ module APIendend+ def default_params_source+ ->(request) do+ request.request_body+ end+ end+def initialize(model:,api_name: model.name.demodulize,instance_generator: default_instance_generator(model),params_modifier: default_params_modifier,+ params_source: default_params_source,process_state: default_process_state,+ before_hook: nil,parse_representer: nil,render_representer: nil,process_service: nil,@@ -60,18 +68,21 @@ module APIself.api_name = api_nameself.instance_generator = instance_generatorself.params_modifier = params_modifier+ self.params_source = params_sourceself.process_state = process_stateself.parse_representer = parse_representer || deduce_parse_representerself.render_representer = render_representer || deduce_render_representerself.process_contract = process_contract || deduce_process_contractself.process_service = process_service || deduce_process_serviceself.parse_service = parse_service || deduce_parse_service+ self.before_hook = before_hookenddef mountupdate = self-> do+ update.before_hook&.(request: self)params = update.parse(self)call = update.process(self, params)@@ -86,7 +97,7 @@ module API.new(request.current_user,model: model,representer: parse_representer)- .call(request.request_body)+ .call(params_source.call(request)).resultend@@ -121,11 +132,13 @@ module API:instance_generator,:parse_representer,:render_representer,+ :params_source,:params_modifier,:process_contract,:process_service,:parse_service,- :process_state+ :process_state,+ :before_hookprivatediff --git a/lib/api/v3/attachments/attachment_parsing_representer.rb b/lib/api/v3/attachments/attachment_parsing_representer.rbnew file mode 100644index 00000000000..563d496ce0d--- /dev/null+++ b/lib/api/v3/attachments/attachment_parsing_representer.rb@@ -0,0 +1,71 @@+#-- encoding: UTF-8++#-- copyright+# OpenProject is an open source project management software.+# Copyright (C) 2012-2021 the OpenProject GmbH+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License version 3.+#+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:+# Copyright (C) 2006-2013 Jean-Philippe Lang+# Copyright (C) 2010-2013 the ChiliProject Team+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License+# as published by the Free Software Foundation; either version 2+# of the License, or (at your option) any later version.+#+# This program is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU General Public License+# along with this program; if not, write to the Free Software+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.+#+# See docs/COPYRIGHT.rdoc for more details.+#++++require 'roar/decorator'+require 'roar/json/hal'++module API+ module V3+ module Attachments+ class AttachmentParsingRepresenter < ::API::Decorators::Single+ nested :metadata do+ property :filename,+ as: :fileName++ property :description,+ getter: ->(*) {+ ::API::Decorators::Formattable.new(description, plain: true)+ },+ setter: ->(fragment:, **) { self.description = fragment['raw'] },+ render_nil: true++ property :content_type,+ as: :contentType,+ render_nil: false++ property :filesize,+ as: :fileSize,+ render_nil: false++ property :digest,+ render_nil: false+ end++ property :file,+ setter: ->(fragment:, represented:, doc:, **) {+ filename = represented.filename || doc.dig('metadata', 'fileName')+ self.file = OpenProject::Files.build_uploaded_file fragment[:tempfile],+ fragment[:type],+ file_name: filename+ }+ end+ end+ end+enddiff --git a/lib/api/v3/attachments/attachment_upload_representer.rb b/lib/api/v3/attachments/attachment_upload_representer.rbindex 3cbe0742d7e..01bdf1e0655 100644--- a/lib/api/v3/attachments/attachment_upload_representer.rb+++ b/lib/api/v3/attachments/attachment_upload_representer.rb@@ -69,7 +69,7 @@ module APIattr_reader :form_url, :form_fields, :attachment- def initialize(attachment, current_user:)+ def initialize(attachment, current_user:, embed_links: false)superfog_hash = DirectFogUploader.direct_fog_hash attachment: attachmentdiff --git a/lib/api/v3/attachments/attachments_api.rb b/lib/api/v3/attachments/attachments_api.rbindex e4cb927667b..f2a1bc8eb8f 100644--- a/lib/api/v3/attachments/attachments_api.rb+++ b/lib/api/v3/attachments/attachments_api.rb@@ -39,25 +39,12 @@ module APIdef containernilend-- def check_attachments_addable- raise API::Errors::Unauthorized if Redmine::Acts::Attachable.attachables.none?(&:attachments_addable?)- endend- post do- check_attachments_addable-- ::API::V3::Attachments::AttachmentRepresenter.new(parse_and_create, current_user: current_user)- end+ post &API::V3::Attachments::AttachmentsByContainerAPI.createnamespace :prepare do- post do- require_direct_uploads- check_attachments_addable-- ::API::V3::Attachments::AttachmentUploadRepresenter.new(parse_and_prepare, current_user: current_user)- end+ post &API::V3::Attachments::AttachmentsByContainerAPI.prepareendroute_param :id, type: Integer, desc: 'Attachment ID' dodiff --git a/lib/api/v3/attachments/attachments_by_container_api.rb b/lib/api/v3/attachments/attachments_by_container_api.rbindex 745096e05ff..bb506529d96 100644--- a/lib/api/v3/attachments/attachments_by_container_api.rb+++ b/lib/api/v3/attachments/attachments_by_container_api.rb@@ -47,114 +47,20 @@ module APIrequest.env['REQUEST_METHOD'] == 'POST'end- def parse_metadata(json)- return nil unless json-- metadata = OpenStruct.new- ::API::V3::Attachments::AttachmentMetadataRepresenter.new(metadata).from_json(json)-- unless metadata.file_name- raise ::API::Errors::Validation.new(- :file_name,- "fileName #{I18n.t('activerecord.errors.messages.blank')}"- )- end-- metadata+ ##+ # Additionally to what would be checked by the contract,+ # we need to restrict permissions in some use cases of the mounts of this endpoint.+ def restrict_permissions(permissions)+ authorize_any(permissions, projects: container.project) unless permissions.empty?end+ end- def parse_and_prepare- metadata = parse_metadata params[:metadata]-- unless metadata- raise ::API::Errors::InvalidRequestBody.new(I18n.t('api_v3.errors.multipart_body_error'))- end-- unless metadata.file_size- raise ::API::Errors::Validation.new(- :file_size,- "fileSize #{I18n.t('activerecord.errors.messages.blank')}"- )- end-- with_handled_create_errors do- create_attachment metadata- end- end-- def create_attachment(metadata)- Attachment.create_pending_direct_upload(- file_name: metadata.file_name,- container: container,- author: current_user,- content_type: metadata.content_type,- file_size: metadata.file_size- )- end-- def parse_and_create- metadata = parse_metadata params[:metadata]- file = params[:file]-- unless metadata && file- raise ::API::Errors::InvalidRequestBody.new(I18n.t('api_v3.errors.multipart_body_error'))- end-- build_and_attach(metadata, file)- end-- def build_and_attach(metadata, file)- uploaded_file = OpenProject::Files.build_uploaded_file file[:tempfile],- file[:type],- file_name: metadata.file_name.to_s-- service = ::Attachments::CreateService.new(container, author: current_user)-- with_handled_create_errors do- service.call uploaded_file: uploaded_file,- description: metadata.description- end- end-- def check_permissions(permissions)- if permissions.empty?- raise API::Errors::Unauthorized unless container.attachments_addable?(current_user)- else- authorize_any(permissions, projects: container.project)- end- end-- def require_direct_uploads- unless OpenProject::Configuration.direct_uploads?- raise API::Errors::NotFound, message: "Only available if direct uploads are enabled."- end- end-- def with_handled_create_errors- yield- rescue ActiveRecord::RecordInvalid => e- raise ::API::Errors::ErrorBase.create_and_merge_errors(e.record.errors)- rescue StandardError => e- log_attachment_saving_error(e)- message =- if e&.class&.to_s == 'Errno::EACCES'- I18n.t('api_v3.errors.unable_to_create_attachment_permissions')- else- I18n.t('api_v3.errors.unable_to_create_attachment')- end- raise ::API::Errors::InternalError.new(message)- end-- def log_attachment_saving_error(error)- container_message = if container- "on #{container.class} with ID #{container.id}"- else- "without container"- end- message = "Failed to save attachment #{container_message}: #{error&.class} - #{error&.message || 'Unknown error'}"-- Rails.logger.error message+ def self.parse_multipart(request)+ request.params.tap do |params|+ params[:metadata] = JSON.parse(params[:metadata]) if params.key?(:metadata)end+ rescue JSON::ParserError+ raise ::API::Errors::InvalidRequestBody.new(I18n.t('api_v3.errors.invalid_json'))enddef self.read@@ -167,21 +73,30 @@ module APIenddef self.create(permissions = [])- -> do- check_permissions permissions-- ::API::V3::Attachments::AttachmentRepresenter.new(parse_and_create,- current_user: current_user)- end+ ::API::V3::Utilities::Endpoints::Create+ .new(model: ::Attachment,+ parse_representer: AttachmentParsingRepresenter,+ params_source: method(:parse_multipart),+ before_hook: ->(request:) { request.restrict_permissions(permissions) },+ params_modifier: ->(params) do+ params.merge(container: container)+ end)+ .mountenddef self.prepare(permissions = [])- -> do- require_direct_uploads- check_permissions permissions-- ::API::V3::Attachments::AttachmentUploadRepresenter.new(parse_and_prepare, current_user: current_user)- end+ ::API::V3::Utilities::Endpoints::Create+ .new(model: ::Attachment,+ parse_representer: AttachmentParsingRepresenter,+ render_representer: AttachmentUploadRepresenter,+ process_service: ::Attachments::PrepareUploadService,+ process_contract: ::Attachments::PrepareUploadContract,+ params_source: method(:parse_multipart),+ before_hook: ->(request:) { request.restrict_permissions(permissions) },+ params_modifier: ->(params) do+ params.merge(container: container)+ end)+ .mountendendenddiff --git a/lib/open_project/content_type_detector.rb b/lib/open_project/content_type_detector.rbindex b4f164bff00..c8146a0ce73 100644--- a/lib/open_project/content_type_detector.rb+++ b/lib/open_project/content_type_detector.rb@@ -91,15 +91,15 @@ module OpenProject# Returns a String describing the file's content typedef detect- type = if blank_name?- SENSIBLE_DEFAULT- elsif empty_file?- EMPTY_TYPE- elsif calculated_type_matches.any?- calculated_type_matches.first- else- type_from_file_command || SENSIBLE_DEFAULT- end.to_s+ if blank_name?+ SENSIBLE_DEFAULT+ elsif empty_file?+ EMPTY_TYPE+ elsif calculated_type_matches.any?+ calculated_type_matches.first+ else+ type_from_file_command || SENSIBLE_DEFAULT+ end.to_sendprivatediff --git a/lib/plugins/acts_as_attachable/lib/acts_as_attachable.rb b/lib/plugins/acts_as_attachable/lib/acts_as_attachable.rbindex a251638085e..d1243713c11 100644--- a/lib/plugins/acts_as_attachable/lib/acts_as_attachable.rb+++ b/lib/plugins/acts_as_attachable/lib/acts_as_attachable.rb@@ -54,8 +54,6 @@ module Redmine:attachments_claimedsend :include, Redmine::Acts::Attachable::InstanceMethods-- OpenProject::Deprecation.deprecate_method self, :attach_filesendprivate@@ -174,26 +172,6 @@ module Redmine(persisted? && allowed_to_on_attachment?(user, self.class.attachable_options[:add_on_persisted_permission]))end- # Bulk attaches a set of files to an object- # @deprecated- # Either use the already existing Attachments::CreateService or- # write/extend Services for the attached to object.- # The service should rely on the attachments_replacements variable.- # See:- # * app/services/attachments/set_replacements.rb- # * app/services/attachments/replace_attachments.rb- def attach_files(attachments)- return unless attachments&.is_a?(Hash)-- attachments.each_value do |attachment|- if attachment['file']- build_attachments_from_hash(attachment)- elsif attachment['id']- memoize_attachment_for_claiming(attachment)- end- end- end-privatedef allowed_to_on_attachment?(user, permissions)@@ -222,21 +200,6 @@ module Redmine(Redmine::Acts::Attachable.attachables & self.class.ancestors).firstend- def build_attachments_from_hash(attachment_hash)- if (file = attachment_hash['file']) && file && file.size.positive?- attachments.build(file: file,- container: self,- description: attachment_hash['description'].to_s.strip,- author: User.current)- end- end-- def memoize_attachment_for_claiming(attachment_hash)- self.attachments_claimed ||= []- attachment = Attachment.find(attachment_hash['id'])- self.attachments_claimed << attachment unless id && attachment.container_id == id- end-def validate_attachments_claimablereturn unless claimed_attachments?diff --git a/modules/avatars/lib/open_project/avatars/patches/user_patch.rb b/modules/avatars/lib/open_project/avatars/patches/user_patch.rbindex f675d5874cb..4b5d96b30e8 100644--- a/modules/avatars/lib/open_project/avatars/patches/user_patch.rb+++ b/modules/avatars/lib/open_project/avatars/patches/user_patch.rb@@ -60,8 +60,12 @@ module OpenProject::Avatarslocal_avatar_attachment&.destroyreset_avatar_attachment_cache!- attach_files('first' => { 'file' => file, 'description' => 'avatar' })- save+ @local_avatar_attachment = Attachments::CreateService+ .new(user: User.system, contract_class: EmptyContract)+ .call(file: file, container: self, filename: file.original_filename, description: 'avatar')+ .result++ touchenddef reset_avatar_attachment_cache!diff --git a/modules/bim/app/contracts/bim/bcf/viewpoints/create_contract.rb b/modules/bim/app/contracts/bim/bcf/viewpoints/create_contract.rbindex 6f568b08231..7edea108901 100644--- a/modules/bim/app/contracts/bim/bcf/viewpoints/create_contract.rb+++ b/modules/bim/app/contracts/bim/bcf/viewpoints/create_contract.rb@@ -84,6 +84,7 @@ module Bim::Bcfattribute :uuidattribute :issue+ attribute :snapshotattribute :json_viewpoint dovalidate_json_viewpoint_presentvalidate_json_viewpoint_hashdiff --git a/modules/bim/app/contracts/bim/ifc_models/base_contract.rb b/modules/bim/app/contracts/bim/ifc_models/base_contract.rbindex d98bf621ef7..2dfbf4dabdc 100644--- a/modules/bim/app/contracts/bim/ifc_models/base_contract.rb+++ b/modules/bim/app/contracts/bim/ifc_models/base_contract.rb@@ -42,7 +42,6 @@ module Bimendvalidate :user_allowed_to_manage- validate :user_is_uploadervalidate :ifc_attachment_existentvalidate :ifc_attachment_is_ifcvalidate :uploader_is_ifc_attachment_author@@ -53,12 +52,6 @@ module Bimendend- def user_is_uploader- if model.uploader_id_changed? && model.uploader != user- errors.add :uploader_id, :invalid- end- end-def ifc_attachment_existenterrors.add :base, :ifc_attachment_missing unless model.ifc_attachmentenddiff --git a/modules/bim/app/controllers/bim/bcf/issues_controller.rb b/modules/bim/app/controllers/bim/bcf/issues_controller.rbindex d8bedcce891..3d3269dd641 100644--- a/modules/bim/app/controllers/bim/bcf/issues_controller.rb+++ b/modules/bim/app/controllers/bim/bcf/issues_controller.rb@@ -213,9 +213,16 @@ module Bimenddef create_attachment- Attachments::CreateService- .new(nil, author: current_user)- .call(uploaded_file: params[:bcf_file], description: params[:bcf_file].original_filename)+ filename = params[:bcf_file].original_filename+ call = Attachments::CreateService+ .bypass_whitelist(user: current_user, whitelist: %w[application/zip])+ .call(file: params[:bcf_file],+ filename: filename,+ description: filename)++ call.on_failure { raise e.message }++ call.resultenddef check_file_paramdiff --git a/modules/bim/app/controllers/bim/ifc_models/ifc_models_controller.rb b/modules/bim/app/controllers/bim/ifc_models/ifc_models_controller.rbindex 511d9f4cacb..337228412f9 100644--- a/modules/bim/app/controllers/bim/ifc_models/ifc_models_controller.rb+++ b/modules/bim/app/controllers/bim/ifc_models/ifc_models_controller.rb@@ -176,14 +176,20 @@ module Bimprivatedef prepare_form(ifc_model)- if OpenProject::Configuration.direct_uploads?- @pending_upload = Attachment.create_pending_direct_upload(file_name: "model.ifc", author: current_user)- @form = DirectFogUploader.direct_fog_hash(- attachment: @pending_upload,- success_action_redirect: direct_upload_finished_bcf_project_ifc_models_url- )- session[:pending_ifc_model_ifc_model_id] = ifc_model.id unless ifc_model.new_record?- end+ return unless OpenProject::Configuration.direct_uploads?++ call = ::Attachments::PrepareUploadService+ .new(user: current_user)+ .call(filename: "model.ifc", filesize: 0)++ call.on_failure { flash[:error] = call.message }++ @pending_upload = call.result+ @form = DirectFogUploader.direct_fog_hash(+ attachment: @pending_upload,+ success_action_redirect: direct_upload_finished_bcf_project_ifc_models_url+ )+ session[:pending_ifc_model_ifc_model_id] = ifc_model.id unless ifc_model.new_record?enddef frontend_redirect(model_ids)diff --git a/modules/bim/app/models/bim/bcf/viewpoint.rb b/modules/bim/app/models/bim/bcf/viewpoint.rbindex bd8e770064a..c9dfdd74d9e 100644--- a/modules/bim/app/models/bim/bcf/viewpoint.rb+++ b/modules/bim/app/models/bim/bcf/viewpoint.rb@@ -37,7 +37,14 @@ module Bim::Bcfdef snapshot=(file)snapshot&.destroy- attach_files('first' => { 'file' => file, 'description' => 'snapshot' })+ build_snapshot file+ end++ def build_snapshot(file, user: User.current)+ ::Attachments::BuildService+ .new(user: user)+ .call(file: file, container: self, filename: file.original_filename, description: 'snapshot')+ .resultendendenddiff --git a/modules/bim/app/models/bim/ifc_models/ifc_model.rb b/modules/bim/app/models/bim/ifc_models/ifc_model.rbindex 1ae55c12cac..940acb76fe1 100644--- a/modules/bim/app/models/bim/ifc_models/ifc_model.rb+++ b/modules/bim/app/models/bim/ifc_models/ifc_model.rb@@ -1,7 +1,9 @@module Bimmodule IfcModelsclass IfcModel < ActiveRecord::Base- acts_as_attachable delete_permission: :manage_ifc_models, view_permission: :view_ifc_models+ acts_as_attachable delete_permission: :manage_ifc_models,+ add_permission: :manage_ifc_models,+ view_permission: :view_ifc_modelsbelongs_to :projectbelongs_to :uploader, class_name: 'User', foreign_key: 'uploader_id'@@ -23,7 +25,11 @@ module Bimenddelete_attachment name- attach_files('first' => { 'file' => file, 'description' => name })+ call = ::Attachments::CreateService+ .bypass_whitelist(user: User.current)+ .call(file: file, container: self, filename: file.original_filename, description: name)++ call.on_failure { Rails.logger.error "Failed to add #{name} attachment: #{call.message}" }endenddiff --git a/modules/bim/app/services/bim/bcf/viewpoints/set_attributes_service.rb b/modules/bim/app/services/bim/bcf/viewpoints/set_attributes_service.rbindex fd861246f6d..c9cce4c2ac9 100644--- a/modules/bim/app/services/bim/bcf/viewpoints/set_attributes_service.rb+++ b/modules/bim/app/services/bim/bcf/viewpoints/set_attributes_service.rb@@ -44,8 +44,9 @@ module Bim::Bcfdef set_snapshotreturn unless snapshot_data_complete? && snapshot_content_type+ name = "snapshot.#{snapshot_extension}"file = OpenProject::Files- .create_uploaded_file(name: "snapshot.#{snapshot_extension}",+ .create_uploaded_file(name: name,content_type: snapshot_content_type,content: snapshot_binary_contents,binary: true)@@ -54,7 +55,8 @@ module Bim::Bcf# to update existing viewpoints as the snapshot method will# delete any existing snapshot right away while the expectation# on a SetAttributesService is to not perform persisted changes.- model.snapshot = file+ model.snapshot&.mark_for_destruction+ model.build_snapshot file, user: userenddef snapshot_data_complete?diff --git a/modules/bim/app/services/bim/ifc_models/set_attributes_service.rb b/modules/bim/app/services/bim/ifc_models/set_attributes_service.rbindex 80661c043bb..b703ceee161 100644--- a/modules/bim/app/services/bim/ifc_models/set_attributes_service.rb+++ b/modules/bim/app/services/bim/ifc_models/set_attributes_service.rb@@ -39,7 +39,7 @@ module Bimsupermodel.change_by_system do- model.uploader = model.ifc_attachment&.author if model.ifc_attachment&.new_record? || model.ifc_attachment&.pending_direct_upload?+ model.uploader = model.ifc_attachment&.authorendend@@ -75,7 +75,9 @@ module Bimmodel.attachments << ifc_attachmentelse- model.attach_files('first' => { 'file' => ifc_attachment, 'description' => 'ifc' })+ ::Attachments::BuildService+ .new(user: user)+ .call(file: ifc_attachment, container: model, filename: ifc_attachment.original_filename, description: 'ifc')endendenddiff --git a/modules/bim/spec/bcf/bcf_xml/issue_writer_spec.rb b/modules/bim/spec/bcf/bcf_xml/issue_writer_spec.rbindex de0e0c659e5..2c3b43f10bd 100644--- a/modules/bim/spec/bcf/bcf_xml/issue_writer_spec.rb+++ b/modules/bim/spec/bcf/bcf_xml/issue_writer_spec.rb@@ -103,9 +103,7 @@ describe ::OpenProject::Bim::BcfXml::IssueWriter dobefore doallow(User).to receive(:current).and_return current_user-- bcf_issue.comments.first.journal.update_attribute('journable_id', work_package.id)- FactoryBot.create(:work_package_journal, notes: "Some note created in OP.", journable_id: work_package.id)+ bcf_issue.comments.first.journal.update_columns(journable_id: work_package.id, version: 2)endshared_examples_for "writes Topic" do@@ -174,6 +172,9 @@ describe ::OpenProject::Bim::BcfXml::IssueWriter doendit 'creates BCF comments for comments that were created within OP.' do+ work_package.journal_notes = 'Some note created in OP.'+ work_package.save!+expect(subject.at('/Markup/Comment[2]/Comment').content).to eql("Some note created in OP.")expect(Bim::Bcf::Comment.count).to eql(2)end@@ -182,7 +183,7 @@ describe ::OpenProject::Bim::BcfXml::IssueWriter douuid = bcf_issue.viewpoints.first.uuidviewpoint_node = subject.at("/Markup/Viewpoints[@Guid='#{uuid}']")expect(viewpoint_node.at('Viewpoint').content).to eql("#{uuid}.xml")- expect(viewpoint_node.at('Snapshot').content).to eql("#{uuid}.jpg")+ expect(viewpoint_node.at('Snapshot').content).to eql("#{uuid}.png")endenddiff --git a/modules/bim/spec/contracts/ifc_models/shared_contract_examples.rb b/modules/bim/spec/contracts/ifc_models/shared_contract_examples.rbindex 82936c81848..d16b8d0adf1 100644--- a/modules/bim/spec/contracts/ifc_models/shared_contract_examples.rb+++ b/modules/bim/spec/contracts/ifc_models/shared_contract_examples.rb@@ -31,22 +31,8 @@require 'spec_helper'shared_examples_for 'ifc model contract' do- let(:current_user) do- FactoryBot.build_stubbed(:user) do |user|- allow(user)- .to receive(:allowed_to?) do |permission, permission_project|- permissions.include?(permission) && model_project == permission_project- end- end- end- let(:other_user) do- FactoryBot.build_stubbed(:user) do |user|- allow(user)- .to receive(:allowed_to?) do |permission, permission_project|- permissions.include?(permission) && model_project == permission_project- end- end- end+ let(:current_user) { FactoryBot.build_stubbed(:user) }+ let(:other_user) { FactoryBot.build_stubbed(:user) }let(:model_project) { FactoryBot.build_stubbed(:project) }let(:ifc_attachment) { FactoryBot.build_stubbed(:attachment, author: model_user) }let(:model_user) { current_user }@@ -56,6 +42,16 @@ shared_examples_for 'ifc model contract' doallow(ifc_model).to receive(:ifc_attachment).and_return(ifc_attachment)++ allow(other_user)+ .to receive(:allowed_to?) do |permission, permission_project|+ permissions.include?(permission) && model_project == permission_project+ end++ allow(current_user)+ .to receive(:allowed_to?) do |permission, permission_project|+ permissions.include?(permission) && model_project == permission_project+ endenddef expect_valid(valid, symbols = {})@@ -109,10 +105,10 @@ shared_examples_for 'ifc model contract' docontext 'if the new ifc file is no valid ifc file' dolet(:ifc_file) { FileHelpers.mock_uploaded_file name: "model.ifc", content_type: 'application/binary', binary: true }let(:ifc_attachment) do- User.execute_as current_user do- ifc_model.attach_files('first' => { 'file' => ifc_file, 'description' => 'ifc' })- ifc_model.attachments.last- end+ ::Attachments::BuildService+ .new(user: current_user)+ .call(file: ifc_file, filename: 'model.ifc')+ .resultendit 'is invalid' do@@ -125,10 +121,10 @@ shared_examples_for 'ifc model contract' doFileHelpers.mock_uploaded_file name: "model.ifc", content_type: 'application/binary', binary: true, content: "ISO-10303-21;"endlet(:ifc_attachment) do- User.execute_as current_user do- ifc_model.attach_files('first' => { 'file' => ifc_file, 'description' => 'ifc' })- ifc_model.attachments.last- end+ ::Attachments::BuildService+ .new(user: current_user)+ .call(file: ifc_file, filename: 'model.ifc')+ .resultendit_behaves_like 'is valid'diff --git a/modules/bim/spec/contracts/ifc_models/update_contract_spec.rb b/modules/bim/spec/contracts/ifc_models/update_contract_spec.rbindex afa42d0ceda..84d71c019b5 100644--- a/modules/bim/spec/contracts/ifc_models/update_contract_spec.rb+++ b/modules/bim/spec/contracts/ifc_models/update_contract_spec.rb@@ -42,13 +42,18 @@ describe Bim::IfcModels::UpdateContract doproject: model_project).tap do |model|model.extend(OpenProject::ChangedBySystem)- model.change_by_system do+ if changed_by_system+ changed_by_system do+ model.uploader = uploader_user+ end+ elsemodel.uploader = uploader_userendendendlet(:permissions) { %i(manage_ifc_models) }let(:uploader_user) { model_user }+ let(:changed_by_system) { false }context 'if the uploader changes' dolet(:model_user) { FactoryBot.build_stubbed(:user) }@@ -56,14 +61,20 @@ describe Bim::IfcModels::UpdateContract dolet(:current_user) { other_user }let(:ifc_attachment) { FactoryBot.build_stubbed(:attachment, author: other_user) }- it_behaves_like 'is valid'+ it 'is invalid as not writable' do+ expect_valid(false, uploader_id: %i(error_readonly))+ end+ end- context 'if the uploader is different from the current_user' do- let(:current_user) { model_user }+ context 'if the uploader changes' do+ let(:model_user) { FactoryBot.build_stubbed(:user) }+ let(:uploader_user) { other_user }+ let(:current_user) { other_user }+ let(:ifc_attachment) { FactoryBot.build_stubbed(:attachment, author: other_user) }+ let(:changed_by_system) { true }- it 'is invalid' do- expect_valid(false, uploader_id: %i(invalid))- end+ it 'is invalid as does not match' do+ expect_valid(false, uploader_id: %i(invalid))endenddiff --git a/modules/bim/spec/controllers/issues_controller_spec.rb b/modules/bim/spec/controllers/issues_controller_spec.rbindex 08eb3e451af..6a24ad68048 100644--- a/modules/bim/spec/controllers/issues_controller_spec.rb+++ b/modules/bim/spec/controllers/issues_controller_spec.rb@@ -103,7 +103,7 @@ describe ::Bim::Bcf::IssuesController, type: :controller dolet(:file) doRack::Test::UploadedFile.new(File.join(Rails.root, "modules/bim/spec/fixtures/files/#{filename}"),- 'application/octet-stream'+ 'application/zip')end@@ -119,7 +119,7 @@ describe ::Bim::Bcf::IssuesController, type: :controller dolet(:file) { FileHelpers.mock_uploaded_file }it 'should redirect back to where we started from' do- expect { action }.to change { Attachment.count }.by(1)+ expect { action }.to change { Attachment.count }.by(0)expect(response).to redirect_to '/projects/bim_project/issues/upload'endenddiff --git a/modules/bim/spec/factories/bcf_viewpoint_attachment_factory.rb b/modules/bim/spec/factories/bcf_viewpoint_attachment_factory.rbindex 84d091df055..8f88d96dec0 100644--- a/modules/bim/spec/factories/bcf_viewpoint_attachment_factory.rb+++ b/modules/bim/spec/factories/bcf_viewpoint_attachment_factory.rb@@ -29,13 +29,15 @@FactoryBot.define dofactory :bcf_viewpoint_attachment, class: 'Attachment' dodescription { "snapshot" }- filename { "snapshot.jpg" }+ filename { "image.png" }content_type { "image/jpeg" }author { User.current }file do- OpenProject::Files.create_uploaded_file name: filename,- content_type: content_type,- binary: true+ Rack::Test::UploadedFile.new(+ Rails.root.join("spec/fixtures/files/image.png"),+ 'image/png',+ true+ )endendenddiff --git a/modules/bim/spec/factories/ifc_model_factory.rb b/modules/bim/spec/factories/ifc_model_factory.rbindex 3162fd232cb..afa99ca606f 100644--- a/modules/bim/spec/factories/ifc_model_factory.rb+++ b/modules/bim/spec/factories/ifc_model_factory.rb@@ -32,11 +32,19 @@ FactoryBot.define doproject factory: :projectuploader factory: :useris_default { true }- ifc_attachment do- Rack::Test::UploadedFile.new(- File.join(Rails.root, "modules/bim/spec/fixtures/files/minimal.ifc"),- 'application/binary'- )+ transient do+ ifc_attachment do+ Rack::Test::UploadedFile.new(+ File.join(Rails.root, "modules/bim/spec/fixtures/files/minimal.ifc"),+ 'application/binary'+ )+ end++ callback(:after_create) do |model, evaluator|+ User.system.run_given do+ model.ifc_attachment = evaluator.ifc_attachment+ end+ endendfactory :ifc_model_minimal_converted do@@ -44,12 +52,19 @@ FactoryBot.define doproject factory: :projectuploader factory: :useris_default { true }+ transient do+ xkt_attachment do+ Rack::Test::UploadedFile.new(+ File.join(Rails.root, "modules/bim/spec/fixtures/files/minimal.xkt"),+ 'application/binary'+ )+ end+ end- xkt_attachment do- Rack::Test::UploadedFile.new(- File.join(Rails.root, "modules/bim/spec/fixtures/files/minimal.xkt"),- 'application/binary'- )+ callback(:after_create) do |model, evaluator|+ User.system.run_given do+ model.xkt_attachment = evaluator.xkt_attachment+ endendendenddiff --git a/modules/bim/spec/features/bim_navigation_spec.rb b/modules/bim/spec/features/bim_navigation_spec.rbindex e444666caff..0f2a3eb0064 100644--- a/modules/bim/spec/features/bim_navigation_spec.rb+++ b/modules/bim/spec/features/bim_navigation_spec.rb@@ -44,7 +44,7 @@ describe 'BIM navigation spec',member_through_role: roleend- let!(:model) do+ let(:model) doFactoryBot.create(:ifc_model_minimal_converted,project: project,uploader: user)@@ -56,16 +56,19 @@ describe 'BIM navigation spec',let(:model_tree) { ::Components::XeokitModelTree.new }let(:destroy_modal) { Components::WorkPackages::DestroyModal.new }+ before do+ login_as user+ model+ end+shared_examples 'can switch from split to viewer to list-only' dobefore do- login_as(user)model_page.visit!model_page.finished_loadingendcontext 'deep link on the page' dobefore do- login_as(user)model_page.visit!model_page.finished_loadingdiff --git a/modules/bim/spec/features/model_management_spec.rb b/modules/bim/spec/features/model_management_spec.rbindex 79049dce541..e45344f7570 100644--- a/modules/bim/spec/features/model_management_spec.rb+++ b/modules/bim/spec/features/model_management_spec.rb@@ -44,14 +44,14 @@ describe 'model management',member_through_role: roleend- let(:model) do+ let!(:model) doFactoryBot.create(:ifc_model_minimal_converted,project: project,uploader: user,is_default: true)end- let(:model2) do+ let!(:model2) doFactoryBot.create(:ifc_model_minimal_converted,project: project,uploader: user)diff --git a/modules/bim/spec/features/model_viewer_spec.rb b/modules/bim/spec/features/model_viewer_spec.rbindex 44ea7c9868d..66eb1932a89 100644--- a/modules/bim/spec/features/model_viewer_spec.rb+++ b/modules/bim/spec/features/model_viewer_spec.rb@@ -43,7 +43,7 @@ describe 'model viewer',member_through_role: roleend- let(:model) do+ let!(:model) doFactoryBot.create(:ifc_model_minimal_converted,project: project,uploader: user)@@ -92,6 +92,8 @@ describe 'model viewer',endcontext 'in a project with no model' do+ let!(:model) { nil }+it 'shows a warning that no IFC models exist yet' dologin_as uservisit defaults_bcf_project_ifc_models_path(project)diff --git a/modules/bim/spec/models/ifc_model_spec.rb b/modules/bim/spec/models/ifc_model_spec.rbindex 4dc28cbc1d5..6542dc65d66 100644--- a/modules/bim/spec/models/ifc_model_spec.rb+++ b/modules/bim/spec/models/ifc_model_spec.rb@@ -16,11 +16,17 @@ describe ::Bim::IfcModels::IfcModel, type: :model doenddescribe 'ifc_attachment=' do- subject { FactoryBot.create :ifc_model_minimal_converted, project: FactoryBot.create(:project) }+ let(:project) { FactoryBot.create(:project, enabled_module_names: %i[bim]) }let(:ifc_attachment) { subject.ifc_attachment }let(:new_attachment) doFileHelpers.mock_uploaded_file name: "model.ifc", content_type: 'application/binary', binary: trueend+ subject { FactoryBot.create :ifc_model_minimal_converted, project: project }+ current_user do+ FactoryBot.create :user,+ member_in_project: project,+ member_with_permissions: %i[manage_ifc_models]+ endit 'replaces the previous attachment' doexpect(ifc_attachment).to be_present@@ -31,7 +37,7 @@ describe ::Bim::IfcModels::IfcModel, type: :model doexpect { ifc_attachment.reload }.to raise_error(ActiveRecord::RecordNotFound)expect(subject.ifc_attachment).not_to eq ifc_attachment- expect(subject.ifc_attachment).not_to be_present+ expect(subject.ifc_attachment).to be_presentexpect(subject.xkt_attachment).not_to be_presentexpect(subject).not_to be_convertedenddiff --git a/modules/bim/spec/requests/api/bcf/v2_1/viewpoints_api_spec.rb b/modules/bim/spec/requests/api/bcf/v2_1/viewpoints_api_spec.rbindex 87aa1c53fad..b672b7dd5e0 100644--- a/modules/bim/spec/requests/api/bcf/v2_1/viewpoints_api_spec.rb+++ b/modules/bim/spec/requests/api/bcf/v2_1/viewpoints_api_spec.rb@@ -202,7 +202,7 @@ describe 'BCF 2.1 viewpoints resource', type: :request, content_type: :json, witit 'responds with the attachment with the appropriate content type and cache headers' doexpect(subject.status).to eq 200- expect(subject.headers['Content-Type']).to eq 'image/jpeg'+ expect(subject.headers['Content-Type']).to eq 'image/png'max_age = OpenProject::Configuration.fog_download_url_expires_in - 10diff --git a/modules/bim/spec/services/bcf/viewpoints/set_attributes_service_spec.rb b/modules/bim/spec/services/bcf/viewpoints/set_attributes_service_spec.rbindex 7bfc3783d4b..2a813b0b39a 100644--- a/modules/bim/spec/services/bcf/viewpoints/set_attributes_service_spec.rb+++ b/modules/bim/spec/services/bcf/viewpoints/set_attributes_service_spec.rb@@ -60,6 +60,13 @@ describe Bim::Bcf::Viewpoints::SetAttributesService, type: :model doBim::Bcf::Viewpoint.newend+ before do+ allow(viewpoint)+ .to receive(:attachments_addable?)+ .with(user, any_args)+ .and_return true+ end+describe 'call' do# We only expect the service to be called for new records. As viewpoints# are immutable.@@ -113,7 +120,7 @@ describe Bim::Bcf::Viewpoints::SetAttributesService, type: :model doexpect(viewpoint.attachments.first.file.read).to eql 'Hello World!'- expect(viewpoint.attachments.first.file.filename)+ expect(viewpoint.attachments.first.filename).to eql 'snapshot.png'enddiff --git a/modules/bim/spec/services/ifc_models/set_attributes_service_spec.rb b/modules/bim/spec/services/ifc_models/set_attributes_service_spec.rbindex 533d859149c..72427087cdf 100644--- a/modules/bim/spec/services/ifc_models/set_attributes_service_spec.rb+++ b/modules/bim/spec/services/ifc_models/set_attributes_service_spec.rb@@ -31,7 +31,10 @@require 'spec_helper'describe Bim::IfcModels::SetAttributesService, type: :model do- let(:user) { FactoryBot.build_stubbed(:user) }+ shared_let(:project) { FactoryBot.create(:project, enabled_module_names: %i[bim]) }+ shared_let(:other_project) { FactoryBot.create(:project, enabled_module_names: %i[bim]) }+ shared_let(:user) { FactoryBot.create(:user, member_in_project: project, member_with_permissions: %i[manage_ifc_models]) }+let(:other_user) { FactoryBot.build_stubbed(:user) }let(:contract_class) docontract = double('contract_class')@@ -58,10 +61,8 @@ describe Bim::IfcModels::SetAttributesService, type: :model doendlet(:call_attributes) { {} }let(:ifc_file) { FileHelpers.mock_uploaded_file(name: "model_2.ifc", content_type: 'application/binary', binary: true) }- let(:ifc_attachment) { FactoryBot.build_stubbed(:attachment) }- let(:project) { FactoryBot.build_stubbed(:project) }let(:model) do- FactoryBot.build_stubbed(:ifc_model, attachments: [ifc_attachment], uploader: other_user)+ FactoryBot.create(:ifc_model, project: project, uploader: other_user)endbefore do@@ -72,7 +73,7 @@ describe Bim::IfcModels::SetAttributesService, type: :model dodescribe 'call' dolet(:call_attributes) do{- project_id: project.id+ project_id: other_project.id}end@@ -96,7 +97,7 @@ describe Bim::IfcModels::SetAttributesService, type: :model dosubjectexpect(model.attributes.slice(*model.changed).symbolize_keys)- .to eql call_attributes+ .to eql call_attributes.merge(uploader_id: user.id)endit 'does not persist the model' do@@ -108,7 +109,7 @@ describe Bim::IfcModels::SetAttributesService, type: :model docontext 'for a new record' dolet(:model) do- Bim::IfcModels::IfcModel.new+ Bim::IfcModels::IfcModel.new project: projectendcontext 'with an ifc_attachment' do@@ -167,6 +168,8 @@ describe Bim::IfcModels::SetAttributesService, type: :model doendit 'marks existing attachments for destruction' do+ ifc_attachment = model.ifc_attachment+subjectexpect(ifc_attachment)diff --git a/modules/bim/spec/workers/work_packages/exports/export_job_spec.rb b/modules/bim/spec/workers/work_packages/exports/export_job_spec.rbindex de62b36fb22..bd0dc398716 100644--- a/modules/bim/spec/workers/work_packages/exports/export_job_spec.rb+++ b/modules/bim/spec/workers/work_packages/exports/export_job_spec.rb@@ -59,22 +59,16 @@ describe WorkPackages::Exports::ExportJob dolet(:mime_type) { :bcf }it 'issues an OpenProject::Bim::BcfXml::Exporter export' do- file = double(File)- allow(file)- .to receive(:is_a?)- .with(File)- .and_return true-result = WorkPackage::Exporter::Result::Success.new(format: 'blubs',- title: 'some_title',- content: file,+ title: "some_title.#{mime_type}",+ content: 'some content',mime_type: "application/octet-stream")service = double('attachments create service')expect(Attachments::CreateService)- .to receive(:new)- .with(export, author: user)+ .to receive(:bypass_whitelist)+ .with(user: user).and_return(service)expect(WorkPackages::Exports::CleanupOutdatedJob)@@ -82,7 +76,7 @@ describe WorkPackages::Exports::ExportJob doexpect(service).to(receive(:call))- .and_return attachment+ .and_return(ServiceResult.new(result: attachment, success: true))allow(OpenProject::Bim::BcfXml::Exporter).to receive(:list)diff --git a/modules/budgets/app/contracts/budgets/base_contract.rb b/modules/budgets/app/contracts/budgets/base_contract.rbnew file mode 100644index 00000000000..ece6c30e1fe--- /dev/null+++ b/modules/budgets/app/contracts/budgets/base_contract.rb@@ -0,0 +1,65 @@+#-- encoding: UTF-8++#-- copyright+# OpenProject is an open source project management software.+# Copyright (C) 2012-2021 the OpenProject GmbH+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License version 3.+#+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:+# Copyright (C) 2006-2013 Jean-Philippe Lang+# Copyright (C) 2010-2013 the ChiliProject Team+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License+# as published by the Free Software Foundation; either version 2+# of the License, or (at your option) any later version.+#+# This program is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU General Public License+# along with this program; if not, write to the Free Software+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.+#+# See docs/COPYRIGHT.rdoc for more details.+#++++module Budgets+ class BaseContract < ::ModelContract+ include Attachments::ValidateReplacements++ def self.model+ Budget+ end++ attribute :subject+ attribute :description+ attribute :fixed_date+ attribute :project+ attribute :new_material_budget_item_attributes,+ readable: false++ attribute :new_labor_budget_item_attributes,+ readable: false++ attribute :existing_material_budget_item_attributes,+ readable: false++ attribute :existing_labor_budget_item_attributes,+ readable: false++ validate :validate_manage_allowed++ private++ def validate_manage_allowed+ unless user.allowed_to?(:edit_budgets, model.project)+ errors.add :base, :error_unauthorized+ end+ end+ end+enddiff --git a/modules/budgets/app/contracts/budgets/create_contract.rb b/modules/budgets/app/contracts/budgets/create_contract.rbnew file mode 100644index 00000000000..8708e9c74ca--- /dev/null+++ b/modules/budgets/app/contracts/budgets/create_contract.rb@@ -0,0 +1,34 @@+#-- encoding: UTF-8++#-- copyright+# OpenProject is an open source project management software.+# Copyright (C) 2012-2021 the OpenProject GmbH+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License version 3.+#+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:+# Copyright (C) 2006-2013 Jean-Philippe Lang+# Copyright (C) 2010-2013 the ChiliProject Team+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License+# as published by the Free Software Foundation; either version 2+# of the License, or (at your option) any later version.+#+# This program is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU General Public License+# along with this program; if not, write to the Free Software+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.+#+# See docs/COPYRIGHT.rdoc for more details.+#++++module Budgets+ class CreateContract < BaseContract+ end+enddiff --git a/modules/budgets/app/contracts/budgets/update_contract.rb b/modules/budgets/app/contracts/budgets/update_contract.rbnew file mode 100644index 00000000000..44a3337b219--- /dev/null+++ b/modules/budgets/app/contracts/budgets/update_contract.rb@@ -0,0 +1,34 @@+#-- encoding: UTF-8++#-- copyright+# OpenProject is an open source project management software.+# Copyright (C) 2012-2021 the OpenProject GmbH+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License version 3.+#+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:+# Copyright (C) 2006-2013 Jean-Philippe Lang+# Copyright (C) 2010-2013 the ChiliProject Team+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License+# as published by the Free Software Foundation; either version 2+# of the License, or (at your option) any later version.+#+# This program is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU General Public License+# along with this program; if not, write to the Free Software+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.+#+# See docs/COPYRIGHT.rdoc for more details.+#++++module Budgets+ class UpdateContract < BaseContract+ end+enddiff --git a/modules/budgets/app/controllers/budgets_controller.rb b/modules/budgets/app/controllers/budgets_controller.rbindex bb26ce92206..370428f6f98 100644--- a/modules/budgets/app/controllers/budgets_controller.rb+++ b/modules/budgets/app/controllers/budgets_controller.rb@@ -27,6 +27,8 @@#++class BudgetsController < ApplicationController+ include AttachableServiceCall+before_action :find_budget, only: %i[show edit update copy]before_action :find_budgets, only: :destroybefore_action :find_project, only: %i[new create update_material_budget_item update_labor_budget_item]@@ -85,11 +87,12 @@ class BudgetsController < ApplicationControllerdef copysource = Budget.find(params[:id].to_i)- @budget = if source- Budget.new_copy(source)- else- Budget.new- end+ @budget =+ if source+ Budget.new_copy(source)+ else+ Budget.new+ end@budget.fixed_date ||= Date.today@@ -97,23 +100,15 @@ class BudgetsController < ApplicationControllerenddef create- @budget = Budget.new- @budget.project_id = @project.id-- # fixed_date must be set before material_budget_items and labor_budget_items- @budget.fixed_date = if params[:budget] && params[:budget][:fixed_date]- params[:budget].delete(:fixed_date)- else- Date.today- end-- @budget.attributes = permitted_params.budget- @budget.attach_files(permitted_params.attachments.to_h)+ call = attachable_create_call ::Budgets::CreateService,+ args: permitted_params.budget.merge(project: @project)+ @budget = call.result- if @budget.save+ if call.success?flash[:notice] = t(:notice_successful_create)redirect_to(params[:continue] ? { action: 'new' } : { action: 'show', id: @budget })else+ @errors = call.errorsrender action: 'new', layout: !request.xhr?endend@@ -123,20 +118,16 @@ class BudgetsController < ApplicationControllerenddef update- @budget.attributes = permitted_params.budget if params[:budget]- if params[:budget][:existing_material_budget_item_attributes].nil?- @budget.existing_material_budget_item_attributes = ({})- end- if params[:budget][:existing_labor_budget_item_attributes].nil?- @budget.existing_labor_budget_item_attributes = ({})- end-- @budget.attach_files(permitted_params.attachments.to_h)+ call = attachable_update_call ::Budgets::UpdateService,+ model: @budget,+ args: permitted_params.budget- if @budget.save+ if call.success?flash[:notice] = t(:notice_successful_update)redirect_to(params[:back_to] || { action: 'show', id: @budget })else+ @budget = call.result+ @errors = call.errorsrender action: 'edit'endrescue ActiveRecord::StaleObjectErrordiff --git a/modules/budgets/app/models/budget.rb b/modules/budgets/app/models/budget.rbindex 47b731947ab..998c43f10fd 100644--- a/modules/budgets/app/models/budget.rb+++ b/modules/budgets/app/models/budget.rb@@ -97,11 +97,6 @@ class Budget < ApplicationRecordendend- def initialize(attributes = nil)- super- self.author = User.current if new_record?- end-def budgetmaterial_budget + labor_budgetenddiff --git a/modules/budgets/app/services/budgets/create_service.rb b/modules/budgets/app/services/budgets/create_service.rbnew file mode 100644index 00000000000..2125f3fc672--- /dev/null+++ b/modules/budgets/app/services/budgets/create_service.rb@@ -0,0 +1,33 @@+#-- copyright+# OpenProject is an open source project management software.+# Copyright (C) 2012-2021 the OpenProject GmbH+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License version 3.+#+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:+# Copyright (C) 2006-2013 Jean-Philippe Lang+# Copyright (C) 2010-2013 the ChiliProject Team+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License+# as published by the Free Software Foundation; either version 2+# of the License, or (at your option) any later version.+#+# This program is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU General Public License+# along with this program; if not, write to the Free Software+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.+#+# See docs/COPYRIGHT.rdoc for more details.+#++++module Budgets+ class CreateService < ::BaseServices::Create+ include Attachments::ReplaceAttachments+ end+enddiff --git a/modules/budgets/app/services/budgets/set_attributes_service.rb b/modules/budgets/app/services/budgets/set_attributes_service.rbnew file mode 100644index 00000000000..71481e2dd65--- /dev/null+++ b/modules/budgets/app/services/budgets/set_attributes_service.rb@@ -0,0 +1,65 @@+#-- encoding: UTF-8++#-- copyright+# OpenProject is an open source project management software.+# Copyright (C) 2012-2021 the OpenProject GmbH+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License version 3.+#+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:+# Copyright (C) 2006-2013 Jean-Philippe Lang+# Copyright (C) 2010-2013 the ChiliProject Team+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License+# as published by the Free Software Foundation; either version 2+# of the License, or (at your option) any later version.+#+# This program is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU General Public License+# along with this program; if not, write to the Free Software+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.+#+# See docs/COPYRIGHT.rdoc for more details.+#++++module Budgets+ class SetAttributesService < ::BaseServices::SetAttributes+ include Attachments::SetReplacements++ private++ def set_attributes(params)+ set_fixed_date(params)+ unset_items(params)++ super+ end++ def set_default_attributes(_params)+ model.change_by_system do+ model.author = user+ end+ end++ # fixed_date must be set before material_budget_items and labor_budget_items+ def set_fixed_date(params)+ model.fixed_date = params.delete(:fixed_date) || Date.today+ end++ def unset_items(params)+ if params[:existing_material_budget_item_attributes].nil?+ model.existing_material_budget_item_attributes = ({})+ end++ if params[:existing_labor_budget_item_attributes].nil?+ model.existing_labor_budget_item_attributes = ({})+ end+ end+ end+enddiff --git a/modules/budgets/app/services/budgets/update_service.rb b/modules/budgets/app/services/budgets/update_service.rbnew file mode 100644index 00000000000..dfa73c33a9d--- /dev/null+++ b/modules/budgets/app/services/budgets/update_service.rb@@ -0,0 +1,35 @@+#-- encoding: UTF-8++#-- copyright+# OpenProject is an open source project management software.+# Copyright (C) 2012-2021 the OpenProject GmbH+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License version 3.+#+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:+# Copyright (C) 2006-2013 Jean-Philippe Lang+# Copyright (C) 2010-2013 the ChiliProject Team+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License+# as published by the Free Software Foundation; either version 2+# of the License, or (at your option) any later version.+#+# This program is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU General Public License+# along with this program; if not, write to the Free Software+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.+#+# See docs/COPYRIGHT.rdoc for more details.+#++++module Budgets+ class UpdateService < ::BaseServices::Update+ include Attachments::ReplaceAttachments+ end+enddiff --git a/modules/budgets/app/views/budgets/_edit.html.erb b/modules/budgets/app/views/budgets/_edit.html.erbindex 4a392b15171..9e195f8027a 100644--- a/modules/budgets/app/views/budgets/_edit.html.erb+++ b/modules/budgets/app/views/budgets/_edit.html.erb@@ -33,7 +33,6 @@ See docs/COPYRIGHT.rdoc for more details.:html => {:multipart => true,:id => 'budget_form',:class => 'form'} do |f| %>- <%= error_messages_for 'budget' %><%= render :partial => 'form', :locals => {:f => f} %><div class="generic-table--action-buttons"><%= styled_button_tag t(:button_submit), class: '-with-icon icon-checkmark -highlight', id: 'budget-table--submit-button'%>diff --git a/modules/budgets/app/views/budgets/_form.html.erb b/modules/budgets/app/views/budgets/_form.html.erbindex e3162429f05..85339408acd 100644--- a/modules/budgets/app/views/budgets/_form.html.erb+++ b/modules/budgets/app/views/budgets/_form.html.erb@@ -28,6 +28,7 @@ See docs/COPYRIGHT.rdoc for more details.++#%><% resource = budget_attachment_representer(f.object) %>+<%= error_messages_for_contract @budget, @errors %><div class="form--field -required"><%= f.text_field :subject, required: true, autofocus: true, container_class: '-wide' %>diff --git a/modules/budgets/app/views/budgets/new.html.erb b/modules/budgets/app/views/budgets/new.html.erbindex 5e8729f9f5e..3f872e89f79 100644--- a/modules/budgets/app/views/budgets/new.html.erb+++ b/modules/budgets/app/views/budgets/new.html.erb@@ -34,7 +34,6 @@ See docs/COPYRIGHT.rdoc for more details.:url => projects_budgets_path(@project),:as => :budget,:html => {:multipart => true, :id => 'budget_form'} do |f| %>- <%= error_messages_for 'budget' %><%= render :partial => 'form', :locals => {:f => f} %><%= styled_button_tag t(:button_create), class: '-with-icon icon-checkmark' %><%= styled_button_tag t(:button_create_and_continue), :name => 'continue',diff --git a/modules/budgets/spec/models/budget_spec.rb b/modules/budgets/spec/models/budget_spec.rbindex 4aed89166ca..a3bb498b0a0 100644--- a/modules/budgets/spec/models/budget_spec.rb+++ b/modules/budgets/spec/models/budget_spec.rb@@ -34,16 +34,6 @@ describe Budget, type: :model dolet(:project) { FactoryBot.create(:project_with_types) }let(:user) { FactoryBot.create(:user) }- describe 'initialization' do- let(:budget) { Budget.new }-- before do- allow(User).to receive(:current).and_return(user)- end-- it { expect(budget.author).to eq(user) }- end-describe 'destroy' dolet(:work_package) { FactoryBot.create(:work_package, project: project) }diff --git a/modules/budgets/spec/services/budgets/create_service_spec.rb b/modules/budgets/spec/services/budgets/create_service_spec.rbnew file mode 100644index 00000000000..4f4ba1949ea--- /dev/null+++ b/modules/budgets/spec/services/budgets/create_service_spec.rb@@ -0,0 +1,36 @@+#-- encoding: UTF-8++#-- copyright+# OpenProject is an open source project management software.+# Copyright (C) 2012-2021 the OpenProject GmbH+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License version 3.+#+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:+# Copyright (C) 2006-2013 Jean-Philippe Lang+# Copyright (C) 2010-2013 the ChiliProject Team+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License+# as published by the Free Software Foundation; either version 2+# of the License, or (at your option) any later version.+#+# This program is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU General Public License+# along with this program; if not, write to the Free Software+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.+#+# See docs/COPYRIGHT.rdoc for more details.+#++++require 'spec_helper'+require 'services/base_services/behaves_like_create_service'++describe Budgets::CreateService, type: :model do+ it_behaves_like 'BaseServices create service'+enddiff --git a/modules/budgets/spec/services/budgets/update_service_spec.rb b/modules/budgets/spec/services/budgets/update_service_spec.rbnew file mode 100644index 00000000000..42051f91157--- /dev/null+++ b/modules/budgets/spec/services/budgets/update_service_spec.rb@@ -0,0 +1,36 @@+#-- encoding: UTF-8++#-- copyright+# OpenProject is an open source project management software.+# Copyright (C) 2012-2021 the OpenProject GmbH+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License version 3.+#+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:+# Copyright (C) 2006-2013 Jean-Philippe Lang+# Copyright (C) 2010-2013 the ChiliProject Team+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License+# as published by the Free Software Foundation; either version 2+# of the License, or (at your option) any later version.+#+# This program is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU General Public License+# along with this program; if not, write to the Free Software+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.+#+# See docs/COPYRIGHT.rdoc for more details.+#++++require 'spec_helper'+require 'services/base_services/behaves_like_update_service'++describe Budgets::UpdateService, type: :model do+ it_behaves_like 'BaseServices update service'+enddiff --git a/modules/costs/spec/requests/api/attachments/attachments_by_budget_resource_spec.rb b/modules/costs/spec/requests/api/attachments/attachments_by_budget_resource_spec.rbindex dd5f1e91eda..f5b6a580a14 100644--- a/modules/costs/spec/requests/api/attachments/attachments_by_budget_resource_spec.rb+++ b/modules/costs/spec/requests/api/attachments/attachments_by_budget_resource_spec.rb@@ -27,118 +27,19 @@#++require 'spec_helper'-require 'rack/test'+require 'requests/api/v3/attachments/attachment_resource_shared_examples'-describe 'API v3 Attachments by budget resource', type: :request do- include Rack::Test::Methods- include API::V3::Utilities::PathHelper- include FileHelpers+describe "budget attachments" do+ it_behaves_like "an APIv3 attachment resource" do+ let(:attachment_type) { :budget }- let(:current_user) do- FactoryBot.create(:user,- member_in_project: project,- member_with_permissions: permissions)- end- let(:project) { FactoryBot.create(:project) }- let(:permissions) { [:view_budgets] }- let(:budget) { FactoryBot.create(:budget, project: project) }-- subject(:response) { last_response }-- before do- allow(User).to receive(:current).and_return current_user- end-- describe '#get' do- let(:get_path) { api_v3_paths.attachments_by_budget budget.id }+ let(:create_permission) { :edit_budgets }+ let(:read_permission) { :view_budgets }+ let(:update_permission) { :edit_budgets }- before do- FactoryBot.create_list(:attachment, 2, container: budget)- get get_path- end-- it 'should respond with 200' do- expect(subject.status).to eq(200)- end-- it_behaves_like 'API V3 collection response', 2, 2, 'Attachment'- end-- describe '#post' do- let(:permissions) { %i[view_budgets edit_budgets] }-- let(:request_path) { api_v3_paths.attachments_by_budget budget.id }- let(:request_parts) { { metadata: metadata.to_json, file: file } }- let(:metadata) { { fileName: 'cat.png' } }- let(:file) { mock_uploaded_file(name: 'original-filename.txt') }- let(:max_file_size) { 1 } # given in kiB-- before do- allow(Setting).to receive(:attachment_max_size).and_return max_file_size.to_s- post request_path, request_parts- end-- it 'should respond with HTTP Created' do- expect(subject.status).to eq(201)- end-- it 'should return the new attachment' do- expect(subject.body).to be_json_eql('Attachment'.to_json).at_path('_type')- end-- it 'ignores the original file name' do- expect(subject.body).to be_json_eql('cat.png'.to_json).at_path('fileName')- end-- context 'metadata section is missing' do- let(:request_parts) { { file: file } }-- it_behaves_like 'invalid request body', I18n.t('api_v3.errors.multipart_body_error')- end-- context 'file section is missing' do- # rack-test won't send a multipart request without a file being present- # however as long as we depend on correctly named sections this test should do just fine- let(:request_parts) { { metadata: metadata.to_json, wrongFileSection: file } }-- it_behaves_like 'invalid request body', I18n.t('api_v3.errors.multipart_body_error')- end-- context 'metadata section is no valid JSON' do- let(:request_parts) { { metadata: '"fileName": "cat.png"', file: file } }-- it_behaves_like 'parse error'- end-- context 'metadata is missing the fileName' do- let(:metadata) { Hash.new }-- it_behaves_like 'constraint violation' do- let(:message) { "fileName #{I18n.t('activerecord.errors.messages.blank')}" }- end- end-- context 'file is too large' do- let(:file) { mock_uploaded_file(content: 'a' * 2.kilobytes) }- let(:expanded_localization) do- I18n.t('activerecord.errors.messages.file_too_large', count: max_file_size.kilobytes)- end-- it_behaves_like 'constraint violation' do- let(:message) { "File #{expanded_localization}" }- end- end-- context 'only allowed to add messages, but no edit permission' do- let(:permissions) { %i[view_messages add_messages] }-- it_behaves_like 'unauthorized access'- end-- context 'only allowed to view messages' do- let(:permissions) { [:view_messages] }-- it_behaves_like 'unauthorized access'+ let(:budget) do+ FactoryBot.create :budget, project: projectendendend+diff --git a/modules/documents/app/contracts/documents/base_contract.rb b/modules/documents/app/contracts/documents/base_contract.rbnew file mode 100644index 00000000000..0670ef94a0f--- /dev/null+++ b/modules/documents/app/contracts/documents/base_contract.rb@@ -0,0 +1,54 @@+#-- encoding: UTF-8++#-- copyright+# OpenProject is an open source project management software.+# Copyright (C) 2012-2021 the OpenProject GmbH+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License version 3.+#+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:+# Copyright (C) 2006-2013 Jean-Philippe Lang+# Copyright (C) 2010-2013 the ChiliProject Team+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License+# as published by the Free Software Foundation; either version 2+# of the License, or (at your option) any later version.+#+# This program is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU General Public License+# along with this program; if not, write to the Free Software+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.+#+# See docs/COPYRIGHT.rdoc for more details.+#++++module Documents+ class BaseContract < ::ModelContract+ include Attachments::ValidateReplacements++ def self.model+ Document+ end++ attribute :project+ attribute :category+ attribute :title+ attribute :description++ validate :validate_manage_allowed++ private++ def validate_manage_allowed+ unless user.allowed_to?(:manage_documents, model.project)+ errors.add :base, :error_unauthorized+ end+ end+ end+enddiff --git a/modules/documents/app/contracts/documents/create_contract.rb b/modules/documents/app/contracts/documents/create_contract.rbnew file mode 100644index 00000000000..29af7bcec61--- /dev/null+++ b/modules/documents/app/contracts/documents/create_contract.rb@@ -0,0 +1,34 @@+#-- encoding: UTF-8++#-- copyright+# OpenProject is an open source project management software.+# Copyright (C) 2012-2021 the OpenProject GmbH+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License version 3.+#+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:+# Copyright (C) 2006-2013 Jean-Philippe Lang+# Copyright (C) 2010-2013 the ChiliProject Team+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License+# as published by the Free Software Foundation; either version 2+# of the License, or (at your option) any later version.+#+# This program is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU General Public License+# along with this program; if not, write to the Free Software+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.+#+# See docs/COPYRIGHT.rdoc for more details.+#++++module Documents+ class CreateContract < BaseContract+ end+enddiff --git a/modules/documents/app/contracts/documents/update_contract.rb b/modules/documents/app/contracts/documents/update_contract.rbnew file mode 100644index 00000000000..1c83f98988e--- /dev/null+++ b/modules/documents/app/contracts/documents/update_contract.rb@@ -0,0 +1,34 @@+#-- encoding: UTF-8++#-- copyright+# OpenProject is an open source project management software.+# Copyright (C) 2012-2021 the OpenProject GmbH+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License version 3.+#+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:+# Copyright (C) 2006-2013 Jean-Philippe Lang+# Copyright (C) 2010-2013 the ChiliProject Team+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License+# as published by the Free Software Foundation; either version 2+# of the License, or (at your option) any later version.+#+# This program is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU General Public License+# along with this program; if not, write to the Free Software+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.+#+# See docs/COPYRIGHT.rdoc for more details.+#++++module Documents+ class UpdateContract < BaseContract+ end+enddiff --git a/modules/documents/app/controllers/documents_controller.rb b/modules/documents/app/controllers/documents_controller.rbindex f805cc106e7..1c3f4a22491 100644--- a/modules/documents/app/controllers/documents_controller.rb+++ b/modules/documents/app/controllers/documents_controller.rb@@ -29,6 +29,7 @@#++class DocumentsController < ApplicationController+ include AttachableServiceCalldefault_search_scope :documentsmodel_object Documentbefore_action :find_project_by_project_id, only: %i[index new create]@@ -64,14 +65,15 @@ class DocumentsController < ApplicationControllerenddef create- @document = @project.documents.build- @document.attributes = document_params- @document.attach_files(permitted_params.attachments.to_h)+ call = attachable_create_call ::Documents::CreateService,+ args: document_params.merge(project: @project)- if @document.save+ if call.success?flash[:notice] = I18n.t(:notice_successful_create)redirect_to project_documents_path(@project)else+ @document = call.result+ @errors = call.errorsrender action: 'new'endend@@ -81,13 +83,16 @@ class DocumentsController < ApplicationControllerenddef update- @document.attributes = document_params- @document.attach_files(permitted_params.attachments.to_h)+ call = attachable_update_call ::Documents::UpdateService,+ model: @document,+ args: document_params- if @document.save+ if call.success?flash[:notice] = I18n.t(:notice_successful_update)redirect_to action: 'show', id: @documentelse+ @document = call.result+ @errors = call.errorsrender action: 'edit'endend@@ -98,18 +103,19 @@ class DocumentsController < ApplicationControllerenddef add_attachment- @document.attach_files(permitted_params.attachments.to_h)- attachments = @document.attachments.select(&:new_record?)+ current_attachments = @document.attachments.pluck(:id)+ call = attachable_update_call ::Documents::UpdateService,+ model: @document,+ args: document_params- @document.save- saved_attachments = attachments.select(&:persisted?)+ if call.success? && Setting.notified_events.include?('document_added')+ added = call.result+ .attachments+ .reject { |a| current_attachments.include?(a.id) }- if saved_attachments.present? && Setting.notified_events.include?('document_added')- users = saved_attachments.first.container.recipients- users.each do |user|- UserMailer.attachments_added(user, saved_attachments).deliver_later- end+ notify_attachments addedend+redirect_to action: 'show', id: @documentend@@ -118,4 +124,14 @@ class DocumentsController < ApplicationControllerdef document_paramsparams.fetch(:document, {}).permit('category_id', 'title', 'description')end++ def notify_attachments(added)+ return if added.empty?++ users = added.first.container.recipients+ users.each do |user|+ UserMailer.attachments_added(user, added).deliver_later+ end+ end+enddiff --git a/modules/documents/app/services/documents/create_service.rb b/modules/documents/app/services/documents/create_service.rbnew file mode 100644index 00000000000..62ba3665e68--- /dev/null+++ b/modules/documents/app/services/documents/create_service.rb@@ -0,0 +1,35 @@+#-- encoding: UTF-8++#-- copyright+# OpenProject is an open source project management software.+# Copyright (C) 2012-2021 the OpenProject GmbH+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License version 3.+#+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:+# Copyright (C) 2006-2013 Jean-Philippe Lang+# Copyright (C) 2010-2013 the ChiliProject Team+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License+# as published by the Free Software Foundation; either version 2+# of the License, or (at your option) any later version.+#+# This program is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU General Public License+# along with this program; if not, write to the Free Software+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.+#+# See docs/COPYRIGHT.rdoc for more details.+#++++module Documents+ class CreateService < ::BaseServices::Create+ include Attachments::ReplaceAttachments+ end+enddiff --git a/modules/documents/app/services/documents/set_attributes_service.rb b/modules/documents/app/services/documents/set_attributes_service.rbnew file mode 100644index 00000000000..c9d4a807f3b--- /dev/null+++ b/modules/documents/app/services/documents/set_attributes_service.rb@@ -0,0 +1,35 @@+#-- encoding: UTF-8++#-- copyright+# OpenProject is an open source project management software.+# Copyright (C) 2012-2021 the OpenProject GmbH+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License version 3.+#+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:+# Copyright (C) 2006-2013 Jean-Philippe Lang+# Copyright (C) 2010-2013 the ChiliProject Team+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License+# as published by the Free Software Foundation; either version 2+# of the License, or (at your option) any later version.+#+# This program is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU General Public License+# along with this program; if not, write to the Free Software+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.+#+# See docs/COPYRIGHT.rdoc for more details.+#++++module Documents+ class SetAttributesService < ::BaseServices::SetAttributes+ include Attachments::SetReplacements+ end+enddiff --git a/modules/documents/app/services/documents/update_service.rb b/modules/documents/app/services/documents/update_service.rbnew file mode 100644index 00000000000..5e7013f28e2--- /dev/null+++ b/modules/documents/app/services/documents/update_service.rb@@ -0,0 +1,35 @@+#-- encoding: UTF-8++#-- copyright+# OpenProject is an open source project management software.+# Copyright (C) 2012-2021 the OpenProject GmbH+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License version 3.+#+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:+# Copyright (C) 2006-2013 Jean-Philippe Lang+# Copyright (C) 2010-2013 the ChiliProject Team+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License+# as published by the Free Software Foundation; either version 2+# of the License, or (at your option) any later version.+#+# This program is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU General Public License+# along with this program; if not, write to the Free Software+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.+#+# See docs/COPYRIGHT.rdoc for more details.+#++++module Documents+ class UpdateService < ::BaseServices::Update+ include Attachments::ReplaceAttachments+ end+enddiff --git a/modules/documents/app/views/documents/_form.html.erb b/modules/documents/app/views/documents/_form.html.erbindex 26cb35da227..3957fc46b5a 100644--- a/modules/documents/app/views/documents/_form.html.erb+++ b/modules/documents/app/views/documents/_form.html.erb@@ -27,7 +27,7 @@ See docs/COPYRIGHT.rdoc for more details.++#%>-<%= error_messages_for 'document' %>+<%= error_messages_for_contract @document, @errors %><div class="form--field -required"><%= f.select :category_id,diff --git a/modules/documents/spec/controllers/documents_controller_spec.rb b/modules/documents/spec/controllers/documents_controller_spec.rbindex 9227b5d9166..98deb4c8c06 100644--- a/modules/documents/spec/controllers/documents_controller_spec.rb+++ b/modules/documents/spec/controllers/documents_controller_spec.rb@@ -128,6 +128,7 @@ describe DocumentsController doenddescribe "with attachments" do+ let(:uncontainered) { FactoryBot.create :attachment, container: nil, author: admin }before donotify_project = projectFactoryBot.create(:member, project: notify_project, user: user, roles: [role])@@ -138,7 +139,7 @@ describe DocumentsController dodocument: FactoryBot.attributes_for(:document, title: "New Document",project_id: notify_project.id,category_id: default_category.id),- attachments: { '1' => { description: "sample file", file: file_attachment } }+ attachments: { '1' => { id: uncontainered.id } }}end@@ -147,8 +148,7 @@ describe DocumentsController doexpect(document.attachments.count).to eql 1attachment = document.attachments.first- expect(attachment.description).to eql "sample file"- expect(attachment.filename).to eql "testfile.txt"+ expect(uncontainered.reload).to eql attachmentendit "should redirect to the documents-page" do@@ -174,12 +174,14 @@ describe DocumentsController doenddescribe '#add_attachment' do+ let(:uncontainered) { FactoryBot.create :attachment, container: nil, author: admin }+before dodocumentpost :add_attachment,params: {id: document.id,- attachments: { '1' => { description: "sample file", file: file_attachment } }+ attachments: { '1' => { id: uncontainered.id } }}end@@ -187,6 +189,7 @@ describe DocumentsController doexpect(response).to be_redirectdocument.reloadexpect(document.attachments.length).to eq(1)+ expect(uncontainered.reload).to eq document.attachments.firstendenddiff --git a/modules/documents/spec/models/document_spec.rb b/modules/documents/spec/models/document_spec.rbindex b76ae232342..12813cb52e9 100644--- a/modules/documents/spec/models/document_spec.rb+++ b/modules/documents/spec/models/document_spec.rb@@ -86,8 +86,8 @@ describe Document doexpect doAttachments::CreateService- .new(valid_document, author: admin)- .call(uploaded_file: FactoryBot.attributes_for(:attachment)[:file], description: '')+ .new(user: admin)+ .call(container: valid_document, file: FactoryBot.attributes_for(:attachment)[:file], filename: 'foo')expect(valid_document.attachments.size).to eql 1end.to(change dodiff --git a/modules/documents/spec/requests/api/v3/attachments/attachments_by_documents_resource_spec.rb b/modules/documents/spec/requests/api/v3/attachments/attachments_by_documents_resource_spec.rbindex 4c12f43f303..552aef077b4 100644--- a/modules/documents/spec/requests/api/v3/attachments/attachments_by_documents_resource_spec.rb+++ b/modules/documents/spec/requests/api/v3/attachments/attachments_by_documents_resource_spec.rb@@ -27,113 +27,19 @@#++require 'spec_helper'-require 'rack/test'+require 'requests/api/v3/attachments/attachment_resource_shared_examples'-describe 'API v3 Attachments by document resource', type: :request do- include Rack::Test::Methods- include API::V3::Utilities::PathHelper- include FileHelpers+describe "document attachments" do+ it_behaves_like "an APIv3 attachment resource" do+ let(:attachment_type) { :document }- let(:current_user) do- FactoryBot.create(:user,- member_in_project: project,- member_through_role: role)- end- let(:project) { FactoryBot.create(:project) }- let(:role) { FactoryBot.create(:role, permissions: permissions) }- let(:permissions) { [:view_documents] }- let(:document) { FactoryBot.create(:document, project: project) }-- subject(:response) { last_response }-- before do- allow(User).to receive(:current).and_return current_user- end-- describe '#get' do- let(:get_path) { api_v3_paths.attachments_by_document document.id }-- before do- FactoryBot.create_list(:attachment, 2, container: document)- get get_path- end-- it 'should respond with 200' do- expect(subject.status).to eq(200)- end-- it_behaves_like 'API V3 collection response', 2, 2, 'Attachment'- end-- describe '#post' do- let(:permissions) { %i[view_documents manage_documents] }-- let(:request_path) { api_v3_paths.attachments_by_document document.id }- let(:request_parts) { { metadata: metadata.to_json, file: file } }- let(:metadata) { { fileName: 'cat.png' } }- let(:file) { mock_uploaded_file(name: 'original-filename.txt') }- let(:max_file_size) { 1 } # given in kiB-- before do- allow(Setting).to receive(:attachment_max_size).and_return max_file_size.to_s- post request_path, request_parts- end-- it 'should respond with HTTP Created' do- expect(subject.status).to eq(201)- end-- it 'should return the new attachment' do- expect(subject.body).to be_json_eql('Attachment'.to_json).at_path('_type')- end+ let(:create_permission) { :manage_documents }+ let(:read_permission) { :view_documents }+ let(:update_permission) { :manage_documents }- it 'ignores the original file name' do- expect(subject.body).to be_json_eql('cat.png'.to_json).at_path('fileName')- end-- context 'metadata section is missing' do- let(:request_parts) { { file: file } }-- it_behaves_like 'invalid request body', I18n.t('api_v3.errors.multipart_body_error')- end-- context 'file section is missing' do- # rack-test won't send a multipart request without a file being present- # however as long as we depend on correctly named sections this test should do just fine- let(:request_parts) { { metadata: metadata.to_json, wrongFileSection: file } }-- it_behaves_like 'invalid request body', I18n.t('api_v3.errors.multipart_body_error')- end-- context 'metadata section is no valid JSON' do- let(:request_parts) { { metadata: '"fileName": "cat.png"', file: file } }-- it_behaves_like 'parse error'- end-- context 'metadata is missing the fileName' do- let(:metadata) { Hash.new }-- it_behaves_like 'constraint violation' do- let(:message) { "fileName #{I18n.t('activerecord.errors.messages.blank')}" }- end- end-- context 'file is too large' do- let(:file) { mock_uploaded_file(content: 'a' * 2.kilobytes) }- let(:expanded_localization) do- I18n.t('activerecord.errors.messages.file_too_large', count: max_file_size.kilobytes)- end-- it_behaves_like 'constraint violation' do- let(:message) { "File #{expanded_localization}" }- end- end-- context 'only allowed to view documents' do- let(:permissions) { [:view_documents] }-- it_behaves_like 'unauthorized access'+ let(:document) do+ FactoryBot.create :document, project: projectendendend+diff --git a/modules/job_status/spec/services/documents/create_service_spec.rb b/modules/job_status/spec/services/documents/create_service_spec.rbnew file mode 100644index 00000000000..7bf9c46ff4a--- /dev/null+++ b/modules/job_status/spec/services/documents/create_service_spec.rb@@ -0,0 +1,6 @@+require 'spec_helper'+require 'services/base_services/behaves_like_create_service'++describe Documents::CreateService, type: :model do+ it_behaves_like 'BaseServices create service'+end\ No newline at end of filediff --git a/modules/job_status/spec/services/documents/update_service_spec.rb b/modules/job_status/spec/services/documents/update_service_spec.rbnew file mode 100644index 00000000000..511f0b398d3--- /dev/null+++ b/modules/job_status/spec/services/documents/update_service_spec.rb@@ -0,0 +1,36 @@+#-- encoding: UTF-8++#-- copyright+# OpenProject is an open source project management software.+# Copyright (C) 2012-2021 the OpenProject GmbH+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License version 3.+#+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:+# Copyright (C) 2006-2013 Jean-Philippe Lang+# Copyright (C) 2010-2013 the ChiliProject Team+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License+# as published by the Free Software Foundation; either version 2+# of the License, or (at your option) any later version.+#+# This program is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU General Public License+# along with this program; if not, write to the Free Software+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.+#+# See docs/COPYRIGHT.rdoc for more details.+#++++require 'spec_helper'+require 'services/base_services/behaves_like_update_service'++describe Documents::UpdateService, type: :model do+ it_behaves_like 'BaseServices update service'+enddiff --git a/modules/meeting/app/contracts/meeting_contents/base_contract.rb b/modules/meeting/app/contracts/meeting_contents/base_contract.rbnew file mode 100644index 00000000000..ed749bf2624--- /dev/null+++ b/modules/meeting/app/contracts/meeting_contents/base_contract.rb@@ -0,0 +1,55 @@+#-- encoding: UTF-8++#-- copyright+# OpenProject is an open source project management software.+# Copyright (C) 2012-2021 the OpenProject GmbH+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License version 3.+#+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:+# Copyright (C) 2006-2013 Jean-Philippe Lang+# Copyright (C) 2010-2013 the ChiliProject Team+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License+# as published by the Free Software Foundation; either version 2+# of the License, or (at your option) any later version.+#+# This program is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU General Public License+# along with this program; if not, write to the Free Software+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.+#+# See docs/COPYRIGHT.rdoc for more details.+#++++module MeetingContents+ class BaseContract < ::ModelContract+ include Attachments::ValidateReplacements++ def self.model+ MeetingContent+ end++ attribute :meeting+ attribute :text+ attribute :lock_version+ attribute :locked+ attribute :type++ validate :type_in_allowed++ private++ def type_in_allowed+ unless [MeetingAgenda.name, MeetingMinutes.name].include?(model.type)+ errors.add(:type, :inclusion)+ end+ end+ end+enddiff --git a/modules/meeting/app/contracts/meeting_contents/update_contract.rb b/modules/meeting/app/contracts/meeting_contents/update_contract.rbnew file mode 100644index 00000000000..605d58ff160--- /dev/null+++ b/modules/meeting/app/contracts/meeting_contents/update_contract.rb@@ -0,0 +1,43 @@+#-- encoding: UTF-8++#-- copyright+# OpenProject is an open source project management software.+# Copyright (C) 2012-2021 the OpenProject GmbH+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License version 3.+#+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:+# Copyright (C) 2006-2013 Jean-Philippe Lang+# Copyright (C) 2010-2013 the ChiliProject Team+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License+# as published by the Free Software Foundation; either version 2+# of the License, or (at your option) any later version.+#+# This program is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU General Public License+# along with this program; if not, write to the Free Software+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.+#+# See docs/COPYRIGHT.rdoc for more details.+#++++module MeetingContents+ class UpdateContract < BaseContract+ validate :validate_editable++ private++ def validate_editable+ unless model.editable?+ errors.add :base, :error_readonly+ end+ end+ end+enddiff --git a/modules/meeting/app/controllers/meeting_contents_controller.rb b/modules/meeting/app/controllers/meeting_contents_controller.rbindex dd89619493a..9ff36aca032 100644--- a/modules/meeting/app/controllers/meeting_contents_controller.rb+++ b/modules/meeting/app/controllers/meeting_contents_controller.rb@@ -27,6 +27,7 @@#++class MeetingContentsController < ApplicationController+ include AttachableServiceCallinclude PaginationHelpermenu_item :meetings@@ -60,26 +61,26 @@ class MeetingContentsController < ApplicationControllerenddef update- (render_403; return) unless @content.editable? # TODO: not tested!- @content.attributes = content_params.merge(author: User.current)- @content.attach_files(permitted_params.attachments.to_h)-- if [email protected]_version_changed?- if @content.save- flash[:notice] = I18n.t(:notice_successful_update)- redirect_back_or_default controller: '/meetings', action: 'show', id: @meeting- end+ call = attachable_update_call ::MeetingContents::UpdateService,+ model: @content,+ args: content_params++ if call.success?+ flash[:notice] = I18n.t(:notice_successful_update)+ redirect_back_or_default controller: '/meetings', action: 'show', id: @meetingelse- render_conflict+ flash.now[:error] = call.message+ params[:tab] ||= 'minutes' if @meeting.agenda.present? && @meeting.agenda.locked?+ render 'meetings/show'endenddef history# don't load text@content_versions = @content.journals.select('id, user_id, notes, created_at, version')- .order(Arel.sql('version DESC'))- .page(page_param)- .per_page(per_page_param)+ .order(Arel.sql('version DESC'))+ .page(page_param)+ .per_page(per_page_param)render 'meeting_contents/history', layout: !request.xhr?end@@ -129,19 +130,13 @@ class MeetingContentsController < ApplicationControllerdef find_meeting@meeting = Meeting.includes(:project, :author, :participants, :agenda, :minutes)- .find(params[:meeting_id])+ .find(params[:meeting_id])@project = @meeting.project@author = User.currentrescue ActiveRecord::RecordNotFoundrender_404end- def render_conflict- flash.now[:error] = I18n.t(:notice_locking_conflict)- params[:tab] ||= 'minutes' if @meeting.agenda.present? && @meeting.agenda.locked?- render 'meetings/show'- end-def content_paramsparams.require(@content_type).permit(:text, :lock_version, :comment)enddiff --git a/modules/meeting/app/services/meeting_contents/set_attributes_service.rb b/modules/meeting/app/services/meeting_contents/set_attributes_service.rbnew file mode 100644index 00000000000..321ea665fda--- /dev/null+++ b/modules/meeting/app/services/meeting_contents/set_attributes_service.rb@@ -0,0 +1,42 @@+#-- encoding: UTF-8++#-- copyright+# OpenProject is an open source project management software.+# Copyright (C) 2012-2021 the OpenProject GmbH+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License version 3.+#+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:+# Copyright (C) 2006-2013 Jean-Philippe Lang+# Copyright (C) 2010-2013 the ChiliProject Team+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License+# as published by the Free Software Foundation; either version 2+# of the License, or (at your option) any later version.+#+# This program is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU General Public License+# along with this program; if not, write to the Free Software+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.+#+# See docs/COPYRIGHT.rdoc for more details.+#++++module MeetingContents+ class SetAttributesService < ::BaseServices::SetAttributes+ include Attachments::SetReplacements+++ def set_default_attributes(_params)+ model.change_by_system do+ model.author = user if model.author.nil?+ end+ end+ end+enddiff --git a/modules/meeting/app/services/meeting_contents/update_service.rb b/modules/meeting/app/services/meeting_contents/update_service.rbnew file mode 100644index 00000000000..8eb13957337--- /dev/null+++ b/modules/meeting/app/services/meeting_contents/update_service.rb@@ -0,0 +1,47 @@+#-- encoding: UTF-8++#-- copyright+# OpenProject is an open source project management software.+# Copyright (C) 2012-2021 the OpenProject GmbH+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License version 3.+#+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:+# Copyright (C) 2006-2013 Jean-Philippe Lang+# Copyright (C) 2010-2013 the ChiliProject Team+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License+# as published by the Free Software Foundation; either version 2+# of the License, or (at your option) any later version.+#+# This program is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU General Public License+# along with this program; if not, write to the Free Software+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.+#+# See docs/COPYRIGHT.rdoc for more details.+#++++module MeetingContents+ class UpdateService < ::BaseServices::Update+ include Attachments::ReplaceAttachments++ def persist(call)+ content = call.result++ if content.lock_version_changed?+ call.errors.add(:base, I18n.t(:notice_locking_conflict))+ call.success = false+ return call+ end++ super+ end+ end+enddiff --git a/modules/meeting/spec/contracts/meeting_contents/update_contract_spec.rb b/modules/meeting/spec/contracts/meeting_contents/update_contract_spec.rbnew file mode 100644index 00000000000..3ebddead893--- /dev/null+++ b/modules/meeting/spec/contracts/meeting_contents/update_contract_spec.rb@@ -0,0 +1,55 @@+#-- encoding: UTF-8++#-- copyright+# OpenProject is an open source project management software.+# Copyright (C) 2012-2021 the OpenProject GmbH+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License version 3.+#+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:+# Copyright (C) 2006-2013 Jean-Philippe Lang+# Copyright (C) 2010-2013 the ChiliProject Team+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License+# as published by the Free Software Foundation; either version 2+# of the License, or (at your option) any later version.+#+# This program is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU General Public License+# along with this program; if not, write to the Free Software+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.+#+# See docs/COPYRIGHT.rdoc for more details.+#++++require 'spec_helper'+require 'contracts/shared/model_contract_shared_context'++describe MeetingContents::UpdateContract do+ include_context 'ModelContract shared context'+ let(:agenda) { FactoryBot.build_stubbed(:meeting_agenda) }+ let(:current_user) { FactoryBot.build_stubbed(:user) }+ let(:contract) { described_class.new(agenda, current_user) }++ context 'when not editable' do+ before do+ allow(agenda).to receive(:editable?).and_return false+ end++ it_behaves_like 'contract is invalid', base: :error_readonly+ end++ context 'when editable' do+ before do+ allow(agenda).to receive(:editable?).and_return true+ end++ it_behaves_like 'contract is valid'+ end+enddiff --git a/modules/meeting/spec/services/meeting_contents/update_service_spec.rb b/modules/meeting/spec/services/meeting_contents/update_service_spec.rbnew file mode 100644index 00000000000..11dc41cc59d--- /dev/null+++ b/modules/meeting/spec/services/meeting_contents/update_service_spec.rb@@ -0,0 +1,38 @@+#-- encoding: UTF-8++#-- copyright+# OpenProject is an open source project management software.+# Copyright (C) 2012-2021 the OpenProject GmbH+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License version 3.+#+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:+# Copyright (C) 2006-2013 Jean-Philippe Lang+# Copyright (C) 2010-2013 the ChiliProject Team+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License+# as published by the Free Software Foundation; either version 2+# of the License, or (at your option) any later version.+#+# This program is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU General Public License+# along with this program; if not, write to the Free Software+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.+#+# See docs/COPYRIGHT.rdoc for more details.+#++++require 'spec_helper'+require 'services/base_services/behaves_like_update_service'++describe MeetingContents::UpdateService, type: :model do+ it_behaves_like 'BaseServices update service' do+ let(:factory) { :meeting_agenda }+ end+enddiff --git a/spec/contracts/attachments/create_contract_spec.rb b/spec/contracts/attachments/create_contract_spec.rbnew file mode 100644index 00000000000..efcce412ac3--- /dev/null+++ b/spec/contracts/attachments/create_contract_spec.rb@@ -0,0 +1,143 @@+#-- encoding: UTF-8++#-- copyright+# OpenProject is an open source project management software.+# Copyright (C) 2012-2021 the OpenProject GmbH+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License version 3.+#+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:+# Copyright (C) 2006-2013 Jean-Philippe Lang+# Copyright (C) 2010-2013 the ChiliProject Team+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License+# as published by the Free Software Foundation; either version 2+# of the License, or (at your option) any later version.+#+# This program is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU General Public License+# along with this program; if not, write to the Free Software+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.+#+# See docs/COPYRIGHT.rdoc for more details.+#++++require 'spec_helper'+require 'contracts/shared/model_contract_shared_context'++describe Attachments::CreateContract do+ include_context 'ModelContract shared context'++ let(:current_user) { FactoryBot.build_stubbed :user }+ let(:model) do+ FactoryBot.build :attachment,+ container: container,+ content_type: content_type,+ file: file,+ filename: filename,+ author: current_user+ end+ let(:contract) { described_class.new model, user, options: contract_options }+ let(:contract_options) { {} }++ let(:user) { current_user }+ let(:container) { nil }+ let(:file) do+ Rack::Test::UploadedFile.new(+ Rails.root.join("spec/fixtures/files/image.png"),+ 'image/png',+ true+ )+ end+ let(:content_type) { 'image/png' }+ let(:filename) { 'image.png' }++ let(:can_attach_global) { true }++ before do+ allow(Redmine::Acts::Attachable.attachables)+ .to receive(:none?).and_return(!can_attach_global)+ end++ context 'with user who has no permissions' do+ let(:can_attach_global) { false }++ it_behaves_like 'contract is invalid', base: :error_unauthorized+ end++ context 'with a user that is not the author' do+ let(:user) { FactoryBot.build_stubbed :user }++ it_behaves_like 'contract is invalid', author: :invalid+ end++ context 'with user who has permissions to add' do+ it_behaves_like 'contract is valid'+ end++ context 'with a container' do+ let(:container) { FactoryBot.build_stubbed :work_package }++ before do+ allow(container)+ .to receive(:attachments_addable?)+ .with(user)+ .and_return(can_attach)+ end++ context 'with user who has no permissions' do+ let(:can_attach) { false }++ it_behaves_like 'contract is invalid', base: :error_unauthorized+ end++ context 'with user who has permissions to add' do+ let(:can_attach) { true }++ it_behaves_like 'contract is valid'+ end++ end++ context 'with an empty whitelist',+ with_settings: { attachment_whitelist: %w[] } do+ it_behaves_like 'contract is valid'+ end++ context 'with a matching mime whitelist',+ with_settings: { attachment_whitelist: %w[image/png] } do+ it_behaves_like 'contract is valid'+ end++ context 'with a matching extension whitelist',+ with_settings: { attachment_whitelist: %w[*.png] } do+ it_behaves_like 'contract is valid'+ end++ context 'with a non-matching whitelist',+ with_settings: { attachment_whitelist: %w[*.jpg image/jpeg] } do+ it_behaves_like 'contract is invalid', content_type: :not_whitelisted++ context 'when disabling the whitelist check' do+ let(:contract_options) do+ { whitelist: [] }+ end++ it_behaves_like 'contract is valid'+ end++ context 'when overriding the whitelist' do+ let(:contract_options) do+ { whitelist: %w[*.png] }+ end++ it_behaves_like 'contract is valid'+ end+ end+enddiff --git a/spec/factories/attachment_factory.rb b/spec/factories/attachment_factory.rbindex e09b57ab4a6..55c37949cb8 100644--- a/spec/factories/attachment_factory.rb+++ b/spec/factories/attachment_factory.rb@@ -45,6 +45,10 @@ FactoryBot.define dobinary: trueend+ callback(:after_build, :after_stub) do |attachment, evaluator|+ attachment.filename = evaluator.filename if evaluator.filename+ end+factory :wiki_attachment docontainer factory: :wiki_page_with_contentenddiff --git a/spec/features/auth/login_spec.rb b/spec/features/auth/login_spec.rbindex f3affef1d09..c1d3c8d1702 100644--- a/spec/features/auth/login_spec.rb+++ b/spec/features/auth/login_spec.rb@@ -28,7 +28,7 @@require 'spec_helper'-describe 'Login', type: :feature do+describe 'Login', type: :feature, clear_cache: true dobefore do@capybara_ignore_elements = Capybara.ignore_hidden_elementsCapybara.ignore_hidden_elements = truediff --git a/spec/lib/api/v3/attachments/attachment_metadata_representer_spec.rb b/spec/lib/api/v3/attachments/attachment_metadata_representer_spec.rbindex 1ea8f18f73d..094cdfb84fb 100644--- a/spec/lib/api/v3/attachments/attachment_metadata_representer_spec.rb+++ b/spec/lib/api/v3/attachments/attachment_metadata_representer_spec.rb@@ -28,15 +28,16 @@require 'spec_helper'-describe ::API::V3::Attachments::AttachmentMetadataRepresenter do+describe ::API::V3::Attachments::AttachmentParsingRepresenter do+ let(:current_user) { FactoryBot.build_stubbed :user }include API::V3::Utilities::PathHelperlet(:metadata) dodata = Hashie::Mash.new- data.file_name = original_file_name+ data.filename = original_file_namedata.description = original_descriptiondata.content_type = original_content_type- data.file_size = original_file_size+ data.filesize = original_file_sizedata.digest = original_digestdataend@@ -47,34 +48,18 @@ describe ::API::V3::Attachments::AttachmentMetadataRepresenter dolet(:original_file_size) { 42 }let(:original_digest) { "0xFF" }- let(:representer) { ::API::V3::Attachments::AttachmentMetadataRepresenter.new(metadata) }-- describe 'generation' do- subject { representer.to_json }-- it 'is a type-less representer' do- is_expected.not_to have_json_path('_type')- end-- it { is_expected.to be_json_eql(original_file_name.to_json).at_path('fileName') }- it { is_expected.to be_json_eql(original_content_type.to_json).at_path('contentType') }- it { is_expected.to be_json_eql(original_file_size.to_json).at_path('fileSize') }- it { is_expected.to be_json_eql(original_digest.to_json).at_path('digest') }-- it_behaves_like 'API V3 formattable', 'description' do- let(:format) { 'plain' }- let(:raw) { original_description }- end- end+ let(:representer) { described_class.new(metadata, current_user: current_user) }describe 'parsing' dolet(:parsed_hash) do{- 'fileName' => 'the parsed name',- 'description' => { 'raw' => 'the parsed description' },- 'contentType' => 'text/html',- 'fileSize' => 43,- 'digest' => '0x00'+ 'metadata' => {+ 'fileName' => 'the parsed name',+ 'description' => { 'raw' => 'the parsed description' },+ 'contentType' => 'text/html',+ 'fileSize' => 43,+ 'digest' => '0x00'+ }}end@@ -84,10 +69,10 @@ describe ::API::V3::Attachments::AttachmentMetadataRepresenter dorepresenter.from_hash parsed_hashend- it { expect(subject.file_name).to eql('the parsed name') }+ it { expect(subject.filename).to eql('the parsed name') }it { expect(subject.description).to eql('the parsed description') }it { expect(subject.content_type).to eql('text/html') }- it { expect(subject.file_size).to eql(43) }+ it { expect(subject.filesize).to eql(43) }it { expect(subject.digest).to eql('0x00') }endenddiff --git a/spec/models/attachment_spec.rb b/spec/models/attachment_spec.rbindex 3a8b70d157c..0235a1c6c24 100644--- a/spec/models/attachment_spec.rb+++ b/spec/models/attachment_spec.rb@@ -183,64 +183,6 @@ describe Attachment, type: :model doendend- describe '.create_pending_direct_upload' do- let(:file_size) { 6 }- let(:file_name) { 'document.png' }- let(:content_type) { "application/octet-stream" }-- subject do- described_class.create_pending_direct_upload(file_name: file_name,- author: author,- container: container,- content_type: content_type,- file_size: file_size)- end-- it 'returns the attachment' do- expect(subject)- .to be_a(Attachment)- end-- it 'sets the content_type' do- expect(subject.content_type)- .to eql content_type- end-- it 'sets the file_size' do- expect(subject.filesize)- .to eql file_size- end-- it 'sets the file for carrierwave' do- expect(subject.file.file.path)- .to end_with "attachment/file/#{subject.id}/#{file_name}"- end-- it 'sets the author' do- expect(subject.author)- .to eql author- end-- it 'sets the digest to empty string' do- expect(subject.digest)- .to eql ""- end-- it 'sets the download count to -1' do- expect(subject.downloads)- .to eql -1- end-- context 'with a special character in the filename' do- let(:file_name) { "document=number 5.png" }-- it 'sets the file for carrierwave' do- expect(subject.file.file.path)- .to end_with "attachment/file/#{subject.id}/document_number_5.png"- end- end- end-### The tests assumes the default, file-based storage is configured and tests against that.# I.e. it does not test fog attachments being deleted from the cloud storage (such as S3).diff --git a/spec/requests/api/v3/attachments/attachment_resource_shared_examples.rb b/spec/requests/api/v3/attachments/attachment_resource_shared_examples.rbindex b0f9b3068de..2788b911f84 100644--- a/spec/requests/api/v3/attachments/attachment_resource_shared_examples.rb+++ b/spec/requests/api/v3/attachments/attachment_resource_shared_examples.rb@@ -45,6 +45,7 @@ shared_examples 'it supports direct uploads' dolet(:request_parts) { { metadata: metadata.to_json, file: file } }let(:metadata) { { fileName: 'cat.png', fileSize: file.size, contentType: 'image/png' } }let(:file) { mock_uploaded_file(name: 'original-filename.txt') }+ let(:json_response) { JSON.parse last_response.body }def request!post request_path, request_parts@@ -57,8 +58,12 @@ shared_examples 'it supports direct uploads' dorequest!end- it 'should respond with HTTP Not Found' do- expect(subject.status).to eq(404)+ it 'should respond with validation error' do+ expect(subject.status).to eq(422)+ end++ it_behaves_like 'constraint violation' do+ let(:message) { "is not available due to a system configuration" }endend@@ -69,10 +74,15 @@ shared_examples 'it supports direct uploads' docontext 'with no filesize metadata' dolet(:metadata) { { fileName: 'cat.png' } }+ let(:json) { JSON.parse subject.body }it 'should respond with 422 due to missing file size metadata' doexpect(subject.status).to eq(422)- expect(subject.body).to include 'fileSize'+ expect(subject.body).to include 'Size'+ end++ it_behaves_like 'constraint violation' do+ let(:message) { "Size #{I18n.t('activerecord.errors.messages.blank')}" }endend@@ -255,7 +265,9 @@ shared_examples 'an APIv3 attachment resource', type: :request, content_type: :jcontext 'metadata section is missing' dolet(:request_parts) { { file: file } }- it_behaves_like 'invalid request body', I18n.t('api_v3.errors.multipart_body_error')+ it_behaves_like 'constraint violation' do+ let(:message) { "File #{I18n.t('activerecord.errors.messages.blank')}" }+ endendcontext 'file section is missing' do@@ -263,7 +275,9 @@ shared_examples 'an APIv3 attachment resource', type: :request, content_type: :j# however as long as we depend on correctly named sections this test should do just finelet(:request_parts) { { metadata: metadata.to_json, wrongFileSection: file } }- it_behaves_like 'invalid request body', I18n.t('api_v3.errors.multipart_body_error')+ it_behaves_like 'constraint violation' do+ let(:message) { "Content type #{I18n.t('activerecord.errors.messages.blank')}" }+ endendcontext 'metadata section is no valid JSON' do@@ -276,12 +290,13 @@ shared_examples 'an APIv3 attachment resource', type: :request, content_type: :jlet(:metadata) { Hash.new }it_behaves_like 'constraint violation' do- let(:message) { "fileName #{I18n.t('activerecord.errors.messages.blank')}" }+ let(:message) { "File #{I18n.t('activerecord.errors.messages.blank')}" }endendcontext 'file is too large' dolet(:file) { mock_uploaded_file(content: 'a' * 2.kilobytes) }+let(:expanded_localization) doI18n.t('activerecord.errors.messages.file_too_large', count: max_file_size.kilobytes)end@@ -538,7 +553,11 @@ shared_examples 'an APIv3 attachment resource', type: :request, content_type: :jcontext 'metadata section is missing' dolet(:request_parts) { { file: file } }- it_behaves_like 'invalid request body', I18n.t('api_v3.errors.multipart_body_error')+ it_behaves_like 'constraint violation' do+ # File here is the localized name for fileName property+ # which is derived from the missing metadata+ let(:message) { "File #{I18n.t('activerecord.errors.messages.blank')}" }+ endendcontext 'file section is missing' do@@ -546,7 +565,9 @@ shared_examples 'an APIv3 attachment resource', type: :request, content_type: :j# however as long as we depend on correctly named sections this test should do just finelet(:request_parts) { { metadata: metadata.to_json, wrongFileSection: file } }- it_behaves_like 'invalid request body', I18n.t('api_v3.errors.multipart_body_error')+ it_behaves_like 'constraint violation' do+ let(:message) { "Content type #{I18n.t('activerecord.errors.messages.blank')}" }+ endendcontext 'metadata section is no valid JSON' do@@ -559,7 +580,7 @@ shared_examples 'an APIv3 attachment resource', type: :request, content_type: :jlet(:metadata) { Hash.new }it_behaves_like 'constraint violation' do- let(:message) { "fileName #{I18n.t('activerecord.errors.messages.blank')}" }+ let(:message) { "File #{I18n.t('activerecord.errors.messages.blank')}" }endenddiff --git a/spec/services/attachments/create_service_integration_spec.rb b/spec/services/attachments/create_service_integration_spec.rbindex d683efde03e..ec8c03291f5 100644--- a/spec/services/attachments/create_service_integration_spec.rb+++ b/spec/services/attachments/create_service_integration_spec.rb@@ -30,19 +30,25 @@require 'spec_helper'describe Attachments::CreateService, 'integration', with_settings: { journal_aggregation_time_minutes: 0 } do- let(:user) { FactoryBot.create(:user) }let(:description) { 'a fancy description' }- subject { described_class.new(container, author: user) }+ subject { described_class.new(user: user) }describe '#call' dodef call_tested_method- subject.call uploaded_file: FileHelpers.mock_uploaded_file(name: 'foobar.txt'),+ subject.call container: container,+ file: FileHelpers.mock_uploaded_file(name: 'foobar.txt'),+ filename: 'foobar.txt',description: descriptionendcontext 'when journalized' do- let(:container) { FactoryBot.create(:work_package) }+ shared_let(:container) { FactoryBot.create(:work_package) }+ shared_let(:user) do+ FactoryBot.create :user,+ member_in_project: container.project,+ member_with_permissions: %i[view_work_packages edit_work_packages]+ endshared_examples 'successful creation' doit 'saves the attachment' do@@ -90,26 +96,22 @@ describe Attachments::CreateService, 'integration', with_settings: { journal_aggendcontext 'with an invalid attachment', with_settings: { attachment_max_size: 0 } do- it 'raises the exception' do+ it 'does not raise exceptions' doexpect { call_tested_method }- .to raise_exception ActiveRecord::RecordInvalid- end-- it 'does not create the attachment' do- begin- call_tested_method- rescue ActiveRecord::RecordInvalid- # expected- end+ .not_to raise_exception ActiveRecord::RecordInvalid- expect(Attachment.count)- .to eq 0+ expect(call_tested_method.errors[:file]).to include "is too large (maximum size is 0 Bytes)."endendendcontext 'when not journalized' do- let(:container) { FactoryBot.create(:message) }+ shared_let(:container) { FactoryBot.create(:message) }+ shared_let(:user) do+ FactoryBot.create :user,+ member_in_project: container.forum.project,+ member_with_permissions: %i[add_messages edit_messages]+ endshared_examples 'successful creation' doit 'saves the attachment' do@@ -158,6 +160,7 @@ describe Attachments::CreateService, 'integration', with_settings: { journal_aggcontext "when uncontainered" dolet(:container) { nil }+ let(:user) { FactoryBot.create :admin }before docall_tested_method@@ -169,5 +172,17 @@ describe Attachments::CreateService, 'integration', with_settings: { journal_aggexpect(attachment.description).to eq descriptionendend++ context "when user with no permissions" do+ let(:container) { nil }+ let(:user) { FactoryBot.build_stubbed :user }++ it 'does not save an attachment' do+ expect do+ expect(call_tested_method).to be_failure+ expect(call_tested_method.errors[:base]).to include 'may not be accessed.'+ end.not_to change { Attachment.count }+ end+ endendenddiff --git a/spec/services/attachments/prepare_upload_service_integration_spec.rb b/spec/services/attachments/prepare_upload_service_integration_spec.rbnew file mode 100644index 00000000000..8db117518fc--- /dev/null+++ b/spec/services/attachments/prepare_upload_service_integration_spec.rb@@ -0,0 +1,98 @@+#-- encoding: UTF-8++#-- copyright+# OpenProject is an open source project management software.+# Copyright (C) 2012-2020 the OpenProject GmbH+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License version 3.+#+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:+# Copyright (C) 2006-2013 Jean-Philippe Lang+# Copyright (C) 2010-2013 the ChiliProject Team+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License+# as published by the Free Software Foundation; either version 2+# of the License, or (at your option) any later version.+#+# This program is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU General Public License+# along with this program; if not, write to the Free Software+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.+#+# See docs/COPYRIGHT.rdoc for more details.++require 'spec_helper'++describe Attachments::PrepareUploadService,+ 'integration' do+ shared_let(:container) { FactoryBot.create(:work_package) }+ shared_let(:user) do+ FactoryBot.create :user,+ member_in_project: container.project,+ member_with_permissions: %i[view_work_packages edit_work_packages]+ end+ let(:instance) { described_class.new(user: user) }++ let(:file_size) { 6 }+ let(:file_name) { 'document.png' }+ let(:content_type) { "application/octet-stream" }++ let(:call) do+ instance.call filename: file_name,+ container: container,+ content_type: content_type,+ filesize: file_size+ end++ let(:attachment) { call.result }++ it 'returns the attachment' do+ expect(attachment)+ .to be_a(Attachment)+ end++ it 'sets the content_type' do+ expect(attachment.content_type)+ .to eql content_type+ end++ it 'sets the file_size' do+ expect(attachment.filesize)+ .to eql file_size+ end++ it 'sets the file for carrierwave' do+ expect(attachment.file.file.path)+ .to end_with "attachment/file/#{attachment.id}/#{file_name}"+ end++ it 'sets the author' do+ expect(attachment.author)+ .to eql user+ end++ it 'sets the digest to empty string' do+ expect(attachment.digest)+ .to eql ""+ end++ it 'sets the download count to -1' do+ expect(attachment.downloads)+ .to eql -1+ end++ context 'with a special character in the filename' do+ let(:file_name) { "document=number 5.png" }++ it 'sets the file for carrierwave' do+ expect(attachment.file.file.path)+ .to end_with "attachment/file/#{attachment.id}/document_number_5.png"+ end+ end+enddiff --git a/spec/support/shared/with_direct_uploads.rb b/spec/support/shared/with_direct_uploads.rbindex 280e3a99d20..ceee1aa2d4c 100644--- a/spec/support/shared/with_direct_uploads.rb+++ b/spec/support/shared/with_direct_uploads.rb@@ -78,14 +78,13 @@ class WithDirectUploadsenddef mock_attachment- allow(Attachment).to receive(:create) do |*args|+ allow_any_instance_of(::Attachments::PrepareUploadService)+ .to receive(:instance) do# We don't use create here because this would cause an infinite loop as FogAttachment's #create# uses the base class's #create which is what we are mocking here. All this is necessary to begin# with because the Attachment class is initialized with the LocalFileUploader before this test# is ever run and we need remote attachments using the FogFileUploader in this scenario.- record = FogAttachment.new *args- record.save- record+ FogAttachment.newend# This is so the uploaded callback works. Since we can't actually substitute the Attachment classdiff --git a/spec/workers/attachments/finish_direct_upload_job_integration_spec.rb b/spec/workers/attachments/finish_direct_upload_job_integration_spec.rbindex dc83bfc03ca..ea16e4d3099 100644--- a/spec/workers/attachments/finish_direct_upload_job_integration_spec.rb+++ b/spec/workers/attachments/finish_direct_upload_job_integration_spec.rb@@ -48,8 +48,9 @@ describe Attachments::FinishDirectUploadJob, 'integration', type: :job doexpect(attachment.downloads).to eql(0)+ # expect to replace the content type with the actual valueexpect(attachment.content_type)- .to eql('application/binary')+ .to eql('text/plain')expect(attachment.digest).to eql("9473fdd0d880a43c21b7778d34872157")enddiff --git a/spec/workers/backup_job_spec.rb b/spec/workers/backup_job_spec.rbindex 03e1c867136..3af5c101394 100644--- a/spec/workers/backup_job_spec.rb+++ b/spec/workers/backup_job_spec.rb@@ -59,7 +59,7 @@ describe BackupJob, type: :model dolet(:arguments) { [{ backup: backup, user: user, **opts }] }- let(:user) { FactoryBot.create :user }+ let(:user) { FactoryBot.create :admin }before doprevious_backup; backup; status # creatediff --git a/spec/workers/extract_fulltext_job_spec.rb b/spec/workers/extract_fulltext_job_spec.rbindex 802b72b53af..1267ebaac83 100644--- a/spec/workers/extract_fulltext_job_spec.rb+++ b/spec/workers/extract_fulltext_job_spec.rb@@ -31,86 +31,89 @@require 'spec_helper'describe ExtractFulltextJob, type: :job do- # These jobs only get created when TSVector is supported by the DB.- if OpenProject::Database.allows_tsv?- let(:text) { 'lorem ipsum' }- let(:attachment) do- FactoryBot.create(:attachment).tap do |attachment|- expect(ExtractFulltextJob)- .to have_been_enqueued- .with(attachment.id)-- perform_enqueued_jobs-- attachment.reload- end+ let(:text) { 'lorem ipsum' }+ let(:attachment) do+ FactoryBot.create(:attachment).tap do |attachment|+ expect(ExtractFulltextJob)+ .to have_been_enqueued+ .with(attachment.id)end+ end++ let(:subject) do+ perform_enqueued_jobs++ attachment.reload+ end++ before do+ allow(Attachment).to receive(:find_by).with(id: attachment.id).and_return(attachment)+ end- context "with successful text extraction" do+ context "with successful text extraction" do+ before do+ allow_any_instance_of(Plaintext::Resolver).to receive(:text).and_return(text)+ end++ context 'attachment is readable' dobefore do- allow_any_instance_of(Plaintext::Resolver).to receive(:text).and_return(text)+ allow(attachment).to receive(:readable?).and_return(true)+ subjectend- context 'attachment is readable' do- before do- allow(attachment).to receive(:readable?).and_return(true)- attachment.reload- end-- it 'updates the attachment\'s DB record with fulltext, fulltext_tsv, and file_tsv' do- expect(attachment.fulltext).to eq text- expect(attachment.fulltext_tsv.size).to be > 0- expect(attachment.file_tsv.size).to be > 0- end+ it 'updates the attachment\'s DB record with fulltext, fulltext_tsv, and file_tsv' do+ expect(attachment.fulltext).to eq text+ expect(attachment.fulltext_tsv.size).to be > 0+ expect(attachment.file_tsv.size).to be > 0+ end- # shared_examples 'no fulltext but file name saved as TSV' do- # end+ # shared_examples 'no fulltext but file name saved as TSV' do+ # end- context 'No content was extracted' do- let(:text) { nil }+ context 'No content was extracted' do+ let(:text) { nil }- # include_examples 'no fulltext but file name saved as TSV'- it 'updates the attachment\'s DB record with file_tsv' do- expect(attachment.fulltext).to be_blank- expect(attachment.fulltext_tsv).to be_blank- expect(attachment.file_tsv.size).to be > 0- end+ # include_examples 'no fulltext but file name saved as TSV'+ it 'updates the attachment\'s DB record with file_tsv' do+ expect(attachment.fulltext).to be_blank+ expect(attachment.fulltext_tsv).to be_blank+ expect(attachment.file_tsv.size).to be > 0endendend+ end- shared_examples 'only file name indexed' do- it 'updates the attachment\'s DB record with file_tsv' do- expect(attachment.fulltext).to be_blank- expect(attachment.fulltext_tsv).to be_blank- expect(attachment.file_tsv.size).to be > 0- end+ shared_examples 'only file name indexed' do+ it 'updates the attachment\'s DB record with file_tsv' do+ expect(attachment.fulltext).to be_blank+ expect(attachment.fulltext_tsv).to be_blank+ expect(attachment.file_tsv.size).to be > 0end+ end- context 'file not readable' do- before do- allow(attachment).to receive(:readable?).and_return(false)- attachment.reload- end-- include_examples 'only file name indexed'+ context 'file not readable' do+ before do+ allow(attachment).to receive(:readable?).and_return(false)+ subjectend- context 'with exception in extraction' do- let(:exception_message) { 'boom-internal-error' }- let(:logger) { Rails.logger }+ include_examples 'only file name indexed'+ end- before do- allow_any_instance_of(Plaintext::Resolver).to receive(:text).and_raise(exception_message)+ context 'with exception in extraction' do+ let(:exception_message) { 'boom-internal-error' }+ let(:logger) { Rails.logger }- # This line is actually part of the test. `expect` call needs to go so far up here, as we want to verify that a message gets logged.- expect(logger).to receive(:error).with(/boom-internal-error/)+ before do+ allow_any_instance_of(Plaintext::Resolver).to receive(:text).and_raise(exception_message)- allow(attachment).to receive(:readable?).and_return(true)- attachment.reload- end+ # This line is actually part of the test. `expect` call needs to go so far up here, as we want to verify that a message gets logged.+ expect(logger).to receive(:error).with(/boom-internal-error/)- include_examples 'only file name indexed'+ allow(attachment).to receive(:readable?).and_return(true)+ subjectend++ include_examples 'only file name indexed'endenddiff --git a/spec/workers/work_packages/exports/export_job_spec.rb b/spec/workers/work_packages/exports/export_job_spec.rbindex e9ae9a9a51f..48ed7ffd6cd 100644--- a/spec/workers/work_packages/exports/export_job_spec.rb+++ b/spec/workers/work_packages/exports/export_job_spec.rb@@ -68,22 +68,22 @@ describe WorkPackages::Exports::ExportJob doservice = double('attachments create service')expect(Attachments::CreateService)- .to receive(:new)- .with(export, author: user)+ .to receive(:bypass_whitelist)+ .with(user: user).and_return(service)expect(WorkPackages::Exports::CleanupOutdatedJob).to receive(:perform_after_grace)expect(service)- .to receive(:call) do |uploaded_file:, description:|- expect(File.basename(uploaded_file))+ .to receive(:call) do |file:, **args|+ expect(File.basename(file)).to start_with 'some_title'- expect(File.basename(uploaded_file))+ expect(File.basename(file)).to end_with ".#{mime_type}"- attachment+ ServiceResult.new(result: attachment, success: true)endallow("WorkPackage::Exporter::#{mime_type.upcase}".constantize)