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

Add authorization state to storages API endpoint (#10785)

Frank Bergmann185dd9c8d095
diff --git a/app/services/oauth_clients/connection_manager.rb b/app/services/oauth_clients/connection_manager.rb
index 1571dd5cef5..5aa686e1fd6 100644
--- a/app/services/oauth_clients/connection_manager.rb
+++ b/app/services/oauth_clients/connection_manager.rb
@@ -31,7 +31,8 @@ require "uri/http"
module OAuthClients
class ConnectionManager
- AUTHORIZATION_CHECK_PATH = '/ocs/v2.php/cloud/capabilities'.freeze
+ # Nextcloud API endpoint to check if Bearer token is valid
+ AUTHORIZATION_CHECK_PATH = '/ocs/v1.php/cloud/user'.freeze
attr_reader :user, :oauth_client
@@ -100,20 +101,39 @@ module OAuthClients
service_result = request_new_token(authorization_code: code)
return service_result unless service_result.success?
- # Create a new OAuthClientToken from Rack::OAuth::AccessToken::Bearer and return
- ServiceResult.new(
- success: true,
- result: create_new_oauth_client_token(service_result.result)
- )
+ # Check for existing OAuthClientToken and update,
+ # or create a new one from Rack::OAuth::AccessToken::Bearer
+ oauth_client_token = get_existing_token
+ if oauth_client_token.present?
+ update_oauth_client_token(oauth_client_token, service_result.result)
+ else
+ oauth_client_token = create_new_oauth_client_token(service_result.result)
+ end
+
+ ServiceResult.new(success: true, result: oauth_client_token)
end
+ # Called by StorageRepresenter to inquire about the status of the OAuth2
+ # authentication server.
+ # Returns :connected/:authorization_failed or :error for a general error.
+ # We have decided to distinguish between only these 3 cases, because the
+ # front-end (and a normal user) probably wouldn't know how to deal with
+ # other options.
def authorization_state
oauth_client_token = get_existing_token
- return :failed_authentication unless oauth_client_token
+ return :failed_authorization unless oauth_client_token
+ # Check for user information. This is the cheapest Nextcloud call that requires
+ # valid authentication, so we use it for testing the validity of the Bearer token.
+ # curl -H "Authorization: Bearer MY_TOKEN" -X GET 'https://my.nextcloud.org/ocs/v1.php/cloud/user' \
+ # -H "OCS-APIRequest: true" -H "Accept: application/json"
RestClient.get(
File.join(oauth_client.integration.host, AUTHORIZATION_CHECK_PATH),
- { :Authorization => "Bearer #{oauth_client_token.access_token}" }
+ {
+ 'Authorization' => "Bearer #{oauth_client_token.access_token}",
+ 'OCS-APIRequest' => "true",
+ 'Accept' => "application/json"
+ }
)
:connected
rescue RestClient::Unauthorized, RestClient::Forbidden => _e
@@ -123,7 +143,7 @@ module OAuthClients
if service_result.result == 'invalid_grant'
# This can happen if the Authorization Server invalidated all tokens.
# Then the user would ideally be asked to reauthorize.
- :failed_authentication
+ :failed_authorization
else
# It could also be that some other error happened, i.e. firewall badly configured.
# Then the user needs to know that something is technically off. The user could try
diff --git a/config/locales/en.yml b/config/locales/en.yml
index 5ac6f2568d5..0596109d2f4 100644
--- a/config/locales/en.yml
+++ b/config/locales/en.yml
@@ -3217,7 +3217,7 @@ en:
urn_connection_status:
connected: "Connected"
error: "Error"
- auth_failed: "Authentication failed"
+ failed_authorization: "Authorization failed"
labels:
label_oauth_integration: "OAuth2 integration"
label_redirect_uri: "Redirect URI"
@@ -3246,14 +3246,18 @@ en:
oauth_state_not_present: "OAuth2 'state' not found in 'callback' endpoint (redirect_uri)."
oauth_state_not_present_explanation: >
The 'state' is used to indicate to OpenProject where to continue
- after a successful OAuth2 authentication.
+ after a successful OAuth2 authorization.
A missing 'state' is an internal error that may appear during setup.
Please contact your system administrator.
rack_oauth2:
- client_secret_invalid: "Client secret is invalid"
+ client_secret_invalid: "Client secret is invalid (client_secret_invalid)"
invalid_request: >
OAuth2 Authorization Server responded with 'invalid_request'.
- This error appears if you try to authorize multiple times.
- invalid_response: "OAuth2 Authorization Server provided an invalid response"
- invalid_grant: "The OAuth2 Authorization Server asks you to reauthorize."
+ This error appears if you try to authorize multiple times or in case of technical issues.
+ invalid_response: "OAuth2 Authorization Server provided an invalid response (invalid_response)"
+ invalid_grant: "The OAuth2 Authorization Server asks you to reauthorize (invalid_grant)."
+ invalid_client: "The OAuth2 Authorization Server doesn't recognize OpenProject (invalid_client)."
+ unauthorized_client: "The OAuth2 Authorization Server rejects the grant type (unauthorized_client)"
+ unsupported_grant_type: "The OAuth2 Authorization Server asks you to reauthorize (unsupported_grant_type)."
+ invalid_scope: "You are not allowed to access the requested resource (invalid_scope)."
you: you
diff --git a/docs/api/apiv3/components/schemas/storage_model.yml b/docs/api/apiv3/components/schemas/storage_model.yml
index 0ca98c32101..ade3b220bb0 100644
--- a/docs/api/apiv3/components/schemas/storage_model.yml
+++ b/docs/api/apiv3/components/schemas/storage_model.yml
@@ -31,7 +31,7 @@ properties:
- self
- type
- origin
- - connectionState
+ - authorizationState
properties:
self:
allOf:
@@ -54,15 +54,15 @@ properties:
Web uri of the storage instance
**Resource**: N/A
- connectionState:
+ authorizationState:
allOf:
- $ref: "./link.yml"
- description: |-
The urn of the storage connection state. Can be one of:
- - urn:openproject-org:api:v3:storages:connection:Connected
- - urn:openproject-org:api:v3:storages:connection:FailedAuthentication
- - urn:openproject-org:api:v3:storages:connection:Error
+ - urn:openproject-org:api:v3:storages:authorization:Connected
+ - urn:openproject-org:api:v3:storages:authorization:FailedAuthorization
+ - urn:openproject-org:api:v3:storages:authorization:Error
**Resource**: N/A
example:
diff --git a/modules/storages/lib/api/v3/storages/storage_representer.rb b/modules/storages/lib/api/v3/storages/storage_representer.rb
index a96ff6cc7a1..d41c1d1e489 100644
--- a/modules/storages/lib/api/v3/storages/storage_representer.rb
+++ b/modules/storages/lib/api/v3/storages/storage_representer.rb
@@ -34,8 +34,9 @@ module API
module V3
module Storages
URN_TYPE_NEXTCLOUD = "#{::API::V3::URN_PREFIX}storages:Nextcloud".freeze
+
URN_CONNECTION_CONNECTED = "#{::API::V3::URN_PREFIX}storages:authorization:Connected".freeze
- URN_CONNECTION_AUTH_FAILED = "#{::API::V3::URN_PREFIX}storages:authorization:FailedAuthentication".freeze
+ URN_CONNECTION_AUTH_FAILED = "#{::API::V3::URN_PREFIX}storages:authorization:FailedAuthorization".freeze
URN_CONNECTION_ERROR = "#{::API::V3::URN_PREFIX}storages:authorization:Error".freeze
class StorageRepresenter < ::API::Decorators::Single
@@ -70,46 +71,18 @@ module API
link :authorizationState do
oauth_client = represented.oauth_client
connection_manager = ::OAuthClients::ConnectionManager.new(user: User.current, oauth_client:)
- status_urn = urn_authorization_state(connection_manager.authorization_state)
+ state = connection_manager.authorization_state.to_s
+ state_urn = "#{::API::V3::URN_PREFIX}storages:authorization:#{state.camelize}"
+ state_title = I18n.t(:"oauth_client.urn_connection_status.#{state}")
{
- href: status_urn,
- title: urn_authorization_state_title(status_urn)
+ href: state_urn,
+ title: state_title
}
end
def _type
'Storage'
end
-
- private
-
- # Check the ConnectionManager for the OAuth2 status
- def urn_authorization_state(authorization_state)
- case authorization_state
- when :error
- URN_CONNECTION_ERROR
- when :connected
- URN_CONNECTION_CONNECTED
- when :failed_authentication
- URN_CONNECTION_AUTH_FAILED
- else
- # This should never happen
- raise StandardError
- end
- end
-
- # Provide a human readable title for the connection status
- def urn_authorization_state_title(token_status)
- case token_status
- when URN_CONNECTION_CONNECTED
- I18n.t(:"urn_authorization_state")
- when URN_CONNECTION_AUTH_FAILED
- I18n.t(:"urn_authorization_state")
- else
- # Mainly covers URN_CONNECTION_ERROR
- I18n.t(:"urn_authorization_state")
- end
- end
end
end
end
diff --git a/modules/storages/spec/lib/api/v3/storages/storages_representer_rendering_spec.rb b/modules/storages/spec/lib/api/v3/storages/storages_representer_rendering_spec.rb
index 83bd1d850a5..9245a757785 100644
--- a/modules/storages/spec/lib/api/v3/storages/storages_representer_rendering_spec.rb
+++ b/modules/storages/spec/lib/api/v3/storages/storages_representer_rendering_spec.rb
@@ -32,10 +32,19 @@ describe ::API::V3::Storages::StorageRepresenter, 'rendering' do
let(:storage) { build_stubbed(:storage) }
let(:user) { build_stubbed(:user) }
let(:representer) { described_class.new(storage, current_user: user) }
+ let(:connection_manager) { instance_double(::OAuthClients::ConnectionManager) }
subject(:generated) { representer.to_json }
describe '_links' do
+ before do
+ # Mock the ConnectionManager to return :connected
+ allow(::OAuthClients::ConnectionManager)
+ .to receive(:new).and_return(connection_manager)
+ allow(connection_manager)
+ .to receive(:authorization_state).and_return(:connected)
+ end
+
describe 'self' do
it_behaves_like 'has a titled link' do
let(:link) { 'self' }
@@ -53,8 +62,8 @@ describe ::API::V3::Storages::StorageRepresenter, 'rendering' do
describe 'connectionState' do
it_behaves_like 'has a titled link' do
- let(:link) { 'connectionState' }
- let(:href) { 'urn:openproject-org:api:v3:storages:connection:Connected' }
+ let(:link) { 'authorizationState' }
+ let(:href) { 'urn:openproject-org:api:v3:storages:authorization:Connected' }
let(:title) { 'Connected' }
end
end
diff --git a/modules/storages/spec/requests/api/v3/storages/storages_spec.rb b/modules/storages/spec/requests/api/v3/storages/storages_spec.rb
index 013bf8a3e99..568161649a2 100644
--- a/modules/storages/spec/requests/api/v3/storages/storages_spec.rb
+++ b/modules/storages/spec/requests/api/v3/storages/storages_spec.rb
@@ -105,7 +105,7 @@ describe 'API v3 storages resource', :enable_storages, type: :request, content_t
let(:current_user) { create(:admin) }
it 'returns an error authorization state' do
- is_expected.to be_json_eql("urn:openproject-org:api:v3:storages:authorization:Error".to_json)
+ expect(subject).to be_json_eql("urn:openproject-org:api:v3:storages:authorization:Error".to_json)
.at_path('_links/authorizationState/href')
end
end
diff --git a/spec/services/oauth_clients/connection_manager_spec.rb b/spec/services/oauth_clients/connection_manager_spec.rb
index 7f4b59ca26a..a3a8a986b8f 100644
--- a/spec/services/oauth_clients/connection_manager_spec.rb
+++ b/spec/services/oauth_clients/connection_manager_spec.rb
@@ -44,7 +44,6 @@ describe ::OAuthClients::ConnectionManager, type: :model do
let(:oauth_client_token) { create(:oauth_client_token, oauth_client:, user:) }
let(:instance) { described_class.new(user:, oauth_client:) }
-
# Test the redirect_to_oauth_authorize function that puts together
# the OAuth2 provider URL (Nextcloud) according to RFC specs.
describe '#redirect_to_oauth_authorize' do
@@ -364,8 +363,8 @@ describe ::OAuthClients::ConnectionManager, type: :model do
subject { instance.authorization_state }
context 'without access token present' do
- it 'returns :failed_authentication' do
- expect(subject).to eq :failed_authentication
+ it 'returns :failed_authorization' do
+ expect(subject).to eq :failed_authorization
end
end
@@ -418,8 +417,8 @@ describe ::OAuthClients::ConnectionManager, type: :model do
context 'with invalid refresh token' do
let(:refresh_service_result) { ServiceResult.new(success: false, result: 'invalid_grant') }
- it 'refreshes the access token and returns :failed_authentication' do
- expect(subject).to eq :failed_authentication
+ it 'refreshes the access token and returns :failed_authorization' do
+ expect(subject).to eq :failed_authorization
expect(instance).to have_received(:refresh_token)
end
end
@@ -436,8 +435,8 @@ describe ::OAuthClients::ConnectionManager, type: :model do
end
context 'with both invalid access token and refresh token', webmock: true do
- it 'returns :failed_authentication' do
- expect(subject).to eq :failed_authentication
+ it 'returns :failed_authorization' do
+ expect(subject).to eq :failed_authorization
end
end
end