Skip to content

Commit 5266f82

Browse files
committed
move to monkeypatch for test, add deps and more clean up
1 parent af9404e commit 5266f82

File tree

3 files changed

+69
-55
lines changed

3 files changed

+69
-55
lines changed

pyproject.toml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ dependencies = [ # runtime deps # https://packaging.python.org/en/latest/guide
2727
"python-dsv-sdk >= 1.0.4", # credentials.thycotic_dsv
2828
"python-tss-sdk >= 1.2.1", # credentials.thycotic_tss
2929
"requests", # credentials.aim, credentials.centrify_vault, credentials.conjur, credentials.hashivault
30+
"datetime", # credentials.aws_assume_role
3031
]
3132
classifiers = [ # Allowlist: https://pypi.org/classifiers/
3233
"Development Status :: 1 - Planning",
@@ -83,6 +84,7 @@ centrify_vault_kv = "awx_plugins.credentials.centrify_vault:centrify_plugin"
8384
thycotic_dsv = "awx_plugins.credentials.dsv:dsv_plugin"
8485
thycotic_tss = "awx_plugins.credentials.tss:tss_plugin"
8586
aws_secretsmanager_credential = "awx_plugins.credentials.aws_secretsmanager:aws_secretmanager_plugin"
87+
aws_assume_role = "awx_plugins.credentials.aws_assume_role:aws_assume_role_plugin"
8688

8789
[project.entry-points."awx_plugins.inventory"] # new entry points group name
8890
azure-rm = "awx_plugins.inventory.plugins:azure_rm"

src/awx_plugins/credentials/aws_assumerole.py

Lines changed: 21 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,8 @@
3737
'label': 'AWS ARN Role Name',
3838
'type': 'string',
3939
'secret': True,
40-
'help_text': _('The ARN Role Name to be assumed in AWS')},
40+
'help_text': _('The ARN Role Name to be assumed in AWS'),
41+
},
4142
],
4243
'metadata': [{'id': 'identifier',
4344
'label': 'Identifier',
@@ -51,20 +52,23 @@
5152

5253
def aws_assumerole_getcreds(access_key, secret_key, role_arn, external_id):
5354
if (access_key is None or len(access_key) == 0) and (
54-
secret_key is None or len(secret_key) == 0):
55+
secret_key is None or len(secret_key) == 0
56+
):
5557
# Connect using credentials in the EE
5658
connection = boto3.client(service_name='sts')
5759
else:
5860
# Connect to AWS using provided credentials
5961
connection = boto3.client(
6062
service_name='sts',
6163
aws_access_key_id=access_key,
62-
aws_secret_access_key=secret_key)
64+
aws_secret_access_key=secret_key,
65+
)
6366
try:
6467
response = connection.assume_role(
6568
RoleArn=role_arn,
6669
RoleSessionName='AAP_AWS_Role_Session1',
67-
ExternalId=external_id)
70+
ExternalId=external_id,
71+
)
6872
except ClientError as ce:
6973
raise ValueError(f'Got a bad client response from AWS: {ce.msg}.')
7074

@@ -74,7 +78,8 @@ def aws_assumerole_getcreds(access_key, secret_key, role_arn, external_id):
7478

7579

7680
def aws_assumerole_backend(**kwargs):
77-
"""This backend function actually contacts AWS to assume a given role for the specified user"""
81+
"""This backend function actually contacts AWS to assume a given role for
82+
the specified user."""
7883
access_key = kwargs.get('access_key')
7984
secret_key = kwargs.get('secret_key')
8085
role_arn = kwargs.get('role_arn')
@@ -87,19 +92,24 @@ def aws_assumerole_backend(**kwargs):
8792
# multiple roles.
8893
#
8994
credential_key_hash = hashlib.sha256(
90-
(str(access_key or '') + role_arn).encode('utf-8'))
95+
(str(access_key or '') + role_arn).encode('utf-8'),
96+
)
9197
credential_key = credential_key_hash.hexdigest()
9298

9399
credentials = _aws_cred_cache.get(credential_key, None)
94100

95101
# If there are no credentials for this user/ARN *or* the credentials
96102
# we have in the cache have expired, then we need to contact AWS again.
97103
#
98-
if (credentials is None) or (credentials['Expiration'] < datetime.datetime.now(
99-
credentials['Expiration'].tzinfo)):
104+
if (credentials is None) or (
105+
credentials['Expiration'] < datetime.datetime.now(
106+
credentials['Expiration'].tzinfo,
107+
)
108+
):
100109

101110
credentials = aws_assumerole_getcreds(
102-
access_key, secret_key, role_arn, external_id)
111+
access_key, secret_key, role_arn, external_id,
112+
)
103113

104114
_aws_cred_cache[credential_key] = credentials
105115

@@ -114,4 +124,5 @@ def aws_assumerole_backend(**kwargs):
114124
aws_assumerole_plugin = CredentialPlugin(
115125
'AWS Assume Role Plugin',
116126
inputs=assume_role_inputs,
117-
backend=aws_assumerole_backend)
127+
backend=aws_assumerole_backend,
128+
)

