Class: Aspera::OAuth::Factory

Inherits:
Object
  • Object
show all
Includes:
Singleton
Defined in:
lib/aspera/oauth/client/factory.rb

Overview

Factory to create tokens and manage their cache

Constant Summary collapse

TOKEN_FIELD =
'access_token'
OBTAINED_AT_FIELD =

fields added to the cached token creation response

'obtained_at'
EXPIRES_AT_FIELD =
'expires_at'

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#parameters ⇒ Object (readonly)

Returns the value of attribute parameters.



107
108
109
# File 'lib/aspera/oauth/client/factory.rb', line 107

def parameters
  @parameters
end

Class Method Details

.bearer_auth?(authorization) ⇒ Boolean

Check if the authorization contains a bearer token

Parameters:

  • authorization (String) —

    The authorization header value

Returns:

  • (Boolean) —

    true if the authorization contains a bearer token, i.e. auth scheme is bearer



47
48
49
# File 'lib/aspera/oauth/client/factory.rb', line 47

def bearer_auth?(authorization)
  return authorization.start_with?(SPACE_BEARER_AUTH_SCHEME)
end

.bearer_authorization(token) ⇒ String

Format a token for use in Authorization header

Parameters:

  • token (String) —

    The token alone

Returns:

  • (String) —

    Value suitable for Authorization header



40
41
42
# File 'lib/aspera/oauth/client/factory.rb', line 40

def bearer_authorization(token)
  return "#{SPACE_BEARER_AUTH_SCHEME}#{token}"
end

.bearer_token(authorization) ⇒ String

Extract only token from Authorization (remove scheme)

Parameters:

  • authorization (String) —

    The authorization header value

Returns:

  • (String) —

    The bearer token without the scheme prefix



54
55
56
57
# File 'lib/aspera/oauth/client/factory.rb', line 54

def bearer_token(authorization)
  Aspera.assert(bearer_auth?(authorization)) { 'not a bearer token, wrong prefix scheme' }
  return authorization.delete_prefix(SPACE_BEARER_AUTH_SCHEME)
end

.cache_id(url, creator_class, *params) ⇒ String

Generate a unique cache id for a token creator

Parameters:

  • url (String) —

    Base URL of the OAuth server

  • creator_class (Class) —

    Class of the token creator

  • params (Array) —

    List of parameters (can be nested) to uniquely identify the token

Returns:

  • (String) —

    a unique cache identifier



64
65
66
# File 'lib/aspera/oauth/client/factory.rb', line 64

def cache_id(url, creator_class, *params)
  return IdGenerator.from_list(PERSIST_CATEGORY_TOKEN, url, Factory.class_to_id(creator_class), params)
end

.class_to_id(creator_class) ⇒ Symbol

Convert a class name to snake_case symbol

Parameters:

  • creator_class (Class) —

    The class to convert

Returns:

  • (Symbol) —

    snake_case version of class name



79
80
81
# File 'lib/aspera/oauth/client/factory.rb', line 79

def class_to_id(creator_class)
  return creator_class.name.split('::').last.capital_to_snake.to_sym
end

.instance ⇒ Factory

Returns the singleton instance of Factory

Returns:

  • (Factory) —

    the singleton instance



20
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
# File 'lib/aspera/oauth/client/factory.rb', line 20

