Skip to content

Commit c752d57

Browse files
author
Mat Lord
authored
Merge pull request #31 from stax-labs/feat/cleanup
chore(staxapp): code cleanup
2 parents 84101da + b74b57e commit c752d57

9 files changed

Lines changed: 136 additions & 96 deletions

File tree

Makefile

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,9 +27,9 @@ lint: install
2727
${ISORT} --diff staxapp/*.py
2828
${BLACK} -t py37 --check --diff staxapp/
2929

30-
format: lint
30+
format:
3131
${ISORT} --apply staxapp/*.py
32-
${BLACK} -t py37 staxapp/
32+
${BLACK} -t py37 staxapp/*.py
3333

3434
download-schema:
3535
curl --fail --compressed -s -o staxapp/data/schema.json https://api.au1.staxapp.cloud/20190206/public/api-document

staxapp/api.py

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,3 @@
1-
import json
2-
import logging
3-
41
import requests
52

63
from staxapp.config import Config
@@ -13,7 +10,7 @@ class Api:
1310
@classmethod
1411
def _auth(cls):
1512
if not cls._requests_auth:
16-
cls._requests_auth = Config.auth().requests_auth(
13+
cls._requests_auth = Config.get_auth_class().requests_auth(
1714
Config.access_key, Config.secret_key
1815
)
1916
return cls._requests_auth
@@ -31,16 +28,15 @@ def get(cls, url_frag, params={}, **kwargs):
3128
url = f"{Config.api_base_url()}/{url_frag.lstrip('/')}"
3229

3330
response = requests.get(url, auth=cls._auth(), params=params, **kwargs)
34-
# logging.debug(f"GET: {response.text}")
3531
cls.handle_api_response(response)
3632
return response.json()
3733

3834
@classmethod
3935
def post(cls, url_frag, payload={}, **kwargs):
4036
url_frag = url_frag.replace(f"/{Config.API_VERSION}", "")
4137
url = f"{Config.api_base_url()}/{url_frag.lstrip('/')}"
38+
4239
response = requests.post(url, json=payload, auth=cls._auth(), **kwargs)
43-
# logging.debug(f"POST: {response.text}")
4440
cls.handle_api_response(response)
4541
return response.json()
4642

staxapp/auth.py

Lines changed: 52 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,27 @@
11
#!/usr/local/bin/python3
2-
import logging
3-
import sys
4-
from datetime import date, datetime, timedelta, timezone
2+
from datetime import datetime, timezone
53

64
import boto3
7-
import jwt
85
from aws_requests_auth.aws_auth import AWSRequestsAuth
96
from botocore import UNSIGNED
107
from botocore.client import Config as BotoConfig
118
from botocore.exceptions import ClientError
12-
from warrant import AWSSRP, Cognito
9+
from warrant import AWSSRP
1310

14-
from staxapp.config import Config as JumaConfig
11+
from staxapp.config import Config as StaxConfig
1512
from staxapp.exceptions import InvalidCredentialsException
1613

1714

1815
class StaxAuth:
1916
def __init__(self, config_branch):
20-
config = JumaConfig.api_config
17+
config = StaxConfig.api_config
2118

2219
self.identity_pool = config.get(config_branch).get("identityPoolId")
2320
self.user_pool = config.get(config_branch).get("userPoolId")
2421
self.client_id = config.get(config_branch).get("userPoolWebClientId")
2522
self.aws_region = config.get(config_branch).get("region")
2623

27-
def requests_auth(self, username, password):
24+
def requests_auth(self, username, password, **kwargs):
2825
if username is None:
2926
raise InvalidCredentialsException(
3027
"Please provide an Access Key to your config"
@@ -34,51 +31,52 @@ def requests_auth(self, username, password):
3431
"Please provide a Secret Key to your config"
3532
)
3633

37-
id_token = self.id_token_from_cognito(username, password)
38-
id_creds = self.sts_from_cognito_identity_pool(id_token)
34+
id_token = self.id_token_from_cognito(username, password, **kwargs)
35+
id_creds = self.sts_from_cognito_identity_pool(id_token, **kwargs)
3936
auth = self.sigv4_signed_auth_headers(id_creds)
4037

41-
JumaConfig.expiration = id_creds.get("Credentials").get("Expiration")
42-
JumaConfig.auth = auth
38+
StaxConfig.expiration = id_creds.get("Credentials").get("Expiration")
39+
StaxConfig.auth = auth
4340

44-
return JumaConfig.auth
41+
return StaxConfig.auth
4542

46-
def id_token_from_cognito(self, username=None, password=None, client=None):
43+
def id_token_from_cognito(
44+
self, username=None, password=None, srp_client=None, **kwargs
45+
):
4746
token = None
48-
if username and password:
49-
if not client:
50-
client = boto3.client(
51-
"cognito-idp",
52-
region_name=self.aws_region,
53-
config=BotoConfig(signature_version=UNSIGNED),
54-
)
55-
aws = AWSSRP(
56-
username=username,
57-
password=password,
58-
pool_id=self.user_pool,
59-
client_id=self.client_id,
60-
client=client,
47+
if not srp_client:
48+
srp_client = boto3.client(
49+
"cognito-idp",
50+
region_name=self.aws_region,
51+
config=BotoConfig(signature_version=UNSIGNED),
6152
)
62-
try:
63-
tokens = aws.authenticate_user()
64-
except ClientError as e:
65-
if e.response["Error"]["Code"] == "NotAuthorizedException":
66-
raise InvalidCredentialsException(
67-
message=str(e), detail="Please check your Secret Key is correct"
68-
)
69-
elif e.response["Error"]["Code"] == "UserNotFoundException":
70-
raise InvalidCredentialsException(
71-
message=str(e),
72-
detail="Please check your Access Key, that you have created your Api Token and that you are using the right STAX REGION",
73-
)
74-
else:
75-
raise InvalidCredentialsException(
76-
f"Unexpected Client Error. Error details: {e}"
77-
)
78-
token = tokens["AuthenticationResult"]["IdToken"]
53+
aws = AWSSRP(
54+
username=username,
55+
password=password,
56+
pool_id=self.user_pool,
57+
client_id=self.client_id,
58+
client=srp_client,
59+
)
60+
try:
61+
tokens = aws.authenticate_user()
62+
except ClientError as e:
63+
if e.response["Error"]["Code"] == "NotAuthorizedException":
64+
raise InvalidCredentialsException(
65+
message=str(e), detail="Please check your Secret Key is correct"
66+
)
67+
elif e.response["Error"]["Code"] == "UserNotFoundException":
68+
raise InvalidCredentialsException(
69+
message=str(e),
70+
detail="Please check your Access Key, that you have created your Api Token and that you are using the right STAX REGION",
71+
)
72+
else:
73+
raise InvalidCredentialsException(
74+
f"Unexpected Client Error. Error details: {e}"
75+
)
76+
token = tokens["AuthenticationResult"]["IdToken"]
7977
return token
8078

81-
def sts_from_cognito_identity_pool(self, token, cognito_client=None):
79+
def sts_from_cognito_identity_pool(self, token, cognito_client=None, **kwargs):
8280
if not cognito_client:
8381
cognito_client = boto3.client(
8482
"cognito-identity",
@@ -91,43 +89,39 @@ def sts_from_cognito_identity_pool(self, token, cognito_client=None):
9189
f"cognito-idp.{self.aws_region}.amazonaws.com/{self.user_pool}": token
9290
},
9391
)
94-
# logging.debug(f"ID: {id}")
95-
9692
id_creds = cognito_client.get_credentials_for_identity(
9793
IdentityId=id["IdentityId"],
9894
Logins={
9995
f"cognito-idp.{self.aws_region}.amazonaws.com/{self.user_pool}": token
10096
},
10197
)
102-
# logging.debug(f"CREDS: {id_creds}")
10398
return id_creds
10499

105100
def sigv4_signed_auth_headers(self, id_creds):
106101
auth = AWSRequestsAuth(
107102
aws_access_key=id_creds.get("Credentials").get("AccessKeyId"),
108103
aws_secret_access_key=id_creds.get("Credentials").get("SecretKey"),
109104
aws_token=id_creds.get("Credentials").get("SessionToken"),
110-
aws_host=f"{JumaConfig.hostname}",
105+
aws_host=f"{StaxConfig.hostname}",
111106
aws_region=self.aws_region,
112107
aws_service="execute-api",
113108
)
114-
# logging.debug(f"AUTH: {auth}")
115109
return auth
116110

117111

118112
class RootAuth:
119113
@staticmethod
120-
def requests_auth(username, password):
121-
if JumaConfig.expiration and JumaConfig.expiration > datetime.now(timezone.utc):
122-
return JumaConfig.auth
114+
def requests_auth(username, password, **kwargs):
115+
if StaxConfig.expiration and StaxConfig.expiration > datetime.now(timezone.utc):
116+
return StaxConfig.auth
123117

124-
return StaxAuth("JumaAuth").requests_auth(username, password)
118+
return StaxAuth("JumaAuth").requests_auth(username, password, **kwargs)
125119

126120

127121
class ApiTokenAuth:
128122
@staticmethod
129-
def requests_auth(username, password):
130-
if JumaConfig.expiration and JumaConfig.expiration > datetime.now(timezone.utc):
131-
return JumaConfig.auth
123+
def requests_auth(username, password, **kwargs):
124+
if StaxConfig.expiration and StaxConfig.expiration > datetime.now(timezone.utc):
125+
return StaxConfig.auth
132126

133-
return StaxAuth("ApiAuth").requests_auth(username, password)
127+
return StaxAuth("ApiAuth").requests_auth(username, password, **kwargs)

staxapp/config.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,6 @@ def set_config(cls):
3737
cls.base_url = f"https://api.{cls.STAX_REGION}/{cls.API_VERSION}"
3838
config_url = f"{cls.api_base_url()}/public/config"
3939
config_response = requests.get(config_url)
40-
# logging.debug(f"IDAM: get config from {config_url}")
4140
try:
4241
config_response.raise_for_status()
4342
except requests.exceptions.HTTPError as e:
@@ -71,8 +70,7 @@ def schema_url(cls):
7170
return f"{cls.base_url}/public/api-document"
7271

7372
@classmethod
74-
def auth(cls):
75-
# logging.debug(f"AUTHCLASS: {cls.auth_class}")
73+
def get_auth_class(cls):
7674
if cls.auth_class is None:
7775
from staxapp.auth import ApiTokenAuth
7876

staxapp/contract.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,6 @@ def validate(cls, data, component):
3838
Validates a request body against an component in a openapi3.0 template
3939
"""
4040
if not cls._swagger_doc:
41-
# logging.info(f"SCHEMA: no swagger defined, loading default template")
4241
cls.set_schema(cls.default_swagger_template())
4342

4443
components = cls._resolved_schema.get("components")

staxapp/exceptions.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,6 @@ def __str__(self):
2424

2525
class ValidationException(Exception):
2626
def __init__(self, message):
27-
# logging.info(f"VALIDATE: {message}")
2827
self.message = message
2928

3029

staxapp/openapi.py

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,7 @@
11
import json
2-
import logging
32
import os
4-
import uuid
53

64
import requests
7-
from jsonschema import validate
8-
from prance import ResolvingParser
95

106
from staxapp.api import Api
117
from staxapp.auth import ApiTokenAuth
@@ -26,7 +22,6 @@ def __init__(self, classname, lambda_client=None):
2622
if not self._initialized:
2723
self._map_paths_to_operations()
2824
StaxContract.set_schema(self._schema)
29-
# logging.info(f"{self._operation_map}")
3025
if not self._operation_map.get(self.classname):
3126
raise ValidationException(
3227
f"No such class: {self.classname}. Please use one of {list(self._operation_map)}"
@@ -44,14 +39,12 @@ def __init__(self, classname, lambda_client=None):
4439
@classmethod
4540
def _load_schema(cls):
4641
if Config.load_live_schema:
47-
# logging.info(f"SCHEMA: loading from {Config.schema_url()}")
4842
schema_response = requests.get(Config.schema_url())
4943
schema_response.raise_for_status()
5044
cls._schema = schema_response.json()
5145
else:
5246
current_dir = os.path.abspath(os.path.dirname(__file__))
5347
schema_file = f"{current_dir}/data/schema.json"
54-
# logging.info(f"SCHEMA: loading from {schema_file}")
5548
with open(schema_file, "r") as f:
5649
cls._schema = json.load(f)
5750

0 commit comments

Comments
 (0)