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 token exchange capability to FetchService

Jan Sandbrinkd7080220e2c5
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 45908f1a367..0de50f9cac2 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
@@ -37,9 +37,12 @@ module OpenIDConnect
class FetchService
include Dry::Monads[:result]
- def initialize(user:, jwt_parser: JwtParser.new(verify_audience: false, verify_expiration: false))
+ def initialize(user:,
+ allow_token_exchange: true,
+ jwt_parser: JwtParser.new(verify_audience: false, verify_expiration: false))
@user = user
@provider = user.authentication_provider
+ @allow_token_exchange = allow_token_exchange
@jwt_parser = jwt_parser
end
@@ -51,6 +54,9 @@ module OpenIDConnect
# identified as being expired. There is no guarantee that all access tokens will be properly
# recognized as expired, so client's still need to make sure to handle rejected access tokens
# properly. Also see #refreshed_access_token_for.
+ #
+ # A token exchange is attempted, if the provider supports OAuth 2.0 Token Exchange and a token
+ # for the target audience either can't be found or it has expired, but has no available refresh token.
def access_token_for(audience:)
token = token_with_audience(audience)
token = token.bind do |t|
@@ -71,6 +77,9 @@ module OpenIDConnect
# The access token will always be refreshed before being returned by this method.
# It is advised to use this method, after learning that a remote service rejected
# an access token, because it was expired.
+ #
+ # A token exchange is attempted, if the provider supports OAuth 2.0 Token Exchange and a token
+ # 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) }
@@ -81,11 +90,67 @@ module OpenIDConnect
def token_with_audience(aud)
token = @user.oidc_user_tokens.where("audiences ? :aud", aud:).first
- token ? Success(token) : Failure("No token for given audience")
+ return Success(token) if token
+
+ return exchange_token_for(aud) if can_exchange_token?
+
+ 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)
- return Failure("Can't refresh the access token") if token.refresh_token.blank?
+ 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"]
@@ -98,6 +163,17 @@ module OpenIDConnect
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)
diff --git a/modules/openid_connect/spec/factories/oidc_provider_factory.rb b/modules/openid_connect/spec/factories/oidc_provider_factory.rb
index 069df379891..ed28a8d6a5c 100644
--- a/modules/openid_connect/spec/factories/oidc_provider_factory.rb
+++ b/modules/openid_connect/spec/factories/oidc_provider_factory.rb
@@ -18,6 +18,13 @@ FactoryBot.define do
"authorization_endpoint" => "https://keycloak.local/realms/master/protocol/openid-connect/auth"
}
end
+
+ trait :token_exchange_capable do
+ callback(:after_build) do |provider|
+ provider.options["grant_types_supported"] ||= []
+ provider.options["grant_types_supported"] << "urn:ietf:params:oauth:grant-type:token-exchange"
+ end
+ end
end
factory :oidc_provider_google, class: "OpenIDConnect::Provider" do
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 3823db6b8a9..42e75dbb1b8 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
@@ -38,6 +38,7 @@ RSpec.describe OpenIDConnect::UserTokens::FetchService, :webmock do
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 }
@@ -50,9 +51,23 @@ RSpec.describe OpenIDConnect::UserTokens::FetchService, :webmock do
}
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])
- stub_request(:post, provider.token_endpoint).to_return(**refresh_response)
+ 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
@@ -63,11 +78,15 @@ RSpec.describe OpenIDConnect::UserTokens::FetchService, :webmock do
end
it "updates the stored access token" do
- expect { subject }.to change { user.oidc_user_tokens.first.access_token }.to("the-access-token-refreshed")
+ expect { subject }.to change { user.oidc_user_tokens.first.access_token }
+ .from(access_token)
+ .to("the-access-token-refreshed")
end
it "updates the stored refresh token" do
- expect { subject }.to change { user.oidc_user_tokens.first.refresh_token }.to("the-refresh-token-refreshed")
+ 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
@@ -93,6 +112,42 @@ RSpec.describe OpenIDConnect::UserTokens::FetchService, :webmock do
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
+ end
end
describe "#access_token_for" do
@@ -118,23 +173,34 @@ RSpec.describe OpenIDConnect::UserTokens::FetchService, :webmock do
let(:parsed_jwt) { { "exp" => Time.now.to_i } }
it_behaves_like "returns a refreshed access token"
-
- context "and 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)
- end
- end
end
context "when audience can't be found" do
let(:queried_audience) { "wrong-audience" }
it { is_expected.to be_failure }
+
+ context "and the provider is token exchange capable" do
+ let(:provider) { create(:oidc_provider, :token_exchange_capable) }
+
+ 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")
+ 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
+ end
end
end
@@ -148,16 +214,5 @@ RSpec.describe OpenIDConnect::UserTokens::FetchService, :webmock do
it { is_expected.to be_failure }
end
-
- context "and 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)
- end
- end
end
end