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

Protect Authorization Code flow from CSRF

Wieland Lindenthal8a4c353381d5
diff --git a/app/controllers/oauth_clients_controller.rb b/app/controllers/oauth_clients_controller.rb
index ba8c19c7f85..77755db8948 100644
--- a/app/controllers/oauth_clients_controller.rb
+++ b/app/controllers/oauth_clients_controller.rb
@@ -30,8 +30,9 @@
# "callback" endpoint.
class OAuthClientsController < ApplicationController
before_action :find_oauth_client
- before_action :set_state
+ before_action :set_redirect_uri
before_action :set_code
+ before_action :set_connection_manager
# Provide the OAuth2 "callback" endpoint.
# The Authorization Server redirects
@@ -43,21 +44,18 @@ class OAuthClientsController < ApplicationController
# state=http%3A%2F%2Flocalhost%3A4200%2Fprojects%2Fdemo-project%2Foauth2_example&
# code=MQoOnUTJGFdAo5jBGD1SqnDH0PV6yioG7NoYM2zZZlK3g6LuKrGUmOxjIS1bIy7fHEfZy2WrgYcx
def callback
- connection_manager = OAuthClients::ConnectionManager.new(user: User.current, oauth_client: @oauth_client)
-
# Exchange the code with a token using a HTTP call to the Authorization Server
- service_result = connection_manager.code_to_token(@code)
+ service_result = @connection_manager.code_to_token(@code)
if service_result.success?
# Redirect the user to the page that initially wanted to access the OAuth2 resource.
- # "state" is a variable that encapsulates the page's URL and status.
- redirect_uri = connection_manager.callback_redirect_uri(@state)
- redirect_to redirect_uri
+ # "state" is a nonce that identifies a cookie which holds that page's URL.
+ redirect_to @redirect_uri
else
# We got a list of errors from ::OAuthClients::ConnectionManager
set_oauth_errors(service_result)
- redirect_user_or_admin(@state) do
+ redirect_user_or_admin(@redirect_uri) do
# If the current user is an admin, we send her directly to the
# settings that she needs to edit.
redirect_to admin_settings_storage_path(@oauth_client.integration)
@@ -79,34 +77,45 @@ class OAuthClientsController < ApplicationController
# So this could either be an error from the Authorization Server (i.e. Nextcloud) or
# ::OAuthClient::ConnectionManager has used the wrong response_type.
@code = params[:code]
+
if @code.blank?
flash[:error] = [I18n.t('oauth_client.errors.oauth_code_not_present'),
I18n.t('oauth_client.errors.oauth_code_not_present_explanation')]
- redirect_user_or_admin params[:state] do
+ redirect_user_or_admin(get_redirect_uri) do
# If the current user is an admin, we send her directly to the
- # settings that she needs to edit.
+ # settings that she needs to edit/fix.
redirect_to admin_settings_storage_path(@oauth_client.integration)
end
end
end
- def set_state
- # state is used by OpenProject to contain the redirection URL where to
- # continue after receiving an OAuth2 access token. So it should not be blank.
- @state = params[:state]
- if @state.blank?
+ def set_redirect_uri
+ # redirect_uri is used by OpenProject to redirect to
+ # after receiving an OAuth2 access token. So it should not be blank.
+ service_result = ::OAuthClients::RedirectUriFromStateService
+ .new(state: params[:state], cookies:)
+ .call
+
+ if service_result.success?
+ @redirect_uri = service_result.result
+ else
+ # To protect against CSRF we cancel this request. There was either no
+ # state parameter given, or there was no corresponding cookie present.
flash[:error] = [I18n.t('oauth_client.errors.oauth_state_not_present'),
I18n.t('oauth_client.errors.oauth_state_not_present_explanation')]
redirect_user_or_admin(nil) do
- # If the current user is an admin, we send her directly to the
- # settings that she needs to edit.
+ # Guide the user to the settings that she needs to edit/fix.
redirect_to admin_settings_storage_path(@oauth_client.integration)
end
end
end
+ def set_connection_manager
+ @connection_manager = OAuthClients::ConnectionManager.new(user: User.current, oauth_client: @oauth_client)
+ end
+
def find_oauth_client
@oauth_client = OAuthClient.find_by(client_id: params[:oauth_client_id])
if @oauth_client.nil?
@@ -117,22 +126,22 @@ class OAuthClientsController < ApplicationController
flash[:error] = [I18n.t('oauth_client.errors.oauth_client_not_found'),
I18n.t('oauth_client.errors.oauth_client_not_found_explanation')]
- redirect_user_or_admin params[:state] do
+ redirect_user_or_admin(get_redirect_uri) do
# Something must be wrong in the storage's setup
redirect_to admin_settings_storages_path
end
end
end
- def redirect_user_or_admin(state = nil)
+ def redirect_user_or_admin(redirect_uri = nil)
# This needs to be modified as soon as we support more integration types.
- if User.current.admin && state && nextcloud?
+ if User.current.admin && redirect_uri && nextcloud?
yield
- elsif ::API::V3::Utilities::PathHelper::ApiV3Path::same_origin? state
+ elsif redirect_uri
flash[:error] = [t(:'oauth_client.errors.oauth_issue_contact_admin')]
- redirect_to state
+ redirect_to redirect_uri
else
- redirect_to home_path
+ redirect_to ::API::V3::Utilities::PathHelper::ApiV3Path::root_url
end
end
@@ -141,4 +150,11 @@ class OAuthClientsController < ApplicationController
@oauth_client.integration.is_a?(::Storages::Storage) && \
@oauth_client.integration.provider_type == 'nextcloud'
end
+
+ def get_redirect_uri
+ ::OAuthClients::RedirectUriFromStateService
+ .new(state: params[:state], cookies:)
+ .call
+ .result
+ end
end
diff --git a/app/services/oauth_clients/connection_manager.rb b/app/services/oauth_clients/connection_manager.rb
index 6e54275be04..d0bbd83afd2 100644
--- a/app/services/oauth_clients/connection_manager.rb
+++ b/app/services/oauth_clients/connection_manager.rb
@@ -72,28 +72,14 @@ module OAuthClients
end
# Redirect to the "authorize" endpoint of the OAuth2 Authorization Server.
- # @param state (OAuth2 RFC) encapsulates the state of the calling page (URL + params) to return
+ # @param state (OAuth2 RFC) is a nonce referencing a cookie containing the calling page (URL + params) to which to
+ # return to at the end of the whole flow.
# @param scope (OAuth2 RFC) specifies the resources to access. Nextcloud only has one global scope.
def redirect_to_oauth_authorize(scope: [], state: nil)
client = rack_oauth_client # Configure and start the rack-oauth2 client
client.authorization_uri(scope:, state:)
end
- # For the OAuth2 callback page: Calculate the redirection URL that will
- # point the browser at the initial page that wanted to access the OAuth2
- # protected resource.
- # @param state (OAuth2 RFC) encapsulates the state of the calling page (URL + params) to return
- def callback_redirect_uri(state)
- # In the current implementation "state" just consists of the URL of
- # the initial page, possibly with "&var=value" added parameters.
- # So we can just return this URI.
- unless ::API::V3::Utilities::PathHelper::ApiV3Path::same_origin?(state)
- return ::API::V3::Utilities::PathHelper::ApiV3Path::root_url
- end
-
- state
- end
-
# Called by callback_page with a cryptographic "code" that indicates
# that the user has successfully authorized the OAuth2 Authorization Server.
# We now are going to exchange this code to a token (bearer+refresh)
diff --git a/spec/requests/oauth_clients/callback_flow_spec.rb b/spec/requests/oauth_clients/callback_flow_spec.rb
index a7261567e60..a5f6d8ae62b 100644
--- a/spec/requests/oauth_clients/callback_flow_spec.rb
+++ b/spec/requests/oauth_clients/callback_flow_spec.rb
@@ -39,7 +39,8 @@ describe 'OAuthClient callback endpoint', :enable_storages, type: :request do
"mBf4v9hNA6hXXCWHd5mZggsAa2FSOXinx9jKx1yjSoDwOPOX4k6zGEgM2radqgg1nRwXCqvIe5xZsfwqMIaTdL" +
"jYnl0OpYOc6ePblzQTmnlp7RYiHW09assYEJjv9zps"
end
- let(:state) do
+ let(:state) { 'asdf1234' }
+ let(:redirect_uri) do
File.join(::API::V3::Utilities::PathHelper::ApiV3Path::root_url, "/my-path?and=some&query=params")
end
let(:oauth_client_token) { create :oauth_client_token }
@@ -69,12 +70,13 @@ describe 'OAuthClient callback endpoint', :enable_storages, type: :request do
refresh_token: 'xyzrefreshtoken')
)
allow(rack_oauth2_client).to receive(:authorization_code=)
+ set_cookie "oauth_state_asdf1234=#{redirect_uri}"
end
- shared_examples 'with errors and state param, not being admin' do
- it 'redirects to URI encode in state' do
+ shared_examples 'with errors and state param with cookie, not being admin' do
+ it 'redirects to URI referenced in the state param and held in a cookie' do
expect(response.status).to eq 302
- expect(response.location).to eq state
+ expect(response.location).to eq redirect_uri
end
end
@@ -88,7 +90,7 @@ describe 'OAuthClient callback endpoint', :enable_storages, type: :request do
shared_examples 'fallback redirect' do
it 'redirects to home' do
expect(response.status).to eq 302
- expect(URI(response.location).path).to eq home_path
+ expect(URI(response.location).path).to eq ::API::V3::Utilities::PathHelper::ApiV3Path::root_path
end
end
@@ -101,18 +103,18 @@ describe 'OAuthClient callback endpoint', :enable_storages, type: :request do
subject
end
- it 'redirects to the URL that was provided by the state param' do
+ it 'redirects to the URL that was referenced by the state param and held by a cookie' do
expect(rack_oauth2_client).to have_received(:authorization_code=).with(code)
expect(response.status).to eq 302
- expect(response.location).to eq state
+ expect(response.location).to eq redirect_uri
expect(::OAuthClientToken.count).to eq 1
expect(::OAuthClientToken.last.access_token).to eq 'xyzaccesstoken'
expect(::OAuthClientToken.last.refresh_token).to eq 'xyzrefreshtoken'
end
end
- context 'with a state param containing a URL pointing to a different host' do
- let(:state) { "https://some-other-domain.com/foo/bar" }
+ context 'with a OAuth state cookie containing a URL pointing to a different host' do
+ let(:redirect_uri) { "https://some-other-domain.com/foo/bar" }
before do
uri.query = URI.encode_www_form([['code', code], ['state', state]])
@@ -144,7 +146,7 @@ describe 'OAuthClient callback endpoint', :enable_storages, type: :request do
end
context 'with current_user not being an admin' do
- it_behaves_like 'with errors and state param, not being admin'
+ it_behaves_like 'with errors and state param with cookie, not being admin'
end
end
end
@@ -158,7 +160,7 @@ describe 'OAuthClient callback endpoint', :enable_storages, type: :request do
end
context 'with current_user not being an admin' do
- it_behaves_like 'with errors and state param, not being admin'
+ it_behaves_like 'with errors and state param with cookie, not being admin'
end
context 'with current_user being an admin' do