class Factory
  include Singleton

  # prefix for persistency of tokens (simplify garbage collect)
  PERSIST_CATEGORY_TOKEN = 'token'
  # prefix for bearer authorization when in header
  SPACE_BEARER_AUTH_SCHEME = 'Bearer '
  TOKEN_FIELD = 'access_token'
  # Separator of the path of a nested token field, e.g. `authed_user.access_token`
  FIELD_PATH_SEPARATOR = '.'
  # fields added to the cached token creation response
  OBTAINED_AT_FIELD = 'obtained_at'
  EXPIRES_AT_FIELD = 'expires_at'

  private_constant :PERSIST_CATEGORY_TOKEN, :SPACE_BEARER_AUTH_SCHEME, :FIELD_PATH_SEPARATOR

  class << self
    # Format a token for use in Authorization header
    # @param token [String] The token alone
    # @return [String] Value suitable for Authorization header
    def bearer_authorization(token)
      return "#{SPACE_BEARER_AUTH_SCHEME}#{token}"
    end

    # Check if the authorization contains a bearer token
    # @param authorization [String] The authorization header value
    # @return [Boolean] true if the authorization contains a bearer token, i.e. auth scheme is bearer
    def bearer_auth?(authorization)
      return authorization.start_with?(SPACE_BEARER_AUTH_SCHEME)
    end

    # Extract only token from Authorization (remove scheme)
    # @param authorization [String] The authorization header value
    # @return [String] The bearer token without the scheme prefix
    def bearer_token(authorization)
      Aspera.assert(bearer_auth?(authorization)) { 'not a bearer token, wrong prefix scheme' }
      return authorization.delete_prefix(SPACE_BEARER_AUTH_SCHEME)
    end

    # Generate a unique cache id for a token creator
    # @param url           [String] Base URL of the OAuth server
    # @param creator_class [Class]  Class of the token creator
    # @param params        [Array]  List of parameters (can be nested) to uniquely identify the token
    # @return [String] a unique cache identifier
    def cache_id(url, creator_class, *params)
      return IdGenerator.from_list(PERSIST_CATEGORY_TOKEN, url, Factory.class_to_id(creator_class), params)
    end

    # Value of the token in a token creation response
    # @param token_data  [Hash{String => Object}] Token creation response
    # @param token_field [String]                 Field that contains the token, or dot-separated path of a nested field, e.g. `authed_user.access_token`
    # @return [Object, nil] Value of the field, `nil` if absent (or an intermediate value is not a Hash)
    def token_value(token_data, token_field)
      token_field.split(FIELD_PATH_SEPARATOR).reduce(token_data) { |data, key| data.is_a?(Hash) ? data[key] : nil }
    end

    # Convert a class name to snake_case symbol
    # @param creator_class [Class] The class to convert
    # @return [Symbol] snake_case version of class name
    def class_to_id(creator_class)
      return creator_class.name.split('::').last.capital_to_snake.to_sym
    end
  end

  private

  # Initialize the factory with default parameters and empty collections
  def initialize
    # persistency manager
    @persist = nil
    # token creation methods
    @token_type_classes = {}
    # list of lambda
    @decoders = []
    # default parameters, others can be added by handlers
    @parameters = {
      # tokens older than this duration in sec. will be discarded from cache
      token_cache_max_age:     1800,
      # tokens valid for less than this duration in sec. will be regenerated
      token_refresh_threshold: 120,
      # tokens obtained since more than this duration in sec. will be regenerated (0: no limit)
      token_refresh_max_age:   0
    }
  end

  public

  attr_reader :parameters

  # Set the persistence manager for token caching
  # @param manager [Object] The persistence manager instance
  def persist_mgr=(manager)
    @persist = manager
    # cleanup expired tokens
    @persist.garbage_collect(PERSIST_CATEGORY_TOKEN, @parameters[:token_cache_max_age])
  end

  # Get or initialize the persistence manager
  # @return [Object] The persistence manager instance
  def persist_mgr
    if @persist.nil?
      # use OAuth::Factory.instance.persist_mgr=PersistencyFolder.new)
      Log.log.debug('Not using persistency')
      # create NULL persistency class
      @persist = Class.new do
        def get(_x); nil; end; def delete(_x); nil; end; def put(_x, _y); nil; end; def garbage_collect(_x, _y); nil; end # rubocop:disable Style/Semicolon
      end.new
    end
    return @persist
  end

  # Delete all existing tokens in cache
  # @return [Array<String>] List of deleted file paths
  def flush_tokens
    persist_mgr.garbage_collect(PERSIST_CATEGORY_TOKEN)
  end

  # Retrieve all persisted tokens with their decoded information
  # @return [Array<Hash>] Array of token information hashes
  def persisted_tokens
    data = persist_mgr.current_items(PERSIST_CATEGORY_TOKEN)
    data.each.map do |k, v|
      info = {id: k}
      begin; info.merge!(JSON.parse(v)); rescue StandardError; nil; end
      token_val = info.delete(TOKEN_FIELD) || info.delete('token')
      d = decode_token(token_val)
      info.merge(d) if d
      info
    end
  end

  # Get token information from cache
  # @param id [String] identifier of token
  # @param token_field [String, nil] Field containing the token (or dot-separated path), or nil to auto-detect
  # @return [Hash] token internal information , including Date object for `expiration_date`
  def get_token_info(id, token_field: nil)
    token_raw_string = persist_mgr.get(id)
    return if token_raw_string.nil?
    token_data = JSON.parse(token_raw_string)
    Aspera.assert_type(token_data, Hash)
    token_value = (self.class.token_value(token_data, token_field) unless token_field.nil?) || token_data[TOKEN_FIELD] || token_data['token']
    decoded_token = decode_token(token_value)
    info = {data: token_data}
    info[:decoded] = decoded_token if decoded_token.is_a?(Hash)
    # TODO: move date decoding to token decoder ?
    expiration_date =
      if    decoded_token.is_a?(Hash) && decoded_token['expires_at'].is_a?(String) then Time.parse(decoded_token['expires_at'])
      elsif decoded_token.is_a?(Hash) && decoded_token['exp'].is_a?(Integer)       then Time.at(decoded_token['exp'])
      elsif token_data[EXPIRES_AT_FIELD].is_a?(String)                             then Time.parse(token_data[EXPIRES_AT_FIELD])
      end
    unless expiration_date.nil?
      info[:expiration] = expiration_date
      info[:ttl_sec] = expiration_date - Time.now
      info[:expired] = info[:ttl_sec] < @parameters[:token_refresh_threshold]
    end
    # Force refresh of an old token, e.g. before its refresh token expires
    max_age = @parameters[:token_refresh_max_age].to_i
    obtained_at = token_data[OBTAINED_AT_FIELD]
    info[:expired] = true if max_age.positive? && obtained_at.is_a?(String) && Time.now - Time.parse(obtained_at) > max_age
    Log.dump(:token_info, info)
    return info
  end

  # Register a bearer token decoder for inspecting token properties
  # @param method [Proc] The decoder lambda/proc to register
  # @return [nil]
  def register_decoder(method)
    @decoders.push(method)
    nil
  end

  # Decode a token using all registered decoders
  # @param token [String] The token to decode
  # @return [Hash, nil] Decoded token data or nil if no decoder succeeded
  def decode_token(token)
    @decoders.each do |decoder|
      result = begin; decoder.call(token); rescue StandardError; nil; end
      return result unless result.nil?
    end
    return
  end

  # Register a token creation method
  # @param creator_class [Class] The token creator class to register
  # @return [nil]
  def register_token_creator(creator_class)
    Aspera.assert_type(creator_class, Class)
    id = Factory.class_to_id(creator_class)
    Log.log.debug { "registering creator for #{id}" }
    @token_type_classes[id] = creator_class
    nil
  end

  # Create a token creator instance for the specified grant method
  # The class of the grant method is registered by its file (`register_token_creator`): the caller requires it.
  # @param parameters [Hash] Parameters including :grant_method and creator-specific options
  # @return [Object] An instance of the registered token creator class
  def create(**parameters)
    Aspera.assert_type(parameters, Hash)
    id = parameters[:grant_method]
    Aspera.assert(@token_type_classes.key?(id)) { "token grant method unknown: '#{id}'" }
    create_parameters = parameters.reject { |k, _v| k.eql?(:grant_method) }
    @token_type_classes[id].new(**create_parameters)
  end
