diff --git a/README.md b/README.md index 4e81b6d..de260ce 100644 --- a/README.md +++ b/README.md @@ -96,8 +96,11 @@ rc.authorize account = rc.get('/restapi/v2/accounts/~').body ``` -Call `authorize` again when the access token expires. Automatic refresh applies -only to tokens issued with a refresh token. +The SDK repeats the client credentials exchange when an API request needs a new +access token. Call `rc.refresh` to renew the token explicitly, or set +`rc.auto_refresh = true` before authorization to schedule renewal in the +background. If you save the token for reuse, keep its `grant_type` and `expires_at` +fields so the SDK can renew it after loading it again. ## Samples @@ -128,9 +131,8 @@ Above will be translated to ### Token Refresh -Access token expires. You need to call `rc.refresh()` before it expires. If you -want the SDK to do auto refresh please `rc.auto_refresh = true` before -authorization. +Call `rc.refresh` to renew an access token explicitly. Set `rc.auto_refresh = true` +before authorization to schedule renewal in the background. ### Load pre-existing token @@ -291,6 +293,13 @@ prints the account response as formatted JSON. bundle exec ruby api_test/client_credentials_smoke.rb ``` +Add `--test-renewal` to simulate expiry and verify that a second account lookup +automatically renews the token and returns the same account. + +```sh +bundle exec ruby api_test/client_credentials_smoke.rb --test-renewal +``` + **JWT** Also set `RINGCENTRAL_JWT_TOKEN` to the JWT for the test extension. @@ -299,6 +308,13 @@ Also set `RINGCENTRAL_JWT_TOKEN` to the JWT for the test extension. bundle exec ruby api_test/jwt_smoke.rb ``` +Add `--test-renewal` to exchange the refresh token and verify that the renewed +access token can retrieve the same account. + +```sh +bundle exec ruby api_test/jwt_smoke.rb --test-renewal +``` + **Authorization code** Register `http://localhost:5000/oauth2callback` as an app redirect URI, or set @@ -311,6 +327,12 @@ the code using PKCE. bundle exec ruby api_test/auth_code_smoke.rb ``` +Add `--test-renewal` to verify the refresh-token exchange after browser approval. + +```sh +bundle exec ruby api_test/auth_code_smoke.rb --test-renewal +``` + ### Continuous integration Normal push/PR CI and release-tag validation run the complete live suite on Ruby diff --git a/api_test/auth_code_smoke.rb b/api_test/auth_code_smoke.rb index a97c876..da624fe 100644 --- a/api_test/auth_code_smoke.rb +++ b/api_test/auth_code_smoke.rb @@ -74,7 +74,7 @@ def wait_for_authorization_code(client, callback, redirect_uri, verifier) callback = loopback_callback(redirect_uri) abort "Set RINGCENTRAL_REDIRECT_URI to a registered HTTP loopback URL with a port, such as #{DEFAULT_REDIRECT_URI}." unless callback -OAuthSmoke.run('Authorization code', server, client_id, client_secret) do |client| +OAuthSmoke.run('Authorization code', server, client_id, client_secret, test_renewal: ARGV.include?('--test-renewal')) do |client| verifier = SecureRandom.urlsafe_base64(32) code = wait_for_authorization_code(client, callback, redirect_uri, verifier) client.authorize(auth_code: code, redirect_uri: redirect_uri, verifier: verifier) diff --git a/api_test/client_credentials_smoke.rb b/api_test/client_credentials_smoke.rb index a95e5e0..e8570c2 100644 --- a/api_test/client_credentials_smoke.rb +++ b/api_test/client_credentials_smoke.rb @@ -1,5 +1,5 @@ require_relative 'oauth_smoke' -OAuthSmoke.run('Client credentials', *OAuthSmoke.load_config) do |client| +OAuthSmoke.run('Client credentials', *OAuthSmoke.load_config, test_renewal: ARGV.include?('--test-renewal')) do |client| client.authorize end diff --git a/api_test/jwt_smoke.rb b/api_test/jwt_smoke.rb index c92ef05..f9965e2 100644 --- a/api_test/jwt_smoke.rb +++ b/api_test/jwt_smoke.rb @@ -2,6 +2,6 @@ server, client_id, client_secret, jwt = OAuthSmoke.load_config('RINGCENTRAL_JWT_TOKEN') -OAuthSmoke.run('JWT', server, client_id, client_secret) do |client| +OAuthSmoke.run('JWT', server, client_id, client_secret, test_renewal: ARGV.include?('--test-renewal')) do |client| client.authorize(jwt: jwt) end diff --git a/api_test/oauth_smoke.rb b/api_test/oauth_smoke.rb index b906771..6486366 100644 --- a/api_test/oauth_smoke.rb +++ b/api_test/oauth_smoke.rb @@ -13,27 +13,57 @@ def self.load_config(*extra_required) ENV.values_at(*required) end - def self.run(flow, server, client_id, client_secret) + def self.run(flow, server, client_id, client_secret, test_renewal: false) operation = "#{flow} authorization" client = RingCentral.new(client_id, client_secret, server) yield client + verify_access_token(client, operation) + + operation = 'Account lookup' + status, account = lookup_account(client) + puts "#{flow} authorization succeeded. Account lookup returned HTTP #{status} with an account ID." + puts JSON.pretty_generate(account) + + if test_renewal + operation = "#{flow} token renewal" + previous_token = client.token + if previous_token['grant_type'] == 'client_credentials' + previous_token = previous_token.merge('expires_at' => Time.now.to_f - 1) + client.token = previous_token + else + abort "#{operation} requires a refresh token from authorization." if previous_token['refresh_token'].to_s.empty? + + client.refresh + verify_access_token(client, operation) + end + + status, renewed_account = lookup_account(client) + if client.token.equal?(previous_token) || renewed_account['id'] != account['id'] + abort "#{operation} did not renew the token and return the same account." + end + puts "#{operation} succeeded. Account lookup returned HTTP #{status} with the same account ID." + puts JSON.pretty_generate(renewed_account) + end + rescue StandardError => error + status = error.message[/\AHTTP status (\d{3}):/, 1] + detail = status ? "HTTP #{status}" : error.class.name + abort "#{operation} failed (#{detail})." + end + + def self.verify_access_token(client, operation) access_token = client.token['access_token'] if client.token.is_a?(Hash) unless access_token.is_a?(String) && !access_token.empty? abort "#{operation} did not return an access token." end + end - operation = 'Account lookup' + def self.lookup_account(client) response = client.get('/restapi/v2/accounts/~') account = response.body unless (200..299).cover?(response.status) && account.is_a?(Hash) && !account['id'].to_s.strip.empty? abort "Account lookup returned HTTP #{response.status} without a successful account response." end - - puts "#{flow} authorization succeeded. Account lookup returned HTTP #{response.status} with an account ID." - puts JSON.pretty_generate(account) - rescue StandardError => error - status = error.message[/\AHTTP status (\d{3}):/, 1] - detail = status ? "HTTP #{status}" : error.class.name - abort "#{operation} failed (#{detail})." + [response.status, account] end + private_class_method :verify_access_token, :lookup_account end diff --git a/lib/ringcentral.rb b/lib/ringcentral.rb index 8a20b4a..a427037 100644 --- a/lib/ringcentral.rb +++ b/lib/ringcentral.rb @@ -1,11 +1,16 @@ require 'base64' require 'addressable/uri' require 'json' +require 'monitor' require 'concurrent' require 'faraday' require 'faraday/multipart' class RingCentral + TOKEN_ENDPOINT = '/restapi/oauth/token' + CLIENT_CREDENTIALS_GRANT = 'client_credentials' + private_constant :TOKEN_ENDPOINT, :CLIENT_CREDENTIALS_GRANT + def self.PRODUCTION_SERVER 'https://platform.ringcentral.com' end @@ -21,6 +26,7 @@ def initialize(client_id, client_secret, server = RingCentral.PRODUCTION_SERVER, @debug_mode = debug_mode @token = nil @timer = nil + @authorization_lock = Monitor.new @faraday = Faraday.new(url: server, request: { params_encoder: Faraday::FlatParamsEncoder }) do |faraday| faraday.request :multipart faraday.request :url_encoded @@ -30,13 +36,17 @@ def initialize(client_id, client_secret, server = RingCentral.PRODUCTION_SERVER, end def token=(value) - @token = value - if @timer != nil - @timer.shutdown + @authorization_lock.synchronize do + @timer&.shutdown @timer = nil - end - if @auto_refresh && value && !value['refresh_token'].to_s.empty? - @timer = Concurrent::TimerTask.new(execution_interval: value['expires_in'] - 120, timeout_interval: 60) { self.refresh } + @token = value + @rejected_app_token = nil + interval = refresh_interval(value) if @auto_refresh && value + return unless interval + + @timer = Concurrent::TimerTask.new(execution_interval: interval, timeout_interval: 60) do + @authorization_lock.synchronize { refresh if @token.equal?(value) } + end @timer.execute end end @@ -45,44 +55,42 @@ def token=(value) # User authorization accepts jwt, auth_code with redirect_uri and optional # verifier, or the deprecated username, password and optional extension. def authorize(**options) - client_credentials = options.empty? - if client_credentials - if @client_id.to_s.empty? || @client_secret.to_s.empty? - raise ArgumentError, 'Client credentials authorization requires a client ID and client secret' + @authorization_lock.synchronize do + if options.empty? + validate_client_credentials + self.token = nil + return exchange_client_credentials end - payload = { grant_type: 'client_credentials' } - else + payload = user_authorization_payload(**options) + self.token = nil + self.token = post(TOKEN_ENDPOINT, payload: payload).body end - self.token = nil - token = post('/restapi/oauth/token', payload: payload).body - if client_credentials - access_token = token['access_token'] if token.is_a?(Hash) - unless access_token.is_a?(String) && !access_token.empty? - raise 'Malformed OAuth response: missing access token' - end - end - self.token = token end def refresh - refresh_token = @token['refresh_token'] if @token - return if refresh_token.to_s.empty? - - payload = { - grant_type: 'refresh_token', - refresh_token: refresh_token - } - self.token = nil - r = self.post('/restapi/oauth/token', payload: payload) - self.token = r.body + @authorization_lock.synchronize do + if client_credentials_token?(@token) + validate_client_credentials + return exchange_client_credentials + end + + refresh_token = @token['refresh_token'] if @token + return if refresh_token.to_s.empty? + + self.token = nil + self.token = post(TOKEN_ENDPOINT, payload: { grant_type: 'refresh_token', refresh_token: refresh_token }).body + end end def revoke - return if @token == nil - payload = { token: @token['access_token'] } - self.token = nil - self.post('/restapi/oauth/revoke', payload: payload) + @authorization_lock.synchronize do + return if @token == nil + + payload = { token: @token['access_token'] } + self.token = nil + post('/restapi/oauth/revoke', payload: payload) + end end def authorize_uri(redirect_uri, hash = {}) @@ -95,116 +103,148 @@ def authorize_uri(redirect_uri, hash = {}) end def get(endpoint, params = {}) - r = @faraday.get do |req| - req.url endpoint - req.params = params - req.headers = headers - end - if @debug_mode - puts r.status, r.body + request(endpoint) do |token| + @faraday.get do |req| + req.url endpoint + req.params = params + req.headers = headers(token) + end end - if r.status >= 400 - raise "HTTP status #{r.status}: - -headers: #{r.headers} + end -body: #{r.body}" + def post(endpoint, payload: nil, params: {}, files: nil) + multipart = files && files.size > 0 + request(endpoint, retry_unauthorized: !multipart) do |token| + @faraday.post do |req| + req.url endpoint + req.params = params + req.headers = headers(token) + if multipart # send fax or MMS + io = StringIO.new(payload.to_json) + req.body = { + json: Faraday::UploadIO.new(io, 'application/json'), + attachment: files.map { |file| Faraday::UploadIO.new(file[0], file[1]) }, + } + elsif payload != nil && token != nil + req.headers['Content-Type'] = 'application/json' + req.body = payload.to_json + else + req.body = payload + end + end end - return r end - def post(endpoint, payload: nil, params: {}, files: nil) - r = @faraday.post do |req| - req.url endpoint - req.params = params - if files != nil && files.size > 0 # send fax or MMS - io = StringIO.new(payload.to_json) - payload = {} - payload[:json] = Faraday::UploadIO.new(io, 'application/json') - payload[:attachment] = files.map{ |file| Faraday::UploadIO.new(file[0], file[1]) } - req.headers = headers - req.body = payload - elsif payload != nil && @token != nil - req.headers = headers.merge({ 'Content-Type': 'application/json' }) + def put(endpoint, payload: nil, params: {}, files: nil) + request(endpoint) do |token| + @faraday.put do |req| + req.url endpoint + req.params = params + req.headers = headers(token).merge({ 'Content-Type': 'application/json' }) req.body = payload.to_json - else - req.headers = headers - req.body = payload end end - if @debug_mode - puts r.status, r.body - end - if r.status >= 400 - raise "HTTP status #{r.status}: - -headers: #{r.headers} + end -body: #{r.body}" + def patch(endpoint, payload: nil, params: {}, files: nil) + request(endpoint) do |token| + @faraday.patch do |req| + req.url endpoint + req.params = params + req.headers = headers(token).merge({ 'Content-Type': 'application/json' }) + req.body = payload.to_json + end end - return r end - def put(endpoint, payload: nil, params: {}, files: nil) - r = @faraday.put do |req| - req.url endpoint - req.params = params - req.headers = headers.merge({ 'Content-Type': 'application/json' }) - req.body = payload.to_json - end - if @debug_mode - puts r.status, r.body + def delete(endpoint, params = {}) + request(endpoint) do |token| + @faraday.delete do |req| + req.url endpoint + req.params = params + req.headers = headers(token) + end end - if r.status >= 400 - raise "HTTP status #{r.status}: + end -headers: #{r.headers} + private -body: #{r.body}" + def validate_client_credentials + if @client_id.to_s.empty? || @client_secret.to_s.empty? + raise ArgumentError, 'Client credentials authorization requires a client ID and client secret' + end end - return r - end - def patch(endpoint, payload: nil, params: {}, files: nil) - r = @faraday.patch do |req| - req.url endpoint - req.params = params - req.headers = headers.merge({ 'Content-Type': 'application/json' }) - req.body = payload.to_json + def client_credentials_token?(token) + token.is_a?(Hash) && token['grant_type'] == CLIENT_CREDENTIALS_GRANT end - if @debug_mode - puts r.status, r.body - end - if r.status >= 400 - raise "HTTP status #{r.status}: -headers: #{r.headers} + def exchange_client_credentials + token = post(TOKEN_ENDPOINT, payload: { grant_type: CLIENT_CREDENTIALS_GRANT }).body + access_token = token['access_token'] if token.is_a?(Hash) + unless access_token.is_a?(String) && !access_token.empty? + raise 'Malformed OAuth response: missing access token' + end -body: #{r.body}" + expires_in = Float(token['expires_in'], exception: false) + token = token.merge('grant_type' => CLIENT_CREDENTIALS_GRANT) + token['expires_at'] = Time.now.to_f + expires_in if expires_in&.finite? + self.token = token end - return r - end - def delete(endpoint, params = {}) - r = @faraday.delete do |req| - req.url endpoint - req.params = params - req.headers = headers + def refresh_interval(token) + if client_credentials_token?(token) + expires_at = Float(token['expires_at'], exception: false) + if expires_at&.finite? + remaining = expires_at - Time.now.to_f + return [remaining - [remaining / 2, 120].min, 1].max + end + elsif !token['refresh_token'].to_s.empty? + return token['expires_in'] - 120 + end end - if @debug_mode - puts r.status, r.body + + def current_app_token + expires_at = Float(@token['expires_at'], exception: false) + expires_in = Float(@token['expires_in'], exception: false) + lead_time = expires_in&.positive? ? [expires_in / 2, 60].min : 0 + if @rejected_app_token.equal?(@token) || @token['access_token'].to_s.empty? || + (expires_at && expires_at <= Time.now.to_f + lead_time) + refresh + end + @token end - if r.status >= 400 - raise "HTTP status #{r.status}: -headers: #{r.headers} + def request(endpoint, retry_unauthorized: true) + token, renew_app_token = @authorization_lock.synchronize do + token = endpoint == TOKEN_ENDPOINT ? nil : @token + renew = client_credentials_token?(token) && same_origin?(endpoint) + [renew ? current_app_token : token, renew] + end + response = yield token -body: #{r.body}" + if renew_app_token && response.status == 401 + retry_token = @authorization_lock.synchronize do + if client_credentials_token?(@token) + @rejected_app_token = token if @token.equal?(token) + current_app_token if retry_unauthorized + end + end + response = yield retry_token if retry_token + end + + puts response.status, response.body if @debug_mode + if response.status >= 400 + raise "HTTP status #{response.status}: \n\nheaders: #{response.headers}\n\nbody: #{response.body}" + end + response end - return r - end - private + def same_origin?(endpoint) + url = @faraday.build_url(endpoint) + origin = @faraday.url_prefix + url.scheme == origin.scheme && url.host&.casecmp?(origin.host) && url.port == origin.port + end def user_authorization_payload(username: nil, extension: nil, password: nil, auth_code: nil, redirect_uri: nil, jwt: nil, verifier: nil) if auth_code != nil @@ -235,14 +275,10 @@ def basic_key Base64.encode64("#{@client_id}:#{@client_secret}").gsub(/\s/, '') end - def autorization_header - @token != nil ? "Bearer #{@token['access_token']}" : "Basic #{basic_key}" - end - - def headers + def headers(token) user_agent_header = "ringcentral/ringcentral-ruby Ruby #{RUBY_VERSION} #{RUBY_PLATFORM}" { - 'Authorization': autorization_header, + 'Authorization': token ? "Bearer #{token['access_token']}" : "Basic #{basic_key}", 'X-User-Agent': user_agent_header, } end diff --git a/spec/authorization_spec.rb b/spec/authorization_spec.rb index c041dd5..2f8c683 100644 --- a/spec/authorization_spec.rb +++ b/spec/authorization_spec.rb @@ -2,7 +2,9 @@ let(:client) { RingCentral.new('client-id', 'client-secret') } let(:stubs) { Faraday::Adapter::Test::Stubs.new } let(:token_path) { '/restapi/oauth/token' } + let(:account_path) { '/restapi/v2/accounts/~' } let(:json_headers) { { 'Content-Type' => 'application/json' } } + let(:basic_headers) { { 'Authorization' => "Basic #{Base64.strict_encode64('client-id:client-secret')}" } } before do client.instance_variable_get(:@faraday).adapter :test, stubs @@ -18,30 +20,106 @@ expect(request.body).to eq('grant_type=client_credentials') [200, json_headers, '{"access_token":"app-token","expires_in":3600}'] end - stubs.get('/restapi/v2/accounts/~', { 'Authorization' => 'Bearer app-token' }) do + stubs.get(account_path, { 'Authorization' => 'Bearer app-token' }) do [200, json_headers, '{"id":"account-id"}'] end - expect(client.authorize).to eq('access_token' => 'app-token', 'expires_in' => 3600) - expect(client.token).to eq('access_token' => 'app-token', 'expires_in' => 3600) - expect(client.get('/restapi/v2/accounts/~').body).to eq('id' => 'account-id') + expect(client.authorize).to eq(client.token) + expect(client.token).to include('access_token' => 'app-token', 'expires_in' => 3600, + 'grant_type' => 'client_credentials', 'expires_at' => be_within(1).of(Time.now.to_f + 3600)) + expect(client.token).not_to have_key('refresh_token') + expect(client.get(account_path).body).to eq('id' => 'account-id') end - it 'keeps a token without a refresh token and allows authorization again' do - client.auto_refresh = true - expect(Concurrent::TimerTask).not_to receive(:new) - stubs.post(token_path, 'grant_type=client_credentials') do + it 'renews an app token with client credentials when refresh is called' do + stubs.post(token_path, 'grant_type=client_credentials', basic_headers) do [200, json_headers, '{"access_token":"first-token","expires_in":3600}'] end + stubs.post(token_path, 'grant_type=client_credentials', basic_headers) do + [200, json_headers, '{"access_token":"second-token","expires_in":3600}'] + end - client.authorize - expect(client.refresh).to be_nil - expect(client.token['access_token']).to eq('first-token') + expect(client.authorize['access_token']).to eq('first-token') + expect(client.refresh['access_token']).to eq('second-token') + expect(client.token).not_to have_key('refresh_token') + end - stubs.post(token_path, 'grant_type=client_credentials') do - [200, json_headers, '{"access_token":"second-token","expires_in":3600}'] + it 'renews a restored app token once for concurrent requests near expiry' do + client.token = { 'access_token' => 'old-token', 'grant_type' => 'client_credentials', + 'expires_in' => 3600, 'expires_at' => Time.now.to_f + 30 } + renewals = 0 + stubs.post(token_path, 'grant_type=client_credentials', basic_headers) do + renewals += 1 + [200, json_headers, '{"access_token":"renewed-token","expires_in":3600}'] + end + stubs.get(account_path, { 'Authorization' => 'Bearer renewed-token' }) do + [200, json_headers, '{"id":"account-id"}'] end - expect(client.authorize['access_token']).to eq('second-token') + + requests = Array.new(2) { Thread.new { client.get(account_path).body } } + expect(requests.map(&:value)).to eq([{ 'id' => 'account-id' }] * 2) + expect(renewals).to eq(1) + end + + it 'renews and retries a request once when an app token is rejected' do + client.token = { 'access_token' => 'old-token', 'grant_type' => 'client_credentials' } + stubs.get(account_path, { 'Authorization' => 'Bearer old-token' }) do + [401, json_headers, '{"message":"Access token expired"}'] + end + stubs.post(token_path, 'grant_type=client_credentials', basic_headers) do + [200, json_headers, '{"access_token":"renewed-token","expires_in":3600}'] + end + stubs.get(account_path, { 'Authorization' => 'Bearer renewed-token' }) do + [200, json_headers, '{"id":"account-id"}'] + end + + expect(client.get(account_path).body).to eq('id' => 'account-id') + end + + it 'reports a failed exchange and can renew on the next request' do + client.token = { 'access_token' => 'old-token', 'grant_type' => 'client_credentials', 'expires_at' => 0 } + stubs.post(token_path, 'grant_type=client_credentials', basic_headers) do + [401, json_headers, '{"error":"invalid_client"}'] + end + stubs.post(token_path, 'grant_type=client_credentials', basic_headers) do + [200, json_headers, '{"access_token":"renewed-token","expires_in":3600}'] + end + stubs.get(account_path, { 'Authorization' => 'Bearer renewed-token' }) do + [200, json_headers, '{"id":"account-id"}'] + end + + expect { client.get(account_path) }.to raise_error(/HTTP status 401/) + expect(client.get(account_path).body).to eq('id' => 'account-id') + end + + it 'schedules renewal in the background for an app token with a short lifetime' do + client.auto_refresh = true + scheduled_refreshes = [] + timer = instance_double(Concurrent::TimerTask, execute: nil, shutdown: nil) + expect(Concurrent::TimerTask).to receive(:new).with(execution_interval: be_within(1).of(30), timeout_interval: 60) + .twice do |**_options, &task| + scheduled_refreshes << task + timer + end + expect(timer).to receive(:execute).twice + expect(timer).to receive(:shutdown).once + stubs.post(token_path, 'grant_type=client_credentials', basic_headers) do + [200, json_headers, '{"access_token":"app-token","expires_in":60}'] + end + stubs.post(token_path, 'grant_type=client_credentials', basic_headers) do + [200, json_headers, '{"access_token":"renewed-token","expires_in":60}'] + end + + client.authorize + scheduled_refreshes.first.call + expect(client.token['access_token']).to eq('renewed-token') + end + + it 'leaves an externally supplied access token without grant metadata alone' do + client.auto_refresh = true + client.token = { 'access_token' => 'external-token', 'expires_in' => 3600 } + expect(client.refresh).to be_nil + expect(client.token['access_token']).to eq('external-token') end it 'requires both application credentials before making a request' do @@ -97,6 +175,7 @@ end it 'refreshes and revokes a JWT token while managing its automatic refresh timer' do + client.token = { 'access_token' => 'app-token', 'grant_type' => 'client_credentials' } client.auto_refresh = true login_timer = instance_double(Concurrent::TimerTask) refresh_timer = instance_double(Concurrent::TimerTask) @@ -109,7 +188,6 @@ expect(refresh_timer).to receive(:execute).ordered expect(refresh_timer).to receive(:shutdown).ordered - basic_headers = { 'Authorization' => "Basic #{Base64.strict_encode64('client-id:client-secret')}" } stubs.post(token_path, nil, basic_headers) do |request| expect(URI.decode_www_form(request.body).to_h).to eq( 'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer', 'assertion' => 'test-jwt'