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
16 changes: 12 additions & 4 deletions scrapinghub/client/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import json
import logging
import binascii
import warnings
from codecs import decode

import six
Expand Down Expand Up @@ -101,10 +102,17 @@ def parse_auth(auth):
"""
if auth is None:
apikey = os.environ.get('SH_APIKEY')
if apikey is None:
raise RuntimeError("No API key provided and SH_APIKEY "
"environment variable not set")
return (apikey, '')
if apikey:
return (apikey, '')

jobauth = os.environ.get('SHUB_JOBAUTH')
if jobauth:
warnings.warn("You are using the SHUB_JOBAUTH environment "
"variable which may not work for some API endpoints")
return _search_for_jwt_credentials(jobauth)

raise RuntimeError("No API key provided and neither SH_APIKEY "
"nor SHUB_JOBAUTH environment variables is set")

if isinstance(auth, tuple):
all_strings = all(isinstance(k, six.string_types) for k in auth)
Expand Down
27 changes: 27 additions & 0 deletions tests/client/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@ def test_parse_auth_none_with_env():
assert parse_auth(None) == ('testkey', '')


@mock.patch.dict(os.environ, {'SH_APIKEY': 'testkey', 'SHUB_JOBAUTH': 'jwt'})
def test_parse_auth_none_with_multiple_env():
assert parse_auth(None) == ('testkey', '')


def test_parse_auth_tuple():
assert parse_auth(('test', 'test')) == ('test', 'test')
assert parse_auth(('apikey', '')) == ('apikey', '')
Expand Down Expand Up @@ -52,6 +57,28 @@ def test_parse_auth_jwt_token():
assert parse_auth(encoded_token) == (test_job, test_token)


def test_parse_auth_jwt_token_with_jwt_token_env():
dummy_test_job, dummy_test_token = '1/2/3', 'some.dummy.jwt.token'
raw_token = (dummy_test_job + ':' + dummy_test_token).encode('utf8')
dummy_encoded_token = encode(raw_token, 'hex_codec').decode('ascii')

test_job, test_token = '1/2/3', 'some.jwt.token'
raw_token = (test_job + ':' + test_token).encode('utf8')
encoded_token = encode(raw_token, 'hex_codec').decode('ascii')

with mock.patch.dict(os.environ, {'SHUB_JOBAUTH': dummy_encoded_token}):
assert parse_auth(encoded_token) == (test_job, test_token)


def test_parse_auth_none_with_jwt_token_env():
test_job, test_token = '1/2/3', 'some.jwt.token'
raw_token = (test_job + ':' + test_token).encode('utf8')
encoded_token = encode(raw_token, 'hex_codec').decode('ascii')

with mock.patch.dict(os.environ, {'SHUB_JOBAUTH': encoded_token}):
assert parse_auth(None) == (test_job, test_token)


def test_parse_job_key():
job_key = parse_job_key('123/10/11')
assert job_key.project_id == '123'
Expand Down