The personal finance app for everyone (by everyone)
Ruby
Serialize /oauth/token issuance with password-change revocation (#5433)
Jason211e429c79ba
diff --git a/app/controllers/oauth/tokens_controller.rb b/app/controllers/oauth/tokens_controller.rbnew file mode 100644index 0000000000..8bf5586e75--- /dev/null+++ b/app/controllers/oauth/tokens_controller.rb@@ -0,0 +1,51 @@+class Oauth::TokensController < Doorkeeper::TokensController+ private++ # A password change takes the user row lock and revokes every token it+ # can see before committing. Doorkeeper does not lock anything on refresh+ # while refresh tokens are revoked on use (the previous_refresh_token+ # column), so a refresh that validated its token before the change could+ # still commit a successor after both revocation sweeps had run.+ #+ # Taking the same lock here, user before token as /api/v1/auth/refresh+ # does, makes every issuance from an existing credential land either+ # wholly before the password change (and get revoked by it) or wholly+ # after it (and find the credential already revoked).+ def authorize_response+ @authorize_response ||= with_resource_owner_lock { super }+ end++ def with_resource_owner_lock+ credential = presented_credential+ return yield unless credential&.resource_owner_id++ user = User.find_by(id: credential.resource_owner_id)+ raise Doorkeeper::Errors::InvalidGrantReuse unless user++ user.with_active_lock! do+ reload_under_lock(credential)+ yield+ end+ rescue User::InactiveError+ raise Doorkeeper::Errors::InvalidGrantReuse+ end++ # Grant types that redeem a credential bound to a user. Client+ # credentials and unknown grant types carry no user and fall through+ # to Doorkeeper unchanged.+ def presented_credential+ case strategy+ when Doorkeeper::Request::RefreshToken then strategy.request.refresh_token+ when Doorkeeper::Request::AuthorizationCode then strategy.request.grant+ end+ end++ # The credential was read before the lock was taken; Doorkeeper must+ # validate the row as it stands now that a password change can no+ # longer be in flight.+ def reload_under_lock(credential)+ credential.reload+ rescue ActiveRecord::RecordNotFound+ raise Doorkeeper::Errors::InvalidGrantReuse+ end+enddiff --git a/app/models/user.rb b/app/models/user.rbindex 6435686581..f120a5defa 100644--- a/app/models/user.rb+++ b/app/models/user.rb@@ -315,12 +315,12 @@ class User < ApplicationRecordafter_update_commit :purge_later, if: -> { saved_change_to_active?(from: true, to: false) }after_update_commit :revoke_all_access_tokens, if: -> { saved_change_to_active?(from: true, to: false) }- # Runs inside the update's transaction: the user row stays locked until commit,- # so a concurrent /api/v1/auth/refresh (which takes the same lock) cannot mint- # a token the revocation misses. Doorkeeper's own /oauth/token refresh locks- # only the old token, so a refresh already holding it can still commit a new- # token the in-transaction sweep does not see; the second sweep after commit- # revokes it, and any later refresh finds the old token revoked.+ # Runs inside the update's transaction, so the user row stays locked until+ # commit. Every endpoint that issues a token from an existing credential+ # (/api/v1/auth/refresh and Oauth::TokensController) takes the same lock+ # first, so none can mint a token this sweep misses. The sweep after commit+ # catches grants issued without that lock, such as an authorization code+ # created by /oauth/authorize while the change was in flight.after_update :revoke_oauth_access, if: :saved_change_to_password_digest?after_update_commit :revoke_oauth_access, if: :saved_change_to_password_digest?diff --git a/config/routes.rb b/config/routes.rbindex e51fa41ae5..283935c993 100644--- a/config/routes.rb+++ b/config/routes.rb@@ -306,7 +306,7 @@ Rails.application.routes.draw doget ".well-known/oauth-authorization-server", to: "oauth_metadata#authorization_server"post "register", to: "oauth_registration#create"use_doorkeeper do |mapping|- mapping.controllers authorizations: "oauth/authorizations"+ mapping.controllers authorizations: "oauth/authorizations", tokens: "oauth/tokens"end# MFA routesresource :mfa, controller: "mfa", only: [ :new, :create ] dodiff --git a/test/controllers/oauth/tokens_controller_test.rb b/test/controllers/oauth/tokens_controller_test.rbnew file mode 100644index 0000000000..2223eb0140--- /dev/null+++ b/test/controllers/oauth/tokens_controller_test.rb@@ -0,0 +1,139 @@+require "test_helper"++class Oauth::TokensControllerTest < ActionDispatch::IntegrationTest+ REDIRECT_URI = "https://client.example.com/callback".freeze++ setup do+ @user = users(:family_member)+ @oauth_app = Doorkeeper::Application.create!(name: "Token endpoint", redirect_uri: REDIRECT_URI, scopes: "read read_write")+ end++ test "refresh issues a successor for the same user, client and scopes" do+ token = issue_token++ post_refresh token.plaintext_refresh_token++ assert_response :success+ successor = Doorkeeper::AccessToken.by_token(response.parsed_body["access_token"])+ assert_equal @user.id, successor.resource_owner_id+ assert_equal @oauth_app.id, successor.application_id+ assert_equal "read_write", successor.scopes.to_s+ assert_not token.reload.revoked?, "the predecessor stays valid until the successor is first used"+ end++ test "refresh is refused once the user is inactive, even if their tokens were not revoked" do+ token = issue_token+ @user.update_column(:active, false)++ assert_no_difference -> { Doorkeeper::AccessToken.count } do+ post_refresh token.plaintext_refresh_token+ end++ assert_response :bad_request+ assert_equal "invalid_grant", response.parsed_body["error"]+ end++ test "refresh is refused when the token's user no longer exists" do+ token = issue_token(resource_owner_id: SecureRandom.uuid)++ assert_no_difference -> { Doorkeeper::AccessToken.count } do+ post_refresh token.plaintext_refresh_token+ end++ assert_response :bad_request+ assert_equal "invalid_grant", response.parsed_body["error"]+ end++ test "refresh is refused when the token disappears before the user lock is taken" do+ token = issue_token+ Doorkeeper::AccessToken.any_instance.stubs(:reload).raises(ActiveRecord::RecordNotFound)++ assert_no_difference -> { Doorkeeper::AccessToken.count } do+ post_refresh token.plaintext_refresh_token+ end++ assert_response :bad_request+ assert_equal "invalid_grant", response.parsed_body["error"]+ end++ test "an unknown refresh token gets Doorkeeper's own error" do+ post_refresh "not-a-refresh-token"++ assert_response :bad_request+ assert_equal "invalid_grant", response.parsed_body["error"]+ end++ test "an authorization code is exchanged for a token" do+ grant = issue_grant++ post_code grant.plaintext_token++ assert_response :success+ assert_equal @user.id, Doorkeeper::AccessToken.by_token(response.parsed_body["access_token"]).resource_owner_id+ assert grant.reload.revoked?+ end++ test "an authorization code is refused once the user is inactive" do+ grant = issue_grant+ @user.update_column(:active, false)++ assert_no_difference -> { Doorkeeper::AccessToken.count } do+ post_code grant.plaintext_token+ end++ assert_response :bad_request+ assert_equal "invalid_grant", response.parsed_body["error"]+ end++ test "client credentials, which carry no user, are left to Doorkeeper" do+ post "/oauth/token", params: {+ grant_type: "client_credentials",+ client_id: @oauth_app.uid,+ client_secret: @oauth_app.plaintext_secret+ }++ assert_response :success+ assert_nil Doorkeeper::AccessToken.by_token(response.parsed_body["access_token"]).resource_owner_id+ end++ private++ def issue_token(resource_owner_id: @user.id)+ Doorkeeper::AccessToken.create!( # pipelock:ignore+ application: @oauth_app,+ resource_owner_id: resource_owner_id,+ scopes: "read_write",+ expires_in: 2.hours,+ use_refresh_token: true+ )+ end++ def issue_grant+ Doorkeeper::AccessGrant.create!(+ application: @oauth_app,+ resource_owner_id: @user.id,+ redirect_uri: REDIRECT_URI,+ scopes: "read_write",+ expires_in: 10.minutes+ )+ end++ def post_refresh(refresh_token)+ post "/oauth/token", params: {+ grant_type: "refresh_token",+ refresh_token: refresh_token,+ client_id: @oauth_app.uid,+ client_secret: @oauth_app.plaintext_secret+ }+ end++ def post_code(code)+ post "/oauth/token", params: {+ grant_type: "authorization_code",+ code: code,+ redirect_uri: REDIRECT_URI,+ client_id: @oauth_app.uid,+ client_secret: @oauth_app.plaintext_secret+ }+ end+enddiff --git a/test/integration/oauth_token_refresh_concurrency_test.rb b/test/integration/oauth_token_refresh_concurrency_test.rbnew file mode 100644index 0000000000..a8401c1305--- /dev/null+++ b/test/integration/oauth_token_refresh_concurrency_test.rb@@ -0,0 +1,176 @@+require "test_helper"+require "timeout"++# A password change has to end every refresh chain that was alive when it+# started, including one whose refresh is already in progress. The refresh+# and the password change each run on their own thread and connection with+# real commits, because what matters is which rows one transaction can see+# of the other.+class OauthTokenRefreshConcurrencyTest < ActionDispatch::IntegrationTest+ self.use_transactional_tests = false++ NEW_PASSWORD = "NewSecure1!pass".freeze++ setup do+ @user = users(:family_member)+ @original_password_digest = @user.password_digest+ @oauth_app = Doorkeeper::Application.create!(+ name: "Refresh race #{SecureRandom.hex(4)}",+ redirect_uri: "https://client.example.com/callback",+ scopes: "read_write"+ )+ @token = Doorkeeper::AccessToken.create!( # pipelock:ignore+ application: @oauth_app,+ resource_owner_id: @user.id,+ scopes: "read_write",+ expires_in: 2.hours,+ use_refresh_token: true+ )+ @threads = []+ @releases = []+ end++ teardown do+ @releases.each { |release| release << true }+ @threads.each do |thread|+ blocking { thread.join(10) }+ thread.kill if thread.alive?+ end+ release_minting+ Doorkeeper::AccessToken.where(application_id: @oauth_app.id).delete_all+ Doorkeeper::AccessGrant.where(application_id: @oauth_app.id).delete_all+ @oauth_app.delete+ User.where(id: @user.id).update_all(password_digest: @original_password_digest)+ end++ test "a refresh that validated its token before a password change leaves no usable successor" do+ minting = Queue.new+ mint = release_queue+ hold_minting(minting, mint)++ refresh = in_thread { refresh_with(@token.plaintext_refresh_token) }+ blocking { Timeout.timeout(10) { minting.pop } }++ change = in_thread { change_password }+ wait_until_finished_or_lock_waiting(change)++ mint << true+ status, body = blocking { refresh.value }+ release_minting+ assert blocking { change.join(10) }, "the password change must finish once the refresh commits"++ assert_equal 200, status, "the refresh started first, so it is allowed to complete"+ successor = Doorkeeper::AccessToken.where(application_id: @oauth_app.id).where.not(id: @token.id).sole+ assert successor.revoked?, "the successor minted during the password change must be revoked by it"+ assert @token.reload.revoked?++ status, body = refresh_with(body["refresh_token"])+ assert_equal 400, status+ assert_equal "invalid_grant", body["error"]+ end++ test "a refresh that arrives during a password change waits for it and is refused" do+ changed = Queue.new+ commit = release_queue+ change = in_thread do+ User.transaction do+ change_password+ changed << true+ commit.pop+ end+ end+ blocking { Timeout.timeout(10) { changed.pop } }++ refresh = in_thread { refresh_with(@token.plaintext_refresh_token) }+ wait_until_finished_or_lock_waiting(refresh)++ commit << true+ assert blocking { change.join(10) }, "the password change must commit"+ status, body = blocking { refresh.value }++ assert_equal 400, status+ assert_equal "invalid_grant", body["error"]+ assert_not Doorkeeper::AccessToken.where(application_id: @oauth_app.id).where.not(id: @token.id).exists?,+ "a refused refresh must not leave a token behind"+ end++ private++ def change_password+ User.find(@user.id).update!(password: NEW_PASSWORD, password_confirmation: NEW_PASSWORD)+ end++ def refresh_with(refresh_token)+ session = open_session+ session.post "/oauth/token", params: {+ grant_type: "refresh_token",+ refresh_token: refresh_token,+ client_id: @oauth_app.uid,+ client_secret: @oauth_app.plaintext_secret+ }+ [ session.response.status, JSON.parse(session.response.body) ]+ end++ def in_thread+ thread = Thread.new do+ ActiveRecord::Base.connection_pool.with_connection { yield }+ end+ thread.report_on_exception = false+ @threads << thread+ thread+ end++ def release_queue+ Queue.new.tap { |queue| @releases << queue }+ end++ # Parks the refresh after Doorkeeper has validated the presented token and+ # before it inserts the successor: the window the password change has to+ # close.+ def hold_minting(minting, mint)+ original = Doorkeeper::AccessToken.method(:create_for)+ Doorkeeper::AccessToken.define_singleton_method(:create_for) do |**attributes|+ minting << true+ mint.pop+ original.call(**attributes)+ end+ end++ def release_minting+ return unless Doorkeeper::AccessToken.singleton_class.method_defined?(:create_for, false)++ Doorkeeper::AccessToken.singleton_class.remove_method(:create_for)+ end++ # The second request either completes on its own or ends up queued behind+ # the first one's row lock; anything else within the deadline means the+ # schedule never formed. Each parallel worker has its own database, so a+ # blocked backend on this one belongs to this test.+ def wait_until_finished_or_lock_waiting(thread)+ deadline = 10.seconds.from_now+ loop do+ return unless thread.alive?+ return if lock_waiting?++ flunk "the concurrent request neither finished nor waited on a lock" if Time.current > deadline+ blocking { sleep 0.01 }+ end+ end++ def lock_waiting?+ ActiveRecord::Base.uncached do+ ActiveRecord::Base.connection.select_value(<<~SQL)+ SELECT EXISTS (+ SELECT 1 FROM pg_stat_activity+ WHERE datname = current_database() AND cardinality(pg_blocking_pids(pid)) > 0+ )+ SQL+ end+ end++ # The test thread holds the autoload interlock; let a request thread load+ # constants while this one is only waiting on it.+ def blocking(&)+ ActiveSupport::Dependencies.interlock.permit_concurrent_loads(&)+ end+enddiff --git a/test/models/user_test.rb b/test/models/user_test.rbindex a6a272c861..a06d4e1d35 100644--- a/test/models/user_test.rb+++ b/test/models/user_test.rb@@ -1716,8 +1716,8 @@ class UserTest < ActiveSupport::TestCaseUser.transaction douser.update!(password: "NewSecure1!pass", password_confirmation: "NewSecure1!pass")- # Stands in for a concurrent /oauth/token refresh that held the old token's- # row lock and committed its replacement after the in-transaction sweep.+ # Stands in for a token issued without the user lock after the+ # in-transaction sweep has run.late_token = Doorkeeper::AccessToken.create!( # pipelock:ignoreapplication: app,resource_owner_id: user.id,