Class: Cuboid::MCP::Auth

Inherits:
Object show all
Defined in:
lib/cuboid/mcp/auth.rb

Overview

Bearer-token authentication middleware for the MCP transport.

Application gems opt in by registering a validator block on their Cuboid::Application subclass:

class MyApplication < Cuboid::Application
    mcp_authenticate_with do |token|
        # Return truthy (typically the User record) on success,
        # nil/false on failure.
        User.find_by( api_token: token )
    end
end

When no validator is registered the middleware passes every request through — useful for smoke tests and for transports terminated behind another auth layer (e.g. a reverse proxy).

On success the resolved validator return value is stashed in ‘env` so downstream middleware / tooling can look up the authenticated principal.

Failure modes follow RFC 6750 — Bearer Token Usage:

* Missing / malformed Authorization header → 401 + WWW-Authenticate
* Token rejected by the validator           → 401 + WWW-Authenticate

Constant Summary collapse

REALM =
'MCP'.freeze
BEARER_PREFIX =

Standard Bearer-prefix per RFC 6750 §2.1, case-insensitive.

/\ABearer\s+/i

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ Auth

Returns a new instance of Auth.



37
38
39
# File 'lib/cuboid/mcp/auth.rb', line 37

def initialize( app )
    @app = app
end

Instance Method Details

#call(env) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/cuboid/mcp/auth.rb', line 41

def call( env )
    validator = current_validator
    return @app.call( env ) if validator.nil?

    token = extract_token( env )
    return unauthorized( 'invalid_request' )      if token.nil?

    principal = safe_validate( validator, token )
    return unauthorized( 'invalid_token' )        if !principal

    env['cuboid.mcp.auth'] = principal
    @app.call( env )
end