Skip to content

Commit f27839d

Browse files
author
Mat Lord
authored
Merge pull request #32 from stax-labs/feat/test-clients
chore(tests): Add aws client tests
2 parents c752d57 + dd30701 commit f27839d

7 files changed

Lines changed: 91 additions & 21 deletions

File tree

staxapp/api.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,10 @@ class Api:
88
_requests_auth = None
99

1010
@classmethod
11-
def _auth(cls):
11+
def _auth(cls, **kwargs):
1212
if not cls._requests_auth:
1313
cls._requests_auth = Config.get_auth_class().requests_auth(
14-
Config.access_key, Config.secret_key
14+
Config.access_key, Config.secret_key, **kwargs
1515
)
1616
return cls._requests_auth
1717

staxapp/auth.py

Lines changed: 17 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -83,18 +83,23 @@ def sts_from_cognito_identity_pool(self, token, cognito_client=None, **kwargs):
8383
region_name=self.aws_region,
8484
config=BotoConfig(signature_version=UNSIGNED),
8585
)
86-
id = cognito_client.get_id(
87-
IdentityPoolId=self.identity_pool,
88-
Logins={
89-
f"cognito-idp.{self.aws_region}.amazonaws.com/{self.user_pool}": token
90-
},
91-
)
92-
id_creds = cognito_client.get_credentials_for_identity(
93-
IdentityId=id["IdentityId"],
94-
Logins={
95-
f"cognito-idp.{self.aws_region}.amazonaws.com/{self.user_pool}": token
96-
},
97-
)
86+
try:
87+
id = cognito_client.get_id(
88+
IdentityPoolId=self.identity_pool,
89+
Logins={
90+
f"cognito-idp.{self.aws_region}.amazonaws.com/{self.user_pool}": token
91+
},
92+
)
93+
id_creds = cognito_client.get_credentials_for_identity(
94+
IdentityId=id["IdentityId"],
95+
Logins={
96+
f"cognito-idp.{self.aws_region}.amazonaws.com/{self.user_pool}": token
97+
},
98+
)
99+
except ClientError as e:
100+
raise InvalidCredentialsException(
101+
f"Unexpected Client Error. Error details: {e}"
102+
)
98103
return id_creds
99104

100105
def sigv4_signed_auth_headers(self, id_creds):

staxapp/contract.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ def validate(cls, data, component):
5454
@staticmethod
5555
def default_swagger_template() -> dict:
5656
# Get the default swagger template from https://api.au1.staxapp.cloud/20190206/public/api-document
57-
schema = requests.get(Config.schema_url()).json()
57+
schema_response = requests.get(Config.schema_url()).json()
5858
template = dict(
5959
openapi="3.0.0",
6060
info={
@@ -75,7 +75,7 @@ def default_swagger_template() -> dict:
7575
"x-amazon-apigateway-authtype": "awsSigv4",
7676
}
7777
},
78-
"schemas": schema,
78+
"schemas": schema_response.get("components").get("schemas"),
7979
"responses": dict(),
8080
"requestBodies": dict(),
8181
},

tests/test_api.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -207,8 +207,10 @@ def testFailedApiException(self):
207207
json=response_dict,
208208
status=500,
209209
)
210-
with self.assertRaises(ApiException):
210+
try:
211211
self.Api.get("/test/no/error")
212+
except ApiException as e:
213+
self.assertIn("Api Exception", str(e))
212214