end

.token_value(token_data, token_field) ⇒ Object?

Value of the token in a token creation response

Parameters:

  • token_data (Hash{String => Object}) —

    Token creation response

  • token_field (String) —

    Field that contains the token, or dot-separated path of a nested field, e.g. authed_user.access_token

Returns:

  • (Object, nil) —

    Value of the field, nil if absent (or an intermediate value is not a Hash)



72
73
74
# File 'lib/aspera/oauth/client/factory.rb', line 72

def token_value(token_data, token_field)
  token_field.split(FIELD_PATH_SEPARATOR).reduce(token_data) { |data, key| data.is_a?(Hash) ? data[key] : nil }
end

Instance Method Details

#create(**parameters) ⇒ Object

Create a token creator instance for the specified grant method The class of the grant method is registered by its file (register_token_creator): the caller requires it.

Parameters:

  • parameters (Hash) —

    Parameters including :grant_method and creator-specific options

Returns:

  • (Object) —

    An instance of the registered token creator class



217
218
219
220
221
222
223
# File 'lib/aspera/oauth/client/factory.rb', line 217

def create(**parameters)
  Aspera.assert_type(parameters, Hash)
  id = parameters[:grant_method]
  Aspera.assert(@token_type_classes.key?(id)) { "token grant method unknown: '#{id}'" }
  create_parameters = parameters.reject { |k, _v| k.eql?(:grant_method) }
  @token_type_classes[id].new(**create_parameters)
end

#decode_token(token) ⇒ Hash?

Decode a token using all registered decoders

Parameters:

  • token (String) —

    The token to decode

Returns:

  • (Hash, nil) —

    Decoded token data or nil if no decoder succeeded



194
195
196
197
198
199
200
# File 'lib/aspera/oauth/client/factory.rb', line 194

def decode_token(token)
  @decoders.each do |decoder|
    result = begin; decoder.call(token); rescue StandardError; nil; end
    return result unless result.nil?
  end
  return
end

#flush_tokens ⇒ Array<String>

Delete all existing tokens in cache

Returns:

  • (Array<String>) —

    List of deleted file paths



133
134
135
# File 'lib/aspera/oauth/client/factory.rb', line 133

def flush_tokens
  persist_mgr.garbage_collect(PERSIST_CATEGORY_TOKEN)
end

#get_token_info(id, token_field: nil) ⇒ Hash

