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
Ruby agile-developmentangularbcfboardsbug-trackerganttgantt-chartifcissue-trackerjira-alternativekanbanopenprojectproduct-managementproject-managementproject-planningroadmaprubyscrumtimelineworkflows
Explicitly store expiration time of access tokens
Jan Sandbrink48f1f081f0a3
diff --git a/modules/openid_connect/app/services/openid_connect/user_tokens/create_service.rb b/modules/openid_connect/app/services/openid_connect/user_tokens/create_service.rbindex 7bfa6b4b729..8d3013ede9c 100644--- a/modules/openid_connect/app/services/openid_connect/user_tokens/create_service.rb+++ b/modules/openid_connect/app/services/openid_connect/user_tokens/create_service.rb@@ -36,7 +36,7 @@ module OpenIDConnect@jwt_parser = jwt_parserend- def call(access_token:, refresh_token: nil, known_audiences: [], clear_previous: false)+ def call(access_token:, refresh_token: nil, known_audiences: [], clear_previous: false, expires_in: nil)if access_token.blank?Rails.logger.error("Could not associate token to user: No access token")return@@ -49,14 +49,15 @@ module OpenIDConnect@user.oidc_user_tokens.destroy_all if clear_previous- token = prepare_token(access_token:, refresh_token:, known_audiences:)+ token = prepare_token(access_token:, refresh_token:, known_audiences:, expires_in:)token.save! if token.audiences.any?endprivate- def prepare_token(access_token:, refresh_token:, known_audiences:)- @user.oidc_user_tokens.build(access_token:, refresh_token:).tap do |token|+ def prepare_token(access_token:, refresh_token:, expires_in:, known_audiences:)+ expires_at = expires_in&.seconds&.from_now+ @user.oidc_user_tokens.build(access_token:, refresh_token:, expires_at:).tap do |token|token.audiences = merge_audiences(known_audiences, discover_audiences(access_token).value_or([]))endenddiff --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.rbindex 073667f1b34..fa6a3cd30e2 100644--- 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@@ -57,13 +57,14 @@ module OpenIDConnectjson = yield exchange_token_request(idp_token, audience)access_token = json["access_token"]+ expires_in = json["expires_in"]return Failure("Token exchange response invalid") if access_token.blank?# We are explicitly opting to not store the refresh token for exchanged tokens# For one there is no need to store one, we can simply exchange a new token once the old expired.# A second reason is that at least Keycloak (an IDP we implement against), offers broken# refresh tokens after token exchange (see https://github.com/keycloak/keycloak/issues/37016)- token = store_exchanged_token(audience:, access_token:, refresh_token: nil)+ token = store_exchanged_token(audience:, access_token:, refresh_token: nil, expires_in:)Success(token)end@@ -88,16 +89,17 @@ module OpenIDConnectFailure(e)end- def store_exchanged_token(audience:, access_token:, refresh_token:)+ def store_exchanged_token(audience:, access_token:, refresh_token:, expires_in:)+ token_data = { access_token:, refresh_token:, expires_at: expires_in&.seconds&.from_now }token = @user.oidc_user_tokens.where("audiences ? :audience", audience:).firstif tokenif token.audiences.size > 1raise "Did not expect to update token with multiple audiences (#{token.audiences}) in-place."end- token.update!(access_token:, refresh_token:)+ token.update!(**token_data)else- token = @user.oidc_user_tokens.create!(access_token:, refresh_token:, audiences: [audience])+ token = @user.oidc_user_tokens.create!(audiences: [audience], **token_data)endtokendiff --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.rbindex 2baa1a62ea0..a83900eba3a 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@@ -61,7 +61,7 @@ module OpenIDConnect# 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 = yield token_with_audience(audience)- token = yield @token_refresh.call(token) if expired?(token.access_token)+ token = yield @token_refresh.call(token) if expired?(token)Success(token.access_token)end@@ -93,11 +93,20 @@ module OpenIDConnectFailure("No token for audience '#{aud}'")end- def expired?(token_string)- exp = @jwt_parser.parse(token_string).fmap { |decoded, _| decoded["exp"] }.value_or(nil)- return false if exp.nil?+ def expired?(token)+ exp_time = expires_at(token)+ return false if exp_time.nil?- exp <= Time.now.to_i+ exp_time.past?+ end++ def expires_at(token)+ return token.expires_at if token.expires_at.present?++ exp = @jwt_parser.parse(token.access_token).fmap { |decoded, _| decoded["exp"] }.value_or(nil)+ return nil if exp.nil?++ Time.zone.at(exp)endendenddiff --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.rbindex 8d73536d6d6..d6a7844f803 100644--- 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@@ -48,9 +48,10 @@ module OpenIDConnectaccess_token = json["access_token"]refresh_token = json["refresh_token"]+ expires_in = json["expires_in"]return Failure("Refresh token response invalid") if access_token.blank?- token.update!(access_token:, refresh_token:)+ token.update!(access_token:, refresh_token:, expires_at: expires_in&.seconds&.from_now)Success(token)enddiff --git a/modules/openid_connect/db/migrate/20250218133700_add_expires_at_to_oidc_user_tokens.rb b/modules/openid_connect/db/migrate/20250218133700_add_expires_at_to_oidc_user_tokens.rbnew file mode 100644index 00000000000..7333351b30e--- /dev/null+++ b/modules/openid_connect/db/migrate/20250218133700_add_expires_at_to_oidc_user_tokens.rb@@ -0,0 +1,35 @@+# 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.+#++++class AddExpiresAtToOidcUserTokens < ActiveRecord::Migration[7.1]+ def change+ add_column :oidc_user_tokens, :expires_at, :datetime, null: true, precision: 0+ end+enddiff --git a/modules/openid_connect/lib/open_project/openid_connect/engine.rb b/modules/openid_connect/lib/open_project/openid_connect/engine.rbindex 145d66bfcf5..a47d08db714 100644--- a/modules/openid_connect/lib/open_project/openid_connect/engine.rb+++ b/modules/openid_connect/lib/open_project/openid_connect/engine.rb@@ -55,6 +55,7 @@ module OpenProject::OpenIDConnectomniauth.oidc_sidomniauth.oidc_access_tokenomniauth.oidc_refresh_token+ omniauth.oidc_expires_in]h[:backchannel_logout_callback] = ->(logout_token) dodiff --git a/modules/openid_connect/lib/open_project/openid_connect/hooks/hook.rb b/modules/openid_connect/lib/open_project/openid_connect/hooks/hook.rbindex 19d544e25dc..d95573aefee 100644--- a/modules/openid_connect/lib/open_project/openid_connect/hooks/hook.rb+++ b/modules/openid_connect/lib/open_project/openid_connect/hooks/hook.rb@@ -44,10 +44,10 @@ module OpenProject::OpenIDConnectOpenIDConnect::UserTokens::CreateService.new(user).call(access_token: session["omniauth.oidc_access_token"],refresh_token: session["omniauth.oidc_refresh_token"],+ expires_in: session["omniauth.oidc_expires_in"],known_audiences: [OpenIDConnect::UserToken::IDP_AUDIENCE],clear_previous: true)-end##@@ -58,6 +58,7 @@ module OpenProject::OpenIDConnectsession["omniauth.oidc_access_token"] = context.dig(:auth_hash, :credentials, :token)session["omniauth.oidc_refresh_token"] = context.dig(:auth_hash, :credentials, :refresh_token)+ session["omniauth.oidc_expires_in"] = context.dig(:auth_hash, :credentials, :expires_in)nilenddiff --git a/modules/openid_connect/spec/requests/openid_connect_spec.rb b/modules/openid_connect/spec/requests/openid_connect_spec.rbindex da0dc9a50b4..4d464896378 100644--- a/modules/openid_connect/spec/requests/openid_connect_spec.rb+++ b/modules/openid_connect/spec/requests/openid_connect_spec.rb@@ -1,3 +1,5 @@+# frozen_string_literal: true+#-- copyright# OpenProject is an open source project management software.# Copyright (C) the OpenProject GmbH@@ -48,6 +50,7 @@ RSpec.describe "OpenID Connect", :skip_2fa_stage, # Prevent redirects to 2FA staendlet(:access_token) { "foo-bar-baz" }let(:refresh_token) { "refreshing-foo-bar-baz" }+ let(:expires_in) { 60 }let(:oidc_sid) { "oidc-session-id-42" }before do@@ -57,6 +60,7 @@ RSpec.describe "OpenID Connect", :skip_2fa_stage, # Prevent redirects to 2FA stainstance_double(OpenIDConnect::AccessToken,access_token:,refresh_token:,+ expires_in:,userinfo!: OpenIDConnect::ResponseObject::UserInfo.new(user_info),id_token: "not-nil").as_null_objectend@@ -72,7 +76,7 @@ RSpec.describe "OpenID Connect", :skip_2fa_stage, # Prevent redirects to 2FA stalet(:limit_self_registration) { false }let!(:provider) { create(:oidc_provider, slug: "keycloak", limit_self_registration:) }- it "signs up and logs in the user" do+ it "signs up and logs in the user", :freeze_time do### it should redirect to the provider's openid connect authentication endpointclick_on_signin("keycloak")@@ -106,9 +110,12 @@ RSpec.describe "OpenID Connect", :skip_2fa_stage, # Prevent redirects to 2FA statoken = user.oidc_user_tokens.firstexpect(token).not_to be_nil- expect(token.access_token).to eq access_token- expect(token.refresh_token).to eq refresh_token- expect(token.audiences).to eq ["__op-idp__"]+ aggregate_failures "OIDC user token details" do+ expect(token.access_token).to eq access_token+ expect(token.refresh_token).to eq refresh_token+ expect(token.expires_at).to eq 60.seconds.from_now.change(usec: 0)+ expect(token.audiences).to eq ["__op-idp__"]+ endendcontext "when the user is already registered" dodiff --git a/modules/openid_connect/spec/services/openid_connect/user_tokens/create_service_spec.rb b/modules/openid_connect/spec/services/openid_connect/user_tokens/create_service_spec.rbindex 523c6e92d25..5b6f19c2932 100644--- a/modules/openid_connect/spec/services/openid_connect/user_tokens/create_service_spec.rb+++ b/modules/openid_connect/spec/services/openid_connect/user_tokens/create_service_spec.rb@@ -54,6 +54,7 @@ RSpec.describe OpenIDConnect::UserTokens::CreateService doexpect(token.access_token).to eq access_tokenexpect(token.refresh_token).to eq refresh_tokenexpect(token.audiences).to contain_exactly("io", "aud1", "aud2")+ expect(token.expires_at).to be_nilendit "logs no error" do@@ -226,4 +227,16 @@ RSpec.describe OpenIDConnect::UserTokens::CreateService doexpect(token.audiences).to contain_exactly("io", "aud2")endend++ context "when passing expires_in", :freeze_time do+ let(:args) { { access_token:, refresh_token:, known_audiences: ["io"], expires_in: } }+ let(:expires_in) { 120 }++ it "creates a user token with correct expires_at", :aggregate_failures do+ expect { subject }.to change(OpenIDConnect::UserToken, :count).by(1)++ token = OpenIDConnect::UserToken.last+ expect(token.expires_at).to eq expires_in.seconds.from_now.change(usec: 0)+ end+ endenddiff --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.rbindex 12a6ebaf890..59f0e9f869a 100644--- 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@@ -44,9 +44,14 @@ RSpec.describe OpenIDConnect::UserTokens::ExchangeService, :webmock do{status: 200,headers: { "Content-Type": "application/json" },- body: { access_token: "#{access_token}-exchanged", refresh_token: "#{refresh_token}-exchanged" }.to_json+ body: {+ access_token: "#{access_token}-exchanged",+ refresh_token: "#{refresh_token}-exchanged",+ expires_in: 45+ }.to_json}end+ let(:expected_expires_at) { 45.seconds.from_now.change(usec: 0) }before douser.oidc_user_tokens.create!(access_token: idp_access_token, audiences: [OpenIDConnect::UserToken::IDP_AUDIENCE])@@ -63,10 +68,11 @@ RSpec.describe OpenIDConnect::UserTokens::ExchangeService, :webmock doit { is_expected.to be_success }- it "creates a new user token", :aggregate_failures do+ it "creates a new user token", :aggregate_failures, :freeze_time doexpect { 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 be_nil+ expect(user.oidc_user_tokens.last.expires_at).to eq(expected_expires_at)endit "returns the new user token" do@@ -79,20 +85,57 @@ RSpec.describe OpenIDConnect::UserTokens::ExchangeService, :webmock do.with(body: hash_including(subject_token: idp_access_token))end+ context "when the response has no expires_in" do+ 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++ it "creates a new user token without expiration", :aggregate_failures do+ expect { subject }.to change(user.oidc_user_tokens, :count).from(2).to(3)+ expect(user.oidc_user_tokens.last.expires_at).to be_nil+ end+ end+context "when exchanging token for an existing user token" dolet(:audience) { existing_audience }it { is_expected.to be_success }- it "creates a new user token", :aggregate_failures do+ it "updates the existing user token", :aggregate_failures, :freeze_time doexpect { 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 be_nil+ expect(user.oidc_user_tokens.last.expires_at).to eq(expected_expires_at)endit "returns the updated user token" doexpect(result.value!).to eq(user.oidc_user_tokens.last)end++ context "and when the response has no expires_in" do+ 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++ it "updates the existing user token without expiration", :aggregate_failures do+ expect { subject }.not_to change(user.oidc_user_tokens, :count)+ expect(user.oidc_user_tokens.last.expires_at).to be_nil+ end+ endendcontext "when provider is not capable of token exchange" dodiff --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.rbindex 47e5f90cd39..b26a600ba22 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@@ -66,7 +66,7 @@ RSpec.describe OpenIDConnect::UserTokens::FetchService, :webmock doexpect(result.value!).to eq(access_token)end- context "when the token can't be parsed as JWT" do+ context "when the token doesn't expire and can't be parsed as JWT" dolet(:jwt_parser) { instance_double(OpenIDConnect::JwtParser, parse: Failure("Not a valid JWT")) }it { is_expected.to be_success }@@ -76,7 +76,31 @@ RSpec.describe OpenIDConnect::UserTokens::FetchService, :webmock doendend- context "when the token is expired" do+ context "when it is expired" do+ before do+ user.oidc_user_tokens.first.update!(expires_at: Time.zone.now)+ end++ 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 it expires in the future" do+ before do+ user.oidc_user_tokens.first.update!(expires_at: 10.seconds.from_now)+ end++ it { is_expected.to be_success }++ it "returns the stored access token" do+ expect(result.value!).to eq(access_token)+ end+ end++ context "when parsing the token reveals, that it is expired" dolet(:parsed_jwt) { { "exp" => Time.now.to_i } }it { is_expected.to be_success }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.rbindex 22e9124af2a..8f3ca391e9e 100644--- 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@@ -48,7 +48,7 @@ RSpec.describe OpenIDConnect::UserTokens::RefreshService, :webmock do{status: 200,headers: { "Content-Type": "application/json" },- body: { access_token: "a-refreshed", refresh_token: "r-refreshed" }.to_json+ body: { access_token: "a-refreshed", refresh_token: "r-refreshed", expires_in: 20 }.to_json}end@@ -73,6 +73,25 @@ RSpec.describe OpenIDConnect::UserTokens::RefreshService, :webmock doexpect { subject }.to change { user.oidc_user_tokens.first.refresh_token }.from("r-token").to("r-refreshed")end+ it "updates the stored expiration time", :freeze_time do+ expect { subject }.to change { user.oidc_user_tokens.first.expires_at }.to(20.seconds.from_now.change(usec: 0))+ end++ context "when the refresh response has no expires_in" do+ let(:refresh_response) do+ {+ status: 200,+ headers: { "Content-Type": "application/json" },+ body: { access_token: "a-refreshed", refresh_token: "r-refreshed" }.to_json+ }+ end++ it "updates the stored expiration time to nil" do+ subject+ expect(user.oidc_user_tokens.first.expires_at).to be_nil+ end+ end+context "when the refresh response is unexpected JSON" dolet(:refresh_response) do{diff --git a/spec/support/shared/timecop.rb b/spec/support/shared/timecop.rbnew file mode 100644index 00000000000..8a7b479e108--- /dev/null+++ b/spec/support/shared/timecop.rb@@ -0,0 +1,36 @@+# 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.+#++++RSpec.configure do |config|+ config.around(:example, :freeze_time) do |example|+ time = example.metadata[:freeze_time] == true ? Time.zone.now : example.metadata[:freeze_time]+ Timecop.freeze(time) { example.run }+ end+end