Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 0 additions & 6 deletions .env.sample

This file was deleted.

1 change: 1 addition & 0 deletions Gemfile
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,5 @@ group :test do
gem 'dotenv'
gem 'rspec'
gem 'simplecov'
gem 'webrick'
end
3 changes: 3 additions & 0 deletions Gemfile.lock
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -63,6 +65,7 @@ DEPENDENCIES
faye-websocket (= 0.12.0)
rspec
simplecov
webrick

BUNDLED WITH
4.0.24
50 changes: 50 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down
81 changes: 81 additions & 0 deletions api_test/auth_code_smoke.rb
Original file line number Diff line number Diff line change
@@ -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
5 changes: 5 additions & 0 deletions api_test/client_credentials_smoke.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
require_relative 'oauth_smoke'

OAuthSmoke.run('Client credentials', *OAuthSmoke.load_config) do |client|
client.authorize
end
7 changes: 7 additions & 0 deletions api_test/jwt_smoke.rb
Original file line number Diff line number Diff line change
@@ -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
39 changes: 39 additions & 0 deletions api_test/oauth_smoke.rb
Original file line number Diff line number Diff line change
@@ -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
74 changes: 48 additions & 26 deletions lib/ringcentral.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down
Loading