Get token information from cache

Parameters:

  • id (String) —

    identifier of token

  • token_field (String, nil) (defaults to: nil) —

    Field containing the token (or dot-separated path), or nil to auto-detect

Returns:

  • (Hash) —

    token internal information , including Date object for expiration_date



155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
# File 'lib/aspera/oauth/client/factory.rb', line 155

def get_token_info(id, token_field: nil)
  token_raw_string = persist_mgr.get(id)
  return if token_raw_string.nil?
  token_data = JSON.parse(token_raw_string)
  Aspera.assert_type(token_data, Hash)
  token_value = (self.class.token_value(token_data, token_field) unless token_field.nil?) || token_data[TOKEN_FIELD] || token_data['token']
  decoded_token = decode_token(token_value)
  info = {data: token_data}
  info[:decoded] = decoded_token if decoded_token.is_a?(Hash)
  # TODO: move date decoding to token decoder ?
  expiration_date =
    if    decoded_token.is_a?(Hash) && decoded_token['expires_at'].is_a?(String) then Time.parse(decoded_token['expires_at'])
    elsif decoded_token.is_a?(Hash) && decoded_token['exp'].is_a?(Integer)       then Time.at(decoded_token['exp'])
    elsif token_data[EXPIRES_AT_FIELD].is_a?(String)                             then Time.parse(token_data[EXPIRES_AT_FIELD])
    end
  unless expiration_date.nil?
    info[:expiration] = expiration_date
    info[:ttl_sec] = expiration_date - Time.now
    info[:expired] = info[:ttl_sec] < @parameters[:token_refresh_threshold]
  end
  # Force refresh of an old token, e.g. before its refresh token expires
  max_age = @parameters[:token_refresh_max_age].to_i
  obtained_at = token_data[OBTAINED_AT_FIELD]
  info[:expired] = true if max_age.positive? && obtained_at.is_a?(String) && Time.now - Time.parse(obtained_at) > max_age
  Log.dump(:token_info, info)
  return info
end

#persist_mgr ⇒ Object

Get or initialize the persistence manager

Returns:

  • (Object) —

    The persistence manager instance



119
120
121
122
123
124
125
126
127
128
129
# File 'lib/aspera/oauth/client/factory.rb', line 119

def persist_mgr
  if @persist.nil?
    # use OAuth::Factory.instance.persist_mgr=PersistencyFolder.new)
    Log.log.debug('Not using persistency')
    # create NULL persistency class
    @persist = Class.new do
      def get(_x); nil; end; def delete(_x); nil; end; def put(_x, _y); nil; end; def garbage_collect(_x, _y); nil; end # rubocop:disable Style/Semicolon
    end.new
  end
  return @persist
end

#persist_mgr=(manager) ⇒ Object

Set the persistence manager for token caching

Parameters:

  • manager (Object) —

    The persistence manager instance



111
112
113
114
115
# File 'lib/aspera/oauth/client/factory.rb', line 111

def persist_mgr=(manager)
  @persist = manager
  # cleanup expired tokens
  @persist.garbage_collect(PERSIST_CATEGORY_TOKEN, @parameters[:token_cache_max_age])
end

#persisted_tokens ⇒ Array<Hash>

Retrieve all persisted tokens with their decoded information

Returns:

  • (Array<Hash>) —

    Array of token information hashes



139
140
141
142
143
144
145
146
147
148
149
# File 'lib/aspera/oauth/client/factory.rb', line 139

def persisted_tokens
  data = persist_mgr.current_items(PERSIST_CATEGORY_TOKEN)
  data.each.map do |k, v|
    info = {id: k}
    begin; info.merge!(JSON.parse(v)); rescue StandardError; nil; end
    token_val = info.delete(TOKEN_FIELD) || info.delete('token')
    d = decode_token(token_val)
    info.merge(d) if d
    info
  end
end

#register_decoder(method) ⇒ nil

Register a bearer token decoder for inspecting token properties

Parameters:

  • method (Proc) —

    The decoder lambda/proc to register

Returns:

  • (nil)


186
187
188
189
# File 'lib/aspera/oauth/client/factory.rb', line 186

def register_decoder(method)
  @decoders.push(method)
  nil
end

#register_token_creator(creator_class) ⇒ nil

Register a token creation method

Parameters:

  • creator_class (Class) —

    The token creator class to register

Returns:

  • (nil)


205
206
207
208
209
210
211
# File 'lib/aspera/oauth/client/factory.rb', line 205

def register_token_creator(creator_class)
  Aspera.assert_type(creator_class, Class)
  id = Factory.class_to_id(creator_class)
  Log.log.debug { "registering creator for #{id}" }
  @token_type_classes[id] = creator_class
  nil
end