Class: Legion::API::Middleware::Auth

Inherits:
Object
  • Object
show all
Defined in:
lib/legion/api/middleware/auth.rb

Constant Summary collapse

SKIP_PATHS =
%w[/api/health /api/ready /api/openapi.json /metrics /api/auth/token /api/auth/worker-token
/api/auth/authorize /api/auth/callback /api/auth/negotiate].freeze
AUTH_HEADER =
'HTTP_AUTHORIZATION'
BEARER_PATTERN =
/\ABearer\s+(.+)\z/i
NEGOTIATE_PATTERN =
/\ANegotiate\s+(.+)\z/i
API_KEY_HEADER =
'HTTP_X_API_KEY'

Instance Method Summary collapse

Constructor Details

#initialize(app, opts = {}) ⇒ Auth

Returns a new instance of Auth.



14
15
16
17
18
19
# File 'lib/legion/api/middleware/auth.rb', line 14

def initialize(app, opts = {})
  @app        = app
  @enabled    = opts.fetch(:enabled, false)
  @signing_key = opts[:signing_key]
  @api_keys = opts.fetch(:api_keys, {})
end

Instance Method Details

#call(env) ⇒ Object



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
# File 'lib/legion/api/middleware/auth.rb', line 21

def call(env)
  return @app.call(env) unless @enabled
  return @app.call(env) if skip_path?(env['PATH_INFO'])

  # Try Negotiate/SPNEGO first (Kerberos)
  result = try_negotiate(env)
  return result if result

  # Try Bearer JWT first
  token = extract_token(env)
  if token
    claims = verify_token(token)
    if claims
      env['legion.auth']        = claims
      env['legion.auth_method'] = 'jwt'
      env['legion.worker_id']   = claims[:worker_id]
      env['legion.owner_msid']  = claims[:sub] || claims[:owner_msid]
      return @app.call(env)
    end
    Legion::Logging.warn "API auth failure: invalid or expired JWT token for #{env['REQUEST_METHOD']} #{env['PATH_INFO']}" if defined?(Legion::Logging)
    return unauthorized('invalid or expired token')
  end

  # Try API key
  api_key = extract_api_key(env)
  if api_key
    key_meta = verify_api_key(api_key)
    if key_meta
      env['legion.auth']        = key_meta
      env['legion.auth_method'] = 'api_key'
      env['legion.worker_id']   = key_meta[:worker_id]
      env['legion.owner_msid']  = key_meta[:owner_msid]
      return @app.call(env)
    end
    Legion::Logging.warn "API auth failure: invalid API key for #{env['REQUEST_METHOD']} #{env['PATH_INFO']}" if defined?(Legion::Logging)
    return unauthorized('invalid API key')
  end

  Legion::Logging.warn "API auth failure: missing Authorization header for #{env['REQUEST_METHOD']} #{env['PATH_INFO']}" if defined?(Legion::Logging)
  unauthorized('missing Authorization header')
end