Skip to content
Open
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
29 changes: 24 additions & 5 deletions ably/pubsub/http/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,7 @@ async def request_token(self, token_params: dict | None = None,
auth_headers = auth_headers or self.auth_options.auth_headers or {}

log.debug(f"Token Params: {token_params}")
signed_with_key = False
if auth_callback:
log.debug("using token auth with authCallback")
try:
Expand All @@ -239,6 +240,7 @@ async def request_token(self, token_params: dict | None = None,
token_request = await self.create_token_request(
token_params, key_name=key_name, key_secret=key_secret,
query_time=query_time)
signed_with_key = True
else:
msg = "Need a new token but auth_options does not include a way to request one"
log.exception(msg)
Expand All @@ -263,11 +265,28 @@ async def request_token(self, token_params: dict | None = None,

token_path = f"/keys/{token_request.key_name}/requestToken"

response = await self.ably.http.post(
token_path,
body=token_request.to_dict(),
skip_auth=True
)
try:
response = await self.ably.http.post(
token_path,
body=token_request.to_dict(),
skip_auth=True
)
except AblyException as e:
# A fallback host retry sends the same body again. When the server used the
# nonce on an attempt whose response was lost, it rejects the retry as a
# replay (40105). Sign a new token request with a new nonce and send it once more.
if not (signed_with_key and e.code == 40105
and token_params.get('nonce') is None and token_params.get('mac') is None):
raise
log.debug("Token request nonce was replayed, sending a new token request")
token_request = await self.create_token_request(
token_params, key_name=key_name, key_secret=key_secret,
query_time=query_time)
response = await self.ably.http.post(
token_path,
body=token_request.to_dict(),
skip_auth=True
)

AblyException.raise_for_response(response)
response_dict = response.to_native()
Expand Down
57 changes: 57 additions & 0 deletions test/unit/token_request_nonce_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import json

import pytest

from ably.pubsub.util.exceptions import AblyException
from test.uts.helpers.client import rest_client
from test.uts.helpers.mock_http import MockHttpClient

KEY = 'appId.keyId:keySecret'
REPLAYED_BODY = {'error': {'code': 40105, 'statusCode': 401, 'message': 'Nonce value replayed'}}
TOKEN_BODY = {'token': 'obtained-token', 'expires': 9999999999999, 'keyName': 'appId.keyId'}


def nonce_server():
"""A requestToken endpoint that uses each nonce one time only and loses the first response."""
used_nonces = []

def on_request(request):
nonce = json.loads(request.body)['nonce']
if nonce in used_nonces:
request.respond_with(401, REPLAYED_BODY)
return
used_nonces.append(nonce)
if len(used_nonces) == 1:
# The server used the nonce, but the response does not reach the client
request.respond_with_timeout()
else:
request.respond_with(200, TOKEN_BODY)

mock_http = MockHttpClient(
on_connection_attempt=lambda conn: conn.respond_with_success(),
on_request=on_request,
)
return mock_http, used_nonces


async def test_request_token_signs_a_new_nonce_after_a_replayed_retry():
mock_http, used_nonces = nonce_server()
client = rest_client(mock_http, key=KEY, use_binary_protocol=False,
fallback_hosts=['a.example.com', 'b.example.com'])

token_details = await client.auth.request_token()

assert token_details.token == 'obtained-token'
assert len(used_nonces) == 2


async def test_request_token_keeps_a_nonce_the_caller_gives():
mock_http, used_nonces = nonce_server()
client = rest_client(mock_http, key=KEY, use_binary_protocol=False,
fallback_hosts=['a.example.com', 'b.example.com'])

with pytest.raises(AblyException) as excinfo:
await client.auth.request_token({'nonce': 'fixed-nonce-value'})

assert excinfo.value.code == 40105
assert used_nonces == ['fixed-nonce-value']