213215
# Test an exception which has no json in response
214216
responses.add(

tests/test_auth.py

Lines changed: 49 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
from botocore.stub import Stubber, ANY
1717
from datetime import datetime, timedelta, timezone
1818

19+
from staxapp.api import Api
1920
from staxapp.auth import StaxAuth, ApiTokenAuth, RootAuth
2021
from staxapp.config import Config
2122
from staxapp.exceptions import InvalidCredentialsException
@@ -59,10 +60,20 @@ def testToken(self):
5960
sa = StaxAuth("ApiAuth")
6061
self.stub_aws_srp(sa, "valid_username")
6162
token = sa.id_token_from_cognito(
62-
username="valid_username", password="correct", srp_client=self.aws_srp_client
63+
username="valid_username",
64+
password="correct",
65+
srp_client=self.aws_srp_client,
6366
)
6467
self.assertEqual(token, "valid_token")
6568

69+
def testTokenClient(self):
70+
"""
71+
Test the AWSSRP client is invoked and throws an error
72+
"""
73+
sa = StaxAuth("ApiAuth")
74+
with self.assertRaises(InvalidCredentialsException):
75+
sa.id_token_from_cognito(username="username", password="password")
76+
6677
def testCredentialErrors(self):
6778
"""
6879
Test that boto errors are caught and converted to InvalidCredentialExceptions
@@ -73,10 +84,12 @@ def testCredentialErrors(self):
7384
user_not_found_success = False
7485
try:
7586
sa.id_token_from_cognito(
76-
username="bad_password", password="wrong", srp_client=self.aws_srp_client
87+
username="bad_password",
88+
password="wrong",
89+
srp_client=self.aws_srp_client,
7790
)
7891
except InvalidCredentialsException as e:
79-
self.assertIn("Please check your Secret Key is correct", e.message)
92+
self.assertIn("Please check your Secret Key is correct", str(e))
8093
user_not_found_success = True
8194
self.assertTrue(user_not_found_success)
8295

@@ -90,7 +103,7 @@ def testCredentialErrors(self):
90103
except InvalidCredentialsException as e:
91104
self.assertIn(
92105
"Please check your Access Key, that you have created your Api Token and that you are using the right STAX REGION",
93-
e.message,
106+
str(e),
94107
)
95108
no_access_success = True
96109
self.assertTrue(no_access_success)
@@ -116,6 +129,16 @@ def testCreds(self):
116129
self.assertIn("Credentials", creds)
117130
self.assertTrue(creds.get("IdentityId").startswith("ap-southeast-2"))
118131

132+
def testCredsClient(self):
133+
"""
134+
Test the cognito client is invoked and throws an error
135+
"""
136+
sa = StaxAuth("ApiAuth")
137+
token = jwt.encode({"sub": "unittest"}, "secret", algorithm="HS256")
138+
jwt_token = jwt.decode(token, verify=False)
139+
with self.assertRaises(InvalidCredentialsException):
140+
sa.sts_from_cognito_identity_pool(jwt_token.get("sub"))
141+
119142
def testAuthErrors(self):
120143
"""
121144
Test that errors are thrown when keys are invalid
@@ -289,6 +312,28 @@ def testRootAuth(self):
289312
)
290313
self.assertIsNotNone(StaxConfig.auth)
291314

315+
def testApiAuth(self):
316+
"""
317+
Test auth through the Api class
318+
"""
319+
sa = StaxAuth("ApiAuth")
320+
StaxConfig = Config
321+
StaxConfig.expiration = None
322+
StaxConfig.access_key = "username"
323+
StaxConfig.secret_key = "password"
324+
325+
token = jwt.encode({"sub": "valid_token"}, "secret", algorithm="HS256")
326+
jwt_token = jwt.decode(token, verify=False)
327+
328+
self.stub_cognito_creds(sa, jwt_token.get("sub"))
329+
self.stub_aws_srp(sa, "username")
330+
331+
Api._requests_auth = None
332+
Api._auth(
333+
srp_client=self.aws_srp_client, cognito_client=self.cognito_client,
334+
)
335+
self.assertIsNotNone(Api._requests_auth)
336+
292337

293338
if __name__ == "__main__":
294339
unittest.main()

tests/test_client.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,13 @@ def testStaxClient(self):
3636
self.assertTrue(client._initialized)
3737
self.assertTrue(client._admin)
3838

39+
def testInvalidStaxClient(self):
40+
"""
41+
Test an invalid Api class raises an error
42+
"""
43+
with self.assertRaises(ValidationException):
44+
StaxClient("fake")
45+
3946
def testLoadLiveSchema(self):
4047
"""
4148
Test loading live schema

tests/test_contract.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,17 @@ class StaxContractTests(unittest.TestCase):
1919
def setUp(self):
2020
self.StaxContract = StaxContract
2121

22+
def testInvalidSchema(self):
23+
"""
24+
Test an error is thrown if no schema is found
25+
"""
26+
sc = StaxContract
27+
sc._swagger_doc = None
28+
data = {"Name": "Unit", "AccountType": "Test"}
29+
component = "accounts.CreateAccount"
30+
sc.validate(data, component)
31+
self.assertIsNotNone(sc._swagger_doc)
32+
2233
def testDefaultSchema(self):
2334
"""
2435
Test the default schema is valid

0 commit comments

Comments
 (0)