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
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ __[Voice](https://developer.ringcentral.com/api-products/voice), [SMS/MMS](https

## Important change logs

### 1.0.0
### 1.0.1

- The SDK requires CPython 3.11 or later. CI tests CPython 3.11 through 3.15.
- WebSocket subscriptions match server responses to requests, report changes after the server confirms them, and prevent duplicate subscription creation.
Expand Down Expand Up @@ -75,7 +75,8 @@ change the current session.
### Client credentials

For an app configured for the OAuth client credentials grant, call `login()` with
no arguments. Call `login()` again when the access token expires.
no arguments. The SDK exchanges the client ID and secret for a fresh access token
when a request needs one. Call `platform.refresh()` to renew the token explicitly.

```py
from ringcentral import SDK
Expand Down
48 changes: 41 additions & 7 deletions api_test/_oauth_smoke.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
import json
import os
from argparse import ArgumentParser

from dotenv import load_dotenv

from ringcentral.http.api_exception import ApiException
from ringcentral.platform.events import Events


ACCOUNT_PATH = '/restapi/v2/accounts/~'


def load_user_config(*extra_required):
Expand All @@ -16,23 +21,52 @@ def load_user_config(*extra_required):
return values


def run_smoke(platform, flow, login):
def renewal_requested():
parser = ArgumentParser()
parser.add_argument('--test-renewal', action='store_true', help='Simulate access token expiry and verify renewal.')
return parser.parse_args().test_renewal


def run_smoke(platform, flow, login, *, test_renewal=False, requires_refresh_token=True):
operation = f'{flow} login'
try:
login()
operation = 'Account lookup'
response = platform.get('/restapi/v2/accounts/~')
response = platform.get(ACCOUNT_PATH)
account = response.json_dict()
if not isinstance(account, dict) or not account.get('id'):
raise SystemExit('The account response did not contain an account ID.')

status = response.response().status_code
print(f'{flow} login succeeded. Account lookup returned HTTP {status}.')
print(json.dumps(account, indent=2))

if test_renewal:
operation = f'{flow} token renewal'
verify_token_renewal(platform, flow, account['id'], requires_refresh_token)
except ApiException as error:
http_response = error.api_response().response()
status = f' (HTTP {http_response.status_code})' if http_response is not None else ''
raise SystemExit(f'{operation} failed{status}.') from None
except Exception as error:
raise SystemExit(f'{operation} failed ({type(error).__name__}).') from None

if not isinstance(account, dict) or not account.get('id'):
raise SystemExit('The account response did not contain an account ID.')

status = response.response().status_code
print(f'{flow} login succeeded. Account lookup returned HTTP {status}.')
print(json.dumps(account, indent=2))
def verify_token_renewal(platform, flow, account_id, requires_refresh_token):
auth = platform.auth()
if requires_refresh_token and not auth.refresh_token_valid():
raise SystemExit(f'The {flow} login must return a valid refresh token to test renewal.')

renewals = []
on_refresh = renewals.append
platform.on(Events.refreshSuccess, on_refresh)
try:
auth.set_data({'expire_time': 0})
response = platform.get(ACCOUNT_PATH)
account = response.json_dict()
finally:
platform.off(Events.refreshSuccess, on_refresh)

if len(renewals) != 1 or not isinstance(account, dict) or account.get('id') != account_id:
raise SystemExit('Expected one token renewal and the same account after simulating expiry.')
print(f'HTTP {response.response().status_code}. Automatic {flow} renewal succeeded.')
5 changes: 3 additions & 2 deletions api_test/auth_code_smoke.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

from ringcentral import SDK

from ._oauth_smoke import load_user_config, run_smoke
from ._oauth_smoke import load_user_config, renewal_requested, run_smoke


DEFAULT_REDIRECT_URI = 'http://localhost:5000/oauth2callback'
Expand Down Expand Up @@ -81,6 +81,7 @@ def log_message(self, format, *args):


def main():
test_renewal = renewal_requested()
server, client_id, client_secret = load_user_config()
redirect_uri = os.getenv('RC_REDIRECT_URI') or DEFAULT_REDIRECT_URI
platform = SDK(client_id, client_secret, server, redirect_uri=redirect_uri).platform()
Expand All @@ -91,7 +92,7 @@ def login():
code = get_authorization_code(platform, redirect_uri, challenge)
platform.login(code=code, verifier=verifier)

run_smoke(platform, 'Authorization-code', login)
run_smoke(platform, 'Authorization-code', login, test_renewal=test_renewal)


if __name__ == '__main__':
Expand Down
5 changes: 3 additions & 2 deletions api_test/client_credentials_smoke.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,11 @@

from ringcentral import SDK

from ._oauth_smoke import run_smoke
from ._oauth_smoke import renewal_requested, run_smoke


def main():
test_renewal = renewal_requested()
load_dotenv()
server = os.getenv('RINGCENTRAL_SERVER_URL')
client_id = os.getenv('RINGCENTRAL_CLIENT_ID')
Expand All @@ -19,7 +20,7 @@ def main():
)

platform = SDK(client_id, client_secret, server).platform()
run_smoke(platform, 'Client credentials', platform.login)
run_smoke(platform, 'Client credentials', platform.login, test_renewal=test_renewal, requires_refresh_token=False)


if __name__ == '__main__':
Expand Down
5 changes: 3 additions & 2 deletions api_test/jwt_smoke.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
from ringcentral import SDK

from ._oauth_smoke import load_user_config, run_smoke
from ._oauth_smoke import load_user_config, renewal_requested, run_smoke


def main():
test_renewal = renewal_requested()
server, client_id, client_secret, jwt = load_user_config('RC_JWT')
platform = SDK(client_id, client_secret, server).platform()
run_smoke(platform, 'JWT', lambda: platform.login(jwt=jwt))
run_smoke(platform, 'JWT', lambda: platform.login(jwt=jwt), test_renewal=test_renewal)


if __name__ == '__main__':
Expand Down
11 changes: 10 additions & 1 deletion dev-notes.md
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,15 @@ in your shell.
uv run --locked python -m api_test.client_credentials_smoke
```

Add `--test-renewal` to any OAuth smoke command to simulate local access token
expiry and verify that one automatic renewal succeeds and returns the same account.
Client credentials renew through a fresh exchange. JWT and authorization-code
renewal require a valid refresh token from the initial login.

```
uv run --locked python -m api_test.client_credentials_smoke --test-renewal
```

### JWT and authorization code

These tests use the same environment variables as the JavaScript SDK smoke tests.
Expand Down Expand Up @@ -289,7 +298,7 @@ version below, run the release tests, build both artifacts into a fresh director
and check both artifacts with strict Twine validation and the shared verifier.

```sh
release_version=1.0.0
release_version=1.0.1
release_commit=$(git rev-parse HEAD) &&
release_dist=$(mktemp -d) &&
uv sync --locked --python 3.15 &&
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"

[project]
name = "ringcentral"
version = "1.0.0"
version = "1.0.1"
description = "RingCentral Python SDK"
readme = "README.md"
authors = [{ name = "Kirill Konshin" }]
Expand Down
37 changes: 20 additions & 17 deletions ringcentral/platform/auth.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,16 @@
from time import time

RELEASE_TIMEOUT = 10
CLIENT_CREDENTIALS = 'client_credentials'
APP_TOKEN_RENEWAL_WINDOW = 60


class Auth:
def __init__(self):
self.reset()

def reset(self):
self.__grant_type = None
self.__remember = False

self.__token_type = ''
Expand All @@ -25,6 +31,9 @@ def set_data(self, auth_data=None):
if auth_data is None:
return self

if 'grant_type' in auth_data or ('access_token' in auth_data and auth_data.get('access_token')):
self.__grant_type = auth_data.get('grant_type')

# Misc

if 'remember' in auth_data:
Expand Down Expand Up @@ -68,7 +77,7 @@ def set_data(self, auth_data=None):
return self

def data(self):
return {
auth_data = {
'remember': self.__remember,
'token_type': self.__token_type,

Expand All @@ -84,21 +93,12 @@ def data(self):
'owner_id': self.__owner_id
}

def reset(self):
self.__remember = False
if self.__grant_type == CLIENT_CREDENTIALS:
auth_data['grant_type'] = self.__grant_type
return auth_data

self.__token_type = ''

self.__access_token = ''
self.__expires_in = 0
self.__expire_time = 0

self.__refresh_token = ''
self.__refresh_token_expires_in = 0
self.__refresh_token_expire_time = 0

self.__scope = ''
self.__owner_id = ''
def grant_type(self):
return self.__grant_type

def access_token(self):
return self.__access_token
Expand All @@ -110,10 +110,13 @@ def token_type(self):
return self.__token_type

def access_token_valid(self):
return self.__is_token_date_valid(self.data().get('expire_time'))
if self.__grant_type == CLIENT_CREDENTIALS:
renewal_window = min(APP_TOKEN_RENEWAL_WINDOW, (self.__expires_in or 0) / 2)
return bool(self.__access_token) and self.__expire_time > time() + renewal_window
return self.__is_token_date_valid(self.__expire_time)

def refresh_token_valid(self):
return self.__is_token_date_valid(self.data().get('refresh_token_expire_time'))
return self.__is_token_date_valid(self.__refresh_token_expire_time)

@staticmethod
def __is_token_date_valid(token_date):
Expand Down
Loading