Skip to content

Commit 1811120

Browse files
authored
Merge pull request #580 from koic/drop_expired_pending_authorizations_from_the_in_memory_storage
Drop expired pending authorizations from the in-memory storage
2 parents 46d47d5 + c78d325 commit 1811120

4 files changed

Lines changed: 126 additions & 20 deletions

File tree

‎docs/_client/authorization.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -225,7 +225,9 @@ The storage must also respond to `save_pending_authorization(state, pending)`, `
225225
`Provider.new` raises `Provider::PendingAuthorizationStorageError` when it does not. A pending authorization is a Hash of JSON-compatible values that includes
226226
the PKCE verifier, so keep it where you keep credentials, persist it as-is, and share it between the processes that can receive the redirect.
227227
`delete_pending_authorization` must remove the entry and return it in one atomic step, such as `GETDEL` in Redis or `DELETE ... RETURNING` in SQL,
228-
and return `nil` when there was none. `InMemoryStorage` implements the methods for a single process.
228+
and return `nil` when there was none. `finish!` touches only the entry its callback's `state` names, and an authorization the user never finishes gets no callback,
229+
so the storage should expire entries older than `pending_authorization_max_age`, with a TTL in Redis or a periodic delete in SQL.
230+
`InMemoryStorage` implements the methods for a single process and drops such entries the next time a pending authorization is saved.
229231

230232
`finish!` redeems the code the way the authorization began, and refuses anything else with `Flow::AuthorizationError`:
231233

‎lib/mcp/client/oauth/in_memory_storage.rb‎

Lines changed: 57 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -20,10 +20,12 @@ module OAuth
2020
# between the request that sends the user to the authorization server and the request that receives
2121
# the redirect (`save_pending_authorization(state, pending)`, `pending_authorization(state)`,
2222
# `delete_pending_authorization(state)`). A pending authorization holds the PKCE verifier, so custom storages
23-
# should treat it as a secret, persist it as-is, and may expire entries older than the provider's
24-
# `pending_authorization_max_age`, which the flow refuses anyway. `delete_pending_authorization` must remove
25-
# the entry and return it in one atomic step (`Hash#delete` here; `GETDEL` in Redis, `DELETE ... RETURNING` in SQL),
26-
# returning `nil` when there was none: the flow redeems the code only when it gets the entry back.
23+
# should treat it as a secret and persist it as-is. `Flow#finish!` touches only the entry its callback's `state`
24+
# names, so an authorization the user never finished stays until the storage drops it: this class drops entries
25+
# older than `pending_authorization_max_age` the next time one is saved, and a custom storage should expire them,
26+
# with a TTL of that age. `delete_pending_authorization` must remove the entry and return it in one atomic step
27+
# (`Hash#delete` under a mutex here; `GETDEL` in Redis, `DELETE ... RETURNING` in SQL), returning `nil` when
28+
# there was none: the flow redeems the code only when it gets the entry back.
2729
#
2830
# This class keeps everything in process memory, so the credentials live
2931
# only for the lifetime of the Ruby process. Applications that need
@@ -38,10 +40,20 @@ module OAuth
3840
class InMemoryStorage
3941
attr_accessor :tokens, :client_information
4042

41-
def initialize
43+
# @param pending_authorization_max_age [Integer] seconds after which a pending authorization that was
44+
# never finished is dropped from this storage, at its next save. `Provider.new` passes its own
45+
# `pending_authorization_max_age` when it builds the default storage, so the two ages agree; a storage built
46+
# by hand defaults to `Provider::DEFAULT_PENDING_AUTHORIZATION_MAX_AGE`.
47+
def initialize(pending_authorization_max_age: Provider::DEFAULT_PENDING_AUTHORIZATION_MAX_AGE)
48+
unless pending_authorization_max_age.is_a?(Integer) && pending_authorization_max_age.positive?
49+
raise ArgumentError, "pending_authorization_max_age must be a positive Integer number of seconds (got #{pending_authorization_max_age.inspect})."
50+
end
51+
4252
@tokens = nil
4353
@client_information = nil
4454
@pending_authorizations = {}
55+
@pending_authorization_max_age = pending_authorization_max_age
56+
@pending_authorizations_mutex = Mutex.new
4557
end
4658

4759
def save_tokens(tokens)
@@ -52,16 +64,53 @@ def save_client_information(info)
5264
@client_information = info
5365
end
5466

