Class: MCPClient::Auth::BrowserOAuth

Inherits:
Object
  • Object
show all
Includes:
PeerText
Defined in:
lib/mcp_client/auth/browser_oauth.rb

Overview

Browser-based OAuth authentication flow helper Provides a complete OAuth flow using browser authentication with a local callback server

Defined Under Namespace

Classes: CallbackServer

Constant Summary

Constants included from PeerText

PeerText::PEER_TEXT_LIMIT, PeerText::UNDECODABLE_BYTE, PeerText::UNREADABLE_TEXT

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from PeerText

decodable, decodable?

Constructor Details

#initialize(oauth_provider, callback_port: 8080, callback_path: '/callback', logger: nil) ⇒ BrowserOAuth

Initialize browser OAuth helper



36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/mcp_client/auth/browser_oauth.rb', line 36

def initialize(oauth_provider, callback_port: 8080, callback_path: '/callback', logger: nil)
  @oauth_provider = oauth_provider
  @callback_port = callback_port
  @callback_path = callback_path
  @logger = logger || Logger.new($stdout, level: Logger::WARN)

  # Ensure OAuth provider's redirect_uri matches our callback server
  expected_redirect_uri = "http://localhost:#{callback_port}#{callback_path}"
  return unless oauth_provider.redirect_uri != expected_redirect_uri

  @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
end

Instance Attribute Details

#callback_path ⇒ String (readonly)



29
# File 'lib/mcp_client/auth/browser_oauth.rb', line 29

attr_reader :oauth_provider, :callback_port, :callback_path, :logger

#callback_port ⇒ Integer (readonly)



29
# File 'lib/mcp_client/auth/browser_oauth.rb', line 29

attr_reader :oauth_provider, :callback_port, :callback_path, :logger

#logger ⇒ Object (readonly)

Returns the value of attribute logger.



29
# File 'lib/mcp_client/auth/browser_oauth.rb', line 29

attr_reader :oauth_provider, :callback_port, :callback_path, :logger

#oauth_provider ⇒ OAuthProvider (readonly)



29
30
31
# File 'lib/mcp_client/auth/browser_oauth.rb', line 29

def oauth_provider
  @oauth_provider
end

Instance Method Details

#authenticate(timeout: 300, auto_open_browser: true) ⇒ Token

Perform complete browser-based OAuth authentication flow This will:

  1. Start a local HTTP server to handle the callback
  2. Open the authorization URL in the user's browser
  3. Wait for the user to authorize and receive the callback
  4. Complete the OAuth flow and return the token

Raises:



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
# File 'lib/mcp_client/auth/browser_oauth.rb', line 62

def authenticate(timeout: 300, auto_open_browser: true)
  # Start authorization flow and get URL
  auth_url = @oauth_provider.start_authorization_flow
  @logger.debug("Authorization URL: #{auth_url}")

  # Create a result container to share data between threads
  result = { code: nil, state: nil, error: nil, completed: false }
  mutex = Mutex.new
  condition = ConditionVariable.new

  # Start local callback server
  server = start_callback_server(result, mutex, condition)

  begin
    # Open browser to authorization URL
    if auto_open_browser
      open_browser(auth_url)
      @logger.info("\nOpening browser for authorization...")
      @logger.info("If browser doesn't open automatically, visit this URL:")
    else
      @logger.info("\nPlease visit this URL to authorize:")
    end
    @logger.info(auth_url)
    @logger.info("\nWaiting for authorization...")

    # Wait for callback with timeout
    mutex.synchronize do
      condition.wait(mutex, timeout) unless result[:completed]
    end

    # Check if we got a response
    raise Timeout::Error, "OAuth authorization timed out after #{timeout} seconds" unless result[:completed]

    # Check for errors
    raise MCPClient::Errors::ConnectionError, "OAuth authorization failed: #{result[:error]}" if result[:error]

    # Complete OAuth flow
    @logger.debug('Completing OAuth authorization flow')
    token = if result.key?(:iss)
              @oauth_provider.complete_authorization_flow(result[:code], result[:state], iss: result[:iss])
            else
              @oauth_provider.complete_authorization_flow(result[:code], result[:state])
            end

    @logger.info("\nAuthentication successful!")
    token
  ensure
    # Always shutdown the server
    server&.shutdown
  end
end

#authorization_error_text(params, fallback) ⇒ String

The text to surface for an error callback: the provider validates the response's issuer first and refuses a mismatching one.



