Class: Legate::Auth::MiddlewareFactory

Inherits:
Object
  • Object
show all
Defined in:
lib/legate/auth/middleware_factory.rb

Overview

Factory for creating authentication middleware instances based on different scheme types and configurations.

Class Method Summary collapse

Class Method Details

.create(scheme:, credential:, **options) ⇒ Legate::Auth::ExconMiddleware

Create middleware for any authentication scheme

Parameters:

Options Hash (**options):

  • :token_store (Legate::Auth::TokenStore)

    Optional token store for caching tokens

  • :token_manager (Legate::Auth::TokenManager)

    Optional token manager for token lifecycle

  • :auto_retry (Boolean)

    Whether to automatically retry on auth errors (default: true)

  • :max_retries (Integer)

    Maximum number of retries (default: 3)

  • :backoff_strategy (Symbol)

    Strategy for retries (:linear, :exponential, :fibonacci, :jitter, :none)

  • :backoff_factor (Float)

    Factor to use for backoff calculation (default: 1.0)

  • :retry_non_idempotent (Boolean)

    Whether to retry non-idempotent requests (default: false)

  • :retry_on (Array<Integer>)

    Additional HTTP status codes to retry on

Returns:



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
62
63
64
# File 'lib/legate/auth/middleware_factory.rb', line 32

def create(scheme:, credential:, **options)
  # Create a token store if not provided
  token_store = options[:token_store]
  unless token_store
    session_service = options[:session_service]
    token_store = Legate::Auth::TokenStore.new(session_service) if session_service
  end

  # Create a token manager if not provided
  token_manager = options[:token_manager]

  # Configure retry options
  auto_retry = options.key?(:auto_retry) ? options[:auto_retry] : true
  max_retries = options[:max_retries] || 3
  backoff_strategy = options[:backoff_strategy] || :exponential
  backoff_factor = options[:backoff_factor] || 1.0
  retry_non_idempotent = options[:retry_non_idempotent] || false
  retry_on = options[:retry_on] || []

  # Create the middleware instance with nil stack (will be set by Excon later)
  Legate::Auth::ExconMiddleware.new(nil, {
                                      scheme: scheme,
                                      credential: credential,
                                      token_store: token_store,
                                      token_manager: token_manager,
                                      auto_retry: auto_retry,
                                      max_retries: max_retries,
                                      backoff_strategy: backoff_strategy,
                                      backoff_factor: backoff_factor,
                                      retry_non_idempotent: retry_non_idempotent,
                                      retry_on: retry_on
                                    })
end

.create_api_key(api_key:, location: 'header', name: 'X-API-Key', **options) ⇒ Legate::Auth::ExconMiddleware

Create middleware specifically for API key authentication

Parameters:

  • api_key (String)

    The API key to use

  • location (String) (defaults to: 'header')

    Where to place the API key (‘header’, ‘query’, ‘cookie’)

  • name (String) (defaults to: 'X-API-Key')

    The name of the parameter/header

  • options (Hash)

    Additional options for the middleware

Returns:



72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/legate/auth/middleware_factory.rb', line 72

def create_api_key(api_key:, location: 'header', name: 'X-API-Key', **options)
  # Create the scheme
  scheme = Legate::Auth::Schemes::ApiKey.new

  # Create the credential
  credential = Legate::Auth::Credential.new(
    auth_type: :api_key,
    api_key: api_key,
    location: location,
    name: name
  )

  # Create and return the middleware
  create(scheme: scheme, credential: credential, **options)
end

.create_basic_auth(username:, password:, **options) ⇒ Legate::Auth::ExconMiddleware

Create middleware specifically for Basic authentication

Parameters:

  • username (String)

    The username for Basic Auth

  • password (String)

    The password for Basic Auth

  • options (Hash)

    Additional options for the middleware

Returns:



256
257
258
259
260
261
262
263
264
265
266
267
268
269
# File 'lib/legate/auth/middleware_factory.rb', line 256