67+
# Drops every pending authorization older than `pending_authorization_max_age` before saving the new one.
68+
# The flow refuses such an entry when it is looked up, but only a callback carrying its `state` looks it up,
69+
# and an authorization the user abandoned never gets one; every `401` a provider without a `callback_handler` meets
70+
# starts another, so without this the entries, each holding the verifier and the authorization server metadata,
71+
# would accumulate for the life of the process.
5572
def save_pending_authorization(state, pending)
56-
@pending_authorizations[state] = pending
73+
@pending_authorizations_mutex.synchronize do
74+
drop_expired_pending_authorizations
75+
@pending_authorizations[state] = pending
76+
end
5777
end
5878

5979
def pending_authorization(state)
60-
@pending_authorizations[state]
80+
@pending_authorizations_mutex.synchronize { @pending_authorizations[state] }
6181
end
6282

83+
# The mutex is what makes the removal and the return one step on every Ruby implementation: `Hash#delete`
84+
# alone is atomic only where a global interpreter lock serializes it, and `Flow#finish!` relies on exactly
85+
# one of two callbacks racing on the same `state` getting the entry back.
6386
def delete_pending_authorization(state)
64-
@pending_authorizations.delete(state)
87+
@pending_authorizations_mutex.synchronize { @pending_authorizations.delete(state) }
88+
end
89+
90+
# Every hash this storage holds may carry a secret (an access token, a client secret, a PKCE verifier),
91+
# and `inspect` is what error reporters and consoles print an object with, so it shows only whether each is present.
92+
def inspect
93+
pending_count = @pending_authorizations_mutex.synchronize { @pending_authorizations.size }
94+
95+
"#<#{self.class.name} tokens=#{present_or_nil(@tokens)} client_information=#{present_or_nil(@client_information)} pending_authorizations=#{pending_count}>"
96+
end
97+
98+
private
99+
100+
# An entry's age is read from the Integer `created_at` the flow records when it saves the entry; an entry without one,
101+
# which the flow never writes, is left alone.
102+
def drop_expired_pending_authorizations
103+
now = Time.now.to_i
104+
105+
@pending_authorizations.delete_if do |_state, pending|
106+
created_at = pending.is_a?(Hash) ? pending["created_at"] : nil
107+
108+
created_at.is_a?(Integer) && now - created_at > @pending_authorization_max_age
109+
end
110+
end
111+
112+
def present_or_nil(value)
113+
value.nil? ? "nil" : "[present]"
65114
end
66115
end
67116
end

‎lib/mcp/client/oauth/provider.rb‎

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,8 @@ module OAuth
4545
# the stale registration and tokens and re-registers.
4646
# Without `callback_handler`, it must also respond to `save_pending_authorization(state, pending)`,
4747
# `pending_authorization(state)`, and `delete_pending_authorization(state)`; the last must remove the entry
48-
# and return it atomically, returning `nil` when there was none.
48+
# and return it atomically, returning `nil` when there was none, and the storage should expire entries
49+
# older than `pending_authorization_max_age`, as `InMemoryStorage` does.
4950
# - `client_id_metadata_document_url` - URL where the client publishes its Client ID Metadata Document
5051
# (`draft-ietf-oauth-client-id-metadata-document-00` and the MCP authorization specification).
5152
# When the authorization server advertises `client_id_metadata_document_supported: true`,
@@ -91,9 +92,11 @@ class InvalidClientIDMetadataDocumentURLError < ArgumentError; end
9192
# and the request that receives the redirect.
9293
class PendingAuthorizationStorageError < ArgumentError; end
9394

94-
# Seconds a pending authorization stays redeemable after the redirect when the provider has no `callback_handler`.
95-
# Long enough for a user to sign in and consent at the authorization server, short enough that an abandoned
96-
# authorization does not keep its PKCE verifier in `storage` indefinitely.
95+
# Seconds a pending authorization stays redeemable, counted from the moment `run!` saves it, when the provider has
96+
# no `callback_handler`; long enough for a user to sign in and consent at the authorization server. It is also
97+
# the age past which `InMemoryStorage` drops an authorization that was never finished, at its next save, so that
98+
# an abandoned one does not keep its PKCE verifier in memory for the life of the process; a custom storage should
99+
# expire entries at the same age.
97100
DEFAULT_PENDING_AUTHORIZATION_MAX_AGE = 600
98101

