Skip to content

Commit

Permalink
Change logging from "root" to module name
Browse files Browse the repository at this point in the history
  • Loading branch information
daviddenis-stx committed Dec 14, 2023
1 parent 7cbb636 commit 1ad75d8
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 21 deletions.
18 changes: 10 additions & 8 deletions src/systemathics/apis/helpers/channel_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
import urllib.request
import logging
import pathlib

logger = logging.getLogger("channel_helpers")

DEFAULT_ENDPOINT = "https://grpc.ganymede.cloud"

Expand All @@ -28,7 +30,7 @@ def get_grpc_channel(endpoint = "") -> grpc.Channel:
endpoint = endpoint if endpoint else os.getenv('GRPC_APIS','')
endpoint = endpoint if endpoint else DEFAULT_ENDPOINT # if no endpoint was provided, use the default one
endpoint = endpoint if endpoint.startswith("http") else f"https://{endpoint}" # if no scheme was provided, assume it's https
logging.debug(f"get_grpc_channel: Using endpoint {endpoint}")
logger.debug(f"get_grpc_channel: Using endpoint {endpoint}")
return _get_grpc_channel(endpoint)

def _get_grpc_channel(endpoint: str) -> grpc.Channel:
Expand All @@ -52,7 +54,7 @@ def get_aio_grpc_channel(endpoint = "") -> grpc.aio.Channel:
endpoint = endpoint if endpoint else os.getenv('GRPC_APIS','')
endpoint = endpoint if endpoint else DEFAULT_ENDPOINT # if no endpoint was provided, use the default one
endpoint = endpoint if endpoint.startswith("http") else f"https://{endpoint}" # if no scheme was provided, assume it's https
logging.debug(f"get_aio_grpc_channel: Using endpoint {endpoint}")
logger.debug(f"get_aio_grpc_channel: Using endpoint {endpoint}")
return _get_aio_grpc_channel(endpoint)

def _get_aio_grpc_channel(endpoint: str) -> grpc.aio.Channel:
Expand All @@ -68,7 +70,7 @@ def _get_channel_credentials() -> grpc.ChannelCredentials:
ssl_cert_file = os.getenv('SSL_CERT_FILE','')
if (ssl_cert_file !='' ):
if (not(os.path.isfile(ssl_cert_file))):
logging.warn(f"_get_channel_credentials: Found SSL_CERT_FILE={ssl_cert_file} environment variable, but file doesn't exist!")
logger.warn(f"_get_channel_credentials: Found SSL_CERT_FILE={ssl_cert_file} environment variable, but file doesn't exist!")
cabundle = ssl_cert_file
# Otherwise try autodetection
else:
Expand All @@ -93,13 +95,13 @@ def _get_current_mozilla_cacert() -> str:
return cafile

try:
logging.debug(f"_get_current_mozilla_cacert: Downloading {url} to {cafile}")
logger.debug(f"_get_current_mozilla_cacert: Downloading {url} to {cafile}")
with urllib.request.urlopen(url) as input:
with open(cafile, 'wb') as output:
output.write(input.read())
logging.debug(f"_get_current_mozilla_cacert: Downloaded {url} to {cafile}")
logger.debug(f"_get_current_mozilla_cacert: Downloaded {url} to {cafile}")
except urllib.error.URLError as e:
logging.debug(f"_get_current_mozilla_cacert: Could not get {url}: {e.reason}")
logger.debug(f"_get_current_mozilla_cacert: Could not get {url}: {e.reason}")

return cafile

Expand All @@ -117,10 +119,10 @@ def _autodetect_ca_bundle() -> str:
# probe
for cabundle in cabundles:
if (os.path.isfile(cabundle)):
logging.debug(f"_autodetect_ca_bundle: Using CA bundle {cabundle}")
logger.debug(f"_autodetect_ca_bundle: Using CA bundle {cabundle}")
return cabundle

# fallback to current mozilla trusted root CA certificate chain
cabundle = _get_current_mozilla_cacert()
logging.debug(f"_autodetect_ca_bundle: Using CA bundle {cabundle}")
logger.debug(f"_autodetect_ca_bundle: Using CA bundle {cabundle}")
return cabundle
28 changes: 15 additions & 13 deletions src/systemathics/apis/helpers/token_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
import jwt
import logging

logger = logging.getLogger("token_helpers")

DEFAULT_AUDIENCE = "https://ganymede-prod"

DEFAULT_TENANT = "ganymede-prod.eu.auth0.com"
Expand Down Expand Up @@ -46,7 +48,7 @@ def get_token() -> str:

