Class: StatelyDB::Common::Auth::Auth0TokenProvider::Actor

Inherits:
Object
  • Object
show all
Defined in:
lib/common/auth/auth0_token_provider.rb

Overview

Actor for managing the token refresh This is designed to be used with Async::Actor and run on a dedicated thread.

Instance Method Summary collapse

Constructor Details

#initialize(origin:, audience:, client_secret:, client_id:) ⇒ Actor

Returns a new instance of Actor.

Parameters:

  • origin (String)

    The origin of the OAuth server

  • audience (String)

    The OAuth Audience for the token

  • client_secret (String)

    The StatelyDB client secret credential

  • client_id (String)

    The StatelyDB client ID credential



63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/common/auth/auth0_token_provider.rb', line 63

def initialize(
  origin:,
  audience:,
  client_secret:,
  client_id:
)
  super()
  @client = Async::HTTP::Client.new(Async::HTTP::Endpoint.parse(origin))
  @client_id = client_id
  @client_secret = client_secret
  @audience = audience

  @access_token = nil
  @expires_at_unix_secs = nil
  @pending_refresh = nil
end

Instance Method Details

#closeObject

Close the token provider and kill any background operations



87
88
89
90
# File 'lib/common/auth/auth0_token_provider.rb', line 87

def close
  @scheduled&.stop
  @client&.close
end

#get_token(force: false) ⇒ String

Get the current access token

Parameters:

  • force (Boolean) (defaults to: false)

    Whether to force a refresh of the token

Returns:

  • (String)

    The current access token



95
96
97
98
99
100
101
102
103
104
105
# File 'lib/common/auth/auth0_token_provider.rb', line 95

def get_token(force: false)
  if force
    @access_token = nil
    @expires_at_unix_secs = nil
  else
    token, ok = valid_access_token
    return token if ok
  end

  refresh_token.wait
end

#initObject

Initialize the actor. This runs on the actor thread which means we can dispatch async operations here.



82
83
84
# File 'lib/common/auth/auth0_token_provider.rb', line 82

def init
  refresh_token
end

#make_auth0_requestObject



189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
# File 'lib/common/auth/auth0_token_provider.rb', line 189

def make_auth0_request
  headers = [["content-type", "application/json"]]
  body = JSON.dump({ "client_id" => @client_id, client_secret: @client_secret, audience: @audience,
                     grant_type: DEFAULT_GRANT_TYPE })
  Sync do
    # TODO: Wrap this in a retry loop and parse errors like we
    # do in the Go SDK.
    response = @client.post("/oauth/token", headers, body)
    raise "Auth request failed" if response.status != 200

    JSON.parse(response.read)
  ensure
    response&.close
  end
end

#refresh_tokenTask

Refresh the access token

Returns:

  • (Task)

    A task that will resolve to the new access token



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
# File 'lib/common/auth/auth0_token_provider.rb', line 119

def refresh_token
  Async do
    # we use an Async::Condition to dedupe multiple requests here
    # if the condition exists, we wait on it to complete
    # otherwise we create a condition, make the request, then signal the condition with the result
    # If there is an error then we signal that instead so we can raise it for the waiters.
    if @pending_refresh.nil?
      begin
        @pending_refresh = Async::Condition.new
        new_access_token = refresh_token_impl
        # now broadcast the new token to any waiters
        @pending_refresh.signal(new_access_token)
        new_access_token
      rescue StandardError => e
        @pending_refresh.signal(e)
        raise e
      ensure
        # delete the condition to restart the process
        @pending_refresh = nil
      end
    else
      res = @pending_refresh.wait
      # if the refresh result is an error, re-raise it.
      # otherwise return the token
      raise res if res.is_a?(StandardError)

      res
    end
  end
end

#refresh_token_implString

Refresh the access token implementation

Returns:

  • (String)

    The new access token



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
# File 'lib/common/auth/auth0_token_provider.rb', line 152

def refresh_token_impl
  Sync do
    resp_data = make_auth0_request

    new_access_token = resp_data["access_token"]
    new_expires_in_secs = resp_data["expires_in"]
    new_expires_at_unix_secs = Time.now.to_i + new_expires_in_secs
    if @expires_at_unix_secs.nil? || new_expires_at_unix_secs > @expires_at_unix_secs

      @access_token = new_access_token
      @expires_at_unix_secs = new_expires_at_unix_secs
    else

      new_access_token = @access_token
      new_expires_in_secs = @expires_at_unix_secs - Time.now.to_i
    end

    # Schedule a refresh of the token ahead of the expiry time
    # Calculate a random multiplier between 0.9 and 0.95 to to apply to the expiry
    # so that we refresh in the background ahead of expiration, but avoid
    # multiple processes hammering the service at the same time.
    jitter = (Random.rand * 0.05) + 0.9
    delay_secs = new_expires_in_secs * jitter

    # do this on the fiber scheduler (the root scheduler) to avoid infinite recursion
    @scheduled ||= Fiber.scheduler.async do
      # Kernel.sleep is non-blocking if Ruby 3.1+ and Async 2+
      # https://github.com/socketry/async/issues/305#issuecomment-1945188193
      sleep(delay_secs)
      refresh_token
      @scheduled = nil
    end

    new_access_token
  end
end

#valid_access_tokenArray

Get the current access token and whether it is valid

Returns:

  • (Array)

    The current access token and whether it is valid



109
110
111
112
113
114
115
# File 'lib/common/auth/auth0_token_provider.rb', line 109

def valid_access_token
  return "", false if @access_token.nil?
  return "", false if @expires_at_unix_secs.nil?
  return "", false if @expires_at_unix_secs < Time.now.to_i

  [@access_token, true]
end