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 service to fetch access token

Jan Sandbrink251cd6a2fe6a
diff --git a/modules/openid_connect/app/services/openid_connect/jwt_parser.rb b/modules/openid_connect/app/services/openid_connect/jwt_parser.rb
index ec789fcaa56..7de07e394ad 100644
--- a/modules/openid_connect/app/services/openid_connect/jwt_parser.rb
+++ b/modules/openid_connect/app/services/openid_connect/jwt_parser.rb
@@ -38,8 +38,9 @@ module OpenIDConnect
RS512
].freeze
- def initialize(verify_audience: true, required_claims: [])
+ def initialize(verify_audience: true, verify_expiration: true, required_claims: [])
@verify_audience = verify_audience
+ @verify_expiration = verify_expiration
@required_claims = required_claims
end
@@ -56,6 +57,7 @@ module OpenIDConnect
true,
{
algorithm: alg,
+ verify_expiration: @verify_expiration,
verify_aud: @verify_audience,
aud: provider.client_id,
required_claims: all_required_claims
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
new file mode 100644
index 00000000000..45908f1a367
--- /dev/null
+++ b/modules/openid_connect/app/services/openid_connect/user_tokens/fetch_service.rb
@@ -0,0 +1,123 @@
+# 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
+ ##
+ # Provides APIs to obtain access tokens of a given user for use at a third-party
+ # application for which we know the audience name, which is typically the application's
+ # client_id at an identity provider that OpenProject and the application have in common.
+ class FetchService
+ include Dry::Monads[:result]
+
+ def initialize(user:, jwt_parser: JwtParser.new(verify_audience: false, verify_expiration: false))
+ @user = user
+ @provider = user.authentication_provider
+ @jwt_parser = jwt_parser
+ end
+
+ ##
+ # Obtains an access token that can be used to make requests in the user's name at the
+ # remote service identified by the +audience+ parameter.
+ #
+ # The access token will be refreshed before being returned by this method, if it can be
+ # 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.
+ def access_token_for(audience:)
+ token = token_with_audience(audience)
+ token = token.bind do |t|
+ if expired?(t.access_token)
+ refresh(t)
+ else
+ Success(t)
+ end
+ end
+
+ token.fmap(&:access_token)
+ end
+
+ ##
+ # Obtains an access token that can be used to make requests in the user's name at the
+ # remote service identified by the +audience+ parameter.
+ #
+ # 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.
+ def refreshed_access_token_for(audience:)
+ token_with_audience(audience)
+ .bind { |t| refresh(t) }
+ .fmap(&:access_token)
+ end
+
+ private
+
+ def token_with_audience(aud)
+ token = @user.oidc_user_tokens.where("audiences ? :aud", aud:).first
+ token ? Success(token) : Failure("No token for given audience")
+ end
+
+ def refresh(token)
+ return Failure("Can't refresh the access token") if token.refresh_token.blank?
+
+ 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 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?
+
+ exp <= Time.now.to_i
+ end
+ end
+ end
+end
diff --git a/modules/openid_connect/spec/services/openid_connect/jwt_parser_spec.rb b/modules/openid_connect/spec/services/openid_connect/jwt_parser_spec.rb
index 21fcb28a65a..8d2508e498b 100644
--- a/modules/openid_connect/spec/services/openid_connect/jwt_parser_spec.rb
+++ b/modules/openid_connect/spec/services/openid_connect/jwt_parser_spec.rb
@@ -33,12 +33,15 @@ RSpec.describe OpenIDConnect::JwtParser do
subject(:parse) { described_class.new.parse(token) }
let(:private_key) { OpenSSL::PKey::RSA.generate(2048) }
- let(:payload) { { "sub" => "M. Curie", "iss" => "International Space Station", "aud" => our_client_id } }
+ let(:payload) do
+ { "exp" => expiration, "sub" => "M. Curie", "iss" => "International Space Station", "aud" => our_client_id }
+ end
let(:token) { JWT.encode(payload, private_key, "RS256", { kid: "key-identifier" }) }
let!(:provider) { create(:oidc_provider) }
let(:known_issuer) { "International Space Station" }
let(:our_client_id) { "openproject.org" }
+ let(:expiration) { 1.minute.from_now.to_i }
before do
allow(JSON::JWK::Set::Fetcher).to receive(:fetch).and_return(
@@ -144,4 +147,16 @@ RSpec.describe OpenIDConnect::JwtParser do
it { is_expected.to be_failure }
end
end
+
+ context "when the token is expired" do
+ let(:expiration) { 1.second.ago.to_i }
+
+ it { is_expected.to be_failure }
+
+ context "and when not verifying expiration" do
+ subject(:parse) { described_class.new(verify_expiration: false).parse(token) }
+
+ it { is_expected.to be_success }
+ 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
new file mode 100644
index 00000000000..3823db6b8a9
--- /dev/null
+++ b/modules/openid_connect/spec/services/openid_connect/user_tokens/fetch_service_spec.rb
@@ -0,0 +1,163 @@
+# 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::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(:jwt_parser) { instance_double(OpenIDConnect::JwtParser, parse: Success([parsed_jwt, nil])) }
+ let(:parsed_jwt) { { "exp" => Time.now.to_i + 60 } }
+
+ let(:access_token) { "the-access-token" }
+ let(:refresh_token) { "the-refresh-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
+
+ before do
+ user.oidc_user_tokens.create!(access_token:, refresh_token:, audiences: [existing_audience])
+ stub_request(:post, provider.token_endpoint).to_return(**refresh_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 }.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")
+ 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
+ end
+
+ describe "#access_token_for" do
+ subject(:result) { service.access_token_for(audience: queried_audience) }
+
+ it { is_expected.to be_success }
+
+ it "returns the stored access token" do
+ expect(result.value!).to eq(access_token)
+ end
+
+ context "when the token can't be parsed as JWT" do
+ let(:jwt_parser) { instance_double(OpenIDConnect::JwtParser, parse: Failure("Not a valid JWT")) }
+
+ it { is_expected.to be_success }
+
+ it "returns the stored access token" do
+ expect(result.value!).to eq(access_token)
+ end
+ end
+
+ context "when the token is expired" 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 }
+ end
+ end
+
+ describe "#refreshed_access_token_for" do
+ subject(:result) { service.refreshed_access_token_for(audience: queried_audience) }
+
+ it_behaves_like "returns a refreshed access token"
+
+ context "when audience can't be found" do
+ let(:queried_audience) { "wrong-audience" }
+
+ 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