Skip to content

Commit dd77597

Browse files
Fixed some tox/style/unittest issues
1 parent 5f2024d commit dd77597

File tree

4 files changed

+51
-81
lines changed

4 files changed

+51
-81
lines changed

.secrets.baseline

+2-2
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
"files": "^.secrets.baseline$",
44
"lines": null
55
},
6-
"generated_at": "2024-04-18T01:09:09Z",
6+
"generated_at": "2024-04-25T01:18:20Z",
77
"plugins_used": [
88
{
99
"name": "AWSKeyDetector"
@@ -554,7 +554,7 @@
554554
"hashed_secret": "a4c805a62a0387010cd172cfed6f6772eb92a5d6",
555555
"is_secret": false,
556556
"is_verified": false,
557-
"line_number": 76,
557+
"line_number": 81,
558558
"type": "Secret Keyword",
559559
"verified_result": null
560560
}

SoftLayer/API.py

+28-54
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,7 @@
66
:license: MIT, see LICENSE for more details.
77
"""
88
# pylint: disable=invalid-name
9-
import os
109
import time
11-
import warnings
1210

1311
import concurrent.futures as cf
1412
import json
@@ -148,7 +146,6 @@ def create_client_from_env(username=None,
148146

149147
def employee_client(username=None,
150148
access_token=None,
151-
password=None,
152149
endpoint_url=None,
153150
timeout=None,
154151
auth=None,
@@ -159,27 +156,22 @@ def employee_client(username=None,
159156
verify=False):
160157
"""Creates an INTERNAL SoftLayer API client using your environment.
161158
162-
Settings are loaded via keyword arguments, environemtal variables and
163-
config file.
159+
Settings are loaded via keyword arguments, environemtal variables and config file.
164160
165161
:param username: your user ID
166-
:param access_token: hash from SoftLayer_User_Employee::performExternalAuthentication(username, password, 2fa_string)
162+
:param access_token: hash from SoftLayer_User_Employee::performExternalAuthentication(username, password, token)
167163
:param password: password to use for employee authentication
168164
:param endpoint_url: the API endpoint base URL you wish to connect to.
169-
Set this to API_PRIVATE_ENDPOINT to connect via SoftLayer's private
170-
network.
165+
Set this to API_PRIVATE_ENDPOINT to connect via SoftLayer's private network.
171166
:param proxy: proxy to be used to make API calls
172167
:param integer timeout: timeout for API requests
173-
:param auth: an object which responds to get_headers() to be inserted into
174-
the xml-rpc headers. Example: `BasicAuthentication`
168+
:param auth: an object which responds to get_headers() to be inserted into the xml-rpc headers.
169+
Example: `BasicAuthentication`
175170
:param config_file: A path to a configuration file used to load settings
176171
:param user_agent: an optional User Agent to report when making API
177172
calls if you wish to bypass the packages built in User Agent string
178-
:param transport: An object that's callable with this signature:
179-
transport(SoftLayer.transports.Request)
180-
:param bool verify: decide to verify the server's SSL/TLS cert. DO NOT SET
181-
TO FALSE WITHOUT UNDERSTANDING THE IMPLICATIONS.
182-
173+
:param transport: An object that's callable with this signature: transport(SoftLayer.transports.Request)
174+
:param bool verify: decide to verify the server's SSL/TLS cert.
183175
"""
184176
settings = config.get_client_settings(username=username,
185177
api_key=None,
@@ -214,7 +206,6 @@ def employee_client(username=None,
214206
verify=verify,
215207
)
216208

217-
218209
if access_token is None:
219210
access_token = settings.get('access_token')
220211

@@ -241,16 +232,23 @@ class BaseClient(object):
241232
:param auth: auth driver that looks like SoftLayer.auth.AuthenticationBase
242233
:param transport: An object that's callable with this signature: transport(SoftLayer.transports.Request)
243234
"""
244-
245235
_prefix = "SoftLayer_"
236+
auth: slauth.AuthenticationBase
246237

247238
def __init__(self, auth=None, transport=None, config_file=None):
248239
if config_file is None:
249240
config_file = CONFIG_FILE
250-
self.auth = auth
251241
self.config_file = config_file
252242
self.settings = config.get_config(self.config_file)
243+
self.__setAuth(auth)
244+
self.__setTransport(transport)
245+
246+
def __setAuth(self, auth=None):
247+
"""Prepares the authentication property"""
248+
self.auth = auth
253249

250+
def __setTransport(self, transport=None):
251+
"""Prepares the transport property"""
254252
if transport is None:
255253
url = self.settings['softlayer'].get('endpoint_url')
256254
if url is not None and '/rest' in url:
@@ -469,6 +467,7 @@ def __repr__(self):
469467
def __len__(self):
470468
return 0
471469

470+
472471
class CertificateClient(BaseClient):
473472
"""Client that works with a X509 Certificate for authentication.
474473
@@ -479,42 +478,20 @@ class CertificateClient(BaseClient):
479478
"""
480479

481480
def __init__(self, auth=None, transport=None, config_file=None):
482-
if config_file is None:
483-
config_file = CONFIG_FILE
484-
self.config_file = config_file
485-
self.settings = config.get_config(self.config_file)
481+
BaseClient.__init__(self, auth, transport, config_file)
482+
self.__setAuth(auth)
486483

484+
def __setAuth(self, auth=None):
485+
"""Prepares the authentication property"""
487486
if auth is None:
488487
auth_cert = self.settings['softlayer'].get('auth_cert')
489488
serv_cert = self.settings['softlayer'].get('server_cert', None)
490489
auth = slauth.X509Authentication(auth_cert, serv_cert)
491-
self.auth = auth
492-
493-
490+
self.auth = auth
494491

495-
if transport is None:
496-
url = self.settings['softlayer'].get('endpoint_url')
497-
if url is not None and '/rest' in url:
498-
# If this looks like a rest endpoint, use the rest transport
499-
transport = transports.RestTransport(
500-
endpoint_url=url,
501-
proxy=self.settings['softlayer'].get('proxy'),
502-
# prevents an exception incase timeout is a float number.
503-
timeout=int(self.settings['softlayer'].getfloat('timeout', 0)),
504-
user_agent=consts.USER_AGENT,
505-
verify=self.settings['softlayer'].getboolean('verify'),
506-
)
507-
else:
508-
# Default the transport to use XMLRPC
509-
transport = transports.XmlRpcTransport(
510-
endpoint_url=url,
511-
proxy=self.settings['softlayer'].get('proxy'),
512-
timeout=int(self.settings['softlayer'].getfloat('timeout', 0)),
513-
user_agent=consts.USER_AGENT,
514-
verify=self.settings['softlayer'].getboolean('verify'),
515-
)
492+
def __repr__(self):
493+
return "CertificateClient(transport=%r, auth=%r)" % (self.transport, self.auth)
516494

517-
self.transport = transport
518495

519496
class IAMClient(BaseClient):
520497
"""IBM ID Client for using IAM authentication
@@ -711,9 +688,8 @@ def __init__(self, auth=None, transport=None, config_file=None, account_id=None)
711688
BaseClient.__init__(self, auth, transport, config_file)
712689
self.account_id = account_id
713690

714-
715-
def authenticate_with_password(self, username, password, security_token=None):
716-
"""Performs IBM IAM Username/Password Authentication
691+
def authenticate_with_internal(self, username, password, security_token=None):
692+
"""Performs internal authentication
717693
718694
:param string username: your softlayer username
719695
:param string password: your softlayer password
@@ -724,12 +700,11 @@ def authenticate_with_password(self, username, password, security_token=None):
724700
if security_token is None:
725701
security_token = input("Enter your 2FA Token now: ")
726702
if len(security_token) != 6:
727-
raise Exception("Invalid security token: {}".format(security_token))
703+
raise exceptions.SoftLayerAPIError("Invalid security token: {}".format(security_token))
728704

729705
auth_result = self.call('SoftLayer_User_Employee', 'performExternalAuthentication',
730706
username, password, security_token)
731707

732-
733708
self.settings['softlayer']['access_token'] = auth_result['hash']
734709
self.settings['softlayer']['userid'] = str(auth_result['userId'])
735710
# self.settings['softlayer']['refresh_token'] = tokens['refresh_token']
@@ -739,8 +714,6 @@ def authenticate_with_password(self, username, password, security_token=None):
739714

740715
return auth_result
741716

742-
743-
744717
def authenticate_with_hash(self, userId, access_token):
745718
"""Authenticates to the Internal SL API with an employee userid + token
746719
@@ -791,6 +764,7 @@ def call(self, service, method, *args, **kwargs):
791764
def __repr__(self):
792765
return "EmployeeClient(transport=%r, auth=%r)" % (self.transport, self.auth)
793766

767+
794768
class Service(object):
795769
"""A SoftLayer Service.
796770

SoftLayer/CLI/login.py

+12-13
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,28 @@
11
"""Login with your employee username, password, 2fa token"""
22
# :license: MIT, see LICENSE for more details.
3+
import os
34

45
import click
5-
import os
66

7-
8-
from SoftLayer.API import EmployeeClient
97
from SoftLayer.CLI.command import SLCommand as SLCommand
8+
from SoftLayer.CLI import environment
109
from SoftLayer import config
1110
from SoftLayer import consts
12-
from SoftLayer.CLI import environment
1311

1412

1513
def censor_password(value):
14+
"""Replaces a password with *s"""
1615
if value:
1716
value = '*' * len(value)
1817
return value
1918

19+
2020
@click.command(cls=SLCommand)
2121
@environment.pass_env
2222
def cli(env):
2323
"""Logs you into the internal SoftLayer Network.
2424
25-
username: Set this in either the softlayer config, or SL_USER ENV variable
25+
username: Set this in either the softlayer config, or SL_USER ENV variable
2626
password: Set this in SL_PASSWORD env variable. You will be prompted for them otherwise.
2727
"""
2828
config_settings = config.get_config(config_file=env.config_file)
@@ -36,18 +36,18 @@ def cli(env):
3636
if settings.get('access_token') and settings.get('userid'):
3737
client.authenticate_with_hash(settings.get('userid'), settings.get('access_token'))
3838
try:
39-
employee = client.call('SoftLayer_User_Employee', 'getObject', id=settings.get('userid'), mask="mask[id,username]")
40-
print(employee)
41-
client.refresh_token(settings.get('userid'), settings.get('access_token'))
42-
refresh = client.call('SoftLayer_User_Employee', 'refreshEncryptedToken', settings.get('access_token'), id=settings.get('userid'))
39+
emp_id = settings.get('userid')
40+
client.call('SoftLayer_User_Employee', 'getObject', id=emp_id, mask="mask[id,username]")
41+
client.refresh_token(emp_id, settings.get('access_token'))
42+
client.call('SoftLayer_User_Employee', 'refreshEncryptedToken', settings.get('access_token'), id=emp_id)
4343

4444
config_settings['softlayer'] = settings
4545
config.write_config(config_settings, env.config_file)
4646
return
47+
# pylint: disable=broad-exception-caught
4748
except Exception as ex:
4849
print("Error with Hash Authentication, try with password: {}".format(ex))
4950

50-
5151
url = settings.get('endpoint_url') or consts.API_EMPLOYEE_ENDPOINT
5252
click.echo("URL: {}".format(url))
5353
if username is None:
@@ -57,11 +57,10 @@ def cli(env):
5757
password = env.getpass("Password: ")
5858
click.echo("Password: {}".format(censor_password(password)))
5959
yubi = input("Yubi: ")
60-
61-
6260
try:
63-
result = client.authenticate_with_password(username, password, str(yubi))
61+
result = client.authenticate_with_internal(username, password, str(yubi))
6462
print(result)
63+
# pylint: disable=broad-exception-caught
6564
except Exception as e:
6665
click.echo("EXCEPTION: {}".format(e))
6766

tests/api_tests.py

+9-12
Original file line numberDiff line numberDiff line change
@@ -6,15 +6,15 @@
66
"""
77
import io
88
import os
9-
from unittest import mock as mock
109
import requests
10+
from unittest import mock as mock
1111

1212
import SoftLayer
1313
import SoftLayer.API
14+
from SoftLayer import auth as slauth
15+
from SoftLayer import exceptions
1416
from SoftLayer import testing
1517
from SoftLayer import transports
16-
from SoftLayer import exceptions
17-
from SoftLayer import auth as slauth
1818

1919

2020
class Initialization(testing.TestCase):
@@ -319,7 +319,6 @@ def test_authenticate_with_password(self, _call):
319319

320320
class EmployeeClientTests(testing.TestCase):
321321

322-
323322
@staticmethod
324323
def setup_response(filename, status_code=200, total_items=1):
325324
basepath = os.path.dirname(__file__)
@@ -333,7 +332,6 @@ def setup_response(filename, status_code=200, total_items=1):
333332
response.status_code = status_code
334333
return response
335334

336-
337335
def set_up(self):
338336
self.client = SoftLayer.API.EmployeeClient(config_file='./tests/testconfig')
339337

@@ -348,7 +346,7 @@ def test_auth_with_pass_failure(self, api_response):
348346
@mock.patch('SoftLayer.transports.xmlrpc.requests.Session.request')
349347
def test_auth_with_pass_success(self, api_response):
350348
api_response.return_value = self.setup_response('successLogin')
351-
result = self.client.authenticate_with_password('testUser', 'testPassword', '123456')
349+
result = self.client.authenticate_with_internal('testUser', 'testPassword', '123456')
352350
print(result)
353351
self.assertEqual(result['userId'], 1234)
354352
self.assertEqual(self.client.settings['softlayer']['userid'], '1234')
@@ -363,10 +361,10 @@ def test_auth_with_hash(self):
363361
@mock.patch('SoftLayer.transports.xmlrpc.requests.Session.request')
364362
def test_refresh_token(self, api_response):
365363
api_response.return_value = self.setup_response('refreshSuccess')
366-
result = self.client.refresh_token(9999, 'qweasdzxcqweasdzxcqweasdzxc')
364+
self.client.refresh_token(9999, 'qweasdzxcqweasdzxcqweasdzxc')
367365
self.assertEqual(self.client.auth.user_id, 9999)
368366
self.assertIn('REFRESHEDTOKENaaaa', self.client.auth.hash)
369-
367+
370368
@mock.patch('SoftLayer.transports.xmlrpc.requests.Session.request')
371369
def test_expired_token_is_refreshed(self, api_response):
372370
api_response.side_effect = [
@@ -379,9 +377,9 @@ def test_expired_token_is_refreshed(self, api_response):
379377
result = self.client.call('SoftLayer_User_Employee', 'getObject', id=5555)
380378
self.assertIn('REFRESHEDTOKENaaaa', self.client.auth.hash)
381379
self.assertEqual('testUser', result['username'])
382-
380+
383381
@mock.patch('SoftLayer.transports.xmlrpc.requests.Session.request')
384-
def test_expired_token_is_really_expored(self, api_response):
382+
def test_expired_token_is_really_expired(self, api_response):
385383
api_response.side_effect = [
386384
self.setup_response('expiredToken'),
387385
self.setup_response('expiredToken')
@@ -391,7 +389,6 @@ def test_expired_token_is_really_expored(self, api_response):
391389
exception = self.assertRaises(
392390
exceptions.SoftLayerAPIError,
393391
self.client.call, 'SoftLayer_User_Employee', 'getObject', id=5555)
394-
self.assertEqual(None, self.client.auth)
395392
self.assertEqual(exception.faultCode, "SoftLayer_Exception_EncryptedToken_Expired")
396393

397394
@mock.patch('SoftLayer.API.BaseClient.call')
@@ -408,4 +405,4 @@ def test_account_check(self, _call):
408405
_call.assert_has_calls([
409406
mock.call(self.client, 'SoftLayer_Account', 'getObject', id=1234),
410407
mock.call(self.client, 'SoftLayer_Account', 'getObject1', id=9999),
411-
])
408+
])

0 commit comments

Comments
 (0)