Class: Aspera::OAuth::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/aspera/oauth/client/base.rb

Overview

OAuth 2 client for the REST client Generate bearer token Bearer tokens are cached in memory and in a file cache for later re-use OAuth 2.0 Authorization Framework: https://tools.ietf.org/html/rfc6749 Bearer Token Usage: https://tools.ietf.org/html/rfc6750

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(params: {}, path_token: 'token', use_query: false, token_field: Factory::TOKEN_FIELD, cache_ids: [], **rest_params) ⇒ Base

Returns a new instance of Base.

Parameters:

  • params (Hash) (defaults to: {}) —

    Parameters for token creation (client_id, client_secret, scope, etc...)

  • path_token (String) (defaults to: 'token') —

    API end point to create a token: path from base URL, or absolute URL (http or https), e.g. on another host

  • use_query (Boolean) (defaults to: false) —

    Provide parameters in query instead of body

  • token_field (String) (defaults to: Factory::TOKEN_FIELD) —

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

  • cache_ids (Array) (defaults to: []) —

    List of unique identifiers for cache id generation

  • rest_params (Hash) —

    Parameters for REST



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/aspera/oauth/client/base.rb', line 51

def initialize(
  params: {},
  path_token: 'token',
  use_query: false,
  token_field: Factory::TOKEN_FIELD,
  cache_ids: [],
  **rest_params
)
  Aspera.assert_type(params, Hash)
  Aspera.assert_type(cache_ids, Array)
  # This is the OAuth API
  @api = Rest::Client.new(**rest_params)
  @params = params.dup.freeze
  @path_token = path_token
  @token_field = token_field
  @use_query = use_query
  @token_cache_id = Factory.cache_id(@api.base_url, self.class, *cache_ids, self.class.client_id_digest(@params[:client_id]), @params[:scope])
end

Instance Attribute Details

#api ⇒ Object (readonly)

The OAuth API Object



71
72
73
# File 'lib/aspera/oauth/client/base.rb', line 71

def api
  @api
end

#params ⇒ Object (readonly)

Parameters to generate token



73
74
75
# File 'lib/aspera/oauth/client/base.rb', line 73

def params
  @params
end

#path_token ⇒ Object (readonly)

Sub path to generate token



75
76
77
# File 'lib/aspera/oauth/client/base.rb', line 75

def path_token
  @path_token
end

Class Method Details

.absolute_url?(path) ⇒ Boolean

Returns true if path is an absolute URL (http or https).

Parameters:

  • path (String) —

    Path of an end point

Returns:

  • (Boolean) —

    true if path is an absolute URL (http or https)



34
# File 'lib/aspera/oauth/client/base.rb', line 34