tests/credential_plugins_test.py

Lines changed: 46 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -132,71 +132,72 @@ def test_hashivault_handle_auth_not_enough_args():
132132
hashivault.handle_auth()
133133

134134

135-
def test_aws_assumerole_with_accesssecret():
136-
'''
137-
Test that the aws_assumerole_backend function call returns a token given the access_key and secret_key.
138-
'''
135+
def test_aws_assumerole_with_accesssecret(monkeypatch):
136+
"""Test that the aws_assumerole_backend function call returns a token given
137+
the access_key and secret_key."""
139138
kwargs = {
140139
'access_key': 'my_access_key',
141140
'secret_key': 'my_secret_key',
142141
'role_arn': 'the_arn',
143142
'identifier': 'access_token',
144143
}
145-
with mock.patch.object(aws_assumerole, 'aws_assumerole_getcreds') as method_mock:
146-
method_mock.return_value = {
144+
145+
def mock_getcreds(access_key, secret_key, role_arn, session_token):
146+
return {
147147
'access_key': 'the_access_key',
148148
'secret_key': 'the_secret_key',
149149
'access_token': 'the_access_token',
150150
'Expiration': datetime.datetime.today() + datetime.timedelta(days=1),
151151
}
152-
token = aws_assumerole.aws_assumerole_backend(**kwargs)
153-
method_mock.assert_called_with(
154-
kwargs.get('access_key'),
155-
kwargs.get('secret_key'),
156-
kwargs.get('role_arn'),
157-
None)
158-
assert token == 'the_access_token'
159-
kwargs['identifier'] = 'secret_key'
160-
method_mock.reset_mock()
161-
token = aws_assumerole.aws_assumerole_backend(**kwargs)
162-
method_mock.assert_not_called()
163-
assert token == 'the_secret_key'
164-
kwargs['identifier'] = 'access_key'
165-
method_mock.reset_mock()
166-
token = aws_assumerole.aws_assumerole_backend(**kwargs)
167-
method_mock.assert_not_called()
168-
assert token == 'the_access_key'
169-
170-
171-
def test_aws_assumerole_with_arnonly():
172-
'''
173-
Test backend function with only the role ARN provided.
174-
'''
152+
153+
monkeypatch.setattr(
154+
aws_assumerole,
155+
'aws_assumerole_getcreds',
156+
mock_getcreds)
157+
158+
token = aws_assumerole.aws_assumerole_backend(**kwargs)
159+
assert token == 'the_access_token'
160+
161+
kwargs['identifier'] = 'secret_key'
162+
token = aws_assumerole.aws_assumerole_backend(**kwargs)
163+
assert token == 'the_secret_key'
164+
165+
kwargs['identifier'] = 'access_key'
166+
token = aws_assumerole.aws_assumerole_backend(**kwargs)
167+
assert token == 'the_access_key'
168+
169+
170+
def test_aws_assumerole_with_arnonly(monkeypatch):
171+
"""Test backend function with only the role ARN provided."""
175172
kwargs = {
176173
'role_arn': 'the_arn',
177174
'identifier': 'access_token',
178175
}
179-
with mock.patch.object(aws_assumerole, 'aws_assumerole_getcreds') as method_mock:
180-
method_mock.return_value = {
176+
177+
# Define a mock function that will replace aws_assumerole_getcreds
178+
def mock_getcreds(*args, **kwargs):
179+
return {
181180
'access_key': 'the_access_key',
182181
'secret_key': 'the_secret_key',
183182
'access_token': 'the_access_token',
184183
'Expiration': datetime.datetime.today() + datetime.timedelta(days=1),
185184
}
186-
token = aws_assumerole.aws_assumerole_backend(**kwargs)
187-
method_mock.assert_called_with(
188-
None, None, kwargs.get('role_arn'), None)
189-
assert token == 'the_access_token'
190-
kwargs['identifier'] = 'secret_key'
191-
method_mock.reset_mock()
192-
token = aws_assumerole.aws_assumerole_backend(**kwargs)
193-
method_mock.assert_not_called()
194-
assert token == 'the_secret_key'
195-
kwargs['identifier'] = 'access_key'
196-
method_mock.reset_mock()
197-
token = aws_assumerole.aws_assumerole_backend(**kwargs)
198-
method_mock.assert_not_called()
199-
assert token == 'the_access_key'
185+
186+
monkeypatch.setattr(
187+
aws_assumerole,
188+
'aws_assumerole_getcreds',
189+
mock_getcreds)
190+
191+
token = aws_assumerole.aws_assumerole_backend(**kwargs)
192+
assert token == 'the_access_token'
193+
194+
kwargs['identifier'] = 'secret_key'
195+
token = aws_assumerole.aws_assumerole_backend(**kwargs)
196+
assert token == 'the_secret_key'
197+
198+
kwargs['identifier'] = 'access_key'
199+
token = aws_assumerole.aws_assumerole_backend(**kwargs)
200+
assert token == 'the_access_key'
200201

201202

202203
class TestDelineaImports:

0 commit comments

Comments
 (0)