|
| 1 | +# Copyright (c) Microsoft Corporation. |
| 2 | +# Licensed under the MIT License. |
| 3 | + |
| 4 | +import os |
| 5 | +from typing import Optional |
| 6 | + |
| 7 | +from azure.core.credentials import AccessToken, TokenCredential |
| 8 | +from azure.core.exceptions import ClientAuthenticationError |
| 9 | + |
| 10 | +from fabric_cli.core import fab_constant as con |
| 11 | +from fabric_cli.core import fab_logger |
| 12 | +from fabric_cli.core.fab_auth import FabAuth |
| 13 | + |
| 14 | +# Bridge-specific: strict .default scope validation |
| 15 | +VALID_DEFATULT_SCOPES = { |
| 16 | + con.SCOPE_FABRIC_DEFAULT[0], |
| 17 | +} |
| 18 | + |
| 19 | +class MsalTokenCredential(TokenCredential): |
| 20 | + """ |
| 21 | + A TokenCredential implementation that wraps the existing Fabric CLI MSAL authentication. |
| 22 | + |
| 23 | + This bridge uses the CLI user's existing authentication and provides it through |
| 24 | + the Azure Identity TokenCredential interface. It handles refresh token management |
| 25 | + automatically via MSAL's silent acquisition flow. |
| 26 | + |
| 27 | + The credential will use whatever authentication the CLI user has already configured: |
| 28 | + - User authentication (from fab auth login) |
| 29 | + - Service principal (from environment variables) |
| 30 | + - Managed identity (when running in Azure) |
| 31 | + - Environment tokens (pre-acquired tokens) |
| 32 | + |
| 33 | + Args: |
| 34 | + fab_auth: FabAuth instance containing the authentication configuration. |
| 35 | + """ |
| 36 | + |
| 37 | + def __init__(self, fab_auth: FabAuth): |
| 38 | + self._fab_auth = fab_auth |
| 39 | + |
| 40 | + def get_token( |
| 41 | + self, |
| 42 | + *scopes: str, |
| 43 | + claims: Optional[str] = None, |
| 44 | + tenant_id: Optional[str] = None, |
| 45 | + enable_cae: bool = False, |
| 46 | + **kwargs |
| 47 | + ) -> AccessToken: |
| 48 | + """ |
| 49 | + Get an access token for the specified scopes. |
| 50 | + |
| 51 | + Args: |
| 52 | + scopes: The scopes for which to request the token |
| 53 | + claims: Optional claims challenge |
| 54 | + tenant_id: Optional tenant ID (not used in this implementation) |
| 55 | + enable_cae: Whether to enable Continuous Access Evaluation (not used) |
| 56 | + **kwargs: Additional keyword arguments |
| 57 | + |
| 58 | + Returns: |
| 59 | + AccessToken object containing the token and expiration time |
| 60 | + |
| 61 | + Raises: |
| 62 | + ClientAuthenticationError: When authentication is not available |
| 63 | + """ |
| 64 | + for scope in scopes: |
| 65 | + if scope not in VALID_DEFATULT_SCOPES: |
| 66 | + fab_logger.log_debug(f"Invalid scope rejected: {scope}") |
| 67 | + raise ClientAuthenticationError( |
| 68 | + f"Security validation failed: requested scope is not supported." |
| 69 | + f"Invalid scope: {scope}. " |
| 70 | + f"Allowed scopes: {', '.join(VALID_DEFATULT_SCOPES)}" |
| 71 | + ) |
| 72 | + try: |
| 73 | + msal_result = self._fab_auth.acquire_token( |
| 74 | + list(scopes), |
| 75 | + interactive_renew=False # Bridge is always headless |
| 76 | + ) |
| 77 | + |
| 78 | + return self._to_azure_access_token(msal_result) |
| 79 | + |
| 80 | + except Exception as e: |
| 81 | + fab_logger.log_debug(f"Token acquisition failed: {e}") |
| 82 | + raise ClientAuthenticationError( |
| 83 | + f"\n{str(e)}" |
| 84 | + ) from e |
| 85 | + |
| 86 | + def _to_azure_access_token(self, msal_result: dict) -> AccessToken: |
| 87 | + """Convert MSAL result to AccessToken object.""" |
| 88 | + access_token = msal_result["access_token"] |
| 89 | + |
| 90 | + # Handle expires_on - MSAL returns Unix timestamp as string or int |
| 91 | + expires_on = msal_result.get("expires_on") |
| 92 | + if expires_on: |
| 93 | + if isinstance(expires_on, str): |
| 94 | + expires_on = int(expires_on) |
| 95 | + else: |
| 96 | + # Fallback: calculate from expires_in if available |
| 97 | + expires_in = msal_result.get("expires_in") |
| 98 | + if expires_in: |
| 99 | + import time |
| 100 | + expires_on = int(time.time() + expires_in) |
| 101 | + else: |
| 102 | + raise ClientAuthenticationError( |
| 103 | + "Token expiration time is required but not available") |
| 104 | + return AccessToken(access_token, int(expires_on)) |
| 105 | + |
| 106 | + def close(self) -> None: |
| 107 | + """Close the credential (no-op for this implementation).""" |
| 108 | + pass |
| 109 | + |
| 110 | + |
| 111 | +def create_fabric_token_credential() -> TokenCredential: |
| 112 | + """ |
| 113 | + Create a TokenCredential that uses the current Fabric CLI authentication. |
| 114 | + |
| 115 | + This function creates a TokenCredential that wraps the existing MSAL authentication |
| 116 | + from the Fabric CLI. It will use whatever authentication the user has already |
| 117 | + configured (user login, service principal, managed identity, or environment tokens). |
| 118 | + Returns: |
| 119 | + TokenCredential that can be used with Azure SDKs |
| 120 | + |
| 121 | + Raises: |
| 122 | + ClientAuthenticationError: When no authentication is configured |
| 123 | + """ |
| 124 | + fab_auth = FabAuth() |
| 125 | + |
| 126 | + identity_type = fab_auth.get_identity_type() |
| 127 | + |
| 128 | + fab_logger.log_debug(f"Creating TokenCredential for identity type: {identity_type}") |
| 129 | + return MsalTokenCredential(fab_auth) |
| 130 | + |
0 commit comments