276
277
278
279
280
281
282
# File 'lib/mcp_client/auth/browser_oauth.rb', line 276

def authorization_error_text(params, fallback)
  return fallback unless @oauth_provider.respond_to?(:authorization_error_message)

  @oauth_provider.authorization_error_message(params)
rescue MCPClient::Errors::ConnectionError => e
  e.message
end

#decoded_parameter(value) ⇒ String

One percent-decoded callback parameter, as text.



340
341
342
343
344
# File 'lib/mcp_client/auth/browser_oauth.rb', line 340

def decoded_parameter(value)
  PeerText.decodable(CGI.unescape(value))
rescue StandardError
  PeerText::UNREADABLE_TEXT
end

#handle_http_request(client, result, mutex, condition) ⇒ Object

Handle HTTP request from OAuth callback



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
# File 'lib/mcp_client/auth/browser_oauth.rb', line 167

def handle_http_request(client, result, mutex, condition)
  # Set read timeout to prevent hanging connections
  client.setsockopt(Socket::SOL_SOCKET, Socket::SO_RCVTIMEO, [5, 0].pack('l_2'))

  # Read request line
  request_line = client.gets
  return unless request_line

  parts = request_line.split
  return unless parts.length >= 2

  method, path = parts[0..1]
  # The query string of a callback carries the authorization code (and
  # the state that binds it to this flow): a credential, and a
  # single-use one only until someone reads the log. Only the path is
  # logged, and only after the peer's bytes are made safe.
  @logger.debug("Received #{method} request: #{safe_error_text(path.split('?', 2).first.to_s)}")

  # Read and discard headers until blank line (with limit to prevent memory exhaustion)
  header_count = 0
  loop do
    break if header_count >= 100 # Limit header count

    line = client.gets
    break if line.nil? || line.strip.empty?

    header_count += 1
  end

  # Parse path and query parameters
  uri_path, query_string = path.split('?', 2)

  # Only handle our callback path
  unless uri_path == @callback_path
    send_http_response(client, 404, 'text/plain', 'Not Found')
    return
  end

  # Parse query parameters
  params = parse_query_params(query_string || '')
  @logger.debug("Callback params: #{params.keys.join(', ')}")

  # Update result and signal waiting thread
  mutex.synchronize do
    record_callback(result, params, query_string.to_s)
    result[:completed] = true

    condition.signal
  end

  # Send HTML response to browser
  if result[:error]
    send_http_response(client, 400, 'text/html', error_page(result[:error]))
  else
    send_http_response(client, 200, 'text/html', success_page)
  end
ensure
  client&.close
end

#open_browser(url) ⇒ Boolean

Open URL in default browser



373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
# File 'lib/mcp_client/auth/browser_oauth.rb', line 373

def open_browser(url)
  case RbConfig::CONFIG['host_os']
  when /darwin/
    system('open', url)
  when /linux|bsd/
    system('xdg-open', url)
  when /mswin|mingw|cygwin/
    system('start', url)
  else
    @logger.warn('Unknown operating system, cannot open browser automatically')
    false
  end
rescue StandardError => e
  @logger.warn("Failed to open browser: #{e.message}")
  false
end

#parse_query_params(query_string) ⇒ Hash

Parse URL query parameters.

CGI.unescape tags its result UTF-8 whatever the escapes decoded to, so a callback of ?error_description=%FF yields a String that strip, match and split all raise ArgumentError on. The query of a callback is the peer's bytes as much as a response body is, so every name and value is made decodable here, once, at the point it stops being bytes and starts being text — nothing downstream (the state comparison, the log line, the error page) can then choke on it.



325
326
327
328
329
330
331
332
333
334
# File 'lib/mcp_client/auth/browser_oauth.rb', line 325

def parse_query_params(query_string)
  params = {}
  PeerText.decodable(query_string).split('&').each do |param|
    next if param.empty?

    key, value = param.split('=', 2)
    params[decoded_parameter(key)] = decoded_parameter(value || '')
  end
  params
end

#record_callback(result, params, query_string = '') ⇒ void

This method returns an undefined value.

Store what the callback carried: the error text of an error response (after the RFC 9207 issuer check), or the code, state and iss of a success response the provider accepted. The browser is answered only after that check, so a rejected callback shows the error page, never "successful".



236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
# File 'lib/mcp_client/auth/browser_oauth.rb', line 236

