Skip to content

Commit

Permalink
Fix bug and improve hashing error handling
Browse files Browse the repository at this point in the history
Prevent returning an un-awaited coroutine when getting code 400 with
multiple hash keys, check that the response on 400s is 'Unauthorized'
before concluding that the key is expired, move on to the next
iteration if receiving code 400 on the first attempt with multiple
keys, include response message in 400 responses that don't say
Unauthorized, trim hash keys to 10 characters in logs and
exceptions to prevent theft.
  • Loading branch information
Noctem committed Apr 19, 2017
1 parent 5be65bc commit c1b4b2c
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 18 deletions.
2 changes: 1 addition & 1 deletion aiopogo/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
__title__ = 'aiopogo'
__version__ = '1.8.0'
__version__ = '1.8.1'
__author__ = 'David Christenson'
__license__ = 'MIT License'
__copyright__ = 'Copyright (c) 2017 David Christenson <https://github.com/Noctem>'
Expand Down
39 changes: 23 additions & 16 deletions aiopogo/hash_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from aiohttp import ClientSession, ClientError, ClientResponseError, ServerConnectionError, ServerTimeoutError

from . import json_dumps, json_loads
from .exceptions import ExpiredHashKeyException, HashingOfflineException, HashingTimeoutException, MalformedHashResponseException, NoHashKeyException, TempHashingBanException, TimeoutException, UnexpectedHashResponseException
from .exceptions import BadHashRequestException, ExpiredHashKeyException, HashingOfflineException, HashingTimeoutException, MalformedHashResponseException, NoHashKeyException, TempHashingBanException, TimeoutException, UnexpectedHashResponseException
from .connector import TimedConnector
from .utilities import f2i

Expand Down Expand Up @@ -58,31 +58,38 @@ async def hash(self, timestamp, latitude, longitude, accuracy, authticket, sessi
for attempt in range(2):
try:
async with self._session.post("http://pokehash.buddyauth.com/api/v131_0/hash", headers=headers, json=payload) as resp:
try:
response = await resp.json(encoding='ascii', loads=json_loads)
except ValueError as e:
raise MalformedHashResponseException('Unable to parse JSON from hash server.') from e
if 400 <= resp.status:
if resp.status == 400:
response = await resp.text()
if response == 'Unauthorized':
if self.multi:
self.log.warning('{:.10}... expired, removing from rotation.'.format(self.instance_token))
self.remove_token(self.instance_token)
if attempt < 1:
self.instance_token = self.auth_token
headers = {'X-AuthToken': self.instance_token}
continue
return await self.hash(timestamp, latitude, longitude, accuracy, authticket, sessiondata, requests)
raise ExpiredHashKeyException("{:.10}... appears to have expired.".format(self.instance_token))
raise BadHashRequestException('400 was returned from the hashing server with the message: {}'.format(response))
raise ClientResponseError(code=resp.status, message=resp.reason)

response = await resp.json(encoding='ascii', loads=json_loads)
headers = resp.headers
break
except ClientResponseError as e:
if e.code == 400:
if self.multi:
self.log.warning('{} expired, removing from rotation.'.format(self.instance_token))
self.remove_token(self.instance_token)
self.instance_token = self.auth_token
return self.hash(timestamp, latitude, longitude, accuracy, authticket, sessiondata, requests)
text = await resp.text()
raise ExpiredHashKeyException("Hash key appears to have expired. {}".format(text))
elif e.code == 403:
if e.code == 403:
raise TempHashingBanException('Your IP was temporarily banned for sending too many requests with invalid keys')
elif e.code == 429:
status['remaining'] = 0
self.instance_token = self.auth_token
return self.hash(timestamp, latitude, longitude, accuracy, authticket, sessiondata, requests)
elif e.code >= 500:
elif e.code >= 500 or e.code == 404:
raise HashingOfflineException('Hashing server error {}: {}'.format(e.code, e.message))
else:
raise UnexpectedHashResponseException('Unexpected hash code {}: {}'.format(e.code, e.message))
except ValueError as e:
raise MalformedHashResponseException('Unable to parse JSON from hash server.') from e
except (TimeoutError, ServerConnectionError, ServerTimeoutError) as e:
if attempt < 1:
self.log.info('Hashing request timed out.')
Expand Down Expand Up @@ -135,7 +142,7 @@ def activate_session(cls, conn_limit=300):
cls._session = ClientSession(connector=conn,
loop=cls.loop,
headers=headers,
raise_for_status=True,
raise_for_status=False,
conn_timeout=4.5,
json_serialize=json_dumps)

Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
author='David Christenson',
author_email='mail@noctem.xyz',
description='Asynchronous Pokemon API lib',
version='1.8.0',
version='1.8.1',
url='https://github.com/Noctem/aiopogo',
packages=find_packages(),
install_requires=[
Expand Down

0 comments on commit c1b4b2c

Please sign in to comment.