-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathbrowser_oauth_provider.rb
More file actions
427 lines (360 loc) · 16.9 KB
/
browser_oauth_provider.rb
File metadata and controls
427 lines (360 loc) · 16.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
# frozen_string_literal: true
module RubyLLM
module MCP
module Auth
# Browser-based OAuth authentication provider
# Provides complete OAuth 2.1 flow with automatic browser opening and local callback server
# Compatible API with OAuthProvider for seamless interchange
class BrowserOAuthProvider
# Serializes logger calls so test doubles and non-thread-safe loggers remain safe
# when callback and main threads log at the same time.
class SynchronizedLogger
def initialize(logger)
@logger = logger
@mutex = Mutex.new
end
def debug(...)
synchronized_log(:debug, ...)
end
def info(...)
synchronized_log(:info, ...)
end
def warn(...)
synchronized_log(:warn, ...)
end
def error(...)
synchronized_log(:error, ...)
end
private
def synchronized_log(level, ...)
@mutex.synchronize do
return unless @logger.respond_to?(level)
@logger.public_send(level, ...)
end
end
end
# Callback worker thread logs are intentionally isolated from the caller logger.
# JRuby + rspec-mocks logger doubles are not safe to share across threads.
class NullLogger
def debug(*) = nil
def info(*) = nil
def warn(*) = nil
def error(*) = nil
end
attr_reader :oauth_provider, :callback_port, :callback_path, :logger
attr_accessor :server_url, :redirect_uri, :scope, :storage
# Expose custom pages for testing/inspection
def custom_success_page
@pages.instance_variable_get(:@custom_success_page)
end
def custom_error_page
@pages.instance_variable_get(:@custom_error_page)
end
# @param server_url [String] OAuth server URL (alternative to oauth_provider)
# @param oauth_provider [OAuthProvider] OAuth provider instance (alternative to server_url)
# @param callback_port [Integer] port for local callback server
# @param callback_path [String] path for callback URL
# @param logger [Logger] logger instance
# @param storage [Object] token storage instance
# @param redirect_uri [String] OAuth redirect URI
# @param scope [String] OAuth scopes
def initialize(server_url: nil, oauth_provider: nil, callback_port: 8080, callback_path: "/callback", # rubocop:disable Metrics/ParameterLists
logger: nil, storage: nil, redirect_uri: nil, scope: nil)
@logger = logger || MCP.logger
@synchronized_logger = SynchronizedLogger.new(@logger)
@callback_logger = NullLogger.new
@callback_port = callback_port
@callback_path = callback_path
# Set redirect_uri before creating oauth_provider
redirect_uri ||= "http://localhost:#{callback_port}#{callback_path}"
# Either accept an existing oauth_provider or create one
if oauth_provider
@oauth_provider = oauth_provider
# Sync attributes from the provided oauth_provider
@server_url = oauth_provider.server_url
@redirect_uri = oauth_provider.redirect_uri
@scope = oauth_provider.scope
@storage = oauth_provider.storage
elsif server_url
@server_url = server_url
@redirect_uri = redirect_uri
@scope = scope
@storage = storage || MemoryStorage.new
# Create a new oauth_provider
@oauth_provider = OAuthProvider.new(
server_url: server_url,
redirect_uri: redirect_uri,
scope: scope,
logger: @synchronized_logger,
storage: @storage
)
else
raise ArgumentError, "Either server_url or oauth_provider must be provided"
end
# Ensure OAuth provider redirect_uri matches our callback server
validate_and_sync_redirect_uri!
# Initialize browser helpers
@http_server = Browser::HttpServer.new(port: @callback_port, logger: @callback_logger)
@callback_handler = Browser::CallbackHandler.new(callback_path: @callback_path, logger: @callback_logger)
@pages = Browser::Pages.new(
custom_success_page: MCP.config.oauth.browser_success_page,
custom_error_page: MCP.config.oauth.browser_error_page
)
@opener = Browser::Opener.new(logger: @synchronized_logger)
end
# Perform complete OAuth authentication flow with browser
# Compatible with OAuthProvider's authentication pattern
# @param timeout [Integer] seconds to wait for authorization
# @param auto_open_browser [Boolean] automatically open browser
# @return [Token] access token
def authenticate(timeout: 300, auto_open_browser: true)
# 1. Start authorization flow and get URL
auth_url = @oauth_provider.start_authorization_flow
@synchronized_logger.debug("Authorization URL: #{auth_url}")
# 2. Create result container for thread coordination
result = { code: nil, state: nil, error: nil, completed: false }
mutex = Mutex.new
condition = ConditionVariable.new
# 3. Start local callback server
server = start_callback_server(result, mutex, condition)
begin
announce_authorization_flow(auth_url, auto_open_browser)
# Allow callback worker to begin processing only after setup logging/browser open
# to reduce cross-thread test-double races under JRuby.
server.start
# 5. Wait for callback with timeout
mutex.synchronize do
condition.wait(mutex, timeout) unless result[:completed]
end
snapshot = mutex.synchronize { result.dup }
unless snapshot[:completed]
raise Errors::TimeoutError.new(message: "OAuth authorization timed out after #{timeout} seconds")
end
if snapshot[:error]
raise Errors::TransportError.new(message: "OAuth authorization failed: #{snapshot[:error]}")
end
# Stop callback server before token exchange to avoid cross-thread races
# (observed under JRuby when background callback logging overlaps main-thread mocks).
server&.shutdown
server = nil
# 6. Complete OAuth flow
@synchronized_logger.debug("Completing OAuth authorization flow")
token = @oauth_provider.complete_authorization_flow(snapshot[:code], snapshot[:state])
@synchronized_logger.info("\nAuthentication successful!")
token
ensure
# Always shutdown the server
server&.shutdown
end
end
# Get current access token (for compatibility with OAuthProvider)
# @return [Token, nil] valid access token or nil
def access_token
@oauth_provider.access_token
end
# Apply authorization header to HTTP request (for compatibility with OAuthProvider)
# @param request [HTTPX::Request] HTTP request object
def apply_authorization(request)
@oauth_provider.apply_authorization(request)
end
# Start authorization flow (for compatibility with OAuthProvider)
# @return [String] authorization URL
def start_authorization_flow
@oauth_provider.start_authorization_flow
end
# Complete authorization flow (for compatibility with OAuthProvider)
# @param code [String] authorization code
# @param state [String] state parameter
# @return [Token] access token
def complete_authorization_flow(code, state)
@oauth_provider.complete_authorization_flow(code, state)
end
# Handle authentication challenge with browser-based auth
# @param www_authenticate [String, nil] WWW-Authenticate header value
# @param resource_metadata [String, nil] Resource metadata URL from response/challenge
# @param resource_metadata_url [String, nil] Legacy alias for resource_metadata
# @param requested_scope [String, nil] Scope from WWW-Authenticate challenge
# @return [Boolean] true if authentication was completed successfully
def handle_authentication_challenge(www_authenticate: nil, resource_metadata: nil, resource_metadata_url: nil,
requested_scope: nil)
@synchronized_logger.debug("BrowserOAuthProvider handling authentication challenge")
# Try standard provider's automatic handling first (token refresh, client credentials)
begin
return @oauth_provider.handle_authentication_challenge(
www_authenticate: www_authenticate,
resource_metadata: resource_metadata,
resource_metadata_url: resource_metadata_url,
requested_scope: requested_scope
)
rescue Errors::AuthenticationRequiredError
# Standard provider couldn't handle it - need interactive auth
@synchronized_logger.info("Automatic authentication failed, starting browser-based OAuth flow")
end
# Perform full browser-based authentication
authenticate(auto_open_browser: true)
true
end
# Parse WWW-Authenticate header (delegate to oauth_provider)
# @param header [String] WWW-Authenticate header value
# @return [Hash] parsed challenge information
def parse_www_authenticate(header)
@oauth_provider.parse_www_authenticate(header)
end
private
# Validate and synchronize redirect_uri between this provider and oauth_provider
def validate_and_sync_redirect_uri!
expected_redirect_uri = "http://localhost:#{@callback_port}#{@callback_path}"
if @oauth_provider.redirect_uri != expected_redirect_uri
@synchronized_logger.warn("OAuth provider redirect_uri (#{@oauth_provider.redirect_uri}) " \
"doesn't match callback server (#{expected_redirect_uri}). " \
"Updating redirect_uri.")
@oauth_provider.redirect_uri = expected_redirect_uri
@redirect_uri = expected_redirect_uri
end
end
# Start local HTTP callback server
# @param result [Hash] result container for callback data
# @param mutex [Mutex] synchronization mutex
# @param condition [ConditionVariable] wait condition
# @return [Browser::CallbackServer] server wrapper
def start_callback_server(result, mutex, condition)
server = @http_server.start_server
@synchronized_logger.debug("Started callback server on http://127.0.0.1:#{@callback_port}#{@callback_path}")
control = build_callback_thread_control
thread = build_callback_worker_thread(server, result, mutex, condition, control)
stop_proc = -> { stop_callback_worker(control) }
start_proc = -> { start_callback_worker(control) }
# Return wrapper with shutdown method
Browser::CallbackServer.new(server, thread, stop_proc, start_proc)
end
# Handle incoming HTTP request on callback server
# @param client [TCPSocket] client socket
# @param result [Hash] result container
# @param mutex [Mutex] synchronization mutex
# @param condition [ConditionVariable] wait condition
def handle_http_request(client, result, mutex, condition)
callback_result = nil
@http_server.configure_client_socket(client)
request_line = @http_server.read_request_line(client)
return unless request_line
method_name, path = @http_server.extract_request_parts(request_line)
return unless method_name && path
@http_server.read_http_headers(client)
# Validate callback path
unless @callback_handler.valid_callback_path?(path)
@http_server.send_http_response(client, 404, "text/plain", "Not Found")
return
end
# Parse and extract OAuth parameters
params = @callback_handler.parse_callback_params(path, @http_server)
oauth_params = @callback_handler.extract_oauth_params(params)
callback_result = build_callback_result(oauth_params)
# Send response
if callback_result[:error]
@http_server.send_http_response(client, 400, "text/html", @pages.error_page(callback_result[:error]))
else
@http_server.send_http_response(client, 200, "text/html", @pages.success_page)
end
ensure
apply_callback_result(callback_result, result, mutex, condition) if callback_result
close_callback_client(client)
end
# Wake the waiting authentication flow with a deterministic error when callback
# processing fails in the worker thread.
def mark_callback_failure(result, mutex, condition, error)
mutex.synchronize do
return if result[:completed]
result[:error] = "OAuth callback processing failed: #{error.message}"
result[:completed] = true
condition.signal
end
@synchronized_logger.warn("OAuth callback worker failed: #{error.class}: #{error.message}")
end
def build_callback_result(oauth_params)
if oauth_params[:error]
{ code: nil, state: nil, error: oauth_params[:error_description] || oauth_params[:error] }
elsif oauth_params[:code] && oauth_params[:state]
{ code: oauth_params[:code], state: oauth_params[:state], error: nil }
else
{ code: nil, state: nil, error: "Invalid callback: missing code or state parameter" }
end
end
def apply_callback_result(callback_result, result, mutex, condition)
mutex.synchronize do
return if result[:completed]
result[:code] = callback_result[:code]
result[:state] = callback_result[:state]
result[:error] = callback_result[:error]
result[:completed] = true
condition.signal
end
end
def close_callback_client(client)
client&.close
rescue IOError, SystemCallError => e
@synchronized_logger.debug("Error closing OAuth callback client socket: #{e.class}: #{e.message}")
end
def announce_authorization_flow(auth_url, auto_open_browser)
if auto_open_browser
@opener.open_browser(auth_url)
@synchronized_logger.info("\nOpening browser for authorization...")
@synchronized_logger.info("If browser doesn't open automatically, visit this URL:")
else
@synchronized_logger.info("\nPlease visit this URL to authorize:")
end
@synchronized_logger.info(auth_url)
@synchronized_logger.info("\nWaiting for authorization...")
end
def build_callback_thread_control
{
mutex: Mutex.new,
condition: ConditionVariable.new,
running: true,
accepting: false
}
end
def build_callback_worker_thread(server, result, result_mutex, condition, control)
Thread.new do
wait_for_callback_worker_start(control)
while callback_worker_running?(control)
begin
# Use wait_readable with timeout to allow checking stop signal
next unless server.wait_readable(0.5)
client = server.accept
handle_http_request(client, result, result_mutex, condition)
break if result_mutex.synchronize { result[:completed] }
rescue IOError, Errno::EBADF
# Server was closed, exit loop
break
rescue StandardError => e
mark_callback_failure(result, result_mutex, condition, e)
break
end
end
end
end
def wait_for_callback_worker_start(control)
control[:mutex].synchronize do
control[:condition].wait(control[:mutex]) until control[:accepting] || !control[:running]
end
end
def callback_worker_running?(control)
control[:mutex].synchronize { control[:running] }
end
def start_callback_worker(control)
control[:mutex].synchronize do
control[:accepting] = true
control[:condition].signal
end
end
def stop_callback_worker(control)
control[:mutex].synchronize do
control[:running] = false
control[:accepting] = true
control[:condition].broadcast
end
end
end
end
end
end