Module: Legion::MCP::Auth

Extended by:
Logging::Helper
Defined in:
lib/legion/mcp/auth.rb

Class Method Summary collapse

Class Method Details

.auth_enabled?Boolean

Returns:

  • (Boolean)


21
22
23
# File 'lib/legion/mcp/auth.rb', line 21

def auth_enabled?
  Legion::Settings.dig(:mcp, :auth, :enabled) == true
end

.authenticate(token) ⇒ Object



10
11
12
13
14
15
16
17
18
19
# File 'lib/legion/mcp/auth.rb', line 10

def authenticate(token)
  log.info('Starting legion.mcp.auth.authenticate')
  return { authenticated: false, error: 'missing_token' } unless token

  if jwt_token?(token)
    verify_jwt(token)
  else
    verify_api_key(token)
  end
end

.jwt_token?(token) ⇒ Boolean

Returns:

  • (Boolean)


29
30
31
# File 'lib/legion/mcp/auth.rb', line 29

def jwt_token?(token)
  token.count('.') == 2
end

.require_auth?Boolean

Returns:

  • (Boolean)


25
26
27
# File 'lib/legion/mcp/auth.rb', line 25

def require_auth?
  Legion::Settings.dig(:mcp, :auth, :require_auth) == true
end

.verify_api_key(token) ⇒ Object



45
46
47
48
49
50
51
52
# File 'lib/legion/mcp/auth.rb', line 45

def verify_api_key(token)
  allowed = Legion::Settings.dig(:mcp, :auth, :allowed_api_keys) || []
  if allowed.include?(token)
    { authenticated: true, identity: { user_id: 'api_key', risk_tier: :low } }
  else
    { authenticated: false, error: 'invalid_api_key' }
  end
end

.verify_jwt(token) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
# File 'lib/legion/mcp/auth.rb', line 33

def verify_jwt(token)
  return { authenticated: false, error: 'crypt_unavailable' } unless defined?(Legion::Crypt::JWT)

  claims = Legion::Crypt::JWT.decode(token)
  { authenticated: true, identity: { user_id: claims[:sub], risk_tier: claims[:risk_tier]&.to_sym,
                                      tenant_id: claims[:tenant_id], worker_id: claims[:worker_id] } }
rescue StandardError => e
  handle_exception(e, level: :warn, operation: 'legion.mcp.auth.verify_jwt')
  log.warn("Auth#verify_jwt failed: #{e.message}")
  { authenticated: false, error: e.message }
end