Class: Keycardai::MCP::RequireBearerAuth

Inherits:
Object
  • Object
show all
Defined in:
lib/keycardai/mcp/require_bearer_auth.rb

Overview

Rack middleware verifying the Authorization bearer token against the zone's JWKS. Fail-closed: unauthenticated requests are rejected with an RFC 6750 challenge advertising the RFC 9728 resource_metadata URL, and never reach the app. On success the verified AccessToken is stored in the Rack env (Keycardai::MCP.auth_info).

use Keycardai::MCP::RequireBearerAuth,
  verifier: Keycardai::OAuth::TokenVerifier.new(issuers: zone_url),
  required_scopes: ["mcp:tools"]

Route-level gating is this same middleware applied per route with a required_scopes set; every configured scope must be present (all-of), a missing one yielding 403 insufficient_scope.

Instance Method Summary collapse

Constructor Details

#initialize(app, verifier:, required_scopes: nil) ⇒ RequireBearerAuth

Returns a new instance of RequireBearerAuth.

Parameters:

  • app (#call)

    the downstream Rack app

  • verifier (#verify_token)

    a TokenVerifier

  • required_scopes (Array<String>, String, nil) (defaults to: nil)

    all-of scope set

Raises:

  • (Keycardai::OAuth::ConfigurationError)

    nil verifier; an auth boundary with no verifier is a programming error caught at boot



24
25
26
27
28
29
30
# File 'lib/keycardai/mcp/require_bearer_auth.rb', line 24

def initialize(app, verifier:, required_scopes: nil)
  raise Keycardai::OAuth::ConfigurationError, "RequireBearerAuth requires a verifier" if verifier.nil?

  @app = app
  @verifier = verifier
  @required_scopes = Array(required_scopes)
end

Instance Method Details

#call(env) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/keycardai/mcp/require_bearer_auth.rb', line 32

def call(env)
  header = env["HTTP_AUTHORIZATION"]
  return RackSupport.challenge_response(env, status: 401) if header.nil? || header.empty?

  parts = header.split
  return [400, { "content-type" => "application/json" }, ['{"error":"invalid_request"}']] if parts.length != 2

  scheme, token = parts
  unless scheme.casecmp("bearer").zero?
    return RackSupport.challenge_response(env, status: 401, error: "invalid_token",
                                               description: "unsupported authorization scheme")
  end

  authorize(env, token)
end