# If we have a token in AUTH0_TOKEN env var, use it as is
if (auth0_token):
logging.debug(f"get_token: Using token from AUTH0_TOKEN")
logger.debug(f"get_token: Using token from AUTH0_TOKEN")
return f"Bearer {auth0_token}" # valid, use it

# If we have a persisted token
Expand All @@ -58,10 +60,10 @@ def get_token() -> str:

if (auth0_token):
if (_validate_token(auth0_token, tenant, audience, "from file " + tokenfile)):
logging.debug(f"get_token: Using token from {tokenfile}")
logger.debug(f"get_token: Using token from {tokenfile}")
return f"Bearer {auth0_token}" # valid, use it
else:
logging.debug(f"get_token: Deleting {tokenfile} (invalid)")
logger.debug(f"get_token: Deleting {tokenfile} (invalid)")
os.remove(tokenfile) # invalid, delete it

# At this stage, if we don't have a valid token, ask one using Auth0 REST API (we need CLIENT_ID and CLIENT_SECRET; Optionally AUDIENCE and TENANT)
Expand All @@ -84,7 +86,7 @@ def _request_token_using_auth0_rest_api(client_id, client_secret, audience, tena
if (tenant == ""):
raise Exception(f"tenant cannot be null")

logging.debug(f"_request_token_using_auth0_rest_api: Calling auth0 API at {tenant} to get a token")
logger.debug(f"_request_token_using_auth0_rest_api: Calling auth0 API at {tenant} to get a token")

# Setup connection and payload
conn = http.client.HTTPSConnection(tenant)
Expand Down Expand Up @@ -117,7 +119,7 @@ def _request_token_using_auth0_rest_api(client_id, client_secret, audience, tena
os.remove(tokenfile)
with open(tokenfile, 'w') as output:
output.write(json_data['access_token'])
logging.debug(f"_request_token_using_auth0_rest_api: Pushed token to file {tokenfile}")
logger.debug(f"_request_token_using_auth0_rest_api: Pushed token to file {tokenfile}")
return token

def _cleanup(input: str) -> str:
Expand All @@ -140,33 +142,33 @@ def _validate_token(token: str, tenant: str, audience: str, token_label: str) ->
if not os.path.exists(pubkeyfile):
try:
url = f'https://{tenant}/.well-known/jwks.json'
logging.debug(f"_validate_token: Downloading public key at {url} to {pubkeyfile}")
logger.debug(f"_validate_token: Downloading public key at {url} to {pubkeyfile}")
with urllib.request.urlopen(url) as input:
with open(pubkeyfile, 'wb') as output:
pubkey = input.read()
output.write(pubkey)
except urllib.error.URLError as e:
logging.error(f"Could not get {url}: {e.reason}")
logger.error(f"Could not get {url}: {e.reason}")
raise

jwks_url = "file:///" + pubkeyfile
logging.debug(f"_validate_token: Using public key store at {jwks_url}")
logger.debug(f"_validate_token: Using public key store at {jwks_url}")
jwks_client = jwt.PyJWKClient(jwks_url)
header = jwt.get_unverified_header(token)
kid = header["kid"]
alg = [header["alg"]]
key = jwks_client.get_signing_key(kid).key
try:
logging.debug(f"_validate_token: Validating token {token_label} with kid={kid} alg={alg} tenant={tenant} audience={audience}")
logger.debug(f"_validate_token: Validating token {token_label} with kid={kid} alg={alg} tenant={tenant} audience={audience}")
jwt.decode(token, key, alg, audience=audience)
logging.debug(f"_validate_token: Validated token {token_label} with kid={kid} alg={alg} tenant={tenant} audience={audience}")
logger.debug(f"_validate_token: Validated token {token_label} with kid={kid} alg={alg} tenant={tenant} audience={audience}")
return True
except jwt.exceptions.ExpiredSignatureError as expiredError:
logging.error(f"_validate_token: Token is expired: {expiredError}")
logger.error(f"_validate_token: Token is expired: {expiredError}")
return False
except jwt.exceptions.DecodeError as decodeError:
logging.error(f"_validate_token: Token could not be decoded: {decodeError}")
logger.error(f"_validate_token: Token could not be decoded: {decodeError}")
return False
except Exception as ex:
logging.error(f"_validate_token: Token is invalid: {ex}")
logger.error(f"_validate_token: Token is invalid: {ex}")
return False

0 comments on commit 1ad75d8

Please sign in to comment.