99102
PENDING_AUTHORIZATION_STORAGE_METHODS = [
@@ -146,7 +149,13 @@ def initialize(
146149

147150
http_client_customizer = validated_http_client_customizer(http_client_customizer)
148151

149-
storage ||= InMemoryStorage.new
152+
unless pending_authorization_max_age.is_a?(Integer) && pending_authorization_max_age.positive?
153+
raise ArgumentError, "pending_authorization_max_age must be a positive Integer number of seconds (got #{pending_authorization_max_age.inspect})."
154+
end
155+
156+
# The default storage drops abandoned pending authorizations at the same age the flow stops redeeming them.
157+
storage ||= InMemoryStorage.new(pending_authorization_max_age: pending_authorization_max_age)
158+
150159
if callback_handler.nil?
151160
missing = PENDING_AUTHORIZATION_STORAGE_METHODS.reject { |method| storage.respond_to?(method) }
152161
unless missing.empty?
@@ -156,12 +165,6 @@ def initialize(
156165
end
157166
end
158167

159-
unless pending_authorization_max_age.is_a?(Integer) && pending_authorization_max_age.positive?
160-
raise ArgumentError,
161-
"pending_authorization_max_age must be a positive Integer number of seconds " \
162-
"(got #{pending_authorization_max_age.inspect})."
163-
end
164-
165168
@client_metadata = client_metadata
166169
@redirect_uri = redirect_uri
167170
@redirect_handler = redirect_handler

‎test/mcp/client/oauth/provider_test.rb‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -301,6 +301,58 @@ def test_in_memory_storage_keeps_pending_authorizations_by_state
301301
assert_nil(storage.pending_authorization("state-1"))
302302
assert_equal({ "code_verifier" => "v2" }, storage.pending_authorization("state-2"))
303303
end
304+
305+
def test_in_memory_storage_drops_pending_authorizations_older_than_the_max_age_when_one_is_saved
306+
storage = InMemoryStorage.new(pending_authorization_max_age: 60)
307+
now = Time.now.to_i
308+
storage.save_pending_authorization("stale", { "code_verifier" => "v1", "created_at" => now - 61 })
309+
storage.save_pending_authorization("fresh", { "code_verifier" => "v2", "created_at" => now - 30 })
310+
storage.save_pending_authorization("undated", { "code_verifier" => "v3" })
311+
312+
assert_nil(storage.pending_authorization("stale"), "the stale entry is dropped by the save that follows it")
313+
314+
storage.save_pending_authorization("new", { "code_verifier" => "v4", "created_at" => now })
315+
316+
assert_equal("v2", storage.pending_authorization("fresh")["code_verifier"])
317+
assert_equal("v3", storage.pending_authorization("undated")["code_verifier"])
318+
assert_equal("v4", storage.pending_authorization("new")["code_verifier"])
319+
assert_equal("v4", storage.delete_pending_authorization("new")["code_verifier"])
320+
assert_nil(storage.delete_pending_authorization("new"))
321+
end
322+
323+
def test_the_default_storage_drops_pending_authorizations_at_the_provider_max_age
324+
arguments = args_for("https://app.example.com/callback")
325+
arguments.delete(:callback_handler)
326+
provider = Provider.new(**arguments, pending_authorization_max_age: 30)
327+
now = Time.now.to_i
328+
provider.save_pending_authorization("stale", { "code_verifier" => "v1", "created_at" => now - 31 })
329+
330+
provider.save_pending_authorization("fresh", { "code_verifier" => "v2", "created_at" => now })
331+
332+
assert_nil(provider.pending_authorization("stale"))
333+
assert_equal("v2", provider.pending_authorization("fresh")["code_verifier"])
334+
end
335+
336+
def test_in_memory_storage_rejects_a_pending_authorization_max_age_that_is_not_a_positive_integer
337+
[0, -1, 1.5, "600", nil].each do |max_age|
338+
error = assert_raises(ArgumentError) { InMemoryStorage.new(pending_authorization_max_age: max_age) }
339+
340+
assert_equal("pending_authorization_max_age must be a positive Integer number of seconds (got #{max_age.inspect}).", error.message)
341+
end
342+
end
343+
344+
def test_in_memory_storage_inspect_shows_no_secrets
345+
storage = InMemoryStorage.new
346+
storage.save_tokens("access_token" => "secret-token", "refresh_token" => "secret-refresh")
347+
storage.save_client_information("client_id" => "client-1", "client_secret" => "secret-client")
348+
storage.save_pending_authorization("state-1", { "code_verifier" => "secret-verifier", "created_at" => Time.now.to_i })
349+
350+
refute_includes(storage.inspect, "secret")
351+
assert_includes(storage.inspect, "tokens=[present]")
352+
assert_includes(storage.inspect, "pending_authorizations=1")
353+
refute_includes(storage.inspect, "\n")
354+
assert_includes(InMemoryStorage.new.inspect, "tokens=nil")
355+
end
304356
end
305357
end
306358
end

0 commit comments

Comments
 (0)