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

Split FetchService into three services

Jan Sandbrink096614222a7f
diff --git a/modules/openid_connect/app/services/openid_connect/user_tokens/exchange_service.rb b/modules/openid_connect/app/services/openid_connect/user_tokens/exchange_service.rb
new file mode 100644
index 00000000000..36891712bf7
--- /dev/null
+++ b/modules/openid_connect/app/services/openid_connect/user_tokens/exchange_service.rb
@@ -0,0 +1,109 @@
+# frozen_string_literal: true
+
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2024 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.
+#++
+
+module OpenIDConnect
+ module UserTokens
+ class ExchangeService
+ include Dry::Monads[:result]
+
+ class Disabled
+ class << self
+ include Dry::Monads[:result]
+
+ def call(_) = Failure("Token exchange disabled")
+
+ def supported? = false
+ end
+ end
+
+ def initialize(user:)
+ @user = user
+ end
+
+ def call(audience)
+ return Failure("Provider does not support token exchange") unless supported?
+
+ FetchService.new(user: @user, token_exchange: Disabled)
+ .access_token_for(audience: UserToken::IDP_AUDIENCE)
+ .bind do |idp_token|
+ exchange_token_request(idp_token, audience).bind do |json|
+ access_token = json["access_token"]
+ refresh_token = json["refresh_token"]
+ break Failure("Token exchange response invalid") if access_token.blank?
+
+ token = store_exchanged_token(audience:, access_token:, refresh_token:)
+
+ Success(token)
+ end
+ end
+ end
+
+ def supported?
+ provider&.token_exchange_capable?
+ end
+
+ private
+
+ def exchange_token_request(access_token, audience)
+ response = OpenProject.httpx
+ .basic_auth(provider.client_id, provider.client_secret)
+ .post(provider.token_endpoint, form: {
+ grant_type: "urn:ietf:params:oauth:grant-type:token-exchange",
+ subject_token: access_token,
+ audience:
+ })
+ response.raise_for_status
+
+ Success(response.json)
+ rescue HTTPX::Error => e
+ Failure(e)
+ end
+
+ def store_exchanged_token(audience:, access_token:, refresh_token:)
+ token = @user.oidc_user_tokens.where("audiences ? :audience", audience:).first
+ if token
+ if token.audiences.size > 1
+ raise "Did not expect to update token with multiple audiences (#{token.audiences}) in-place."
+ end
+
+ token.update!(access_token:, refresh_token:)
+ else
+ token = @user.oidc_user_tokens.create!(access_token:, refresh_token:, audiences: [audience])
+ end
+
+ token
+ end
+
+ def provider
+ @user.authentication_provider
+ end
+ end
+ end
+end
diff --git a/modules/openid_connect/app/services/openid_connect/user_tokens/fetch_service.rb b/modules/openid_connect/app/services/openid_connect/user_tokens/fetch_service.rb
index 0de50f9cac2..6ca2ff4a951 100644
--- a/modules/openid_connect/app/services/openid_connect/user_tokens/fetch_service.rb
+++ b/modules/openid_connect/app/services/openid_connect/user_tokens/fetch_service.rb
@@ -38,11 +38,12 @@ module OpenIDConnect
include Dry::Monads[:result]
def initialize(user:,
- allow_token_exchange: true,
- jwt_parser: JwtParser.new(verify_audience: false, verify_expiration: false))
+ jwt_parser: JwtParser.new(verify_audience: false, verify_expiration: false),
+ token_exchange: ExchangeService.new(user:),
+ token_refresh: RefreshService.new(user:, token_exchange:))
@user = user
- @provider = user.authentication_provider
- @allow_token_exchange = allow_token_exchange
+ @token_exchange = token_exchange
+ @token_refresh = token_refresh
@jwt_parser = jwt_parser
end
@@ -61,7 +62,7 @@ module OpenIDConnect
token = token_with_audience(audience)
token = token.bind do |t|
if expired?(t.access_token)
- refresh(t)
+ @token_refresh.call(t)
else
Success(t)
end
@@ -82,7 +83,7 @@ module OpenIDConnect
# for the target audience either can't be found or it has expired, but has no available refresh token.
def refreshed_access_token_for(audience:)
token_with_audience(audience)
- .bind { |t| refresh(t) }
+ .bind { |t| @token_refresh.call(t) }
.fmap(&:access_token)
end
@@ -92,102 +93,11 @@ module OpenIDConnect
token = @user.oidc_user_tokens.where("audiences ? :aud", aud:).first
return Success(token) if token
- return exchange_token_for(aud) if can_exchange_token?
+ return @token_exchange.call(aud) if @token_exchange.supported?
Failure("No token for audience '#{aud}'")
end
- def can_exchange_token?
- @allow_token_exchange && @provider&.token_exchange_capable?
- end
-
- def exchange_token_for(audience)
- self.class.new(user: @user, allow_token_exchange: false)
- .access_token_for(audience: UserToken::IDP_AUDIENCE)
- .bind do |idp_token|
- exchange_token_request(idp_token, audience).bind do |json|
- access_token = json["access_token"]
- refresh_token = json["refresh_token"]
- break Failure("Token exchange response invalid") if access_token.blank?
-
- token = store_exchanged_token(audience:, access_token:, refresh_token:)
-
- Success(token)
- end
- end
- end
-
- def exchange_token_request(access_token, audience)
- response = OpenProject.httpx
- .basic_auth(@provider.client_id, @provider.client_secret)
- .post(@provider.token_endpoint, form: {
- grant_type: "urn:ietf:params:oauth:grant-type:token-exchange",
- subject_token: access_token,
- audience:
- })
- response.raise_for_status
-
- Success(response.json)
- rescue HTTPX::Error => e
- Failure(e)
- end
-
- def store_exchanged_token(audience:, access_token:, refresh_token:)
- token = @user.oidc_user_tokens.where("audiences ? :audience", audience:).first
- if token
- if token.audiences.size > 1
- raise "Did not expect to update token with multiple audiences (#{token.audiences}) in-place."
- end
-
- token.update!(access_token:, refresh_token:)
- else
- token = @user.oidc_user_tokens.create!(access_token:, refresh_token:, audiences: [audience])
- end
-
- token
- end
-
- def refresh(token)
- if token.refresh_token.blank?
- return exchange_instead_of_refresh(token)
- end
-
- refresh_token_request(token.refresh_token).bind do |json|
- access_token = json["access_token"]
- refresh_token = json["refresh_token"]
- break Failure("Refresh token response invalid") if access_token.blank?
-
- token.update!(access_token:, refresh_token:)
-
- Success(token)
- end
- end
-
- def exchange_instead_of_refresh(token)
- # We can attempt a token exchange instead of a refresh, if we previously exchanged the token.
- # For simplicity we do not consider scenarios where the original token had a wider audience,
- # because all tokens obtained through exchange in this service will have exactly one audience.
- if can_exchange_token? && token.audiences.size == 1
- return exchange_token_for(token.audiences.first)
- end
-
- Failure("Can't refresh the access token")
- end
-
- def refresh_token_request(refresh_token)
- response = OpenProject.httpx
- .basic_auth(@provider.client_id, @provider.client_secret)
- .post(@provider.token_endpoint, form: {
- grant_type: :refresh_token,
- refresh_token:
- })
- response.raise_for_status
-
- Success(response.json)
- rescue HTTPX::Error => e
- Failure(e)
- end
-
def expired?(token_string)
exp = @jwt_parser.parse(token_string).fmap { |decoded, _| decoded["exp"] }.value_or(nil)
return false if exp.nil?
diff --git a/modules/openid_connect/app/services/openid_connect/user_tokens/refresh_service.rb b/modules/openid_connect/app/services/openid_connect/user_tokens/refresh_service.rb
new file mode 100644
index 00000000000..f8658d89205
--- /dev/null
+++ b/modules/openid_connect/app/services/openid_connect/user_tokens/refresh_service.rb
@@ -0,0 +1,89 @@
+# frozen_string_literal: true
+
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 2012-2024 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.
+#++
+
+module OpenIDConnect
+ module UserTokens
+ class RefreshService
+ include Dry::Monads[:result]
+
+ def initialize(user:, token_exchange:)
+ @user = user
+ @token_exchange = token_exchange
+ end
+
+ def call(token)
+ if token.refresh_token.blank?
+ return exchange_instead_of_refresh(token)
+ end
+
+ refresh_token_request(token.refresh_token).bind do |json|
+ access_token = json["access_token"]
+ refresh_token = json["refresh_token"]
+ break Failure("Refresh token response invalid") if access_token.blank?
+
+ token.update!(access_token:, refresh_token:)
+
+ Success(token)
+ end
+ end
+
+ private
+
+ def exchange_instead_of_refresh(token)
+ # We can attempt a token exchange instead of a refresh, if we previously exchanged the token.
+ # For simplicity we do not consider scenarios where the original token had a wider audience,
+ # because all tokens obtained through exchange in this service will have exactly one audience.
+ if @token_exchange.supported? && token.audiences.size == 1
+ return @token_exchange.call(token.audiences.first)
+ end
+
+ Failure("Can't refresh the access token")
+ end
+
+ def refresh_token_request(refresh_token)
+ response = OpenProject.httpx
+ .basic_auth(provider.client_id, provider.client_secret)
+ .post(provider.token_endpoint, form: {
+ grant_type: :refresh_token,
+ refresh_token:
+ })
+ response.raise_for_status
+
+ Success(response.json)
+ rescue HTTPX::Error => e
+ Failure(e)
+ end
+
+ def provider
+ @user.authentication_provider
+ end
+ end
+ end
+end
diff --git a/modules/openid_connect/spec/services/openid_connect/user_tokens/exchange_service_spec.rb b/modules/openid_connect/spec/services/openid_connect/user_tokens/exchange_service_spec.rb
new file mode 100644
index 00000000000..cf8ebc9b263
--- /dev/null
+++ b/modules/openid_connect/spec/services/openid_connect/user_tokens/exchange_service_spec.rb
@@ -0,0 +1,116 @@
+# frozen_string_literal: true
+
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 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"
+
+RSpec.describe OpenIDConnect::UserTokens::ExchangeService, :webmock do
+ let(:service) { described_class.new(user:) }
+ let(:user) { create(:user, identity_url: "#{provider.slug}:1337") }
+ let(:provider) { create(:oidc_provider, :token_exchange_capable) }
+
+ let(:access_token) { "the-access-token" }
+ let(:refresh_token) { "the-refresh-token" }
+ let(:idp_access_token) { "the-idp-access-token" }
+
+ let(:existing_audience) { "existing-audience" }
+
+ let(:exchange_response) do
+ {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ body: { access_token: "#{access_token}-exchanged", refresh_token: "#{refresh_token}-exchanged" }.to_json
+ }
+ end
+
+ before do
+ user.oidc_user_tokens.create!(access_token: idp_access_token, audiences: [OpenIDConnect::UserToken::IDP_AUDIENCE])
+ user.oidc_user_tokens.create!(access_token:, refresh_token:, audiences: [existing_audience])
+ stub_request(:post, provider.token_endpoint)
+ .with(body: hash_including(grant_type: "urn:ietf:params:oauth:grant-type:token-exchange"))
+ .to_return(**exchange_response)
+ end
+
+ describe "#call" do
+ subject(:result) { service.call(audience) }
+
+ let(:audience) { "new-audience" }
+
+ it { is_expected.to be_success }
+
+ it "creates a new user token", :aggregate_failures do
+ expect { subject }.to change(user.oidc_user_tokens, :count).from(2).to(3)
+ expect(user.oidc_user_tokens.last.access_token).to eq("the-access-token-exchanged")
+ expect(user.oidc_user_tokens.last.refresh_token).to eq("the-refresh-token-exchanged")
+ end
+
+ it "returns the new user token" do
+ expect(result.value!).to eq(user.oidc_user_tokens.last)
+ end
+
+ it "used the IDP access token to perform the exchange" do
+ subject
+ expect(WebMock).to have_requested(:post, provider.token_endpoint)
+ .with(body: hash_including(subject_token: idp_access_token))
+ end
+
+ context "when exchanging token for an existing user token" do
+ let(:audience) { existing_audience }
+
+ it { is_expected.to be_success }
+
+ it "creates a new user token", :aggregate_failures do
+ expect { subject }.not_to change(user.oidc_user_tokens, :count)
+ expect(user.oidc_user_tokens.last.access_token).to eq("the-access-token-exchanged")
+ expect(user.oidc_user_tokens.last.refresh_token).to eq("the-refresh-token-exchanged")
+ end
+
+ it "returns the updated user token" do
+ expect(result.value!).to eq(user.oidc_user_tokens.last)
+ end
+ end
+
+ context "when provider is not capable of token exchange" do
+ let(:provider) { create(:oidc_provider) }
+
+ it { is_expected.to be_failure }
+ end
+ end
+
+ describe "#supported?" do
+ subject { service.supported? }
+
+ it { is_expected.to be_truthy }
+
+ context "when provider is not capable of token exchange" do
+ let(:provider) { create(:oidc_provider) }
+
+ it { is_expected.to be_falsey }
+ end
+ end
+end
diff --git a/modules/openid_connect/spec/services/openid_connect/user_tokens/fetch_service_spec.rb b/modules/openid_connect/spec/services/openid_connect/user_tokens/fetch_service_spec.rb
index 42e75dbb1b8..47e5f90cd39 100644
--- a/modules/openid_connect/spec/services/openid_connect/user_tokens/fetch_service_spec.rb
+++ b/modules/openid_connect/spec/services/openid_connect/user_tokens/fetch_service_spec.rb
@@ -30,123 +30,30 @@
require "spec_helper"
RSpec.describe OpenIDConnect::UserTokens::FetchService, :webmock do
- let(:service) { described_class.new(user:, jwt_parser:) }
- let(:user) { create(:user, identity_url: "#{provider.slug}:1337") }
- let(:provider) { create(:oidc_provider) }
+ let(:service) { described_class.new(user:, jwt_parser:, token_exchange:, token_refresh:) }
+ let(:user) { create(:user) }
let(:jwt_parser) { instance_double(OpenIDConnect::JwtParser, parse: Success([parsed_jwt, nil])) }
let(:parsed_jwt) { { "exp" => Time.now.to_i + 60 } }
+ let(:token_exchange) { instance_double(OpenIDConnect::UserTokens::ExchangeService, supported?: false) }
+ let(:token_refresh) { instance_double(OpenIDConnect::UserTokens::RefreshService) }
+
let(:access_token) { "the-access-token" }
let(:refresh_token) { "the-refresh-token" }
- let(:idp_access_token) { "the-idp-access-token" }
let(:existing_audience) { "existing-audience" }
let(:queried_audience) { existing_audience }
- let(:refresh_response) do
- {
- status: 200,
- headers: { "Content-Type": "application/json" },
- body: { access_token: "#{access_token}-refreshed", refresh_token: "#{refresh_token}-refreshed" }.to_json
- }
- end
-
- let(:exchange_response) do
- {
- status: 200,
- headers: { "Content-Type": "application/json" },
- body: { access_token: "#{access_token}-exchanged", refresh_token: "#{refresh_token}-exchanged" }.to_json
- }
- end
-
before do
user.oidc_user_tokens.create!(access_token:, refresh_token:, audiences: [existing_audience])
- user.oidc_user_tokens.create!(access_token: idp_access_token, audiences: [OpenIDConnect::UserToken::IDP_AUDIENCE])
- stub_request(:post, provider.token_endpoint)
- .with(body: hash_including(grant_type: "refresh_token"))
- .to_return(**refresh_response)
- stub_request(:post, provider.token_endpoint)
- .with(body: hash_including(grant_type: "urn:ietf:params:oauth:grant-type:token-exchange"))
- .to_return(**exchange_response)
- end
-
- shared_examples_for "returns a refreshed access token" do
- it { is_expected.to be_success }
-
- it "returns a refreshed access token" do
- expect(result.value!).to eq("the-access-token-refreshed")
- end
-
- it "updates the stored access token" do
- expect { subject }.to change { user.oidc_user_tokens.first.access_token }
- .from(access_token)
- .to("the-access-token-refreshed")
+ allow(token_refresh).to receive(:call) do |token|
+ token.update!(access_token: "access-token-refreshed", refresh_token: "refresh-token-refreshed")
+ Success(token)
end
-
- it "updates the stored refresh token" do
- expect { subject }.to change { user.oidc_user_tokens.first.refresh_token }
- .from(refresh_token)
- .to("the-refresh-token-refreshed")
- end
-
- context "when the refresh response is unexpected JSON" do
- let(:refresh_response) do
- {
- status: 200, # misbehaving server responds with wrong JSON for success status
- headers: { "Content-Type": "application/json" },
- body: { error: "I can't let you do that Dave!" }.to_json
- }
- end
-
- it { is_expected.to be_failure }
- end
-
- context "when the refresh response has unexpected status" do
- let(:refresh_response) do
- {
- status: 502,
- headers: { "Content-Type": "text/html" },
- body: "<html><body>502 Bad Gateway</body></html>"
- }
- end
-
- it { is_expected.to be_failure }
- end
-
- context "when there is no refresh token" do
- let(:refresh_token) { nil }
-
- it { is_expected.to be_failure }
-
- it "does not try to perform a token refresh" do
- subject
- expect(WebMock).not_to have_requested(:post, provider.token_endpoint)
- .with(body: hash_including(grant_type: "refresh_token"))
- end
-
- context "and the provider is token exchange capable" do
- let(:provider) { create(:oidc_provider, :token_exchange_capable) }
-
- it { is_expected.to be_success }
-
- it "does not create a new user token (updates in-place)" do
- expect { subject }.not_to change(user.oidc_user_tokens, :count)
- end
-
- it "updates the stored access token" do
- expect { subject }.to change { user.oidc_user_tokens.first.access_token }
- .from(access_token)
- .to("the-access-token-exchanged")
- end
-
- it "updates the stored refresh token" do
- expect { subject }.to change { user.oidc_user_tokens.first.refresh_token }.from(nil).to("-exchanged")
- end
-
- it "returns the exchanged access token" do
- expect(result.value!).to eq("the-access-token-exchanged")
- end
- end
+ allow(token_exchange).to receive(:call) do |aud|
+ Success(user.oidc_user_tokens.create!(access_token: "access-token-exchanged",
+ refresh_token: "refresh-token-exchanged",
+ audiences: [aud]))
end
end
@@ -172,7 +79,11 @@ RSpec.describe OpenIDConnect::UserTokens::FetchService, :webmock do
context "when the token is expired" do
let(:parsed_jwt) { { "exp" => Time.now.to_i } }
- it_behaves_like "returns a refreshed access token"
+ it { is_expected.to be_success }
+
+ it "returns the refreshed access token" do
+ expect(result.value!).to eq("access-token-refreshed")
+ end
end
context "when audience can't be found" do
@@ -180,25 +91,23 @@ RSpec.describe OpenIDConnect::UserTokens::FetchService, :webmock do
it { is_expected.to be_failure }
+ it "does not attempt a token exchange" do
+ subject
+ expect(token_exchange).not_to have_received(:call)
+ end
+
context "and the provider is token exchange capable" do
- let(:provider) { create(:oidc_provider, :token_exchange_capable) }
+ let(:token_exchange) { instance_double(OpenIDConnect::UserTokens::ExchangeService, supported?: true) }
it { is_expected.to be_success }
- it "creates a new user token", :aggregate_failures do
- expect { subject }.to change(user.oidc_user_tokens, :count).from(2).to(3)
- expect(user.oidc_user_tokens.last.access_token).to eq("the-access-token-exchanged")
- expect(user.oidc_user_tokens.last.refresh_token).to eq("the-refresh-token-exchanged")
- end
-
it "returns the exchanged access token" do
- expect(result.value!).to eq("the-access-token-exchanged")
+ expect(result.value!).to eq("access-token-exchanged")
end
- it "used the IDP access token to perform the exchange" do
+ it "tries to exchange the correct audience" do
subject
- expect(WebMock).to have_requested(:post, provider.token_endpoint)
- .with(body: hash_including(subject_token: idp_access_token))
+ expect(token_exchange).to have_received(:call).with(queried_audience)
end
end
end
@@ -207,7 +116,11 @@ RSpec.describe OpenIDConnect::UserTokens::FetchService, :webmock do
describe "#refreshed_access_token_for" do
subject(:result) { service.refreshed_access_token_for(audience: queried_audience) }
- it_behaves_like "returns a refreshed access token"
+ it { is_expected.to be_success }
+
+ it "returns the refreshed access token" do
+ expect(result.value!).to eq("access-token-refreshed")
+ end
context "when audience can't be found" do
let(:queried_audience) { "wrong-audience" }
diff --git a/modules/openid_connect/spec/services/openid_connect/user_tokens/refresh_service_spec.rb b/modules/openid_connect/spec/services/openid_connect/user_tokens/refresh_service_spec.rb
new file mode 100644
index 00000000000..22e9124af2a
--- /dev/null
+++ b/modules/openid_connect/spec/services/openid_connect/user_tokens/refresh_service_spec.rb
@@ -0,0 +1,130 @@
+# frozen_string_literal: true
+
+#-- copyright
+# OpenProject is an open source project management software.
+# Copyright (C) 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"
+
+RSpec.describe OpenIDConnect::UserTokens::RefreshService, :webmock do
+ subject(:result) { service.call(token) }
+
+ let(:service) { described_class.new(user:, token_exchange:) }
+ let(:user) { create(:user, identity_url: "#{provider.slug}:1337") }
+ let(:provider) { create(:oidc_provider) }
+
+ let(:token_exchange) do
+ instance_double(OpenIDConnect::UserTokens::ExchangeService, supported?: false)
+ end
+
+ let(:token) do
+ user.oidc_user_tokens.create!(access_token: "a-token", refresh_token: "r-token", audiences: ["the-audience"])
+ end
+
+ let(:refresh_response) do
+ {
+ status: 200,
+ headers: { "Content-Type": "application/json" },
+ body: { access_token: "a-refreshed", refresh_token: "r-refreshed" }.to_json
+ }
+ end
+
+ before do
+ stub_request(:post, provider.token_endpoint)
+ .with(body: hash_including(grant_type: "refresh_token"))
+ .to_return(**refresh_response)
+ token.save!
+ end
+
+ it { is_expected.to be_success }
+
+ it "returns the updated token" do
+ expect(result.value!).to eq(user.oidc_user_tokens.first)
+ end
+
+ it "updates the stored access token" do
+ expect { subject }.to change { user.oidc_user_tokens.first.access_token }.from("a-token").to("a-refreshed")
+ end
+
+ it "updates the stored refresh token" do
+ expect { subject }.to change { user.oidc_user_tokens.first.refresh_token }.from("r-token").to("r-refreshed")
+ end
+
+ context "when the refresh response is unexpected JSON" do
+ let(:refresh_response) do
+ {
+ status: 200, # misbehaving server responds with wrong JSON for success status
+ headers: { "Content-Type": "application/json" },
+ body: { error: "I can't let you do that Dave!" }.to_json
+ }
+ end
+
+ it { is_expected.to be_failure }
+ end
+
+ context "when the refresh response has unexpected status" do
+ let(:refresh_response) do
+ {
+ status: 502,
+ headers: { "Content-Type": "text/html" },
+ body: "<html><body>502 Bad Gateway</body></html>"
+ }
+ end
+
+ it { is_expected.to be_failure }
+ end
+
+ context "when there is no refresh token" do
+ let(:token) do
+ user.oidc_user_tokens.create!(access_token: "a-token", refresh_token: nil, audiences: ["the-audience"])
+ end
+
+ it { is_expected.to be_failure }
+
+ it "does not try to perform a token refresh" do
+ subject
+ expect(WebMock).not_to have_requested(:post, provider.token_endpoint)
+ .with(body: hash_including(grant_type: "refresh_token"))
+ end
+
+ context "and the provider is token exchange capable" do
+ let(:token_exchange) do
+ instance_double(OpenIDConnect::UserTokens::ExchangeService, supported?: true, call: Success("exchange-result"))
+ end
+
+ it { is_expected.to be_success }
+
+ it "returns the exchanged access token" do
+ expect(result.value!).to eq("exchange-result")
+ end
+
+ it "tries to exchange for the token's audience" do
+ subject
+ expect(token_exchange).to have_received(:call).with("the-audience")
+ end
+ end
+ end
+end