Skip to content

OpenProject is the leading open source project management software for product, project and portfolio management. A powerful Jira alternative with agile planning, issue tracking, roadmaps, Gantt charts, time tracking, collaboration features, and more. Available on premises or in the cloud. ⭐ Star us on GitHub

Fetch live data for a set of file IDs from Nextcloud when requesting file links

Frank Bergmannb6e83c8ec49c
diff --git a/app/services/oauth_clients/connection_manager.rb b/app/services/oauth_clients/connection_manager.rb
index a51f44d0dc6..f27e85d3d44 100644
--- a/app/services/oauth_clients/connection_manager.rb
+++ b/app/services/oauth_clients/connection_manager.rb
@@ -46,6 +46,7 @@ module OAuthClients
# Returns an OAuthClientToken object or a String in case a renew is required.
# @param state (OAuth2 RFC) encapsulates the state of the calling page (URL + params) to return
# @param scope (OAuth2 RFC) specifies the resources to access. Nextcloud only has one global scope.
+ # @return ServiceResult with ServiceResult.result being either an OAuthClientToken or a redirection URL
def get_access_token(scope: [], state: nil)
# Check for an already existing token from last call
token = get_existing_token
diff --git a/lib/api/v3/utilities/path_helper.rb b/lib/api/v3/utilities/path_helper.rb
index 499ec95eac2..afd3932600c 100644
--- a/lib/api/v3/utilities/path_helper.rb
+++ b/lib/api/v3/utilities/path_helper.rb
@@ -480,6 +480,10 @@ module API
"#{work_package(id)}/relations"
end
+ def self.work_package_file_links(id)
+ "#{work_package(id)}/file_links"
+ end
+
def self.work_package_relation(id, work_package_id)
"#{work_package_relations(work_package_id)}/#{id}"
end
diff --git a/modules/storages/app/models/storages/file_link.rb b/modules/storages/app/models/storages/file_link.rb
index 79317938a9f..e3eec7ba579 100644
--- a/modules/storages/app/models/storages/file_link.rb
+++ b/modules/storages/app/models/storages/file_link.rb
@@ -38,6 +38,9 @@
# Additional attributes and constraints are defined in
# db/migrate/20220113144759_create_file_links.rb migration.
class Storages::FileLink < ApplicationRecord
+ # Is this file shared with me in Nextcloud? This attribute is _not_ stored in the DB
+ attr_accessor :origin_permission
+
# Every FileLink references its Storage. A "on delete cascade" is defined in
# the migration, so this FileLink will be deleted when deleting the Storage.
belongs_to :storage
diff --git a/modules/storages/app/services/storages/file_link_sync_service.rb b/modules/storages/app/services/storages/file_link_sync_service.rb
new file mode 100644
index 00000000000..4a35e947b17
--- /dev/null
+++ b/modules/storages/app/services/storages/file_link_sync_service.rb
@@ -0,0 +1,209 @@
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2022 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 COPYRIGHT and LICENSE files for more details.
+#++
+
+# Handle synchronization of FileLinks with external data store such as Storages
+class Storages::FileLinkSyncService
+ # @param user Current user
+ # @param file_links An array of FileLink objects
+ def initialize(user:)
+ @user = user
+ @service_result = ServiceResult.success(result: [])
+ end
+
+ # Synchronize the "cached" FileLinks in the database with a Nextcloud response.
+ # We assume a OAuthClientToken is present, because this service is called after
+ # the storage endpoint.
+ # @return ServiceResult with FileLinks in the result
+ def call(file_links)
+ @file_links = file_links
+ # Reset permissions to nil (undefined) by default.
+ @file_links.each { |file_link| file_link.origin_permission = nil }
+
+ # Group by storage_id, creating a hash { storage_id => [file_links] }
+ storage_file_link_hash = @file_links.group_by(&:storage_id)
+
+ # Iterate over storages and send the list of file_links to Nextcloud
+ storage_file_link_hash.each do |storage_id, storage_file_links|
+ # Get the OAuthClientToken that will authenticate us against Nextcloud
+ oauth_client = OAuthClient.find_by(integration_id: storage_id)
+ connection_manager = ::OAuthClients::ConnectionManager.new(user: @user, oauth_client:)
+ service_result = connection_manager.get_access_token # No scope for Nextcloud...
+ oauth_client_token = service_result.result
+
+ # Return the error codes from ConnectionManager.get_access_token to calling method
+ return service_result unless service_result.success
+
+ # Get info about files. Result is either an Exception or Net::HTTPOK with body
+ storage_origin_file_ids = storage_file_links.map(&:origin_id)
+
+ tries = 2
+ parsed_response = :not_authorized
+ while parsed_response == :not_authorized && tries > 0
+ tries -= 1
+ http_response = request_files_info(oauth_client_token, storage_origin_file_ids)
+ parsed_response = parse_files_info_response(http_response) # symbol for errors, Hash for 200 result
+
+ if parsed_response == :not_authorized && tries > 0
+ refresh_service_result = connection_manager.refresh_token
+ unless refresh_service_result.success?
+ @service_result.merge!(refresh_service_result)
+ break # parsed_response is correctly :not_authorized here
+ end
+ end
+ end
+
+ if parsed_response.class.to_s != "Hash"
+ @service_result.result += storage_file_links.each { |file_link| file_link.origin_permission = :error }
+ @service_result.success = false
+ break
+ end
+
+ storage_file_links.each do |file_link|
+ origin_file_info_hash = parsed_response[file_link.origin_id]
+
+ case origin_file_info_hash['statuscode']
+ when 200 # Successfully found - update infos
+ next if origin_file_info_hash['trashed'] # moved to trash in Nextcloud
+
+ sync_single_file(file_link, origin_file_info_hash)
+ file_link.origin_permission = :view
+ @service_result.result << file_link
+ when 403 # Forbidden - file from other user?
+ file_link.origin_permission = :not_allowed
+ @service_result.result << file_link
+ when 404 # Not found - internal error?
+ file_link.destroy
+ else
+ file_link.origin_permission = :error
+ @service_result.result << file_link
+ end
+
+ # Only saves to database if some field has actually changed.
+ file_link.save unless file_link.destroyed?
+ end
+ end
+
+ @service_result
+ end
+
+ # Write the updated information from Nextcloud to a single file
+ # @param storage Storage of the file
+ # @param origin_file_id Nextcloud ID of the file
+ # @param origin_file_info_hash Hash with updated information from Nextcloud
+ # "24" => {
+ # "id" : 24, # origin_file_id
+ # "ctime" : 0, # Linux epoch file creation +overwrite
+ # "mtime" : 1655301278, # Linux epoch file modification +overwrite
+ # "mimetype" : "application/pdf", # +overwrite
+ # "name" : "Nextcloud Manual.pdf", # "Canonical" name, could changed by owner +overwrite
+ # "owner_id" : "admin", # ID at Nextcloud side +overwrite
+ # "owner_name" : "admin", # Name at Nextcloud side +overwrite
+ # "size" : 12706214, # Not used yet in OpenProject +overwrite
+ # "status" : "OK", # Not used yet
+ # "statuscode" : 200, # Not used yet
+ # "trashed" : false # Exclude trashed files from result array of FileLinks
+ # }
+ #
+ # ToDo:
+ # In case of permission errors (depending on the current user) we get:
+ # "24" => { "status" => "Forbidden", "statuscode" => 403 }
+ # In case of completely deleted file or other errors we might also get:
+ # "24" = { "status" => "Not Found", "statuscode" => 404 }
+ # ToDo: What happens if nothing at all or an empty hash comes back for an origin_file_id
+ def sync_single_file(file_link, origin_file_info_hash)
+ file_link.origin_mime_type = origin_file_info_hash["mimetype"]
+ file_link.origin_created_by_name = origin_file_info_hash["owner_name"]
+ file_link.origin_name = origin_file_info_hash["name"]
+ file_link.origin_created_at = Time.zone.at(origin_file_info_hash["ctime"])
+ file_link.origin_updated_at = Time.zone.at(origin_file_info_hash["mtime"])
+
+ file_link
+ end
+
+ private
+
+ # Check the Nextcloud status of a list of files:
+ # The endpoint returns "canonical" infos per file. Canonical means that the attributes are the same
+ # as the owner sees them and not the current user. If it was the current user the file name could be
+ # different for that user as a shared file can be renamed.
+ # @param oauth_client_token A OAuth2 authentication token also carrying the host
+ # @param file_ids An array of Nextcloud IDs of files to check
+ # @return A HTTP response or an Exception object
+ #
+ # curl -H "Accept: application/json" -H "Content-Type:application/json" -H "OCS-APIRequest: true"
+ # -u USER:PASSWD http://my.nc.org/ocs/v1.php/apps/integration_openproject/filesinfo
+ # -X POST -d '{"fileIds":[FILE_ID_1,FILE_ID_2,...]}'
+ def request_files_info(oauth_client_token, file_ids)
+ host = oauth_client_token.oauth_client.integration.host
+ uri = URI.parse(File.join(host, "/ocs/v1.php/apps/integration_openproject/filesinfo"))
+ request = Net::HTTP::Post.new(uri)
+
+ json_hash = { fileIds: file_ids }
+ request.body = json_hash.to_json
+ request['Content-Type'] = 'application/json'
+ request['OCS-APIRequest'] = 'true'
+ request['Accept'] = 'application/json'
+ request['Authorization'] = "Bearer #{oauth_client_token.access_token}"
+ # request.basic_auth 'admin', 'admin'
+
+ # ToDo: Handle token error requiring a refresh
+
+ req_options = {
+ max_retries: 0,
+ open_timeout: 5, # seconds
+ read_timeout: 3 # seconds
+ }
+
+ begin
+ Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
+ http.request(request)
+ end
+ rescue StandardError => e
+ e
+ end
+ end
+
+ # Takes a response from querying Nextcloud file IDS (an Exception or a HTTP::Response),
+ # parses the returned JSON and
+ # @return array of file information or an :error symbol
+ def parse_files_info_response(response)
+ return :error if response.is_a? StandardError
+ return :error unless response.key?('content-type') # Reply without content-type can't be valid.
+ return :error if response['content-type'].split(';').first.strip.downcase != 'application/json'
+ return :not_authorized if response.code == "401" # Nextcloud response if token has expired
+ return :error if response.code != "200" # Interpret any other response as an error
+
+ begin
+ response_hash = JSON.parse(response.body).dig('ocs', 'data')
+ rescue JSON::ParserError
+ return :error
+ end
+
+ response_hash
+ end
+end
diff --git a/modules/storages/lib/api/v3/file_links/file_link_representer.rb b/modules/storages/lib/api/v3/file_links/file_link_representer.rb
index 385f5ccfd97..acea66ed135 100644
--- a/modules/storages/lib/api/v3/file_links/file_link_representer.rb
+++ b/modules/storages/lib/api/v3/file_links/file_link_representer.rb
@@ -31,6 +31,22 @@ module API
module FileLinks
URN_PERMISSION_VIEW = "#{::API::V3::URN_PREFIX}file-links:permission:View".freeze
URN_PERMISSION_NOT_ALLOWED = "#{::API::V3::URN_PREFIX}file-links:permission:NotAllowed".freeze
+ URN_PERMISSION_ERROR = "#{::API::V3::URN_PREFIX}file-links:permission:Error".freeze
+
+ PERMISSION_LINKS = {
+ view: {
+ href: URN_PERMISSION_VIEW,
+ title: 'View'
+ },
+ not_allowed: {
+ href: URN_PERMISSION_NOT_ALLOWED,
+ title: 'Not allowed'
+ },
+ error: {
+ href: URN_PERMISSION_ERROR,
+ title: 'Error'
+ }
+ }
class FileLinkRepresenter < ::API::Decorators::Single
include API::Decorators::LinkedResource
@@ -69,12 +85,9 @@ module API
}
end
- link :permission do
- # TODO: replace with service to check real permission state
- {
- href: URN_PERMISSION_VIEW,
- title: 'View'
- }
+ # Show a permission link only if we have actual permission information for a specific user
+ link :permission, uncacheable: true do
+ PERMISSION_LINKS[represented.origin_permission] unless represented.origin_permission.nil?
end
link :originOpen do
diff --git a/modules/storages/lib/api/v3/file_links/work_packages_file_links_api.rb b/modules/storages/lib/api/v3/file_links/work_packages_file_links_api.rb
index 20c4efc90dd..a64a8b1a9f6 100644
--- a/modules/storages/lib/api/v3/file_links/work_packages_file_links_api.rb
+++ b/modules/storages/lib/api/v3/file_links/work_packages_file_links_api.rb
@@ -42,18 +42,49 @@ module API
reply_with_not_found_if_module_inactive
end
+ # ToDo: Check race condition if two users try to get the same WP file_links?
+
# The `:resources` keyword defines the API namespace -> /api/v3/work_packages/:id/file_links/...
resources :file_links do
- # A helper is used to define the behaviour at GET /api/v3/work_packages/:id/file_links
- get &::API::V3::Utilities::Endpoints::Index
- .new(model: ::Storages::FileLink,
- scope: -> { visible_file_links_scope.where(container_id: @work_package.id) },
- self_path: -> { api_v3_paths.file_links(params[:id]) })
- .mount
+ # Get the list of FileLinks related to a work package, with updated information from Nextcloud.
+ get do
+ # API supports query filters on storages:
+ # storage: { operator: '=', values: [storage_id]
+ query = ParamsToQueryService
+ .new(::Storages::Storage,
+ current_user,
+ query_class: ::Queries::Storages::FileLinks::FileLinkQuery)
+ .call(params)
+ # raise "Error" unless query.valid?
+
+ # Get the list of all FileLinks for the work package.
+ # This could be a huge array in some cases...
+ file_links = query
+ .results
+ .where(id: visible_file_links_scope
+ .where(container_id: @work_package.id, container_type: 'WorkPackage'))
+ .all
+
+ # ToDo: API allows queries on storages, how to integrate here?
+ # Example: -> grids_api.rb
+
+ # Synchronize with Nextcloud. StorageAPI handles OAuth2 for us.
+ service_result = ::Storages::FileLinkSyncService
+ .new(user: current_user)
+ .call(file_links)
+
+ if service_result.success?
+ ::API::V3::FileLinks::FileLinkCollectionRepresenter.new(
+ service_result.result,
+ self_link: api_v3_paths.work_package_file_links(@work_package.id),
+ current_user:
+ )
+ else
+ # There was an error during the SyncService, which should normally not occur.
+ raise StandardError, message: service_result.message
+ end
+ end
- # A helper is used to define the behaviour at POST /api/v3/work_packages/:id/file_links.
- # Additional classes are provided, that overwrite standard behaviour for parsing request parameters or
- # rendering the response.
post &CreateEndpoint
.new(
model: ::Storages::FileLink,
diff --git a/modules/storages/spec/lib/api/v3/file_links/file_link_representer_rendering_spec.rb b/modules/storages/spec/lib/api/v3/file_links/file_link_representer_rendering_spec.rb
index 5b8a43a8a46..2f4ad79c42b 100644
--- a/modules/storages/spec/lib/api/v3/file_links/file_link_representer_rendering_spec.rb
+++ b/modules/storages/spec/lib/api/v3/file_links/file_link_representer_rendering_spec.rb
@@ -34,7 +34,8 @@ describe ::API::V3::FileLinks::FileLinkRepresenter, 'rendering' do
let(:storage) { build_stubbed(:storage) }
let(:container) { build_stubbed(:work_package) }
let(:creator) { build_stubbed(:user, firstname: 'Rey', lastname: 'Palpatine') }
- let(:file_link) { build_stubbed(:file_link, storage:, container:, creator:) }
+ let(:origin_permission) { :view }
+ let(:file_link) { build_stubbed(:file_link, storage:, container:, creator:, origin_permission: origin_permission) }
let(:user) { build_stubbed(:user) }
let(:representer) { described_class.new(file_link, current_user: user) }
@@ -84,10 +85,40 @@ describe ::API::V3::FileLinks::FileLinkRepresenter, 'rendering' do
end
describe 'permission' do
- it_behaves_like 'has a titled link' do
- let(:link) { 'permission' }
- let(:href) { 'urn:openproject-org:api:v3:file-links:permission:View' }
- let(:title) { 'View' }
+ context 'with permission granted' do
+ it_behaves_like 'has a titled link' do
+ let(:link) { 'permission' }
+ let(:href) { 'urn:openproject-org:api:v3:file-links:permission:View' }
+ let(:title) { 'View' }
+ end
+ end
+
+ context 'with permission NotAllowed' do
+ let(:origin_permission) { :not_allowed }
+
+ it_behaves_like 'has a titled link' do
+ let(:link) { 'permission' }
+ let(:href) { 'urn:openproject-org:api:v3:file-links:permission:NotAllowed' }
+ let(:title) { 'Not allowed' }
+ end
+ end
+
+ context 'with permission not defined (nil)' do
+ let(:origin_permission) { nil }
+
+ it_behaves_like 'has no link' do
+ let(:link) { 'permission' }
+ end
+ end
+
+ context 'with permission check had an Error' do
+ let(:origin_permission) { :error }
+
+ it_behaves_like 'has a titled link' do
+ let(:link) { 'permission' }
+ let(:href) { 'urn:openproject-org:api:v3:file-links:permission:Error' }
+ let(:title) { 'Error' }
+ end
end
end
diff --git a/modules/storages/spec/requests/api/v3/file_links/file_links_spec.rb b/modules/storages/spec/requests/api/v3/file_links/file_links_spec.rb
index 427f834bf63..7de3b8cb18d 100644
--- a/modules/storages/spec/requests/api/v3/file_links/file_links_spec.rb
+++ b/modules/storages/spec/requests/api/v3/file_links/file_links_spec.rb
@@ -29,7 +29,7 @@
require 'spec_helper'
require_module_spec_helper
-describe 'API v3 file links resource', with_flag: { storages_module_active: true }, type: :request do
+describe 'API v3 file links resource', with_flag: { storages_module_active: true }, type: :request, webmock: true do
include API::V3::Utilities::PathHelper
let(:permissions) { %i(view_work_packages view_file_links) }
@@ -45,8 +45,11 @@ describe 'API v3 file links resource', with_flag: { storages_module_active: true
let(:storage) { create(:storage, creator: current_user) }
let(:another_storage) { create(:storage, creator: current_user) }
+ let(:oauth_client) { create(:oauth_client, integration: storage) }
+ let(:oauth_client_token) { create(:oauth_client_token, oauth_client:, user: current_user) }
+
let!(:project_storage) { create(:project_storage, project:, storage:) }
- let!(:another_project_storage) { nil }
+ let!(:another_project_storage) { nil } # create(:project_storage, project:, storage: another_storage)
let(:file_link) do
create(:file_link, creator: current_user, container: work_package, storage:)
@@ -56,21 +59,34 @@ describe 'API v3 file links resource', with_flag: { storages_module_active: true
end
# If a storage mapping between a project and a storage is removed, the file link still persist. This can occur on
# moving a work package to another project, too, if target project does not yet have the storage mapping.
- let(:file_link_of_unlinked_storage) do
+ let(:file_link_of_another_storage) do
create(:file_link, creator: current_user, container: work_package, storage: another_storage)
end
let(:connection_manager) { instance_double(::OAuthClients::ConnectionManager) }
+ let(:sync_service) { instance_double(::Storages::FileLinkSyncService) }
subject(:response) { last_response }
before do
+ # Mock ConnectionManager to behave as if connected
allow(::OAuthClients::ConnectionManager)
.to receive(:new).and_return(connection_manager)
+ allow(connection_manager)
+ .to receive(:get_access_token)
+ .and_return(ServiceResult.success(result: oauth_client_token))
allow(connection_manager)
.to receive(:authorization_state).and_return(:connected)
allow(connection_manager)
.to receive(:redirect_to_oauth_authorize).and_return('https://example.com/authorize')
+
+ # Mock FileLinkSyncService as if Nextcloud would respond positively
+ allow(::Storages::FileLinkSyncService)
+ .to receive(:new).and_return(sync_service)
+ allow(sync_service).to receive(:call) do |file_links|
+ ServiceResult.success(result: file_links)
+ end
+
login_as current_user
end
@@ -80,12 +96,14 @@ describe 'API v3 file links resource', with_flag: { storages_module_active: true
before do
file_link
file_link_of_other_work_package
- file_link_of_unlinked_storage
+ file_link_of_another_storage
get path
end
- it_behaves_like 'API V3 collection response', 1, 1, 'FileLink', 'Collection' do
- let(:elements) { [file_link] }
+ context 'with all preconditions met (happy path)' do
+ it_behaves_like 'API V3 collection response', 1, 1, 'FileLink', 'Collection' do
+ let(:elements) { [file_link] }
+ end
end
context 'if user has not sufficient permissions' do
@@ -130,10 +148,14 @@ describe 'API v3 file links resource', with_flag: { storages_module_active: true
it_behaves_like 'API V3 collection response', 1, 1, 'FileLink', 'Collection' do
# has the now linked storage's file links
- let(:elements) { [file_link_of_unlinked_storage] }
+ let(:elements) { [file_link_of_another_storage] }
end
end
end
+
+ context 'with connection error to Nextcloud' do
+ pending "Check that a suitable error message is returned"
+ end
end
describe 'POST /api/v3/work_packages/:work_package_id/file_links' do
@@ -379,7 +401,7 @@ describe 'API v3 file links resource', with_flag: { storages_module_active: true
end
context 'if file link is in a work package, while its project is not mapped to the file link\'s storage.' do
- let(:path) { api_v3_paths.file_link(file_link_of_unlinked_storage.id) }
+ let(:path) { api_v3_paths.file_link(file_link_of_another_storage.id) }
it_behaves_like 'not found'
end
diff --git a/modules/storages/spec/services/storages/file_links/file_link_sync_service_spec.rb b/modules/storages/spec/services/storages/file_links/file_link_sync_service_spec.rb
new file mode 100644
index 00000000000..526b34d3d1b
--- /dev/null
+++ b/modules/storages/spec/services/storages/file_links/file_link_sync_service_spec.rb
@@ -0,0 +1,361 @@
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2022 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 COPYRIGHT and LICENSE files for more details.
+#++
+
+require 'spec_helper'
+require 'webmock/rspec'
+
+# The FileLinkSyncService takes an array of FileLink models and
+# performs a REST call to a Nextcloud server to check which of the
+# links are visible to the current user ("shared_with_me").
+# We want to test that permissions are processed correctoy and also
+# test the reaction to various types of network issues.
+# This spec bears some similarities to the connection_manager_spec.rb.
+describe ::Storages::FileLinkSyncService, type: :model do
+ let(:user) { create :user }
+ let(:role) { create(:existing_role, permissions: [:manage_file_links]) }
+ let(:project) { create(:project, members: { user => role }) }
+ let(:work_package) { create(:work_package, project:) }
+
+ # We want to check the case of file_links from multiple storages
+ let(:host1) { "http://host-1.example.org" }
+ let(:host2) { "http://host-2.example.org" }
+ let(:storage1) { create(:storage, host: host1) }
+ let(:storage2) { create(:storage, host: host2) }
+ let(:oauth_client1) { create(:oauth_client, integration: storage1) }
+ let(:oauth_client2) { create(:oauth_client, integration: storage2) }
+ let(:oauth_client_token1) { create(:oauth_client_token, oauth_client: oauth_client1, user:) }
+ let(:oauth_client_token2) { create(:oauth_client_token, oauth_client: oauth_client2, user:) }
+ let(:file_link1) do
+ create(:file_link,
+ origin_id: "24",
+ origin_updated_at: Time.zone.at(1655301000),
+ storage: storage1,
+ container: work_package)
+ end
+ let(:file_link2) do
+ create(:file_link,
+ origin_id: '25',
+ origin_updated_at: Time.zone.at(1655301000),
+ storage: storage2,
+ container: work_package)
+ end
+
+ # We're going to mock OAuth2 autentication failures below
+ let(:connection_manager) { instance_double(::OAuthClients::ConnectionManager) }
+ let(:authorize_url) { 'https://example.com/authorize' }
+ let(:instance) { described_class.new(user:) }
+
+ # Indication from Nextcloud, true means that file has been deleted and should not be shown
+ let(:trashed) { false }
+ let(:file_links) { [file_link1] }
+
+ # Nextcloud response part for valid file
+ let(:file_info1_s200) do
+ {
+ id: 24,
+ status: "OK",
+ statuscode: 200,
+ name: "Nextcloud Manual.pdf",
+ mtime: 1655301234,
+ ctime: 1655334567,
+ mimetype: "application/pdf",
+ size: 12706214,
+ owner_id: "admin",
+ owner_name: "admin",
+ trashed:
+ }
+ end
+
+ # Meta information from Nextcloud as part of replies - per HTTP status code
+ let(:ocs_meta_s200) { { status: "ok", statuscode: 100, message: "OK", totalitems: "", itemsperpage: "" } }
+ let(:ocs_meta_s401) { { status: "failure", statuscode: 997, message: "No login", totalitems: "", itemsperpage: "" } }
+
+ # Reply from Nextcloud if not allowed to access file:
+ # OP should still show the file.
+ # This reply appears for example when some other user shares a file with a OP WorkPackage.
+ # ToDo: Design error of Nextcloud openproject_integration? Should include attributes!
+ let(:file_info_s403) { { status: "Forbidden", statuscode: 403 } }
+
+ # Reply from Nextcloud if Nextcloud internally can't find the file:
+ # OP should not show the file
+ # This reply appears if we send an invalid origin_id to Nextcloud files_info endpoint.
+ let(:file_info_s404) { { status: "Not Found", statuscode: 404 } }
+
+ before do
+ oauth_client_token1
+ oauth_client_token2
+ end
+
+ # Test the main function of the service, which is to
+ # the OAuth2 provider URL (Nextcloud) according to RFC specs.
+ describe '#call', webmock: true do
+ subject { instance.call(file_links) }
+
+ context 'with access tokens' do
+ context 'with one FileLink and one storage' do
+ let(:response) { { ocs: { meta: ocs_meta_s401, data: { '24': file_info1_s200 } } }.to_json }
+
+ before do
+ # Simulate a successfully authorized reply with updates from Nextcloud
+ stub_request(:post, File.join(host1, '/ocs/v1.php/apps/integration_openproject/filesinfo'))
+ .to_return(status: 200, headers: { 'Content-Type': 'application/json' }, body: response)
+ end
+
+ it 'returns file_link1 a successful ServiceResult with updated mtime' do
+ expect(subject.success).to be_truthy
+ expect(subject.result.count).to be 1
+ expect(subject.result[0].origin_id).to eql '24'
+ expect(subject.result[0].origin_updated_at).to eql Time.zone.at(1655301234) # updated
+ end
+ end
+
+ context 'without permission to read file (403)' do
+ let(:response) { { ocs: { meta: ocs_meta_s200, data: { '24': file_info_s403 } } }.to_json }
+
+ before do
+ stub_request(:post, File.join(host1, '/ocs/v1.php/apps/integration_openproject/filesinfo'))
+ .to_return(status: 200, headers: { 'Content-Type': 'application/json' }, body: response)
+ end
+
+ it 'returns a FileLink with #origin_permission :not_allowed' do
+ expect(subject.success).to be_truthy
+ expect(subject.result[0].origin_permission).to be :not_allowed
+ end
+ end
+
+ context 'with 2 storages, each with one FileLink, one updated and other not allowed' do
+ let(:file_links) { [file_link1, file_link2] }
+ let(:response1) { { ocs: { meta: ocs_meta_s200, data: { '24': file_info1_s200 } } }.to_json }
+ let(:response2) { { ocs: { meta: ocs_meta_s200, data: { '25': file_info_s403 } } }.to_json }
+
+ before do
+ # Simulate a successfully authorized reply with updates from Nextcloud
+ stub_request(:post, File.join(host1, '/ocs/v1.php/apps/integration_openproject/filesinfo'))
+ .to_return(status: 200, headers: { 'Content-Type': 'application/json' }, body: response1)
+ stub_request(:post, File.join(host2, '/ocs/v1.php/apps/integration_openproject/filesinfo'))
+ .to_return(status: 200, headers: { 'Content-Type': 'application/json' }, body: response2)
+ end
+
+ it 'returns a successful ServiceResult with two FileLinks with different permissions' do
+ expect(subject.success).to be_truthy
+ expect(subject.result.count).to be 2
+ expect(subject.result[0].origin_id).to eql '24'
+ expect(subject.result[1].origin_id).to eql '25'
+ expect(subject.result[0].origin_permission).to be :view
+ expect(subject.result[1].origin_permission).to be :not_allowed
+ end
+ end
+
+ context 'when file was not found (404)' do
+ # Nextcloud returns 404 if it internally can't find the origin_id of the file.
+ # I'm not sure for reasons (internal error, ...), but the file shouldn't be shown then.
+ let(:file_links) { [file_link1] }
+ let(:response) { { ocs: { meta: ocs_meta_s200, data: { '24': file_info_s404 } } }.to_json }
+
+ before do
+ # Simulate a successfully authorized reply with updates from Nextcloud
+ stub_request(:post, File.join(host1, '/ocs/v1.php/apps/integration_openproject/filesinfo'))
+ .to_return(status: 200, headers: { 'Content-Type': 'application/json' }, body: response)
+ end
+
+ it 'deletes the FileLink' do
+ expect(subject.success).to be_truthy
+ expect(subject.result.count).to be 0
+ expect(::Storages::FileLink.all.count).to be 0
+ end
+ end
+
+ context 'with connection timeout Nextcloud' do
+ before do
+ # Simulate a complete disconnection
+ stub_request(:any, File.join(host1, '/ocs/v1.php/apps/integration_openproject/filesinfo'))
+ .to_timeout
+ end
+
+ it 'leaves the list of file_links unchanged with permissions = :error' do
+ expect(subject.success).to be_falsey
+ expect(subject.result[0].origin_permission).to be :error
+ end
+ end
+
+ context 'with connection to Nextcloud1, permission from Nextcloud1 and some updates' do
+ let(:response) { { ocs: { meta: ocs_meta_s200, data: { '24': file_info1_s200 } } }.to_json }
+
+ before do
+ stub_request(:post, File.join(host1, '/ocs/v1.php/apps/integration_openproject/filesinfo'))
+ .to_return(status: 200, headers: { 'Content-Type': 'application/json' }, body: response)
+ end
+
+ # Just test a single update (mtime). Detailed update testing is further below.
+ it 'updates the file_link information' do
+ expect(subject).to be_a ServiceResult
+ expect(subject.success).to be_truthy
+ expect(subject.result[0].origin_updated_at).to eql Time.zone.at(1655301234) # updated
+ end
+
+ it 'updates the origin_permission' do
+ expect(subject.success).to be_truthy
+ expect(subject.result[0].origin_permission).to be :view # updated
+ end
+ end
+
+ context 'with expired OAuth2 token, successful refresh and updated information from Nextcloud' do
+ before do
+ # Mock the OAuth2 connection manager to return a valid token
+ allow(::OAuthClients::ConnectionManager)
+ .to receive(:new)
+ .and_return(connection_manager)
+ allow(connection_manager)
+ .to receive(:refresh_token)
+ .and_return(ServiceResult.success(result: oauth_client_token1))
+ allow(connection_manager)
+ .to receive(:get_access_token)
+ .and_return(ServiceResult.success(result: oauth_client_token1))
+
+ # Mock Nextcloud to return:
+ # first: a 401 indicating an outdated OAuth2 Bearer token and
+ # then: a 200 with a reasonable result
+ stub_request(:post, File.join(host1, '/ocs/v1.php/apps/integration_openproject/filesinfo'))
+ .to_return(status: 401,
+ headers: { 'Content-Type': 'application/json; charset=utf-8' },
+ body: { ocs: { meta: ocs_meta_s401, data: [] } }.to_json)
+ .times(1)
+ .then
+ .to_return(status: 200,
+ headers: { 'Content-Type': 'application/json; charset=utf-8' },
+ body: { ocs: { meta: ocs_meta_s200, data: { '24': file_info1_s200 } } }.to_json)
+ end
+
+ # Just check that some update has happened.
+ it 'updates the file_link information' do
+ expect(subject).to be_a ServiceResult
+ expect(subject.success).to be_truthy
+ expect(subject.result[0].origin_updated_at).to eql Time.zone.at(1655301234) # updated
+ end
+ end
+
+ context 'with expired OAuth2 token and refresh failed' do
+ before do
+ # Mock Nextcloud to return 401 (not authorized) indicating an expired OAuth2 Bearer token
+ stub_request(:post, File.join(host1, '/ocs/v1.php/apps/integration_openproject/filesinfo'))
+ .to_return(status: 401,
+ headers: { 'Content-Type': 'application/json; charset=utf-8' },
+ body: { ocs: { meta: ocs_meta_s401, data: [] } }.to_json)
+
+ # Mock the OAuth2 connection manager to return some token on :get_access_token
+ # (that is considered 401-not authorized in the WebMock above) and then
+ # to return a failed ServiceResult on :refresh_token.
+ allow(::OAuthClients::ConnectionManager)
+ .to receive(:new).and_return(connection_manager)
+ allow(connection_manager)
+ .to receive(:refresh_token)
+ .and_return(
+ ServiceResult.failure.tap do |result|
+ result.errors.add(:base, "Error")
+ end
+ )
+ allow(connection_manager)
+ .to receive(:get_access_token).and_return(ServiceResult.success(result: oauth_client_token1))
+ end
+
+ it 'returns a failed ServiceResult with an error' do
+ expect(subject).to be_a ServiceResult
+ expect(subject.success).to be_falsey
+ expect(subject.message).to include "Error"
+ end
+ end
+
+ context 'with FileLink trashed in nextcloud' do
+ let(:trashed) { true } # trashed is included in body: response below
+ let(:response) { { ocs: { meta: ocs_meta_s200, data: { '24': file_info1_s200 } } }.to_json }
+
+ before do
+ stub_request(:post, File.join(host1, '/ocs/v1.php/apps/integration_openproject/filesinfo'))
+ .to_return(status: 200, headers: { 'Content-Type': 'application/json' }, body: response)
+ end
+
+ it 'returns an empty list of FileLinks' do
+ expect(subject).to be_a ServiceResult
+ expect(subject.success).to be_truthy
+ expect(subject.result.length).to be 0
+ end
+ end
+ end
+
+ context 'without access token' do
+ # Simulate a Storage for which we don't have an access token at all
+ # We don't need to Web-mock anything, we just don't setup an oauth_client_token below.
+ let(:host3) { "http://host-3.example.org" }
+ let(:storage3) { create(:storage, host: host3) }
+ let(:oauth_client3) { create(:oauth_client, integration: storage3) }
+ # Please notice the missing let(:oauth_client_token3) here
+ let(:file_link3) { create(:file_link, storage: storage3, container: work_package) }
+ let(:file_links) { [file_link3] }
+
+ before do
+ oauth_client3
+ end
+
+ it 'returns a falsey ServiceResults coming from ConnectionManager' do
+ expect(subject.success).to be_falsey
+ end
+ end
+ end
+
+ # Test the update of fields of a single FileLink based on information returned from Nextcloud.
+ describe '#sync_single_file' do
+ let(:file_link1_all_modified_hash) do
+ # Simulates Nextcloud update reply with strings ()and not symbols!) as Hash keys
+ # We can simulate this using JSON.parse(response.to_json).
+ JSON.parse({
+ id: '24',
+ ctime: 1755334567, # -> origin_created_at
+ mtime: 1755301234, # -> origin_updated_at
+ mimetype: "application/text", # -> origin_mime_type
+ name: "Readme.txt", # -> origin_name
+ owner_id: "fraber_id",
+ owner_name: "fraber", # -> origin_created_by_name
+ size: 1270,
+ trashed: true
+ }.to_json)
+ end
+
+ subject { instance.sync_single_file(file_link1, file_link1_all_modified_hash) }
+
+ context 'with updated information for all FileLinks (happy path)' do
+ it 'updates all relevant fields and leaves the list of file_links unchanged' do
+ expect(subject).to be_a ::Storages::FileLink
+ expect(subject.origin_created_at).to eql Time.zone.at(1755334567)
+ expect(subject.origin_updated_at).to eql Time.zone.at(1755301234)
+ expect(subject.origin_mime_type).to eql "application/text"
+ expect(subject.origin_name).to eql "Readme.txt"
+ expect(subject.origin_created_by_name).to eql "fraber"
+ end
+ end
+ end
+end