def absolute_url?(path) = path.match?(%r{\Ahttps?://}i)

.client_id_digest(client_id) ⇒ String?

A token is given to an API client: another client of the same server and user gets its own token. A digest, of fixed size, keeps the name of the cache file short, whatever the length of the identifier of the client.

Parameters:

  • client_id (String, nil) —

    Identifier of the API client

Returns:

  • (String, nil) —

    Digest of the API client in the cache id, nil: no client (cache id unchanged)



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

def client_id_digest(client_id)
  return if client_id.nil?
  OpenSSL::Digest::SHA256.hexdigest(client_id.to_s)[0, CLIENT_DIGEST_LENGTH]
end

Instance Method Details

#authorization ⇒ String

Get the value of the HTTP Authorization header for this OAuth client, i.e. Bearer <token>. The bearer token is obtained through #token (cached, refreshed or generated).

Returns:

  • (String) —

    Value suitable for Authorization header



121
122
123
# File 'lib/aspera/oauth/client/base.rb', line 121

def authorization
  OAuth::Factory.bearer_authorization(token)
end

#base_parameters(include_secret: false, **other_params) ⇒ Hash

Parameters for token creation call

Parameters:

  • include_secret (Boolean) (defaults to: false) —

    Add secret in default call parameters

  • other_params (Hash) —

    Other parameters to merge

Returns:

  • (Hash) —

    Token creation parameters



98
99
100
# File 'lib/aspera/oauth/client/base.rb', line 98

def base_parameters(include_secret: false, **other_params)
  (include_secret ? @params : @params.except(:client_secret)).merge(other_params)
end

#create_token_base(include_secret: false, **other_params) ⇒ Net::HTTPResponse

Helper method to create token as per RFC

Parameters:

  • include_secret (Boolean) (defaults to: false) —

    Add secret in call parameters

  • other_params (Hash) —

    Additional parameter to base parameters

Returns:

  • (Net::HTTPResponse) —

    Raw HTTP response with token

Raises:



107
108
109
110
111
112
113
114
115
116
# File 'lib/aspera/oauth/client/base.rb', line 107

def create_token_base(include_secret: false, **other_params)
  Log.log.debug { 'Generating a new token'.bg(:green) }
  creation_params = base_parameters(include_secret: include_secret, **other_params)
  # Credentials of the request are hidden wherever they appear, e.g. logs of its body or URL
  Secret::Hider.instance.add_secrets_in(creation_params)
  Secret::Hider.instance.add_secret_values(*creation_params.filter_map { |k, v| v if CREDENTIAL_PARAMS.include?(k.to_s) })
  token_api, subpath = endpoint_api(@path_token)
  return token_api.create(subpath, nil, query: creation_params, ret: :resp) if @use_query
  token_api.create(subpath, creation_params, content_type: Mime::WWW, ret: :resp)
end

#endpoint_api(path) ⇒ Array(Rest::Client, String)

API and subpath to call an end point of the OAuth server An absolute URL (e.g. token on another host than authorization) gets its own API, same parameters. The token cache id does not depend on it: it uses the base URL.

Parameters:

  • path (String) —

    Path from the base URL, or absolute URL (http or https)

Returns:



89
90
91
92
# File 'lib/aspera/oauth/client/base.rb', line 89

def endpoint_api(path)
  return [@api, path] unless Base.absolute_url?(path)
  [Rest::Client.new(**@api.params.merge(base_url: path)), '']
end

#endpoint_url(path) ⇒ String

URL of an end point of the OAuth server

Parameters:

  • path (String) —

    Path from the base URL, or absolute URL (http or https), used as is

Returns:

  • (String) —

    URL of the end point



80
81
82
# File 'lib/aspera/oauth/client/base.rb', line 80

def endpoint_url(path)
  Base.absolute_url?(path) ? path : "#{@api.base_url}/#{path}"
end

#renew_token ⇒ String

Get a new OAuth v2 token, discarding the cached one. Use the refresh token of the cached token, if any, else generate a new token.

Returns:

  • (String) —

    The bearer token

Raises:

  • (StandardError) —

    Error of the generation of a new token



151
152
153
# File 'lib/aspera/oauth/client/base.rb', line 151

def renew_token
  bearer_token(refreshed_token_data(discard_cached_token) || save_token_data(create_token))
end

#renewed_authorization ⇒ String

Get the value of the HTTP Authorization header with a renewed token, i.e. Bearer <token>. To be used when the server rejected the current token. The bearer token is obtained through #renew_token.

Returns:

  • (String) —

    Value suitable for Authorization header



129
130
131
# File 'lib/aspera/oauth/client/base.rb', line 129

def renewed_authorization
  OAuth::Factory.bearer_authorization(renew_token)
end

#token ⇒ String

Get a OAuth v2 token: the cached one, unless it expires soon, else a renewed one. Checking expiration in advance helps a transfer agent which cannot renew the token itself (direct agent is equipped with renewal code). If the server rejects the token (API returns 4xx), call #renew_token.

Returns:

  • (String) —

    The bearer token



138
139
140
141
142
143
144
145
# File 'lib/aspera/oauth/client/base.rb', line 138

def token
  token_info = cached_token_info
  unless token_info.nil?
    return bearer_token(token_info[:data]) unless token_info[:expired]
    Log.log.trace1 { 'Cached token expires soon' }
  end
  renew_token
end