def create_basic_auth(username:, password:, **options)
  # Basic auth is handled by the HTTPBearer scheme with a different type
  scheme = Legate::Auth::Schemes::HTTPBearer.new(auth_type: :basic)

  # Create the credential
  credential = Legate::Auth::Credential.new(
    auth_type: :basic,
    username: username,
    password: password
  )

  # Create and return the middleware
  create(scheme: scheme, credential: credential, **options)
end

.create_bearer(token:, **options) ⇒ Legate::Auth::ExconMiddleware

Create middleware specifically for Bearer token authentication

Parameters:

  • token (String)

    The bearer token to use

  • options (Hash)

    Additional options for the middleware

Returns:



92
93
94
95
96
97
98
99
100
101
102
103
104
# File 'lib/legate/auth/middleware_factory.rb', line 92

def create_bearer(token:, **options)
  # Create the scheme
  scheme = Legate::Auth::Schemes::HTTPBearer.new

  # Create the credential
  credential = Legate::Auth::Credential.new(
    auth_type: :http_bearer,
    bearer_token: token
  )

  # Create and return the middleware
  create(scheme: scheme, credential: credential, **options)
end

.create_from_provider(provider_id, **options) ⇒ Legate::Auth::ExconMiddleware

Create middleware for a pre-configured authentication provider

Parameters:

  • provider_id (String)

    The ID of the pre-configured provider

  • options (Hash)

    Additional options for the middleware

Returns:

Raises:

  • (ArgumentError)


275
276
277
278
279
280
281
282
283
284
285
286
# File 'lib/legate/auth/middleware_factory.rb', line 275

def create_from_provider(provider_id, **options)
  # Retrieve the stored credential from Legate::Auth
  exchanged_credential = Legate::Auth.get_exchanged_credential(provider_id)
  raise ArgumentError, "No credential found for provider ID: #{provider_id}" unless exchanged_credential

  # Get the scheme
  scheme = Legate::Auth.get_scheme_for_provider(provider_id)
  raise ArgumentError, "No scheme found for provider ID: #{provider_id}" unless scheme

  # Create and return the middleware
  create(scheme: scheme, credential: exchanged_credential, **options)
end

.create_oauth2(client_id:, client_secret:, authorization_url:, token_url:, scopes: nil, **options) ⇒ Legate::Auth::ExconMiddleware

Create middleware specifically for OAuth2 authentication

Parameters:

  • client_id (String)

    The OAuth client ID

  • client_secret (String)

    The OAuth client secret

  • authorization_url (String)

    The authorization URL for the OAuth provider

  • token_url (String)

    The token URL for the OAuth provider

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

    The OAuth scopes to request

  • options (Hash)

    Additional options for the middleware

Options Hash (**options):

  • :redirect_uri (String)

    The redirect URI for the OAuth flow

  • :additional_params (Hash)

    Additional parameters to include in the authorization request

Returns:



116
117
118
119
120
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
# File 'lib/legate/auth/middleware_factory.rb', line 116

def create_oauth2(client_id:, client_secret:, authorization_url:, token_url:, scopes: nil, **options)
  # Extract OAuth2-specific options
  redirect_uri = options.delete(:redirect_uri)
  additional_params = options.delete(:additional_params) || {}

  # Create the scheme with additional params
  scheme_options = {
    authorization_url: authorization_url,
    token_url: token_url,
    scopes: scopes
  }

  # Add redirect_uri if provided
  scheme_options[:redirect_uri] = redirect_uri if redirect_uri

  # Add any additional parameters
  scheme_options[:additional_params] = additional_params unless additional_params.empty?

  # Create the scheme
  scheme = Legate::Auth::Schemes::OAuth2.new(**scheme_options)

  # Create the credential
  credential = Legate::Auth::Credential.new(
    auth_type: :oauth2,
    client_id: client_id,
    client_secret: client_secret
  )

  # Create and return the middleware
  create(scheme: scheme, credential: credential, **options)
end

.create_oidc(client_id:, client_secret:, discovery_url: nil, authorization_url: nil, token_url: nil, userinfo_url: nil, jwks_url: nil, scopes: nil, **options) ⇒ Legate::Auth::ExconMiddleware

Create middleware specifically for OpenID Connect authentication

