"""A test utility for generating tokens.""" from dataclasses import dataclass import os from typing import Any from jwtauth.utils import jwt_auth_from_environment from owsclient.constants import QA_ENVIRONMENT import requests from secrets_manager.python_ext import PythonSecretsManager APPLICATION = 'moneyhub-integration-test' # Secrets for ows-pdp-test application in auth0 MONEYHUB_APP_CLIENT_ID = 'MONEYHUB_APP_CLIENT_ID' MONEYHUB_APP_CLIENT_SECRET = 'MONEYHUB_APP_CLIENT_SECRET' # Test user in auth0 MONEYHUB_TEST_USER = 'MONEYHUB_TEST_USER' MONEYHUB_TEST_USER_PASSWORD = 'MONEYHUB_TEST_USER_PASSWORD' AUTH_URL = 'https://qa-orchard.auth0.com/oauth/token' AUTH_AUDIENCE = 'https://workstation.qaorch.com/api' @dataclass class LoginInfo: """Holds auth0 login info.""" username: str password: str auth_client_id: str auth_client_secret: str def _decode_token(token: str) -> dict[str, Any]: """Extract claims from token.""" auth = jwt_auth_from_environment(environment=QA_ENVIRONMENT) return auth.get_token(token) def _login_from_secrets_manager() -> LoginInfo: """Fetch Auth0 secrets from AWS Secret Manager.""" secrets_manager_client = PythonSecretsManager( environment=QA_ENVIRONMENT, service_name=APPLICATION ) username = secrets_manager_client.get_cred(MONEYHUB_TEST_USER) password = secrets_manager_client.get_cred(MONEYHUB_TEST_USER_PASSWORD) auth_client_id = secrets_manager_client.get_cred(MONEYHUB_APP_CLIENT_ID) auth_client_secret = secrets_manager_client.get_cred(MONEYHUB_APP_CLIENT_SECRET) return LoginInfo( username=username, password=password, auth_client_id=auth_client_id, auth_client_secret=auth_client_secret, ) def generate_auth_token() -> str: """Generate Auth0 token for pdp test user.""" if not os.getenv('CI', False): personal_token = os.getenv('BEARER_TOKEN', '') if len(personal_token) > 0: return personal_token raise OSError('Add an authorisation token to your .env file. See README for more details.') loginInfo = _login_from_secrets_manager() data = { 'grant_type': 'password', 'username': loginInfo.username, 'password': loginInfo.password, 'audience': 'https://workstation.qaorch.com/api', 'client_id': loginInfo.auth_client_id, 'client_secret': loginInfo.auth_client_secret, } r = requests.post('https://qa-orchard.auth0.com/oauth/token', data=data) resp = r.json() if 'error' in resp: raise ValueError(f'Auth0 error: {resp}') return resp['access_token'] if __name__ == '__main__': token = generate_auth_token() print(f'Your token decoded: \n\n{_decode_token(token)}')