From fa8f92a24ef6f9639e8a7ad78a5b24a938a26c9e Mon Sep 17 00:00:00 2001 From: Henrik Nygren Date: Tue, 24 Nov 2026 09:57:49 +0200 Subject: [PATCH 1/5] Accept known courses.mooc.fi tokens during an outage, cache for 60 s --- .../courses_mooc_fi_token_introspector.rb | 46 ++++++++++++++- ...courses_mooc_fi_token_introspector_spec.rb | 59 ++++++++++++++++++- 2 files changed, 101 insertions(+), 4 deletions(-) diff --git a/app/services/courses_mooc_fi_token_introspector.rb b/app/services/courses_mooc_fi_token_introspector.rb index 6aef62418..57c384ed9 100644 --- a/app/services/courses_mooc_fi_token_introspector.rb +++ b/app/services/courses_mooc_fi_token_introspector.rb @@ -16,13 +16,20 @@ class Unavailable < StandardError; end Result = Struct.new(:sub, :upstream_id, :expires_at, keyword_init: true) REQUIRED_SCOPE = 'exercise-services' - MAX_CACHE_TTL = 300 # seconds + # Bounds how long a token revoked on courses.mooc.fi is still honoured; a revocation is only + # noticed on the next introspection. Per token, so sp331 sees at most one request a minute each. + MAX_CACHE_TTL = 60 # seconds + # How long a token seen active before is honoured through an outage; its own expiry ends it sooner. + STALE_TTL_CAP = 3600 # seconds + # Between retries of a down courses.mooc.fi for a token served from the stale entry. + STALE_RETRY_INTERVAL = 15 # seconds REJECTION_CACHE_TTL = 30 # seconds CACHE_NAMESPACE = 'courses_mooc_fi_introspection' REJECTED = :rejected # Returns the Result for a token courses.mooc.fi vouches for, or nil when it rejects the token. - # Raises Unavailable when it cannot answer; that is never cached. + # When it cannot answer, a token it vouched for earlier and that has not expired is still + # accepted; for any other token this raises Unavailable, which is never cached. sig { params(token: String).returns(T.nilable(Result)) } def self.introspect(token) new.introspect(token) @@ -36,7 +43,17 @@ def introspect(token) cached = Rails.cache.read(cache_key) return (cached == REJECTED ? nil : cached) unless cached.nil? - body = request_introspection(token) + begin + body = request_introspection(token) + rescue Unavailable => e + stale = fresh_stale_result(cache_key) + raise unless stale + + Rails.logger.warn("courses.mooc.fi token introspection unavailable, accepting a token seen active earlier: #{e.message}") + ttl = cache_ttl(stale.expires_at) + Rails.cache.write(cache_key, stale, expires_in: [ttl, STALE_RETRY_INTERVAL].min) if ttl + return stale + end reason = reject_reason(body) if reason Rails.logger.warn("courses.mooc.fi token rejected: #{reason}") @@ -51,6 +68,8 @@ def introspect(token) ) ttl = cache_ttl(result.expires_at) Rails.cache.write(cache_key, result, expires_in: ttl) if ttl + stale_ttl = stale_cache_ttl(result.expires_at) + Rails.cache.write(stale_cache_key(cache_key), result, expires_in: stale_ttl) if stale_ttl result end @@ -87,6 +106,8 @@ def request_introspection(token) response.body when 401 raise Unavailable, "courses.mooc.fi rejected tmc-server's introspection client credentials; check COURSES_MOOC_FI_INTROSPECTION_CLIENT_ID and COURSES_MOOC_FI_INTROSPECTION_SECRET" + when 429 + raise Unavailable, 'courses.mooc.fi rate-limited introspection (HTTP 429); check that RACK_ATTACK_SAFE_API_KEY matches its RATELIMIT_PROTECTION_SAFE_API_KEY' else raise Unavailable, "introspection answered HTTP #{response.status}" end @@ -108,6 +129,25 @@ def reject_reason(body) nil end + sig { params(cache_key: String).returns(String) } + def stale_cache_key(cache_key) + "#{cache_key}:stale" + end + + sig { params(cache_key: String).returns(T.nilable(Result)) } + def fresh_stale_result(cache_key) + stale = Rails.cache.read(stale_cache_key(cache_key)) + stale if stale.is_a?(Result) && (stale.expires_at.nil? || stale.expires_at > Time.now) + end + + # In seconds; nil when the token has already expired. + sig { params(expires_at: T.nilable(Time)).returns(T.nilable(Integer)) } + def stale_cache_ttl(expires_at) + return STALE_TTL_CAP if expires_at.nil? + remaining = (expires_at - Time.now).floor + [remaining, STALE_TTL_CAP].min if remaining.positive? + end + # In seconds; nil when the token has already expired. sig { params(expires_at: T.nilable(Time)).returns(T.nilable(Integer)) } def cache_ttl(expires_at) diff --git a/spec/services/courses_mooc_fi_token_introspector_spec.rb b/spec/services/courses_mooc_fi_token_introspector_spec.rb index f878dca4d..c67bd371f 100644 --- a/spec/services/courses_mooc_fi_token_introspector_spec.rb +++ b/spec/services/courses_mooc_fi_token_introspector_spec.rb @@ -118,6 +118,11 @@ def introspect end end + it 'names the bypass key when courses.mooc.fi rate-limits it' do + stub_provider(status: 429, body: 'Retry later', content_type: 'text/plain') + expect { introspect }.to raise_error(described_class::Unavailable, /RACK_ATTACK_SAFE_API_KEY/) + end + it 'raises Unavailable without asking when the client credentials are not configured' do allow(AppSecrets).to receive(:courses_mooc_fi_introspection_secret).and_return('') expect { introspect }.to raise_error(described_class::Unavailable, /not set/) @@ -132,6 +137,58 @@ def introspect end end + describe 'during an outage' do + let(:status) { { code: 200 } } + + before do + provider.post(introspection_path) do |env| + provider_requests << env + status[:code] == 200 ? [200, { 'Content-Type' => 'application/json' }, active_body.to_json] : [503, {}, ''] + end + end + + def go_down + status[:code] = 503 + cache.delete("#{described_class::CACHE_NAMESPACE}:#{Digest::SHA256.hexdigest(token)}") + end + + it 'accepts a token seen active before' do + introspect + go_down + expect(introspect).to have_attributes(sub: sub) + end + + it 'retries courses.mooc.fi only every STALE_RETRY_INTERVAL' do + introspect + go_down + 3.times { introspect } + expect(provider_requests.size).to eq(2) + end + + it 'raises Unavailable for a token never seen' do + status[:code] = 503 + expect { introspect }.to raise_error(described_class::Unavailable) + end + + it 'raises Unavailable once the token has expired' do + allow(Time).to receive(:now).and_call_original + introspect + go_down + allow(Time).to receive(:now).and_return(Time.at(active_body['exp']) + 1) + cache.clear + expect { introspect }.to raise_error(described_class::Unavailable) + end + + it 'does not accept a token courses.mooc.fi has rejected' do + introspect + status[:code] = 200 + provider.post(introspection_path) { [200, { 'Content-Type' => 'application/json' }, { 'active' => false }.to_json] } + cache.clear + allow(Rails.logger).to receive(:warn) + expect(introspect).to be_nil + end + end + describe 'caching' do it 'asks the provider once for an active token' do stub_provider(status: 200, body: active_body) @@ -165,7 +222,7 @@ def introspect allow(cache).to receive(:write).and_call_original stub_provider(status: 200, body: active_body.merge('exp' => (Time.now + 60).to_i)) introspect - expect(cache).to have_received(:write).with(anything, anything, expires_in: be_between(1, 60)) + expect(cache).to have_received(:write).with(anything, anything, expires_in: be_between(1, 60)).at_least(:once) end it 'does not cache an already-expired token' do From a6e7c28a59da5f89f29ea7a1688f64621ea2ac95 Mon Sep 17 00:00:00 2001 From: Henrik Nygren Date: Tue, 24 Nov 2026 09:57:49 +0200 Subject: [PATCH 2/5] Warn at boot when the introspection rate-limit bypass key is unset --- app/services/courses_mooc_fi_rate_limit_bypass.rb | 5 +++++ .../courses_mooc_fi_rate_limit_bypass_check.rb | 10 ++++++++++ 2 files changed, 15 insertions(+) create mode 100644 config/initializers/courses_mooc_fi_rate_limit_bypass_check.rb diff --git a/app/services/courses_mooc_fi_rate_limit_bypass.rb b/app/services/courses_mooc_fi_rate_limit_bypass.rb index 0a5613713..68ea16d4b 100644 --- a/app/services/courses_mooc_fi_rate_limit_bypass.rb +++ b/app/services/courses_mooc_fi_rate_limit_bypass.rb @@ -12,4 +12,9 @@ def self.headers key = ENV['RACK_ATTACK_SAFE_API_KEY'] key.present? ? { HEADER => key } : {} end + + sig { returns(T::Boolean) } + def self.configured? + headers.any? + end end diff --git a/config/initializers/courses_mooc_fi_rate_limit_bypass_check.rb b/config/initializers/courses_mooc_fi_rate_limit_bypass_check.rb new file mode 100644 index 000000000..9ba5289ea --- /dev/null +++ b/config/initializers/courses_mooc_fi_rate_limit_bypass_check.rb @@ -0,0 +1,10 @@ +# typed: strict +# frozen_string_literal: true + +# Without the bypass key, introspection counts against courses.mooc.fi's per-IP limits and starts +# failing with 429 under load, which logins answer as 503. +Rails.application.config.after_initialize do + if Rails.configuration.x.accept_courses_mooc_fi_tokens && !CoursesMoocFiRateLimitBypass.configured? + Rails.logger.warn('ACCEPT_COURSES_MOOC_FI_TOKENS is on but RACK_ATTACK_SAFE_API_KEY is not set; courses.mooc.fi token introspection will hit its per-IP rate limits') + end +end From 22bf7db609a51c53c0964734dba4d3f42d931700 Mon Sep 17 00:00:00 2001 From: Henrik Nygren Date: Tue, 24 Nov 2026 09:57:49 +0200 Subject: [PATCH 3/5] Expire editor tokens and revoke them on password change --- app/models/user.rb | 19 +++++++++- app/services/access_token_authentication.rb | 27 ++++++++++++++ config/initializers/doorkeeper.rb | 9 ++++- .../api/v8/application/password_login_spec.rb | 16 ++++++++ spec/models/user_spec.rb | 37 +++++++++++++++++++ 5 files changed, 105 insertions(+), 3 deletions(-) diff --git a/app/models/user.rb b/app/models/user.rb index 40c2996a3..b5d5ae230 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -75,9 +75,17 @@ class User < ApplicationRecord scope :non_legitimate_students, -> { where(legitimate_student: false) } sig { returns(T.nilable(String)) } - attr_accessor :password + attr_reader :password + + sig { params(new_password: T.nilable(String)).void } + def password=(new_password) + @password = T.let(new_password, T.nilable(String)) + @password_assigned = T.let(true, T.nilable(T::Boolean)) + end + before_save :encrypt_password after_save :revoke_handoff_tokens, if: :saved_change_to_administrator? + after_save :revoke_access_tokens_after_password_change sig { params(course: Course).returns(ActiveRecord::Relation) } def self.course_students(course) @@ -328,6 +336,7 @@ def update_password_via_courses_mooc_fi(old_password, new_password) end clear_stale_local_password + AccessTokenAuthentication.revoke_editor_tokens(self) true rescue Faraday::ClientError => e @@ -742,6 +751,14 @@ def revoke_handoff_tokens AccessTokenAuthentication.revoke_handoff_tokens(self) if administrator? end + sig { void } + def revoke_access_tokens_after_password_change + # The password is kept on the instance after saving, so only an assignment counts as a change. + assigned = @password_assigned + @password_assigned = nil + AccessTokenAuthentication.revoke_editor_tokens(self) if assigned && password.present? && !previously_new_record? + end + # Unchecked because specs stub Faraday.new with plain doubles. sig { returns(Faraday::Connection).checked(:never) } def courses_mooc_fi_connection diff --git a/app/services/access_token_authentication.rb b/app/services/access_token_authentication.rb index 5e3bc717b..b5d9044b3 100644 --- a/app/services/access_token_authentication.rb +++ b/app/services/access_token_authentication.rb @@ -30,6 +30,15 @@ def self.revoke_handoff_tokens(user) .update_all(revoked_at: Time.current) end + # Revokes the user's tokens of the editor clients, for when their password changes. Tokens of + # other applications are left alone so that older clients keep working. + sig { params(user: User).void } + def self.revoke_editor_tokens(user) + Doorkeeper::AccessToken + .where(resource_owner_id: user.id, revoked_at: nil, application_id: Doorkeeper::Application.where(name: editor_client_names).select(:id)) + .update_all(revoked_at: Time.current) + end + # Whether the token lets its client call UserAccessTokensController; the client still has to be # an allow-listed issuer. sig { params(token: Doorkeeper::AccessToken).returns(T::Boolean) } @@ -43,6 +52,24 @@ def self.handoff?(token) token.includes_scope?(HANDOFF_SCOPE) end + # Password-grant tokens of editor clients carry no refresh token; the editor logs in again. + EDITOR_TOKEN_TTL = T.let(90.days, ActiveSupport::Duration) + + # Names of the IDE clients in the valid_clients setting, which CredentialsController hands out by + # name. Other password-grant apps keep non-expiring tokens. + sig { returns(T::Array[String]) } + def self.editor_client_names + clients = SiteSetting.value('valid_clients') + return [] unless clients.is_a?(Enumerable) + + clients.pluck('name') + end + + sig { params(application: T.nilable(Doorkeeper::Application)).returns(T::Boolean) } + def self.editor_application?(application) + !application.nil? && editor_client_names.include?(application.name) + end + # Uids of the Doorkeeper applications allowed to issue tokens. sig { returns(T::Array[String]) } def self.issuer_application_uids diff --git a/config/initializers/doorkeeper.rb b/config/initializers/doorkeeper.rb index 75ef3ea70..70c0e0d75 100644 --- a/config/initializers/doorkeeper.rb +++ b/config/initializers/doorkeeper.rb @@ -38,9 +38,14 @@ # access_token_expires_in 2.hours access_token_expires_in nil - # Issuer tokens are re-fetched by their clients; every other token stays non-expiring. + # Issuer tokens are re-fetched by their clients and editor password-grant tokens are renewed by + # logging in again; every other token stays non-expiring. custom_access_token_expires_in do |context| - 1.hour.to_i if context.grant_type == Doorkeeper::OAuth::CLIENT_CREDENTIALS && context.scopes&.exists?(AccessTokenAuthentication::ISSUER_SCOPE) + if context.grant_type == Doorkeeper::OAuth::CLIENT_CREDENTIALS && context.scopes&.exists?(AccessTokenAuthentication::ISSUER_SCOPE) + 1.hour.to_i + elsif context.grant_type == Doorkeeper::OAuth::PASSWORD && AccessTokenAuthentication.editor_application?(context.client) + AccessTokenAuthentication::EDITOR_TOKEN_TTL.to_i + end end # Assign a custom TTL for implicit grants. diff --git a/spec/controllers/api/v8/application/password_login_spec.rb b/spec/controllers/api/v8/application/password_login_spec.rb index 6c027d21e..1b2999af2 100644 --- a/spec/controllers/api/v8/application/password_login_spec.rb +++ b/spec/controllers/api/v8/application/password_login_spec.rb @@ -44,4 +44,20 @@ def exchange_password(app, password) expect(response).to have_http_status(:bad_request) expect(response.parsed_body['error']).to eq('invalid_grant') end + + describe 'token lifetime' do + def issued_token(app) + exchange_password(app, 'correct horse') + Doorkeeper::AccessToken.find_by!(token: response.parsed_body['access_token']) + end + + it 'expires the token of an editor client' do + expect(issued_token(credentials('vscode_plugin')).expires_in).to eq(AccessTokenAuthentication::EDITOR_TOKEN_TTL.to_i) + end + + it 'keeps the token of any other client non-expiring' do + other = Doorkeeper::Application.create!(name: 'elements-of-ai', redirect_uri: 'urn:ietf:wg:oauth:2.0:oob') + expect(issued_token('application_id' => other.uid, 'secret' => other.plaintext_secret || other.secret).expires_in).to be_nil + end + end end diff --git a/spec/models/user_spec.rb b/spec/models/user_spec.rb index 5b4024560..f26d8d7b3 100644 --- a/spec/models/user_spec.rb +++ b/spec/models/user_spec.rb @@ -14,6 +14,43 @@ end end + describe 'access tokens on password change' do + let(:user) { FactoryBot.create(:user, password: 'old password') } + let(:application) { Doorkeeper::Application.create!(name: 'vscode_plugin', redirect_uri: 'urn:ietf:wg:oauth:2.0:oob') } + let!(:token) { Doorkeeper::AccessToken.create!(application: application, resource_owner_id: user.id, scopes: 'public') } + + it 'revokes the user\'s editor client tokens when a new password is saved' do + user.update!(password: 'new password') + expect(token.reload).to be_revoked + end + + it 'keeps them when the user is saved without a new password' do + User.find(user.id).update!(email: 'changed@example.com') + expect(token.reload).not_to be_revoked + end + + it 'keeps the user\'s tokens of other applications' do + other_app = Doorkeeper::Application.create!(name: 'elements-of-ai', redirect_uri: 'urn:ietf:wg:oauth:2.0:oob') + other = Doorkeeper::AccessToken.create!(application: other_app, resource_owner_id: user.id, scopes: 'public') + user.update!(password: 'new password') + expect(other.reload).not_to be_revoked + end + + it 'keeps another user\'s tokens' do + other = Doorkeeper::AccessToken.create!(application: application, resource_owner_id: FactoryBot.create(:user).id, scopes: 'public') + user.update!(password: 'new password') + expect(other.reload).not_to be_revoked + end + + it 'revokes them when the password is changed via courses.mooc.fi' do + conn = instance_double(Faraday::Connection, post: instance_double(Faraday::Response, body: true)) + allow(user).to receive(:courses_mooc_fi_connection).and_return(conn) + allow(user).to receive(:courses_mooc_fi_url).and_return('https://courses.mooc.fi/change-password') + expect(user.update_password_via_courses_mooc_fi('old password', 'new password')).to be(true) + expect(token.reload).to be_revoked + end + end + describe 'scopes' do before :each do @user1 = FactoryBot.create(:user) From 617dafb366981e9f2ab0d2e762e3c742d87c6903 Mon Sep 17 00:00:00 2001 From: Henrik Nygren Date: Tue, 24 Nov 2026 10:08:25 +0200 Subject: [PATCH 4/5] Drop the stale introspection entry when a token is rejected --- app/services/courses_mooc_fi_token_introspector.rb | 1 + .../courses_mooc_fi_token_introspector_spec.rb | 11 +++++++++++ 2 files changed, 12 insertions(+) diff --git a/app/services/courses_mooc_fi_token_introspector.rb b/app/services/courses_mooc_fi_token_introspector.rb index 57c384ed9..f4b20d5dc 100644 --- a/app/services/courses_mooc_fi_token_introspector.rb +++ b/app/services/courses_mooc_fi_token_introspector.rb @@ -57,6 +57,7 @@ def introspect(token) reason = reject_reason(body) if reason Rails.logger.warn("courses.mooc.fi token rejected: #{reason}") + Rails.cache.delete(stale_cache_key(cache_key)) Rails.cache.write(cache_key, REJECTED, expires_in: REJECTION_CACHE_TTL) return nil end diff --git a/spec/services/courses_mooc_fi_token_introspector_spec.rb b/spec/services/courses_mooc_fi_token_introspector_spec.rb index c67bd371f..0c00b6602 100644 --- a/spec/services/courses_mooc_fi_token_introspector_spec.rb +++ b/spec/services/courses_mooc_fi_token_introspector_spec.rb @@ -187,6 +187,17 @@ def go_down allow(Rails.logger).to receive(:warn) expect(introspect).to be_nil end + + it 'does not fall back to the stale entry once the rejection has expired' do + introspect + status[:code] = 200 + provider.post(introspection_path) { [200, { 'Content-Type' => 'application/json' }, { 'active' => false }.to_json] } + cache.delete("#{described_class::CACHE_NAMESPACE}:#{Digest::SHA256.hexdigest(token)}") + allow(Rails.logger).to receive(:warn) + expect(introspect).to be_nil + go_down + expect { introspect }.to raise_error(described_class::Unavailable) + end end describe 'caching' do From 8dd997659c03fea3833af6637e94b4d63bee9ed4 Mon Sep 17 00:00:00 2001 From: Henrik Nygren Date: Tue, 24 Nov 2026 10:09:04 +0200 Subject: [PATCH 5/5] Share one TTL helper between fresh and stale introspection caches --- .../courses_mooc_fi_token_introspector.rb | 18 +++++------------- 1 file changed, 5 insertions(+), 13 deletions(-) diff --git a/app/services/courses_mooc_fi_token_introspector.rb b/app/services/courses_mooc_fi_token_introspector.rb index f4b20d5dc..25feec02c 100644 --- a/app/services/courses_mooc_fi_token_introspector.rb +++ b/app/services/courses_mooc_fi_token_introspector.rb @@ -69,7 +69,7 @@ def introspect(token) ) ttl = cache_ttl(result.expires_at) Rails.cache.write(cache_key, result, expires_in: ttl) if ttl - stale_ttl = stale_cache_ttl(result.expires_at) + stale_ttl = cache_ttl(result.expires_at, STALE_TTL_CAP) Rails.cache.write(stale_cache_key(cache_key), result, expires_in: stale_ttl) if stale_ttl result end @@ -142,18 +142,10 @@ def fresh_stale_result(cache_key) end # In seconds; nil when the token has already expired. - sig { params(expires_at: T.nilable(Time)).returns(T.nilable(Integer)) } - def stale_cache_ttl(expires_at) - return STALE_TTL_CAP if expires_at.nil? + sig { params(expires_at: T.nilable(Time), cap: Integer).returns(T.nilable(Integer)) } + def cache_ttl(expires_at, cap = MAX_CACHE_TTL) + return cap if expires_at.nil? remaining = (expires_at - Time.now).floor - [remaining, STALE_TTL_CAP].min if remaining.positive? - end - - # In seconds; nil when the token has already expired. - sig { params(expires_at: T.nilable(Time)).returns(T.nilable(Integer)) } - def cache_ttl(expires_at) - return MAX_CACHE_TTL if expires_at.nil? - remaining = (expires_at - Time.now).floor - [remaining, MAX_CACHE_TTL].min if remaining.positive? + [remaining, cap].min if remaining.positive? end end