|
| 1 | +# -------------------------------------------------------------------------------------------- |
| 2 | +# Copyright (c) Microsoft Corporation. All rights reserved. |
| 3 | +# Licensed under the MIT License. See License.txt in the project root for license information. |
| 4 | +# -------------------------------------------------------------------------------------------- |
| 5 | + |
| 6 | +"""Authentication and client management for Analytics Frontend API""" |
| 7 | + |
| 8 | +from azure.cli.core._profile import Profile |
| 9 | +from azure.cli.core.commands.client_factory import get_subscription_id |
| 10 | +from azure.cli.core.util import CLIError |
| 11 | +from knack.log import get_logger |
| 12 | + |
| 13 | +logger = get_logger(__name__) |
| 14 | + |
| 15 | + |
| 16 | +def get_frontend_token(cmd): |
| 17 | + """Get access token from MSAL cache or Azure context |
| 18 | +
|
| 19 | + Authentication priority: |
| 20 | + 1. MSAL token (device code flow) - if user ran 'frontend login' |
| 21 | + 2. Azure CLI token (az login) - fallback |
| 22 | +
|
| 23 | + :param cmd: CLI command context |
| 24 | + :return: Tuple of (access_token, subscription, tenant) |
| 25 | + :raises: CLIError if token cannot be obtained |
| 26 | + """ |
| 27 | + from ._msal_auth import get_msal_token, get_auth_scope |
| 28 | + |
| 29 | + profile = Profile(cli_ctx=cmd.cli_ctx) |
| 30 | + subscription = get_subscription_id(cmd.cli_ctx) |
| 31 | + auth_scope = get_auth_scope(cmd) |
| 32 | + |
| 33 | + logger.debug("Using auth scope: %s", auth_scope) |
| 34 | + |
| 35 | + try: |
| 36 | + msal_token = get_msal_token(cmd) |
| 37 | + if msal_token: |
| 38 | + logger.debug("Using MSAL device code flow token") |
| 39 | + return (msal_token[0], subscription, msal_token[2]) |
| 40 | + |
| 41 | + logger.debug("Using Azure CLI (az login) token") |
| 42 | + return profile.get_raw_token( |
| 43 | + subscription=subscription, |
| 44 | + resource=auth_scope |
| 45 | + ) |
| 46 | + |
| 47 | + except Exception as ex: |
| 48 | + raise CLIError( |
| 49 | + f'Failed to get access token: {str(ex)}\n\n' |
| 50 | + 'Please authenticate using one of:\n' |
| 51 | + ' 1. az managedcleanroom frontend login (MSAL device code flow)\n' |
| 52 | + ' 2. az login (Azure CLI authentication)\n') |
| 53 | + |
| 54 | + |
| 55 | +def get_frontend_config(cmd): |
| 56 | + """Read frontend endpoint configuration from Azure CLI config |
| 57 | +
|
| 58 | + :param cmd: CLI command context |
| 59 | + :return: Configured endpoint URL or None |
| 60 | + :rtype: str or None |
| 61 | + """ |
| 62 | + config = cmd.cli_ctx.config |
| 63 | + return config.get('managedcleanroom-frontend', 'endpoint', fallback=None) |
| 64 | + |
| 65 | + |
| 66 | +def set_frontend_config(cmd, endpoint): |
| 67 | + """Store frontend endpoint in Azure CLI config |
| 68 | +
|
| 69 | + :param cmd: CLI command context |
| 70 | + :param endpoint: API endpoint URL to store |
| 71 | + :type endpoint: str |
| 72 | + """ |
| 73 | + cmd.cli_ctx.config.set_value( |
| 74 | + 'managedcleanroom-frontend', |
| 75 | + 'endpoint', |
| 76 | + endpoint) |
| 77 | + |
| 78 | + |
| 79 | +def get_frontend_client(cmd, endpoint=None): |
| 80 | + """Create Analytics Frontend API client with Azure authentication |
| 81 | +
|
| 82 | + Uses Profile.get_raw_token() to fetch access token from Azure context. |
| 83 | + Token is fetched fresh on every invocation. |
| 84 | +
|
| 85 | + :param cmd: CLI command context |
| 86 | + :param endpoint: Optional explicit endpoint URL (overrides config) |
| 87 | + :type endpoint: str |
| 88 | + :return: Configured AnalyticsFrontendAPI client |
| 89 | + :raises: CLIError if token fetch fails or endpoint not configured |
| 90 | + """ |
| 91 | + from .analytics_frontend_api import AnalyticsFrontendAPI |
| 92 | + from azure.core.pipeline.policies import BearerTokenCredentialPolicy, SansIOHTTPPolicy |
| 93 | + |
| 94 | + api_endpoint = endpoint or get_frontend_config(cmd) |
| 95 | + if not api_endpoint: |
| 96 | + raise CLIError( |
| 97 | + 'Analytics Frontend API endpoint not configured.\n' |
| 98 | + 'Configure using: az config set managedcleanroom-frontend.endpoint=<url>\n' |
| 99 | + 'Or use the --endpoint flag with your command.') |
| 100 | + |
| 101 | + access_token_obj, _, _ = get_frontend_token(cmd) |
| 102 | + |
| 103 | + logger.debug( |
| 104 | + "Creating Analytics Frontend API client for endpoint: %s", |
| 105 | + api_endpoint) |
| 106 | + |
| 107 | + # Check if this is a local development endpoint |
| 108 | + is_local = api_endpoint.startswith( |
| 109 | + 'http://localhost') or api_endpoint.startswith('http://127.0.0.1') |
| 110 | + |
| 111 | + # Create simple credential wrapper for the access token |
| 112 | + credential = type('TokenCredential', (), { |
| 113 | + 'get_token': lambda self, *args, **kwargs: access_token_obj |
| 114 | + })() |
| 115 | + |
| 116 | + if is_local: |
| 117 | + # For local development, create a custom auth policy that bypasses |
| 118 | + # HTTPS check |
| 119 | + class LocalBearerTokenPolicy(SansIOHTTPPolicy): |
| 120 | + """Bearer token policy that allows HTTP for local development""" |
| 121 | + |
| 122 | + def __init__(self, token_obj): |
| 123 | + self._token = token_obj # AccessToken object |
| 124 | + |
| 125 | + def on_request(self, request): |
| 126 | + """Add authorization header with bearer token""" |
| 127 | + # Extract token string from AccessToken object |
| 128 | + # The token might be a tuple ('Bearer', 'token_string') or just |
| 129 | + # the token string |
| 130 | + if hasattr(self._token, 'token'): |
| 131 | + token_value = self._token.token |
| 132 | + else: |
| 133 | + token_value = self._token |
| 134 | + |
| 135 | + # If it's a tuple, extract the actual token (second element) |
| 136 | + if isinstance(token_value, tuple) and len(token_value) >= 2: |
| 137 | + token_string = token_value[1] |
| 138 | + else: |
| 139 | + token_string = str(token_value) |
| 140 | + |
| 141 | + auth_header = f'Bearer {token_string}' |
| 142 | + logger.debug( |
| 143 | + "Setting Authorization header: Bearer %s...", token_string[:50]) |
| 144 | + request.http_request.headers['Authorization'] = auth_header |
| 145 | + |
| 146 | + auth_policy = LocalBearerTokenPolicy(access_token_obj) |
| 147 | + else: |
| 148 | + # For production, use standard bearer token policy with HTTPS |
| 149 | + # enforcement |
| 150 | + # Use configured auth_scope with .default suffix for Azure SDK |
| 151 | + from ._msal_auth import get_auth_scope |
| 152 | + scope = get_auth_scope(cmd) |
| 153 | + if not scope.endswith('/.default'): |
| 154 | + scope = f'{scope}/.default' |
| 155 | + |
| 156 | + auth_policy = BearerTokenCredentialPolicy( |
| 157 | + credential, |
| 158 | + scope |
| 159 | + ) |
| 160 | + |
| 161 | + # Return configured client |
| 162 | + return AnalyticsFrontendAPI( |
| 163 | + endpoint=api_endpoint, |
| 164 | + authentication_policy=auth_policy |
| 165 | + ) |
0 commit comments