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
adapt the api authorization to the bcf api
ulferts17bd411b534e
diff --git a/app/controllers/oauth/auth_base_controller.rb b/app/controllers/oauth/auth_base_controller.rbindex 326ba4cb9b4..ce4c7117ec7 100644--- a/app/controllers/oauth/auth_base_controller.rb+++ b/app/controllers/oauth/auth_base_controller.rb@@ -27,7 +27,6 @@# See docs/COPYRIGHT.rdoc for more details.#++-module OAuth### Base controller for doorkeeper to skip the login checkdiff --git a/app/views/oauth/applications/_form.html.erb b/app/views/oauth/applications/_form.html.erbindex 8a1e5a6528d..c2b4709046b 100644--- a/app/views/oauth/applications/_form.html.erb+++ b/app/views/oauth/applications/_form.html.erb@@ -44,6 +44,26 @@ See docs/COPYRIGHT.rdoc for more details.<code><%= ::Doorkeeper.configuration.native_redirect_uri %></code></span></div>++ <% if Doorkeeper.configuration.scopes.all.length > 1 %>+ <div class="form--field">+ <label class="form--label">Scopes:</label>+ <% Doorkeeper.configuration.scopes.each do |scope| %>+ <div class="form--field-container -vertical">+ <label class="form--label-with-check-box">+ <div class="form--check-box-container">+ <%= styled_check_box_tag 'application[scopes][]', scope, f.object.scopes.include?(scope) %>+ </div>+ <%= scope %>+ </label>+ </div>+ <% end %>+ <span class="form--field-instructions">+ <%= t('oauth.application.instructions.scopes') %>+ </span>+ </div>+ <% end %>+<div class="form--field"><%= f.check_box :confidential %><span class="form--field-instructions">diff --git a/config/locales/en.yml b/config/locales/en.ymlindex 1da045c6b9c..4ea70c7863b 100644--- a/config/locales/en.yml+++ b/config/locales/en.yml@@ -2710,6 +2710,7 @@ en:<br/>If you're registering a desktop application, use the following URL.confidential: "Check if the application will be used where the client secret can be kept confidential. Native mobile apps and Single Page Apps are assumed non-confidential."+ scopes: "Check the scopes you want the application to grant access to. If no scope is checked, api_v3 is assumed."client_credential_user_id: "Optional user ID to impersonate when clients use this application. Leave empty to allow public access only"register_intro: "If you are developing an OAuth API client application for OpenProject, you can register it using this form for all users to use."default_scopes: ""@@ -2727,8 +2728,8 @@ en:<br/><strong>It has requested the following permissions:</strong>scopes:- api_v3: "Full API access"- api_v3_text: "Application will receive full read & write access to the OpenProject API to perform actions on your behalf."+ api_v3: "Full API v3 access"+ api_v3_text: "Application will receive full read & write access to the OpenProject API v3 to perform actions on your behalf."grants:created_date: "Approved on"scopes: "Permissions"diff --git a/lib/api/root.rb b/lib/api/root.rbindex 7510ef236ed..d06d515575d 100644--- a/lib/api/root.rb+++ b/lib/api/root.rb@@ -38,6 +38,7 @@ module APIparser :json, API::V3::Parser.newerror_representer ::API::V3::Errors::ErrorRepresenter+ authentication_scope OpenProject::Authentication::Scope::API_V3version 'v3', using: :path domount API::V3::Rootdiff --git a/lib/api/root_api.rb b/lib/api/root_api.rbindex 9afc2201cee..37586aaeb79 100644--- a/lib/api/root_api.rb+++ b/lib/api/root_api.rb@@ -66,9 +66,9 @@ module APIenddef authenticate- warden.authenticate! scope: API_V3+ warden.authenticate! scope: authentication_scope- User.current = warden.user scope: API_V3+ User.current = warden.user scope: authentication_scopeif Setting.login_required? and not logged_in?raise ::API::Errors::Unauthenticated@@ -187,7 +187,7 @@ module APIdef self.auth_headerslambda doheader = OpenProject::Authentication::WWWAuthenticate- .response_header(scope: API_V3, request_headers: env)+ .response_header(scope: authentication_scope, request_headers: env){ 'WWW-Authenticate' => header }end@@ -207,13 +207,27 @@ module API@error_representerend+ def self.authentication_scope(sym = nil)+ if sym+ @authentication_scope = sym++ # Have the representer class available in the instances+ # via a helper.+ helpers do+ define_method(:authentication_scope, -> { sym })+ end+ end++ @authentication_scope+ end+### Return JSON error response on authentication failure.OpenProject::Authentication.handle_failure(scope: API_V3) do |warden, _opts|e = grape_error_for warden.env, selferror_message = I18n.t('api_v3.errors.code_401_wrong_credentials')api_error = ::API::Errors::Unauthenticated.new error_message- representer = ::API::V3::Errors::ErrorRepresenter.new api_error+ representer = error_representer.new api_errore.error_response status: 401, message: representer.to_json, headers: warden.headers, log: falseenddiff --git a/modules/bcf/app/controllers/bcf/api/root.rb b/modules/bcf/app/controllers/bcf/api/root.rbindex 5b3ee97435a..b7b661fb042 100644--- a/modules/bcf/app/controllers/bcf/api/root.rb+++ b/modules/bcf/app/controllers/bcf/api/root.rb@@ -42,6 +42,8 @@ module Bcf::APIerror_representer ::Bcf::API::V2_1::Errors::ErrorRepresentererror_formatter :json, ::Bcf::API::ErrorFormatter::Json+ authentication_scope OpenProject::Authentication::Scope::BCF_V2_1+version '2.1', using: :path do# /projectsmount ::Bcf::API::V2_1::ProjectsAPIdiff --git a/modules/bcf/config/locales/en.yml b/modules/bcf/config/locales/en.ymlindex d88b9cfb485..591205a0980 100644--- a/modules/bcf/config/locales/en.yml+++ b/modules/bcf/config/locales/en.yml@@ -67,3 +67,8 @@ en:project_module_bcf: "BCF"permission_view_linked_issues: "View BCF issues"permission_manage_bcf: "Import and manage BCF issues"++ oauth:+ scopes:+ bcf_v2_1: "Full access to the BCF v2.1 API"+ bcf_v2_1_text: "Application will receive full read & write access to the OpenProject BCF API v2.1 to perform actions on your behalf."diff --git a/modules/bcf/lib/open_project/bcf/engine.rb b/modules/bcf/lib/open_project/bcf/engine.rbindex 6dd5fc61755..cf10abb9d90 100644--- a/modules/bcf/lib/open_project/bcf/engine.rb+++ b/modules/bcf/lib/open_project/bcf/engine.rb@@ -145,6 +145,19 @@ module OpenProject::BcfMime::Type.register "application/octet-stream", :bcfzip unless Mime::Type.lookup_by_extension(:bcfzip)end+ initializer 'bcf.add_api_scope' do+ Doorkeeper.configuration.scopes.add(:bcf_v2_1)++ module OpenProject::Authentication::Scope+ BCF_V2_1 = :bcf_v2_1+ end++ OpenProject::Authentication.update_strategies(OpenProject::Authentication::Scope::BCF_V2_1,+ store: false) do |_strategies|+ %i[oauth session]+ end+ end+config.to_prepare do::WorkPackage::Exporter.register_for_list(:bcf, OpenProject::Bcf::BcfXml::Exporter)diff --git a/modules/bcf/spec/features/bcf_api_authorization.rb b/modules/bcf/spec/features/bcf_api_authorization.rbnew file mode 100644index 00000000000..26c29ea4f0e--- /dev/null+++ b/modules/bcf/spec/features/bcf_api_authorization.rb@@ -0,0 +1,146 @@+#-- copyright+# OpenProject is a project management system.+# Copyright (C) 2012-2018 the OpenProject Foundation (OPF)+#+# 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-2017 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 'authorization for BCF api', type: :feature, js: true do+ let!(:user) { FactoryBot.create(:admin) }+ let(:client_secret) { app.plaintext_secret }+ let(:scope) { 'bcf_v2_1' }+ let!(:project) { FactoryBot.create(:project) }++ def oauth_path(client_id)+ "/oauth/authorize?response_type=code&client_id=#{client_id}&redirect_uri=urn:ietf:wg:oauth:2.0:oob&scope=#{scope}"+ end++ before do+ login_with user.login, 'adminADMIN!'++ visit oauth_applications_path+ end++ it 'can create and later authorize and manage an OAuth application grant and then use the access token for the bcf api' do+ # Initially empty+ expect(page).to have_selector('.generic-table--empty-row', text: 'There is currently nothing to display')++ # Create application+ find('.button', text: 'Add').click+ fill_in 'application_name', with: 'My API application'+ # Limit to bcf access+ check scope+ # Fill invalid redirect_uri+ fill_in 'application_redirect_uri', with: "not a url!"+ click_on 'Create'++ expect(page).to have_selector('.errorExplanation', text: 'Redirect URI must be an absolute URI.')+ fill_in 'application_redirect_uri', with: "urn:ietf:wg:oauth:2.0:oob\nhttps://localhost/my/callback"+ click_on 'Create'++ expect(page).to have_selector('.flash.notice', text: 'Successful creation.')++ expect(page).to have_selector('.attributes-key-value--key', text: 'Client ID')+ expect(page).to have_selector('.attributes-key-value--value', text: "urn:ietf:wg:oauth:2.0:oob\nhttps://localhost/my/callback")++ # Should print secret on initial visit+ expect(page).to have_selector('.attributes-key-value--key', text: 'Client secret')+ client_secret = page.first('.attributes-key-value--value code').text+ expect(client_secret).to match /\w+/++ app = ::Doorkeeper::Application.first++ visit oauth_path app.uid++ # We get to the authorization screen+ expect(page).to have_selector('h2', text: 'Authorize My API application')++ # With the correct scope printed+ expect(page).to have_selector('li strong', text: I18n.t('oauth.scopes.bcf_v2_1'))+ expect(page).to have_selector('li', text: I18n.t('oauth.scopes.bcf_v2_1_text'))++ # Authorize+ find('input.button[value="Authorize"]').click++ # Expect auth token+ code = find('#authorization_code').text++ # And also have a grant for this application+ user.oauth_grants.reload+ expect(user.oauth_grants.count).to eq 1+ expect(user.oauth_grants.first.application).to eq app++ parameters = {+ client_id: app.uid,+ client_secret: client_secret,+ code: code,+ grant_type: :authorization_code,+ redirect_uri: app.redirect_uri.split.first+ }++ session = ActionDispatch::Integration::Session.new(Rails.application)+ response = session.post("/oauth/token", params: parameters)+ expect(response).to eq 200+ body = JSON.parse(session.response.body)++ expect(body['access_token']).to be_present+ expect(body['refresh_token']).to be_present+ expect(body['scope']).to eq scope++ access_token = body['access_token']++ # Should show that grant in my account+ visit my_account_path+ click_on 'Access token'++ expect(page).to have_selector("#oauth-application-grant-#{app.id}", text: app.name)+ expect(page).to have_selector('td', text: app.name)++ # While being logged in, the api can be accessed with the session+ visit("/api/bcf/2.1/projects/#{project.id}")+ expect(page)+ .to have_content(JSON.dump(project_id: project.id, name: project.name))++ logout++ # While not being logged in and without a token, the api cannot be accessed+ visit("/api/bcf/2.1/projects/#{project.id}")+ expect(page)+ .to have_content(JSON.dump(message: "The requested resource could not be found."))++ ## Without the access token, access is denied+ api_session = ActionDispatch::Integration::Session.new(Rails.application)+ response = api_session.get("/api/bcf/2.1/projects/#{project.id}")+ expect(response).to eq 404++ # With the access token, access is allowed+ response = api_session.get("/api/bcf/2.1/projects/#{project.id}",+ headers: { 'Authorization': "Bearer #{access_token}" })+ expect(response).to eq 200+ expect(api_session.response.body)+ .to be_json_eql({ project_id: project.id, name: project.name }.to_json)+ end+enddiff --git a/spec/features/admin/oauth/oauth_applications_management_spec.rb b/spec/features/admin/oauth/oauth_applications_management_spec.rbindex 4009496b577..69d5fbf31bc 100644--- a/spec/features/admin/oauth/oauth_applications_management_spec.rb+++ b/spec/features/admin/oauth/oauth_applications_management_spec.rb@@ -47,7 +47,6 @@ describe 'OAuth applications management', type: :feature, js: true dofill_in 'application_redirect_uri', with: "not a url!"click_on 'Create'-expect(page).to have_selector('.errorExplanation', text: 'Redirect URI must be an absolute URI.')fill_in 'application_redirect_uri', with: "urn:ietf:wg:oauth:2.0:oob\nhttps://localhost/my/callback"click_on 'Create'