"""Lambda populate_m2m_jwt function module.""" import datetime import time import config from sentry_sdk import capture_exception from src.constants import general from auth0.authentication import GetToken from lambdacommon.common_config import logger from lambdacommon import util util.init_sentry_for_lambda() def handler(event, context): """Lambda entry point.""" call_datadog_with_metric(config.DATADOG_ATTEMPT) try: jwt = get_jwt_token(get_auth0_m2m_creds()) populate_jwt_to_secrets(jwt) call_datadog_with_metric(config.DATADOG_SUCCESS) return {'status': 'OK'} except Exception as e: capture_exception(e) logger.exception(str(e)) call_datadog_with_metric(config.DATADOG_FAILURE) raise e def get_auth0_m2m_creds(): """Get Auth0 M2M Client Credentials. Returns: dict: Auth0 M2M Client Credentials """ return { 'm2m_client_id': config.AUTH0_M2M_CLIENT_ID, 'm2m_client_secret': config.secrets_manager_client.get_secret( config.M2M_CLIENT_SECRET_NAME) } def get_jwt_token(m2m_client_creds): """Generate Auth0 m2m jwt token. Args: m2m_client_creds (dict): Auth0 M2M Client Credentials. Returns: str: Auth0 m2m jwt token """ get_token = GetToken( domain=config.AUTH0_DOMAIN, client_id=m2m_client_creds.get('m2m_client_id'), client_secret=m2m_client_creds.get('m2m_client_secret') ) return get_token.client_credentials(config.AUTH0_API_AUDIENCE) def populate_jwt_to_secrets(jwt): """Update jwt and jwt_expiry to secrets. Args: jwt (dict): oauth token response for jwt. Returns: None """ logger.info('Computing expiration time from the expires_in value for jwt') token_expiration_time = str( (datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta( seconds=jwt.get('expires_in'))).strftime('%Y-%m-%d %H:%M:%S.%f')) logger.info('Updating expiration time of jwt to secret') config.secrets_manager_client.update_secret( general.JWT_EXPIRY_SECRET_KEY, token_expiration_time) logger.info('Updating jwt to secret') config.secrets_manager_client.update_secret( general.JWT_SECRET_KEY, jwt.get('access_token')) logger.info('Finished') def call_datadog_with_metric(metric): """For Datadog Metric Call. Args: jwt (dict): oauth token response for jwt. Returns: None """ with util.datadog_connection( config.DATADOG_API_KEY, config.DATADOG_APP_KEY, ) as datadog_conn: now = time.time() datadog_conn.Metric.send([ { 'metric': '{}.{}'.format(general.SERVICE_NAME, metric), 'type': 'count', 'interval': 60, 'points': (now, 1), 'tags': [ 'environment:{}'.format(config.ENVIRONMENT) ] } ])