Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 18 additions & 1 deletion app/models/user.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
27 changes: 27 additions & 0 deletions app/services/access_token_authentication.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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) }
Expand All @@ -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
Expand Down
5 changes: 5 additions & 0 deletions app/services/courses_mooc_fi_rate_limit_bypass.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
47 changes: 40 additions & 7 deletions app/services/courses_mooc_fi_token_introspector.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -36,10 +43,21 @@ 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}")
Rails.cache.delete(stale_cache_key(cache_key))
Rails.cache.write(cache_key, REJECTED, expires_in: REJECTION_CACHE_TTL)
return nil
end
Expand All @@ -51,6 +69,8 @@ def introspect(token)
)
ttl = cache_ttl(result.expires_at)
Rails.cache.write(cache_key, result, expires_in: ttl) if ttl
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

Expand Down Expand Up @@ -87,6 +107,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
Expand All @@ -108,11 +130,22 @@ 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 cache_ttl(expires_at)
return MAX_CACHE_TTL 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, MAX_CACHE_TTL].min if remaining.positive?
[remaining, cap].min if remaining.positive?
end
end
10 changes: 10 additions & 0 deletions config/initializers/courses_mooc_fi_rate_limit_bypass_check.rb
Original file line number Diff line number Diff line change
@@ -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
9 changes: 7 additions & 2 deletions config/initializers/doorkeeper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
16 changes: 16 additions & 0 deletions spec/controllers/api/v8/application/password_login_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
37 changes: 37 additions & 0 deletions spec/models/user_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
70 changes: 69 additions & 1 deletion spec/services/courses_mooc_fi_token_introspector_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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/)
Expand All @@ -132,6 +137,69 @@ 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

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
it 'asks the provider once for an active token' do
stub_provider(status: 200, body: active_body)
Expand Down Expand Up @@ -165,7 +233,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
Expand Down
Loading