Parameters:

  • client_id (String)

    The OAuth client ID

  • client_secret (String)

    The OAuth client secret

  • discovery_url (String, nil) (defaults to: nil)

    The OIDC discovery URL

  • authorization_url (String, nil) (defaults to: nil)

    The authorization URL (if not using discovery)

  • token_url (String, nil) (defaults to: nil)

    The token URL (if not using discovery)

  • userinfo_url (String, nil) (defaults to: nil)

    The userinfo URL (if not using discovery)

  • jwks_url (String, nil) (defaults to: nil)

    The JWKS URL (if not using discovery)

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

    The OAuth scopes to request

  • options (Hash)

    Additional options for the middleware

Options Hash (**options):

  • :redirect_uri (String)

    The redirect URI for the OIDC flow

  • :additional_params (Hash)

    Additional parameters to include in the authorization request

  • :verify_id_token (Boolean)

    Whether to verify the ID token

Returns:



162
163
164
165
166
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
# File 'lib/legate/auth/middleware_factory.rb', line 162

def create_oidc(client_id:, client_secret:, discovery_url: nil, authorization_url: nil,
                token_url: nil, userinfo_url: nil, jwks_url: nil, scopes: nil, **options)
  # Extract OIDC-specific options
  redirect_uri = options.delete(:redirect_uri)
  additional_params = options.delete(:additional_params) || {}
  verify_id_token = options.key?(:verify_id_token) ? options.delete(:verify_id_token) : true

  # Determine how to initialize the scheme
  scheme_options = if discovery_url
                     {
                       discovery_url: discovery_url,
                       scopes: scopes,
                       verify_id_token: verify_id_token
                     }
                   else
                     {
                       authorization_url: authorization_url,
                       token_url: token_url,
                       userinfo_url: userinfo_url,
                       jwks_url: jwks_url,
                       scopes: scopes,
                       verify_id_token: verify_id_token
                     }
                   end

  # Add redirect_uri if provided
  scheme_options[:redirect_uri] = redirect_uri if redirect_uri

  # Add any additional parameters
  scheme_options[:additional_params] = additional_params unless additional_params.empty?

  # Create the scheme
  scheme = Legate::Auth::Schemes::OIDC.new(**scheme_options)

  # Create the credential
  credential = Legate::Auth::Credential.new(
    auth_type: :oidc,
    client_id: client_id,
    client_secret: client_secret
  )

  # Create and return the middleware
  create(scheme: scheme, credential: credential, **options)
end

.create_service_account(service_account_key:, token_url: nil, scopes: nil, audience: nil, **options) ⇒ Legate::Auth::ExconMiddleware

Create middleware specifically for Service Account authentication

Parameters:

  • service_account_key (String, Hash)

    The service account key as JSON string or Hash

  • token_url (String, nil) (defaults to: nil)

    The token URL for the service account

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

    The scopes to request

  • audience (String, nil) (defaults to: nil)

    The audience for the token

  • options (Hash)

    Additional options for the middleware

Options Hash (**options):

  • :token_lifetime (Integer)

    Time in seconds for token expiration (default: 3600)

Returns:



215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
# File 'lib/legate/auth/middleware_factory.rb', line 215

def (service_account_key:, token_url: nil, scopes: nil, audience: nil, **options)
  # Extract service account specific options
  token_lifetime = options.delete(:token_lifetime) || 3600

  # Parse the key if it's a string
  key_data = if .is_a?(String)
               begin
                 JSON.parse()
               rescue JSON::ParserError
                 raise ArgumentError, 'Invalid service account key: not valid JSON'
               end
             else
               
             end

  # Use token_url from the key if not provided
  token_url ||= key_data['token_uri']

  # Create the scheme
  scheme = Legate::Auth::Schemes::ServiceAccount.new(
    token_url: token_url,
    audience: audience,
    scopes: scopes,
    token_lifetime: token_lifetime
  )

  # Create the credential
  credential = Legate::Auth::Credential.new(
    auth_type: :service_account,
    service_account_key: .is_a?(String) ?  : .to_json
  )

  # Create and return the middleware
  create(scheme: scheme, credential: credential, **options)
end