datagrout-conduit 0.7.0 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,845 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "base64"
5
+ require "digest"
6
+ require "securerandom"
7
+ require "uri"
8
+ require "faraday"
9
+
10
+ module DatagroutConduit
11
+ # OAuth 2.1 **authorization code + PKCE** — browser-consent sign-in.
12
+ #
13
+ # The +client_credentials+ grant in {OAuth} authenticates a *machine*: it
14
+ # needs a client secret issued out of band. This module authenticates a
15
+ # *person*: the app opens a browser, the user consents at the gateway, and the
16
+ # app receives a grant bound to that user's account. It is what a desktop or
17
+ # CLI application needs, and the only way to use
18
+ # +https://gateway.datagrout.ai/connect+, where the server binding is chosen
19
+ # at consent time and lives in the token rather than the URL.
20
+ #
21
+ # == Flow
22
+ #
23
+ # 1. {Flow.discover} — fetch protected-resource metadata, then the
24
+ # authorization server's metadata.
25
+ # 2. {Flow#register} — RFC 7591 dynamic client registration, as a **public
26
+ # client** (no secret; PKCE takes its place).
27
+ # 3. {Flow#authorize_url} — build the consent URL and hold the PKCE verifier
28
+ # and CSRF state in a {PendingAuthorization}.
29
+ # 4. The caller opens that URL and captures the redirect.
30
+ # {AuthCode::LoopbackListener} does the capturing.
31
+ # 5. {Flow#exchange} — trade the code for a {Grant}.
32
+ #
33
+ # flow = DatagroutConduit::AuthCode::Flow.discover("https://gateway.datagrout.ai/connect")
34
+ # registered = flow.register("My App", "http://127.0.0.1:8765/callback")
35
+ #
36
+ # url, pending = flow.authorize_url
37
+ # puts "Open: #{url}"
38
+ #
39
+ # grant = flow.exchange(pending, code, state)
40
+ # client = DatagroutConduit::Client.new(url: GATEWAY, auth: { authorization_code: grant })
41
+ #
42
+ # == Persisting the grant
43
+ #
44
+ # This module owns the {Grant} shape and its refresh logic; it deliberately
45
+ # does *not* choose where a grant is stored. That is the application's
46
+ # decision — a keychain, a config file, a vault — and baking a filesystem
47
+ # opinion into an SDK makes it wrong for half its callers.
48
+ #
49
+ # {Grant#expires_at} is Unix seconds rather than a monotonic reading precisely
50
+ # so a grant survives serialization: it is written by one process and read by
51
+ # another, possibly in a different language.
52
+ module AuthCode
53
+ # Scopes requested when the caller does not specify.
54
+ #
55
+ # Matches the authorization server's own registration default rather than
56
+ # inventing a finer-grained vocabulary: DataGrout splits the scope string on
57
+ # whitespace and stores what it is given, so a made-up scope is accepted
58
+ # silently and then means nothing.
59
+ DEFAULT_SCOPE = "mcp tools"
60
+
61
+ # Refresh this many seconds before the token actually expires.
62
+ REFRESH_SKEW_SECONDS = 60
63
+
64
+ # ── Errors ───────────────────────────────────────────────────────────────
65
+ #
66
+ # The taxonomy is part of the cross-language contract: every conduit SDK
67
+ # distinguishes these same cases, so callers can branch identically. Ruby
68
+ # callers branch by rescuing a subclass; {Error#kind} gives the same
69
+ # distinction as a symbol, and its name is the one the other SDKs use.
70
+
71
+ # Base class for every authorization-code failure.
72
+ class Error < DatagroutConduit::AuthError
73
+ # @return [Symbol] the cross-language error kind
74
+ attr_reader :kind
75
+ # @return [Integer, nil] HTTP status, when the failure came from a response
76
+ attr_reader :status
77
+ # @return [String, nil] response body, when the failure came from a response
78
+ attr_reader :body
79
+
80
+ def initialize(message, kind: :http, status: nil, body: nil)
81
+ @kind = kind
82
+ @status = status
83
+ @body = body
84
+ super(message)
85
+ end
86
+ end
87
+
88
+ # Metadata discovery failed or returned something unusable.
89
+ class DiscoveryError < Error
90
+ def initialize(message)
91
+ super("OAuth discovery failed: #{message}", kind: :discovery)
92
+ end
93
+ end
94
+
95
+ # The authorization server does not advertise dynamic client registration.
96
+ class NoRegistrationEndpointError < Error
97
+ def initialize(_message = nil)
98
+ super(
99
+ "authorization server has no registration endpoint — register a " \
100
+ "client manually and use Flow#with_client_id",
101
+ kind: :no_registration_endpoint
102
+ )
103
+ end
104
+ end
105
+
106
+ # Dynamic client registration was rejected.
107
+ class RegistrationRejectedError < Error
108
+ def initialize(status:, body:)
109
+ super(
110
+ "client registration rejected (HTTP #{status}): #{body}",
111
+ kind: :registration_rejected, status: status, body: body
112
+ )
113
+ end
114
+ end
115
+
116
+ # +authorize_url+ was called before a client id was known.
117
+ class NoClientIdError < Error
118
+ def initialize(_message = nil)
119
+ super(
120
+ "no client_id — call register or with_client_id first",
121
+ kind: :no_client_id
122
+ )
123
+ end
124
+ end
125
+
126
+ # The server does not support PKCE with S256.
127
+ #
128
+ # Downgrading to +plain+, or to no PKCE at all, would defeat the point of
129
+ # the flow for a public client, so this is refused rather than negotiated.
130
+ class PkceUnsupportedError < Error
131
+ def initialize(_message = nil)
132
+ super(
133
+ "authorization server does not support PKCE S256; refusing to downgrade",
134
+ kind: :pkce_unsupported
135
+ )
136
+ end
137
+ end
138
+
139
+ # The +state+ returned by the redirect did not match the one sent.
140
+ #
141
+ # A CSRF signal: the response belongs to a different authorization request.
142
+ # Never proceed past this.
143
+ class StateMismatchError < Error
144
+ def initialize(_message = nil)
145
+ super(
146
+ "state mismatch — the authorization response does not match this request",
147
+ kind: :state_mismatch
148
+ )
149
+ end
150
+ end
151
+
152
+ # The token endpoint rejected the exchange or refresh.
153
+ class TokenExchangeError < Error
154
+ def initialize(status:, body:)
155
+ super(
156
+ "token exchange failed (HTTP #{status}): #{body}",
157
+ kind: :token_exchange, status: status, body: body
158
+ )
159
+ end
160
+ end
161
+
162
+ # The grant has no refresh token, so it cannot be renewed.
163
+ class NotRefreshableError < Error
164
+ def initialize(_message = nil)
165
+ super(
166
+ "grant has expired and carries no refresh_token — re-authorize",
167
+ kind: :not_refreshable
168
+ )
169
+ end
170
+ end
171
+
172
+ # The authorization server returned an error at the redirect.
173
+ class DeniedError < Error
174
+ def initialize(error:, description: nil)
175
+ message = "authorization denied: #{error}"
176
+ message += " — #{description}" if description
177
+ super(message, kind: :denied)
178
+ end
179
+ end
180
+
181
+ # Transport failure talking to the authorization server.
182
+ class HttpError < Error
183
+ def initialize(message)
184
+ super(message, kind: :http)
185
+ end
186
+ end
187
+
188
+ # ── Metadata ─────────────────────────────────────────────────────────────
189
+
190
+ # RFC 8414 authorization server metadata (the fields this flow uses).
191
+ class ServerMetadata
192
+ attr_reader :issuer, :authorization_endpoint, :token_endpoint,
193
+ :registration_endpoint, :code_challenge_methods_supported,
194
+ :grant_types_supported, :scopes_supported
195
+
196
+ def initialize(data)
197
+ @issuer = data["issuer"].to_s
198
+ @authorization_endpoint = data["authorization_endpoint"]
199
+ @token_endpoint = data["token_endpoint"]
200
+ @registration_endpoint = data["registration_endpoint"]
201
+ @code_challenge_methods_supported = Array(data["code_challenge_methods_supported"])
202
+ @grant_types_supported = Array(data["grant_types_supported"])
203
+ @scopes_supported = Array(data["scopes_supported"])
204
+
205
+ return if @authorization_endpoint && @token_endpoint
206
+
207
+ raise DiscoveryError,
208
+ "metadata is missing authorization_endpoint or token_endpoint"
209
+ end
210
+
211
+ # Whether the server can do PKCE with S256.
212
+ #
213
+ # An empty list means the server did not advertise. RFC 8414 makes the
214
+ # field optional and DataGrout omits it on some paths, so absence is
215
+ # treated as "assume S256" rather than as a refusal — a server that truly
216
+ # cannot do S256 will reject the authorize request anyway.
217
+ def supports_s256?
218
+ return true if @code_challenge_methods_supported.empty?
219
+
220
+ @code_challenge_methods_supported.any? { |m| m.to_s.casecmp("S256").zero? }
221
+ end
222
+ end
223
+
224
+ # ── Registered client ────────────────────────────────────────────────────
225
+
226
+ # A dynamically-registered client: the id **and** the redirect URI it is
227
+ # bound to.
228
+ #
229
+ # These travel together because an authorization server matches the redirect
230
+ # URI *exactly* against the value registered — there is no loopback-port
231
+ # exemption to rely on. Persisting the id alone means a later
232
+ # re-authorization on a freshly-chosen port is rejected as
233
+ # +invalid_redirect_uri+, and the failure only shows up once the first grant
234
+ # can no longer be refreshed.
235
+ #
236
+ # Persist this next to the {Grant} and restore it with
237
+ # {Flow#with_registered_client}.
238
+ class RegisteredClient
239
+ attr_reader :client_id, :redirect_uri
240
+
241
+ def initialize(client_id:, redirect_uri:)
242
+ @client_id = client_id
243
+ @redirect_uri = redirect_uri
244
+ end
245
+
246
+ def to_h
247
+ { "client_id" => @client_id, "redirect_uri" => @redirect_uri }
248
+ end
249
+
250
+ def self.from_h(data)
251
+ new(client_id: data["client_id"], redirect_uri: data["redirect_uri"])
252
+ end
253
+
254
+ def ==(other)
255
+ other.is_a?(RegisteredClient) && to_h == other.to_h
256
+ end
257
+ end
258
+
259
+ # ── Grant ────────────────────────────────────────────────────────────────
260
+
261
+ # A user's authorization, ready to persist.
262
+ #
263
+ # The serialized shape is part of the cross-language contract: a grant
264
+ # written by one conduit SDK must be readable by another. Field names and
265
+ # types are therefore fixed, and +expires_at+ is Unix seconds — never a
266
+ # monotonic reading, which is meaningless once written to disk.
267
+ class Grant
268
+ attr_reader :access_token, :refresh_token, :expires_at, :client_id,
269
+ :token_endpoint, :scope, :resource
270
+
271
+ def initialize(access_token:, client_id:, token_endpoint:,
272
+ refresh_token: nil, expires_at: nil, scope: nil, resource: nil)
273
+ @access_token = access_token
274
+ @refresh_token = refresh_token
275
+ @expires_at = expires_at
276
+ @client_id = client_id
277
+ @token_endpoint = token_endpoint
278
+ @scope = scope
279
+ @resource = resource
280
+ end
281
+
282
+ # The cross-language wire shape. Absent optionals are omitted rather than
283
+ # written as nulls, so a grant round-trips through any of the SDKs.
284
+ def to_h
285
+ h = {
286
+ "access_token" => @access_token,
287
+ "client_id" => @client_id,
288
+ "token_endpoint" => @token_endpoint
289
+ }
290
+ h["refresh_token"] = @refresh_token if @refresh_token
291
+ h["expires_at"] = @expires_at if @expires_at
292
+ h["scope"] = @scope if @scope
293
+ h["resource"] = @resource if @resource
294
+ h
295
+ end
296
+
297
+ def self.from_h(data)
298
+ new(
299
+ access_token: data["access_token"],
300
+ client_id: data["client_id"],
301
+ token_endpoint: data["token_endpoint"],
302
+ refresh_token: data["refresh_token"],
303
+ expires_at: data["expires_at"]&.to_i,
304
+ scope: data["scope"],
305
+ resource: data["resource"]
306
+ )
307
+ end
308
+
309
+ # True when the access token is expired, or within the refresh skew of it.
310
+ #
311
+ # A grant with no stated expiry is treated as live: the server chose not
312
+ # to say, and guessing an expiry would throw away working tokens.
313
+ def expired?
314
+ return false if @expires_at.nil?
315
+
316
+ AuthCode.now_secs + REFRESH_SKEW_SECONDS >= @expires_at
317
+ end
318
+
319
+ # Whether this grant can renew itself without user interaction.
320
+ def refreshable?
321
+ !@refresh_token.nil?
322
+ end
323
+
324
+ # Exchange the refresh token for a fresh grant.
325
+ #
326
+ # Returns a new Grant; the old one should be discarded. DataGrout rotates
327
+ # refresh tokens, so keeping the previous grant around and using it again
328
+ # can invalidate the whole family.
329
+ def refresh
330
+ raise NotRefreshableError unless refreshable?
331
+
332
+ form = {
333
+ "grant_type" => "refresh_token",
334
+ "refresh_token" => @refresh_token,
335
+ "client_id" => @client_id
336
+ }
337
+ form["resource"] = @resource if @resource
338
+
339
+ token = AuthCode.post_form(@token_endpoint, form)
340
+
341
+ Grant.new(
342
+ access_token: token["access_token"],
343
+ # A server that does not rotate returns no new refresh token; keep the
344
+ # existing one rather than silently making the grant unrefreshable
345
+ # from here on.
346
+ refresh_token: token["refresh_token"] || @refresh_token,
347
+ expires_at: token["expires_in"] && AuthCode.now_secs + token["expires_in"].to_i,
348
+ client_id: @client_id,
349
+ token_endpoint: @token_endpoint,
350
+ scope: token["scope"] || @scope,
351
+ resource: @resource
352
+ )
353
+ end
354
+ end
355
+
356
+ # ── Pending authorization ────────────────────────────────────────────────
357
+
358
+ # The secrets held between building the consent URL and redeeming the code.
359
+ class PendingAuthorization
360
+ attr_reader :code_verifier, :state, :redirect_uri
361
+
362
+ def initialize(code_verifier:, state:, redirect_uri:)
363
+ @code_verifier = code_verifier
364
+ @state = state
365
+ @redirect_uri = redirect_uri
366
+ freeze
367
+ end
368
+ end
369
+
370
+ # ── The flow ─────────────────────────────────────────────────────────────
371
+
372
+ # Drives discovery, registration, consent, and exchange.
373
+ class Flow
374
+ attr_reader :metadata, :resource, :client_id, :redirect_uri, :scope
375
+
376
+ def initialize(metadata:, resource:, client_id: nil, redirect_uri: nil,
377
+ scope: DEFAULT_SCOPE)
378
+ @metadata = metadata
379
+ @resource = resource
380
+ @client_id = client_id
381
+ @redirect_uri = redirect_uri
382
+ @scope = scope
383
+ end
384
+
385
+ # Discover the authorization server protecting +resource_url+.
386
+ #
387
+ # +resource_url+ is the MCP endpoint being connected to — for DataGrout,
388
+ # +https://gateway.datagrout.ai/connect+ or a +.../servers/{uuid}/mcp+
389
+ # URL.
390
+ #
391
+ # Tries RFC 9728 protected-resource metadata first, then RFC 8414
392
+ # authorization-server metadata on whatever that names. Falls back to the
393
+ # resource's own origin, which is where DataGrout serves it.
394
+ def self.discover(resource_url)
395
+ resource = resource_url.to_s.sub(%r{/+\z}, "")
396
+
397
+ prm = AuthCode.fetch_resource_metadata(resource)
398
+ servers = Array(prm && prm["authorization_servers"])
399
+ issuer = servers.first
400
+ if issuer.nil?
401
+ # No PRM, or it named no servers: DataGrout serves AS metadata at the
402
+ # origin, so try there before giving up.
403
+ issuer = AuthCode.origin_of(resource)
404
+ raise DiscoveryError, "not a URL: #{resource}" if issuer.nil?
405
+ end
406
+
407
+ metadata = AuthCode.fetch_server_metadata(issuer)
408
+ raise PkceUnsupportedError unless metadata.supports_s256?
409
+
410
+ new(metadata: metadata, resource: resource)
411
+ end
412
+
413
+ # Use a client id registered out of band, skipping dynamic registration.
414
+ def with_client_id(client_id, redirect_uri)
415
+ @client_id = client_id
416
+ @redirect_uri = redirect_uri
417
+ self
418
+ end
419
+
420
+ # Reuse a client registered on a previous run.
421
+ #
422
+ # Prefer this over {#with_client_id}: it carries the redirect URI with the
423
+ # id, which is not optional bookkeeping — an authorization server matches
424
+ # the redirect URI *exactly* against what was registered, so a client id
425
+ # reused with a different URI is rejected.
426
+ def with_registered_client(registered)
427
+ with_client_id(registered.client_id, registered.redirect_uri)
428
+ end
429
+
430
+ # Request scopes other than {DEFAULT_SCOPE}.
431
+ def with_scope(scope)
432
+ @scope = scope
433
+ self
434
+ end
435
+
436
+ # Register this application via RFC 7591 dynamic client registration.
437
+ #
438
+ # Registers a **public client** — +token_endpoint_auth_method: "none"+, no
439
+ # secret issued. A desktop or CLI application cannot keep a secret, and
440
+ # PKCE is what stands in for one.
441
+ #
442
+ # Returns a {RegisteredClient}: the id **and** the redirect URI it is
443
+ # bound to. Persist the pair and restore it with
444
+ # {#with_registered_client} — re-registering on every launch creates a new
445
+ # client record each time, and reusing an id against a different redirect
446
+ # URI is rejected.
447
+ def register(client_name, redirect_uri)
448
+ endpoint = @metadata.registration_endpoint
449
+ raise NoRegistrationEndpointError unless endpoint
450
+
451
+ body = {
452
+ "client_name" => client_name,
453
+ "redirect_uris" => [redirect_uri],
454
+ "grant_types" => %w[authorization_code refresh_token],
455
+ "response_types" => ["code"],
456
+ "token_endpoint_auth_method" => "none",
457
+ "application_type" => "native"
458
+ }
459
+
460
+ response = AuthCode.post_json(endpoint, body)
461
+ unless response.success?
462
+ raise RegistrationRejectedError.new(status: response.status, body: response.body.to_s)
463
+ end
464
+
465
+ begin
466
+ data = JSON.parse(response.body.to_s)
467
+ rescue JSON::ParserError => e
468
+ raise HttpError, "bad registration response: #{e.message}"
469
+ end
470
+
471
+ with_client_id(data["client_id"], redirect_uri)
472
+ RegisteredClient.new(client_id: data["client_id"], redirect_uri: redirect_uri)
473
+ end
474
+
475
+ # Build the consent URL, plus the {PendingAuthorization} needed to redeem
476
+ # the resulting code.
477
+ #
478
+ # The caller opens the URL however suits it — a browser, a printed
479
+ # instruction, a QR code. This gem does not launch browsers.
480
+ #
481
+ # @return [Array(String, PendingAuthorization)]
482
+ def authorize_url
483
+ raise NoClientIdError unless @client_id && @redirect_uri
484
+
485
+ code_verifier = AuthCode.generate_verifier
486
+ state = AuthCode.generate_state
487
+
488
+ query = {
489
+ "response_type" => "code",
490
+ "client_id" => @client_id,
491
+ "redirect_uri" => @redirect_uri,
492
+ "scope" => @scope,
493
+ "state" => state,
494
+ "code_challenge" => AuthCode.challenge_s256(code_verifier),
495
+ "code_challenge_method" => "S256",
496
+ # RFC 8707: bind the token to this resource so it cannot be replayed
497
+ # against a different one.
498
+ "resource" => @resource
499
+ }.map { |k, v| "#{k}=#{AuthCode.urlencode(v)}" }.join("&")
500
+
501
+ separator = @metadata.authorization_endpoint.include?("?") ? "&" : "?"
502
+ url = "#{@metadata.authorization_endpoint}#{separator}#{query}"
503
+
504
+ [url, PendingAuthorization.new(code_verifier: code_verifier, state: state,
505
+ redirect_uri: @redirect_uri)]
506
+ end
507
+
508
+ # Redeem an authorization code for a {Grant}.
509
+ #
510
+ # +returned_state+ is the +state+ parameter from the redirect. It is
511
+ # checked against the pending request before anything is sent: a mismatch
512
+ # means the response belongs to a different authorization request, and the
513
+ # exchange is refused rather than attempted.
514
+ def exchange(pending, code, returned_state)
515
+ raise StateMismatchError unless AuthCode.secure_compare(pending.state, returned_state)
516
+ raise NoClientIdError unless @client_id
517
+
518
+ token = AuthCode.post_form(
519
+ @metadata.token_endpoint,
520
+ "grant_type" => "authorization_code",
521
+ "code" => code,
522
+ "redirect_uri" => pending.redirect_uri,
523
+ "client_id" => @client_id,
524
+ "code_verifier" => pending.code_verifier,
525
+ "resource" => @resource
526
+ )
527
+
528
+ Grant.new(
529
+ access_token: token["access_token"],
530
+ refresh_token: token["refresh_token"],
531
+ expires_at: token["expires_in"] && AuthCode.now_secs + token["expires_in"].to_i,
532
+ client_id: @client_id,
533
+ token_endpoint: @metadata.token_endpoint,
534
+ scope: token["scope"],
535
+ resource: @resource
536
+ )
537
+ end
538
+ end
539
+
540
+ # ── Provider ─────────────────────────────────────────────────────────────
541
+
542
+ # Holds a {Grant} and keeps its access token fresh.
543
+ #
544
+ # Mirrors {OAuth::TokenProvider} so both grant types reach the transports
545
+ # through the same path — +get_token+ on the way out, +invalidate!+ on a
546
+ # 401. Thread-safe via Mutex, as that one is.
547
+ class Provider
548
+ def initialize(grant)
549
+ @grant = grant
550
+ @dirty = false
551
+ # Two locks with distinct jobs. @mutex guards the state and is held
552
+ # only for as long as it takes to read or swap it — never across the
553
+ # network. @refresh_mutex serializes the refresh itself, so concurrent
554
+ # callers make one request rather than a stampede of them.
555
+ @mutex = Mutex.new
556
+ @refresh_mutex = Mutex.new
557
+ # Bumped each time a refresh attempt settles, alongside the failure of
558
+ # the one that failed. A caller that queued behind a failing attempt
559
+ # takes its outcome instead of launching another.
560
+ @attempt = 0
561
+ @last_error = nil
562
+ end
563
+
564
+ # The current access token, refreshing first if it is at or near expiry.
565
+ #
566
+ # A refresh does not hold the state lock, so {#grant}, {#dirty?},
567
+ # {#take_if_dirty} and {#invalidate!} keep answering while one is in
568
+ # flight — a persistence loop must not stall behind a slow token
569
+ # endpoint, and a hung one must not wedge the whole provider.
570
+ def get_token
571
+ current, seen = @mutex.synchronize { [@grant, @attempt] }
572
+ return current.access_token unless current.expired?
573
+
574
+ @refresh_mutex.synchronize do
575
+ current, attempt, error = @mutex.synchronize { [@grant, @attempt, @last_error] }
576
+
577
+ # Another thread refreshed while we queued: nothing left to do.
578
+ return current.access_token unless current.expired?
579
+
580
+ # An attempt settled while we queued and left the grant expired, so
581
+ # it failed. Share that rather than hammering an endpoint we have
582
+ # just watched fail — a dead one should cost one request, not one
583
+ # per waiter. The backtrace is the leader's, which is where it
584
+ # actually broke.
585
+ raise error if attempt != seen && error
586
+
587
+ perform_refresh(current)
588
+ end
589
+ end
590
+
591
+ # A snapshot of the current grant, for persisting.
592
+ def grant
593
+ @mutex.synchronize { @grant }
594
+ end
595
+
596
+ # Whether the grant changed since the last {#take_if_dirty}.
597
+ def dirty?
598
+ @mutex.synchronize { @dirty }
599
+ end
600
+
601
+ # Return the grant if it has changed since the last call, clearing the
602
+ # flag.
603
+ #
604
+ # The intended use is a persistence loop: call periodically and write
605
+ # whatever comes back, so a rotated refresh token is never lost.
606
+ def take_if_dirty
607
+ @mutex.synchronize do
608
+ next nil unless @dirty
609
+
610
+ @dirty = false
611
+ @grant
612
+ end
613
+ end
614
+
615
+ # Force the next {#get_token} to refresh. Call on a 401.
616
+ def invalidate!
617
+ @mutex.synchronize do
618
+ # Expire in the past rather than clearing the token: the refresh token
619
+ # is what matters, and dropping the grant would make recovery
620
+ # impossible.
621
+ @grant = Grant.new(
622
+ access_token: @grant.access_token,
623
+ refresh_token: @grant.refresh_token,
624
+ expires_at: 0,
625
+ client_id: @grant.client_id,
626
+ token_endpoint: @grant.token_endpoint,
627
+ scope: @grant.scope,
628
+ resource: @grant.resource
629
+ )
630
+ end
631
+ end
632
+
633
+ # Build a provider from whatever an +auth:+ hash carried under
634
+ # +:authorization_code+, or nil when it carried nothing.
635
+ #
636
+ # Accepts a {Provider} the caller keeps (so a rotated refresh token can be
637
+ # written back), a {Grant}, or a grant hash straight from JSON.
638
+ def self.from_auth(value)
639
+ case value
640
+ when nil then nil
641
+ when Provider then value
642
+ when Grant then new(value)
643
+ when Hash then new(Grant.from_h(AuthCode.stringify_keys(value)))
644
+ else
645
+ raise ArgumentError,
646
+ "authorization_code must be a Grant, a grant Hash, or an " \
647
+ "AuthCode::Provider (got #{value.class})"
648
+ end
649
+ end
650
+
651
+ private
652
+
653
+ # Runs with @refresh_mutex held and @mutex free, so the state stays
654
+ # readable while the request is out. Records the outcome either way, so
655
+ # whoever queued behind this attempt can take it.
656
+ def perform_refresh(stale)
657
+ refreshed = stale.refresh
658
+
659
+ @mutex.synchronize do
660
+ @grant = refreshed
661
+ @dirty = true
662
+ @attempt += 1
663
+ @last_error = nil
664
+ end
665
+
666
+ refreshed.access_token
667
+ rescue StandardError => e
668
+ @mutex.synchronize do
669
+ @attempt += 1
670
+ @last_error = e
671
+ end
672
+ raise
673
+ end
674
+ end
675
+
676
+ # ── PKCE and helpers ─────────────────────────────────────────────────────
677
+
678
+ # Generate an RFC 7636 code verifier: 43 characters of base64url.
679
+ def self.generate_verifier
680
+ SecureRandom.urlsafe_base64(32, false)
681
+ end
682
+
683
+ # The S256 challenge for a verifier: +base64url(sha256(verifier))+.
684
+ def self.challenge_s256(verifier)
685
+ Base64.urlsafe_encode64(Digest::SHA256.digest(verifier), padding: false)
686
+ end
687
+
688
+ def self.generate_state
689
+ SecureRandom.urlsafe_base64(16, false)
690
+ end
691
+
692
+ def self.now_secs
693
+ Time.now.to_i
694
+ end
695
+
696
+ # Length-independent comparison, so a state check cannot be timed.
697
+ def self.secure_compare(a, b)
698
+ a = a.to_s.b
699
+ b = b.to_s.b
700
+ return false unless a.bytesize == b.bytesize
701
+
702
+ a.bytes.zip(b.bytes).reduce(0) { |acc, (x, y)| acc | (x ^ y) }.zero?
703
+ end
704
+
705
+ # Percent-encode a query parameter value.
706
+ #
707
+ # Unreserved set per RFC 3986. Everything else is escaped — including +/+
708
+ # and +:+, which appear in redirect URIs and resource URLs and must not be
709
+ # taken as structure by the authorization server. CGI.escape is wrong here:
710
+ # it encodes a space as +++.
711
+ def self.urlencode(value)
712
+ value.to_s.b.each_byte.map do |byte|
713
+ if (48..57).cover?(byte) || (65..90).cover?(byte) || (97..122).cover?(byte) ||
714
+ [45, 46, 95, 126].include?(byte)
715
+ byte.chr
716
+ else
717
+ format("%%%02X", byte)
718
+ end
719
+ end.join
720
+ end
721
+
722
+ # The scheme, host and port of a URL, with the path dropped.
723
+ def self.origin_of(url)
724
+ parsed = URI.parse(url.to_s)
725
+ return nil unless parsed.scheme && parsed.host
726
+
727
+ if parsed.port && parsed.port != parsed.default_port
728
+ "#{parsed.scheme}://#{parsed.host}:#{parsed.port}"
729
+ else
730
+ "#{parsed.scheme}://#{parsed.host}"
731
+ end
732
+ rescue URI::InvalidURIError
733
+ nil
734
+ end
735
+
736
+ # A Hash with symbol keys turned into strings, so a grant hash written in
737
+ # either style loads.
738
+ def self.stringify_keys(hash)
739
+ hash.each_with_object({}) { |(k, v), out| out[k.to_s] = v }
740
+ end
741
+
742
+ # RFC 9728 protected-resource metadata, or nil if unavailable.
743
+ def self.fetch_resource_metadata(resource)
744
+ # Path-appended form first (what MCP servers with a path segment use),
745
+ # then the origin-level one.
746
+ candidates = ["#{resource}/.well-known/oauth-protected-resource"]
747
+ origin = origin_of(resource)
748
+ candidates << "#{origin}/.well-known/oauth-protected-resource" if origin
749
+
750
+ candidates.each do |url|
751
+ begin
752
+ response = connection(url).get
753
+ rescue Faraday::Error
754
+ next
755
+ end
756
+ next unless response.success?
757
+
758
+ begin
759
+ body = JSON.parse(response.body.to_s)
760
+ rescue JSON::ParserError
761
+ next
762
+ end
763
+ # A non-object body is not metadata; fall through to the next candidate
764
+ # rather than handing the caller something unusable.
765
+ return body if body.is_a?(Hash)
766
+ end
767
+
768
+ nil
769
+ end
770
+
771
+ def self.fetch_server_metadata(issuer)
772
+ base = issuer.to_s.sub(%r{/+\z}, "")
773
+ candidates = [
774
+ "#{base}/.well-known/oauth-authorization-server",
775
+ "#{base}/.well-known/openid-configuration"
776
+ ]
777
+
778
+ last = ""
779
+ candidates.each do |url|
780
+ begin
781
+ response = connection(url).get
782
+ rescue Faraday::Error => e
783
+ last = "#{url} → #{e.message}"
784
+ next
785
+ end
786
+
787
+ unless response.success?
788
+ last = "#{url} → HTTP #{response.status}"
789
+ next
790
+ end
791
+
792
+ begin
793
+ return ServerMetadata.new(JSON.parse(response.body.to_s))
794
+ rescue JSON::ParserError => e
795
+ raise DiscoveryError, "bad metadata at #{url}: #{e.message}"
796
+ end
797
+ end
798
+
799
+ raise DiscoveryError,
800
+ "no authorization server metadata found (last attempt: #{last})"
801
+ end
802
+
803
+ def self.post_json(endpoint, body)
804
+ connection(endpoint).post do |req|
805
+ req.headers["Content-Type"] = "application/json"
806
+ req.body = JSON.generate(body)
807
+ end
808
+ rescue Faraday::Error => e
809
+ raise HttpError, "HTTP error: #{e.message}"
810
+ end
811
+
812
+ def self.post_form(endpoint, form)
813
+ begin
814
+ response = connection(endpoint) { |f| f.request :url_encoded }
815
+ .post { |req| req.body = form }
816
+ rescue Faraday::Error => e
817
+ raise HttpError, "HTTP error: #{e.message}"
818
+ end
819
+
820
+ unless response.success?
821
+ raise TokenExchangeError.new(status: response.status, body: response.body.to_s)
822
+ end
823
+
824
+ begin
825
+ parsed = JSON.parse(response.body.to_s)
826
+ rescue JSON::ParserError => e
827
+ raise HttpError, "bad token response: #{e.message}"
828
+ end
829
+
830
+ unless parsed.is_a?(Hash)
831
+ raise HttpError, "bad token response: expected a JSON object, got #{parsed.class}"
832
+ end
833
+
834
+ parsed
835
+ end
836
+
837
+ # A Faraday connection for one request. Overridden in tests.
838
+ def self.connection(url)
839
+ Faraday.new(url: url) do |f|
840
+ yield f if block_given?
841
+ f.adapter Faraday.default_adapter
842
+ end
843
+ end
844
+ end
845
+ end