def record_callback(result, params, query_string = '')
  if (repeated = repeated_parameter(query_string))
    return result[:error] = "Invalid callback: the #{repeated} parameter is included more than once " \
                            '(RFC 6749 Section 3.1)'
  end

  code = params['code']
  state = params['state']
  if params['error']
    result[:error] = authorization_error_text(params, params['error_description'] || params['error'])
  elsif code && state
    problem = success_callback_problem(params)
    return result[:error] = problem if problem

    result[:code] = code
    result[:state] = state
    # RFC 9207 issuer identification, validated again by the provider
    result[:iss] = params['iss'] if params.key?('iss')
  else
    result[:error] = 'Invalid callback: missing code or state parameter'
  end
end

#repeated_parameter(query_string) ⇒ String?

The name of the first callback parameter that appears more than once, or nil when each appears at most once.

RFC 6749 Section 3.1: "Request and response parameters MUST NOT be included more than once." The parsed parameters are a Hash, where the last value of a repeated name silently wins — so ?iss=attacker&iss=recorded passes every check this client makes while a reader that takes the first value (a proxy, a log pipeline, a differently written client sharing the redirect URI) sees another authorization server entirely. That disagreement is the whole reason the RFC forbids the repetition, and there is nothing to reconcile here: the response is refused, whether the values conflict or not, and whichever parameter was repeated.



300
301
302
303
304
305
306
307
308
309
310
311
# File 'lib/mcp_client/auth/browser_oauth.rb', line 300

def repeated_parameter(query_string)
  seen = {}
  PeerText.decodable(query_string).split('&').each do |param|
    next if param.empty?

    name = decoded_parameter(param.split('=', 2).first.to_s)
    return safe_error_text(name) if seen.key?(name)

    seen[name] = true
  end
  nil
end

#send_http_response(client, status_code, content_type, body) ⇒ Object

Send HTTP response to client



352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
# File 'lib/mcp_client/auth/browser_oauth.rb', line 352

def send_http_response(client, status_code, content_type, body)
  status_text = case status_code
                when 200 then 'OK'
                when 400 then 'Bad Request'
                when 404 then 'Not Found'
                else 'Unknown'
                end

  response = "HTTP/1.1 #{status_code} #{status_text}\r\n"
  response += "Content-Type: #{content_type}; charset=utf-8\r\n"
  response += "Content-Length: #{body.bytesize}\r\n"
  response += "Connection: close\r\n"
  response += "\r\n"
  response += body

  client.print(response)
end

#start_callback_server(result, mutex, condition) ⇒ CallbackServer

Start the local callback server using TCPServer

Raises:



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
# File 'lib/mcp_client/auth/browser_oauth.rb', line 121

def start_callback_server(result, mutex, condition)
  begin
    server = TCPServer.new('127.0.0.1', @callback_port)
    @logger.debug("Started callback server on http://127.0.0.1:#{@callback_port}#{@callback_path}")
  rescue Errno::EADDRINUSE
    raise MCPClient::Errors::ConnectionError,
          "Cannot start OAuth callback server: port #{@callback_port} is already in use. " \
          'Please close the application using this port or choose a different callback_port.'
  rescue StandardError => e
    raise MCPClient::Errors::ConnectionError,
          "Failed to start OAuth callback server on port #{@callback_port}: #{e.message}"
  end

  running = true

  # Start server in background thread
  thread = Thread.new do
    while running
      begin
        # Use wait_readable with timeout to allow checking the running flag
        next unless server.wait_readable(0.5)

        client = server.accept
        handle_http_request(client, result, mutex, condition)
      rescue IOError, Errno::EBADF
        # Server was closed, exit loop
        break
      rescue StandardError => e
        # The request being handled is whatever the browser (or
        # anything else that reached the loopback port) sent: an
        # exception raised over it can quote those bytes.
        @logger.error("Error handling callback request: #{safe_error_text(e.message)}")
      end
    end
  end

  # Return an object with shutdown method for compatibility
  CallbackServer.new(server, thread, -> { running = false })
end

#success_callback_problem(params) ⇒ String?

Why a success callback is not acceptable, or nil when it is.



262
263
264
265
266
267
268
269
# File 'lib/mcp_client/auth/browser_oauth.rb', line 262

def success_callback_problem(params)
  return nil unless @oauth_provider.respond_to?(:validate_authorization_response!)

  @oauth_provider.validate_authorization_response!(params['state'], iss: params['iss'])
  nil
rescue MCPClient::Errors::ConnectionError, ArgumentError => e
  e.message
end