diff --git a/.env.sample b/.env.sample deleted file mode 100644 index 49109e8..0000000 --- a/.env.sample +++ /dev/null @@ -1,6 +0,0 @@ -RINGCENTRAL_SERVER_URL=https://platform.ringcentral.com -RINGCENTRAL_CLIENT_ID= -RINGCENTRAL_CLIENT_SECRET= -RINGCENTRAL_JWT_TOKEN= -RINGCENTRAL_RECEIVER= -RINGCENTRAL_SENDER= diff --git a/Gemfile b/Gemfile index 5f087a0..2b9f81d 100644 --- a/Gemfile +++ b/Gemfile @@ -10,4 +10,5 @@ group :test do gem 'dotenv' gem 'rspec' gem 'simplecov' + gem 'webrick' end diff --git a/Gemfile.lock b/Gemfile.lock index e81bfae..d776bab 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -44,12 +44,14 @@ GEM simplecov (1.3.2) timeout (0.6.1) uri (1.1.2) + webrick (1.9.2) websocket-driver (0.8.2) base64 websocket-extensions (>= 0.1.0) websocket-extensions (0.1.5) PLATFORMS + arm64-darwin-24 arm64-darwin-25 x86_64-darwin-20 x86_64-darwin-22 @@ -63,6 +65,7 @@ DEPENDENCIES faye-websocket (= 0.12.0) rspec simplecov + webrick BUNDLED WITH 4.0.24 diff --git a/README.md b/README.md index e655de0..4e81b6d 100644 --- a/README.md +++ b/README.md @@ -83,6 +83,22 @@ expect(r).not_to be_nil expect('101').to eq(r.body['extensionNumber']) ``` +### Client credentials + +For an app configured for the OAuth client credentials grant, initialize the SDK +with the app's client ID and secret, then call `authorize` without arguments. + +```ruby +require 'ringcentral' + +rc = RingCentral.new(ENV.fetch('RINGCENTRAL_CLIENT_ID'), ENV.fetch('RINGCENTRAL_CLIENT_SECRET')) +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. + ## Samples For more code samples, please refer to the test cases in `spec` folder. @@ -261,6 +277,40 @@ bundle exec rspec spec/ringcentral_spec.rb:15 Coverage is written to `coverage/index.html` for both full and selected runs. A selected run measures only the SDK code exercised by those examples. +### OAuth smoke tests + +Set `RINGCENTRAL_SERVER_URL`, `RINGCENTRAL_CLIENT_ID`, and +`RINGCENTRAL_CLIENT_SECRET` in `.env` or export them in your shell. Use an app +configured for the grant you are testing. Each smoke test requests an access +token, verifies that `GET /restapi/v2/accounts/~` returns an account ID, and +prints the account response as formatted JSON. + +**Client credentials** + +```sh +bundle exec ruby api_test/client_credentials_smoke.rb +``` + +**JWT** + +Also set `RINGCENTRAL_JWT_TOKEN` to the JWT for the test extension. + +```sh +bundle exec ruby api_test/jwt_smoke.rb +``` + +**Authorization code** + +Register `http://localhost:5000/oauth2callback` as an app redirect URI, or set +`RINGCENTRAL_REDIRECT_URI` to another registered HTTP loopback URL with an +explicit port. Open the printed URL in your browser and approve the request +within five minutes. The smoke test checks the callback state and exchanges +the code using PKCE. + +```sh +bundle exec ruby api_test/auth_code_smoke.rb +``` + ### 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 new file mode 100644 index 0000000..a97c876 --- /dev/null +++ b/api_test/auth_code_smoke.rb @@ -0,0 +1,81 @@ +require 'digest' +require 'securerandom' +require 'uri' +require 'webrick' +require_relative 'oauth_smoke' + +DEFAULT_REDIRECT_URI = 'http://localhost:5000/oauth2callback' + +def loopback_callback(redirect_uri) + callback = Addressable::URI.parse(redirect_uri) + return callback if callback.scheme == 'http' && %w[localhost 127.0.0.1].include?(callback.host) && + (1..65_535).cover?(callback.port) && !callback.userinfo && !callback.query && !callback.fragment +rescue Addressable::URI::InvalidURIError + nil +end + +def wait_for_authorization_code(client, callback, redirect_uri, verifier) + state = SecureRandom.urlsafe_base64(32) + challenge = Base64.urlsafe_encode64(Digest::SHA256.digest(verifier), padding: false) + login_url = client.authorize_uri(redirect_uri, state: state, code_challenge: challenge, code_challenge_method: 'S256') + callback_path = callback.path.empty? ? '/' : callback.path + results = Queue.new + + server = WEBrick::HTTPServer.new( + BindAddress: callback.host, Port: callback.port, RequestTimeout: 5, + AccessLog: [], Logger: WEBrick::Log.new(File::NULL), + StartCallback: lambda do + puts 'Open this URL in your browser and authorize the app.' + puts login_url + $stdout.flush + end + ) + server.mount_proc('/') do |request, response| + response['Content-Type'] = 'text/plain; charset=utf-8' + response['Cache-Control'] = 'no-store' + unless request.request_method == 'GET' && request.request_uri.path == callback_path + response.status = 404 + next + end + + params = URI.decode_www_form(request.query_string.to_s).group_by(&:first).transform_values { |pairs| pairs.map(&:last) } + unless params['state'] == [state] + response.status = 400 + response.body = 'OAuth state did not match. Use the URL printed in the terminal.' + next + end + + codes = params.fetch('code', []) + code = codes.first if !params.key?('error') && codes.one? && !codes.first.empty? + if code + response.body = 'Authorization received. Return to the terminal for the smoke test result.' + else + response.status = 400 + response.body = 'Authorization failed. See the terminal for the smoke test result.' + end + results << code + server.shutdown + end + + timer = Thread.new { sleep 300; server.shutdown } + server.start + abort 'Timed out waiting for the authorization callback.' if results.empty? + + results.pop || abort('The authorization callback did not return a usable authorization code.') +rescue SystemCallError, SocketError + abort "The authorization callback could not listen on #{callback.host}:#{callback.port}." +ensure + timer&.kill +end + +server, client_id, client_secret = OAuthSmoke.load_config +redirect_uri = ENV['RINGCENTRAL_REDIRECT_URI'] +redirect_uri = DEFAULT_REDIRECT_URI if redirect_uri.to_s.empty? +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| + 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) +end diff --git a/api_test/client_credentials_smoke.rb b/api_test/client_credentials_smoke.rb new file mode 100644 index 0000000..a95e5e0 --- /dev/null +++ b/api_test/client_credentials_smoke.rb @@ -0,0 +1,5 @@ +require_relative 'oauth_smoke' + +OAuthSmoke.run('Client credentials', *OAuthSmoke.load_config) do |client| + client.authorize +end diff --git a/api_test/jwt_smoke.rb b/api_test/jwt_smoke.rb new file mode 100644 index 0000000..c92ef05 --- /dev/null +++ b/api_test/jwt_smoke.rb @@ -0,0 +1,7 @@ +require_relative 'oauth_smoke' + +server, client_id, client_secret, jwt = OAuthSmoke.load_config('RINGCENTRAL_JWT_TOKEN') + +OAuthSmoke.run('JWT', server, client_id, client_secret) do |client| + client.authorize(jwt: jwt) +end diff --git a/api_test/oauth_smoke.rb b/api_test/oauth_smoke.rb new file mode 100644 index 0000000..b906771 --- /dev/null +++ b/api_test/oauth_smoke.rb @@ -0,0 +1,39 @@ +require 'dotenv' +require 'json' +require_relative '../lib/ringcentral' + +module OAuthSmoke + def self.load_config(*extra_required) + Dotenv.load(File.expand_path('../.env', __dir__), overwrite: true) + + required = %w[RINGCENTRAL_SERVER_URL RINGCENTRAL_CLIENT_ID RINGCENTRAL_CLIENT_SECRET] + extra_required + missing = required.select { |name| ENV[name].to_s.strip.empty? } + abort "Set #{missing.join(', ')} in .env or export them in your shell." unless missing.empty? + + ENV.values_at(*required) + end + + def self.run(flow, server, client_id, client_secret) + operation = "#{flow} authorization" + client = RingCentral.new(client_id, client_secret, server) + yield client + 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 + + operation = 'Account lookup' + 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})." + end +end diff --git a/lib/ringcentral.rb b/lib/ringcentral.rb index f188802..8a20b4a 100644 --- a/lib/ringcentral.rb +++ b/lib/ringcentral.rb @@ -35,46 +35,43 @@ def token=(value) @timer.shutdown @timer = nil end - if @auto_refresh && value != nil + 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 } @timer.execute end end - def authorize(username: nil, extension: nil, password: nil, auth_code: nil, redirect_uri: nil, jwt: nil, verifier: nil) - if auth_code != nil - payload = { - grant_type: 'authorization_code', - code: auth_code, - redirect_uri: redirect_uri, - } - if verifier != nil - payload["code_verifier"] = verifier + # Call without arguments to authorize using the client credentials grant. + # 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' end - elsif jwt != nil - payload = { - grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer', - assertion: jwt - } + payload = { grant_type: 'client_credentials' } else - warn('Password auth is deprecated. Use JWT auth or OAuth instead.') - payload = { - grant_type: 'password', - username: username, - extension: extension, - password: password, - } + payload = user_authorization_payload(**options) end self.token = nil - r = self.post('/restapi/oauth/token', payload: payload) - self.token = r.body + 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 - return if @token == nil + refresh_token = @token['refresh_token'] if @token + return if refresh_token.to_s.empty? + payload = { grant_type: 'refresh_token', - refresh_token: @token['refresh_token'] + refresh_token: refresh_token } self.token = nil r = self.post('/restapi/oauth/token', payload: payload) @@ -209,6 +206,31 @@ def delete(endpoint, params = {}) private + def user_authorization_payload(username: nil, extension: nil, password: nil, auth_code: nil, redirect_uri: nil, jwt: nil, verifier: nil) + if auth_code != nil + payload = { + grant_type: 'authorization_code', + code: auth_code, + redirect_uri: redirect_uri, + } + payload['code_verifier'] = verifier if verifier != nil + payload + elsif jwt != nil + { + grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer', + assertion: jwt + } + else + warn('Password auth is deprecated. Use JWT auth or OAuth instead.') + { + grant_type: 'password', + username: username, + extension: extension, + password: password, + } + end + end + def basic_key Base64.encode64("#{@client_id}:#{@client_secret}").gsub(/\s/, '') end diff --git a/spec/authorization_spec.rb b/spec/authorization_spec.rb new file mode 100644 index 0000000..c041dd5 --- /dev/null +++ b/spec/authorization_spec.rb @@ -0,0 +1,129 @@ +RSpec.describe RingCentral, 'OAuth authorization' do + let(:client) { RingCentral.new('client-id', 'client-secret') } + let(:stubs) { Faraday::Adapter::Test::Stubs.new } + let(:token_path) { '/restapi/oauth/token' } + let(:json_headers) { { 'Content-Type' => 'application/json' } } + + before do + client.instance_variable_get(:@faraday).adapter :test, stubs + end + + after { stubs.verify_stubbed_calls } + + it 'exchanges the app credentials and uses the new bearer token for account lookup' do + client.token = { 'access_token' => 'user-token', 'refresh_token' => 'user-refresh-token' } + stubs.post(token_path) do |request| + expect(request.request_headers['Authorization']).to eq("Basic #{Base64.strict_encode64('client-id:client-secret')}") + expect(request.request_headers['Content-Type']).to eq('application/x-www-form-urlencoded') + 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 + [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') + 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 + [200, json_headers, '{"access_token":"first-token","expires_in":3600}'] + end + + client.authorize + expect(client.refresh).to be_nil + expect(client.token['access_token']).to eq('first-token') + + stubs.post(token_path, 'grant_type=client_credentials') do + [200, json_headers, '{"access_token":"second-token","expires_in":3600}'] + end + expect(client.authorize['access_token']).to eq('second-token') + end + + it 'requires both application credentials before making a request' do + [RingCentral.new('', 'client-secret'), RingCentral.new('client-id', nil)].each do |unconfigured_client| + expect(unconfigured_client).not_to receive(:post) + expect { unconfigured_client.authorize }.to raise_error(ArgumentError, /requires a client ID and client secret/) + end + end + + it 'rejects a token response without an access token' do + stubs.post(token_path) { [200, json_headers, '{"expires_in":3600}'] } + + expect { client.authorize }.to raise_error('Malformed OAuth response: missing access token') + expect(client.token).to be_nil + end + + it 'keeps a supplied nil JWT on the legacy authorization path' do + stubs.post(token_path) do |request| + expect(request.body).to include('grant_type=password') + [400, json_headers, '{}'] + end + + expect do + expect { client.authorize(jwt: nil) }.to raise_error(/HTTP status 400/) + end.to output(/Password auth is deprecated/).to_stderr + end + + it 'continues to prefer an authorization code and send its PKCE verifier' do + stubs.post(token_path) do |request| + expect(URI.decode_www_form(request.body).to_h).to eq( + 'grant_type' => 'authorization_code', 'code' => 'auth-code', + 'redirect_uri' => 'https://example.com', 'code_verifier' => 'verifier' + ) + [200, json_headers, '{"access_token":"user-token","refresh_token":"user-refresh-token"}'] + end + + client.authorize(auth_code: 'auth-code', redirect_uri: 'https://example.com', verifier: 'verifier', jwt: 'unused-jwt') + expect(client.token['refresh_token']).to eq('user-refresh-token') + end + + it 'keeps explicit password authorization and its deprecation warning' do + stubs.post(token_path) do |request| + expect(URI.decode_www_form(request.body).to_h).to eq( + 'grant_type' => 'password', 'username' => 'test-user', 'extension' => '101', 'password' => 'test-password' + ) + [200, json_headers, '{"access_token":"user-token"}'] + end + + expect do + client.authorize(username: 'test-user', extension: '101', password: 'test-password') + end.to output(/Password auth is deprecated/).to_stderr + expect(client.token['access_token']).to eq('user-token') + end + + it 'refreshes and revokes a JWT token while managing its automatic refresh timer' do + client.auto_refresh = true + login_timer = instance_double(Concurrent::TimerTask) + refresh_timer = instance_double(Concurrent::TimerTask) + expect(Concurrent::TimerTask).to receive(:new).with(execution_interval: 3480, timeout_interval: 60) + .ordered.and_return(login_timer) + expect(login_timer).to receive(:execute).ordered + expect(login_timer).to receive(:shutdown).ordered + expect(Concurrent::TimerTask).to receive(:new).with(execution_interval: 1680, timeout_interval: 60) + .ordered.and_return(refresh_timer) + 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' + ) + [200, json_headers, '{"access_token":"initial-token","refresh_token":"initial-refresh-token","expires_in":3600}'] + end + stubs.post(token_path, 'grant_type=refresh_token&refresh_token=initial-refresh-token', basic_headers) do + [200, json_headers, '{"access_token":"refreshed-token","refresh_token":"new-refresh-token","expires_in":1800}'] + end + stubs.post('/restapi/oauth/revoke', 'token=refreshed-token', basic_headers) { [200, json_headers, '{}'] } + + expect(client.authorize(jwt: 'test-jwt')['access_token']).to eq('initial-token') + expect(client.refresh['access_token']).to eq('refreshed-token') + client.revoke + expect(client.token).to be_nil + end +end