Skip to content

Commit e9578d3

Browse files
committed
feat(auth) convert boto error's into staxapp errors
1 parent feecb9a commit e9578d3

5 files changed

Lines changed: 119 additions & 2 deletions

File tree

Pipfile

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
[[source]]
2+
name = "pypi"
3+
url = "https://pypi.org/simple"
4+
verify_ssl = true
5+
6+
[dev-packages]
7+
8+
[packages]
9+
aws-requests-auth = "*"
10+
black = "*"
11+
boto3 = "*"
12+
isort = "*"
13+
jsonschema = "*"
14+
nose2 = "*"
15+
openapi-spec-validator = "*"
16+
prance = "*"
17+
pycodestyle = "*"
18+
pycrypto = "*"
19+
pylint = "*"
20+
pytest = "*"
21+
pytest-cov = "*"
22+
requests = "*"
23+
responses = "*"
24+
warrant = "*"
25+
PyJWT = "*"
26+
27+
[requires]
28+
python_version = "3.7"

examples/test.py

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import os
2+
import sys
3+
import boto3
4+
5+
from staxapp.config import Config
6+
from staxapp.openapi import StaxClient
7+
from staxapp.api import Api
8+
from staxapp.exceptions import ApiException
9+
10+
sts = boto3.client("sts")
11+
12+
security_account = '750975847145'
13+
api_token_name = 'dean-token'
14+
15+
response = sts.assume_role(RoleArn=f"arn:aws:iam::{security_account}:role/{api_token_name}-access-role", RoleSessionName=f"{api_token_name}-ssm-role")
16+
assumed_ssm = boto3.client("ssm",
17+
aws_access_key_id=response["Credentials"]["AccessKeyId"],
18+
aws_secret_access_key=response["Credentials"]["SecretAccessKey"],
19+
aws_session_token=response["Credentials"]["SessionToken"]
20+
)
21+
api_token_access_key = assumed_ssm.get_parameter(Name=f"/stax/api-tokens/{api_token_name}/AccessKey", WithDecryption=True)
22+
api_token_secret_key = assumed_ssm.get_parameter(Name=f"/stax/api-tokens/{api_token_name}/SecretKey", WithDecryption=True)
23+
24+
Config.access_key = api_token_access_key['Parameter']['Value']
25+
Config.secret_key = api_token_secret_key['Parameter']['Value']
26+
27+
Config.access_key = 'fake'
28+
Config.secret_key = 'fake'
29+
30+
31+
# fake_client = StaxClient("fake")
32+
client = StaxClient("accounts")
33+
34+
allAccounts = client.ReadAccounts()
35+
print(f'{len(allAccounts["Accounts"])}')
36+
print(client.ReadAccounts(limit=1, offset=0))
37+
print(client.ReadAccounts(account_id="9fc4fd2e-1b4a-49b9-a341-d7ee77ea132d"))
38+
print(client.ReadAccounts(filter="ERROR", account_id="9fc4fd2e-1b4a-49b9-a341-d7ee77ea132d"))
39+
40+
41+
client = StaxClient("workloads")
42+
# client.FakeMethod()
43+
# print(client.ReadCatalogueItems())
44+
response = client.ReadCatalogueItems(catalogue_id='9c4fc016-5221-460d-8bf8-4104178e9e10')
45+
print(client.ReadCatalogueVersion(version_id='545489ae-c090-45cd-9322-42f9b2ed7b6a', catalogue_id='9c4fc016-5221-460d-8bf8-4104178e9e10'))
46+
print(client.ReadCatalogueVersion(version_id='d58ad318-fa36-4310-9766-e7f5e4a34f8d', include_parameters=False, catalogue_id='f13dd683-4aa6-4b88-abc8-ad58a7ee04f9'))
47+
48+
# print(client.DeleteCatalogueVersion(catalogue_id='fake'))
49+
print(client.ReadCatalogueVersion(version_id='d58ad318-fa36-4310-9766-e7f5e4a34f8d', include_parameters=False))
50+
51+
# print(fake_client.ReadAccounts(limit=1, offset=0))

staxapp/auth.py

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
from warrant import AWSSRP, Cognito
1212

1313
from staxapp.config import Config as JumaConfig
14+
from staxapp.exceptions import InvalidCredentialsException
1415

1516

1617
class StaxAuth:
@@ -23,6 +24,11 @@ def __init__(self, config_branch):
2324
self.aws_region = config.get(config_branch).get("region")
2425

2526
def requests_auth(self, username, password):
27+
if username is None:
28+
raise InvalidCredentialsException("Please provide an Access Key to your config")
29+
if password is None:
30+
raise InvalidCredentialsException("Please provide a Secret Key to your config")
31+
2632
id_token = self.id_token_from_cognito(username, password)
2733
id_creds = self.sts_from_cognito_identity_pool(id_token)
2834
auth = self.sigv4_signed_auth_headers(id_creds)
@@ -47,7 +53,14 @@ def id_token_from_cognito(self, username=None, password=None):
4753
client_id=self.client_id,
4854
client=client,
4955
)
50-
tokens = aws.authenticate_user()
56+
try:
57+
tokens = aws.authenticate_user()
58+
except client.exceptions.NotAuthorizedException as e:
59+
logging.error(e)
60+
raise InvalidCredentialsException(message=str(e), detail="Please check your Secret Key is correct")
61+
except client.exceptions.UserNotFoundException as e:
62+
raise InvalidCredentialsException(message=str(e), detail="Please check your Access Key, that you have created your Api Token and that you are using the right STAX REGION")
63+
5164
# logging.debug(f"TOKEN: {tokens}")
5265
token = tokens["AuthenticationResult"]["IdToken"]
5366
else:

staxapp/exceptions.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,3 +26,14 @@ class ValidationException(Exception):
2626
def __init__(self, message):
2727
# logging.info(f"VALIDATE: {message}")
2828
self.message = message
29+
30+
31+
class InvalidCredentialsException(Exception):
32+
def __init__(self, message, detail=""):
33+
prefix = f"InvalidCredentialsException: "
34+
if detail:
35+
prefix = f"{prefix}{detail} - "
36+
self.message = f"{prefix}{message}"
37+
38+
def __str__(self):
39+
return self.message

tests/test_auth.py

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
from botocore.stub import Stubber
1616

1717
from staxapp.auth import StaxAuth
18-
18+
from staxapp.exceptions import InvalidCredentialsException
1919

2020
class StaxAuthTests(unittest.TestCase):
2121
"""
@@ -63,6 +63,20 @@ def testCreds(self):
6363
self.assertIn("Credentials", creds)
6464
self.assertTrue(creds.get("IdentityId").startswith("ap-southeast-2"))
6565

66+
def testCredentialErrors(self):
67+
"""
68+
Test that errors are thrown when keys are invalid
69+
"""
70+
sa = StaxAuth("ApiAuth")
71+
# Test with no username
72+
with self.assertRaises(InvalidCredentialsException):
73+
sa.requests_auth(username=None, password='valid')
74+
# Test with no username
75+
with self.assertRaises(InvalidCredentialsException):
76+
sa.requests_auth(username='valid', password=None)
77+
# Test with invalid username password
78+
# Todo
79+
6680
def stub_cognito_creds(self, token: str):
6781
sa = StaxAuth("ApiAuth")
6882

0 commit comments

Comments
 (0)