async def test_bearer_policy_token_caching():
    good_for_one_hour = AccessToken("token", time.time() + 3600)
    expected_token = good_for_one_hour
    get_token_calls = 0

    async def get_token(_):
        nonlocal get_token_calls
        get_token_calls += 1
        return expected_token

    credential = Mock(get_token=get_token)
    policies = [AsyncBearerTokenCredentialPolicy(credential, "scope"), Mock(send=asyncio.coroutine(lambda _: Mock()))]
    pipeline = AsyncPipeline(transport=Mock, policies=policies)

    await pipeline.run(HttpRequest("GET", "https://spam.eggs"))
    assert get_token_calls == 1  # policy has no token at first request -> it should call get_token

    await pipeline.run(HttpRequest("GET", "https://spam.eggs"))
    assert get_token_calls == 1  # token is good for an hour -> policy should return it from cache

    expired_token = AccessToken("token", time.time())
    get_token_calls = 0
    expected_token = expired_token
    policies = [AsyncBearerTokenCredentialPolicy(credential, "scope"), Mock(send=asyncio.coroutine(lambda _: Mock()))]
    pipeline = AsyncPipeline(transport=Mock(), policies=policies)

    await pipeline.run(HttpRequest("GET", "https://spam.eggs"))
    assert get_token_calls == 1

    await pipeline.run(HttpRequest("GET", "https://spam.eggs"))
    assert get_token_calls == 2  # token expired -> policy should call get_token
async def test_bearer_policy_adds_header():
    """The bearer token policy should add a header containing a token from its credential"""
    # 2524608000 == 01/01/2050 @ 12:00am (UTC)
    expected_token = AccessToken("expected_token", 2524608000)

    async def verify_authorization_header(request):
        assert request.http_request.headers[
            "Authorization"] == "Bearer {}".format(expected_token.token)
        return Mock()

    get_token_calls = 0

    async def get_token(_):
        nonlocal get_token_calls
        get_token_calls += 1
        return expected_token

    fake_credential = Mock(get_token=get_token)
    policies = [
        AsyncBearerTokenCredentialPolicy(fake_credential, "scope"),
        Mock(send=verify_authorization_header)
    ]
    pipeline = AsyncPipeline(transport=Mock(), policies=policies)

    await pipeline.run(HttpRequest("GET", "https://spam.eggs"), context=None)
    assert get_token_calls == 1

    await pipeline.run(HttpRequest("GET", "https://spam.eggs"), context=None)
    # Didn't need a new token
    assert get_token_calls == 1
Exemple #3
0
    def _create_appconfig_pipeline(self, credential, base_url=None, aad_mode=False, **kwargs):
        transport = kwargs.get('transport')
        policies = kwargs.get('policies')

        if policies is None:  # [] is a valid policy list
            if aad_mode:
                scope = base_url.strip("/") + "/.default"
                if hasattr(credential, "get_token"):
                    credential_policy = AsyncBearerTokenCredentialPolicy(credential, scope)
                else:
                    raise TypeError("Please provide an instance from azure-identity "
                                    "or a class that implement the 'get_token protocol")
            else:
                credential_policy = AppConfigRequestsCredentialsPolicy(credential)

            policies = [
                self._config.headers_policy,
                self._config.user_agent_policy,
                credential_policy,
                self._config.retry_policy,
                SyncTokenPolicy(),
                self._config.logging_policy,  # HTTP request/response log
                DistributedTracingPolicy(**kwargs),
                HttpLoggingPolicy(**kwargs),
            ]

        if not transport:
            transport = AsyncioRequestsTransport(**kwargs)

        return AsyncPipeline(
            transport,
            policies,
        )
Exemple #4
0
async def test_bearer_policy_optionally_enforces_https():
    """HTTPS enforcement should be controlled by a keyword argument, and enabled by default"""
    async def assert_option_popped(request, **kwargs):
        assert "enforce_https" not in kwargs, "AsyncBearerTokenCredentialPolicy didn't pop the 'enforce_https' option"

    credential = Mock(get_token=lambda *_, **__: get_completed_future(
        AccessToken("***", 42)))
    pipeline = AsyncPipeline(
        transport=Mock(send=assert_option_popped),
        policies=[AsyncBearerTokenCredentialPolicy(credential, "scope")])

    # by default and when enforce_https=True, the policy should raise when given an insecure request
    with pytest.raises(ServiceRequestError):
        await pipeline.run(HttpRequest("GET", "http://not.secure"))
    with pytest.raises(ServiceRequestError):
        await pipeline.run(HttpRequest("GET", "http://not.secure"),
                           enforce_https=True)

    # when enforce_https=False, an insecure request should pass
    await pipeline.run(HttpRequest("GET", "http://not.secure"),
                       enforce_https=False)

    # https requests should always pass
    await pipeline.run(HttpRequest("GET", "https://secure"),
                       enforce_https=False)
    await pipeline.run(HttpRequest("GET", "https://secure"),
                       enforce_https=True)
    await pipeline.run(HttpRequest("GET", "https://secure"))
Exemple #5
0
    def __init__(self, endpoint: str, credential: CommunicationTokenCredential,
                 thread_id: str, **kwargs: Any):  # type: (...) -> None
        if not thread_id:
            raise ValueError("thread_id can not be None or empty")

        if not credential:
            raise ValueError("credential can not be None")

        try:
            if not endpoint.lower().startswith('http'):
                endpoint = "https://" + endpoint
        except AttributeError:
            raise ValueError("Host URL must be a string")

        parsed_url = urlparse(endpoint.rstrip('/'))
        if not parsed_url.netloc:
            raise ValueError("Invalid URL: {}".format(endpoint))

        self._thread_id = thread_id
        self._endpoint = endpoint
        self._credential = credential

        self._client = AzureCommunicationChatService(
            endpoint,
            authentication_policy=AsyncBearerTokenCredentialPolicy(
                self._credential),
            sdk_moniker=SDK_MONIKER,
            **kwargs)
async def test_bearer_policy_adds_header():
    """The bearer token policy should add a header containing a token from its credential"""
    expected_token = "expected_token"

    async def verify_authorization_header(request):
        assert request.http_request.headers[
            "Authorization"] == "Bearer {}".format(expected_token)

    get_token_calls = 0

    async def get_token(_):
        nonlocal get_token_calls
        get_token_calls += 1
        return expected_token

    fake_credential = Mock(get_token=get_token)
    policies = [
        AsyncBearerTokenCredentialPolicy(fake_credential, "scope"),
        Mock(spec=HTTPPolicy, send=verify_authorization_header),
    ]
    pipeline = AsyncPipeline(transport=Mock(spec=AsyncHttpTransport),
                             policies=policies)

    await pipeline.run(HttpRequest("GET", "https://spam.eggs"), context=None)
    assert get_token_calls == 1
 def _build_pipeline(self, **kwargs):  # pylint: disable=no-self-use
     transport = kwargs.get('transport')
     policies = kwargs.get('policies')
     credential_policy = \
         AsyncServiceBusSharedKeyCredentialPolicy(self._endpoint, self._credential, "Authorization") \
         if isinstance(self._credential, ServiceBusSharedKeyCredential) \
         else AsyncBearerTokenCredentialPolicy(self._credential, JWT_TOKEN_SCOPE)
     if policies is None:  # [] is a valid policy list
         policies = [
             RequestIdPolicy(**kwargs),
             self._config.headers_policy,
             self._config.user_agent_policy,
             self._config.proxy_policy,
             ContentDecodePolicy(**kwargs),
             ServiceBusXMLWorkaroundPolicy(),
             self._config.redirect_policy,
             self._config.retry_policy,
             credential_policy,
             self._config.logging_policy,
             DistributedTracingPolicy(**kwargs),
             HttpLoggingPolicy(**kwargs),
         ]
     if not transport:
         transport = AioHttpTransport(**kwargs)
     return AsyncPipeline(transport, policies)
def get_authentication_policy(
        endpoint, # type: str
        credential, # type: TokenCredential or str
        decode_url=False, # type: bool
        is_async=False, # type: bool
):
    # type: (...) -> BearerTokenCredentialPolicy or HMACCredentialPolicy
    """Returns the correct authentication policy based
    on which credential is being passed.
    :param endpoint: The endpoint to which we are authenticating to.
    :type endpoint: str
    :param credential: The credential we use to authenticate to the service
    :type credential: TokenCredential or str
    :param isAsync: For async clients there is a need to decode the url
    :type bool: isAsync or str
    :rtype: ~azure.core.pipeline.policies.BearerTokenCredentialPolicy
    ~HMACCredentialsPolicy
    """

    if credential is None:
        raise ValueError("Parameter 'credential' must not be None.")
    if hasattr(credential, "get_token"):
        if is_async:
            from azure.core.pipeline.policies import AsyncBearerTokenCredentialPolicy
            return AsyncBearerTokenCredentialPolicy(
                credential, "https://communication.azure.com//.default")
        from azure.core.pipeline.policies import BearerTokenCredentialPolicy
        return BearerTokenCredentialPolicy(
            credential, "https://communication.azure.com//.default")
    if isinstance(credential, str):
        from .._shared.policy import HMACCredentialsPolicy
        return HMACCredentialsPolicy(endpoint, credential, decode_url=decode_url)

    raise TypeError("Unsupported credential: {}. Use an access token string to use HMACCredentialsPolicy"
                    "or a token credential from azure.identity".format(type(credential)))
    def _create_pipeline(self, credential, **kwargs):
        credential_policy = None
        if credential is None:
            raise ValueError("Parameter 'credential' must not be None.")
        if hasattr(credential, "get_token"):
            credential_policy = AsyncBearerTokenCredentialPolicy(
                credential, "https://cognitiveservices.azure.com/.default")
        elif isinstance(credential, six.string_types):
            credential_policy = CognitiveServicesCredentialPolicy(credential)
        elif credential is not None:
            raise TypeError("Unsupported credential: {}".format(credential))

        config = self._create_configuration(**kwargs)
        config.transport = kwargs.get("transport")  # type: ignore
        if not config.transport:
            try:
                from azure.core.pipeline.transport import AioHttpTransport
            except ImportError:
                raise ImportError(
                    "Unable to create async transport. Please check aiohttp is installed."
                )
            config.transport = AioHttpTransport(**kwargs)

        policies = [
            config.headers_policy, config.user_agent_policy,
            RequestIdPolicy(**kwargs), config.proxy_policy,
            AsyncRedirectPolicy(**kwargs),
            AsyncRetryPolicy(**kwargs), credential_policy,
            config.logging_policy,
            AsyncTextAnalyticsResponseHook(**kwargs),
            DistributedTracingPolicy(**kwargs),
            HttpLoggingPolicy(**kwargs)
        ]
        return AsyncPipeline(config.transport, policies=policies)
 def _configure_credential(self, credential):
     # type: (Any) -> None
     self._credential_policy = None
     if hasattr(credential, "get_token"):
         self._credential_policy = AsyncBearerTokenCredentialPolicy(
             credential, STORAGE_OAUTH_SCOPE)
     elif isinstance(credential, SharedKeyCredentialPolicy):
         self._credential_policy = credential
     elif credential is not None:
         raise TypeError("Unsupported credential: {}".format(credential))
Exemple #11
0
 def create_config(credential: "TokenCredential",
                   api_version: str = None,
                   **kwargs: Mapping[str, Any]) -> Configuration:
     if api_version is None:
         api_version = KeyVaultClient.DEFAULT_API_VERSION
     config = KeyVaultClient.get_configuration_class(api_version,
                                                     aio=True)(credential,
                                                               **kwargs)
     config.authentication_policy = AsyncBearerTokenCredentialPolicy(
         credential, KEY_VAULT_SCOPE)
     return config
Exemple #12
0
    def __init__(self, endpoint: str, account_id: str, account_domain: str,
                 credential: Union["AsyncTokenCredential", AzureKeyCredential,
                                   AccessToken], **kwargs) -> None:

        self._api_version = kwargs.pop("api_version",
                                       RemoteRenderingApiVersion.V2021_01_01)
        validate_api_version(self._api_version)

        self._account_id = account_id

        if not endpoint:
            raise ValueError("endpoint cannot be None")

        if not account_id:
            raise ValueError("account_id cannot be None")

        if not account_domain:
            raise ValueError("account_domain cannot be None")

        if not credential:
            raise ValueError("credential cannot be None")

        endpoint_url = kwargs.pop(
            'authentication_endpoint_url',
            construct_endpoint_url(account_domain))  # type: str

        if isinstance(credential, AccessToken):
            cred = StaticAccessTokenCredential(
                credential)  # type: AsyncTokenCredential
        elif isinstance(credential, AzureKeyCredential):
            cred = MixedRealityAccountKeyCredential(account_id=account_id,
                                                    account_key=credential)
        else:
            cred = credential
            # otherwise assume it is a TokenCredential and simply pass it through
        pipeline_credential = get_mixedreality_credential(
            account_id=account_id,
            account_domain=account_domain,
            credential=cred,
            endpoint_url=endpoint_url)

        self.polling_interval = kwargs.pop("polling_interval", 5)

        authentication_policy = AsyncBearerTokenCredentialPolicy(
            pipeline_credential, endpoint_url + '/.default')

        self._account_id = account_id

        self._client = RemoteRenderingRestClient(
            endpoint=endpoint,
            authentication_policy=authentication_policy,
            sdk_moniker=SDK_MONIKER,
            api_version=self._api_version,
            **kwargs)
Exemple #13
0
def get_metrics_authentication_policy(
        credential: 'TokenCredential') -> AsyncBearerTokenCredentialPolicy:
    """Returns the correct authentication policy
    """

    if credential is None:
        raise ValueError("Parameter 'credential' must not be None.")
    if hasattr(credential, "get_token"):
        return AsyncBearerTokenCredentialPolicy(
            credential, "https://management.azure.com/.default")

    raise TypeError("Unsupported credential")
def get_metrics_authentication_policy(
        credential: "AsyncTokenCredential",
        audience: str = None) -> AsyncBearerTokenCredentialPolicy:
    """Returns the correct authentication policy"""
    if not audience:
        audience = "https://management.azure.com/"
    scope = audience.rstrip('/') + "/.default"
    if credential is None:
        raise ValueError("Parameter 'credential' must not be None.")
    if hasattr(credential, "get_token"):
        return AsyncBearerTokenCredentialPolicy(credential, scope)

    raise TypeError("Unsupported credential")
async def test_bearer_policy_send():
    """The bearer token policy should invoke the next policy's send method and return the result"""
    expected_request = HttpRequest("GET", "https://spam.eggs")
    expected_response = Mock()

    async def verify_request(request):
        assert request.http_request is expected_request
        return expected_response

    fake_credential = Mock(get_token=asyncio.coroutine(lambda _: AccessToken("", 0)))
    policies = [AsyncBearerTokenCredentialPolicy(fake_credential, "scope"), Mock(send=verify_request)]
    response = await AsyncPipeline(transport=Mock(), policies=policies).run(expected_request)

    assert response is expected_response
Exemple #16
0
 def __init__(self, credential, **kwargs):  # pylint:disable=super-init-not-called
     self._set_universal(**kwargs)
     # async-specific azure pipeline policies
     if isinstance(credential, str):
         self.headers_policy.add_header("Ocp-Apim-Subscription-Key",
                                        credential)
     else:
         scopes = kwargs.pop("scopes", [])
         self.authentication_policy = AsyncBearerTokenCredentialPolicy(
             credential, *scopes, **kwargs)
     self.retry_policy = kwargs.get("retry_policy",
                                    AsyncRetryPolicy(**kwargs))
     self.redirect_policy = kwargs.get("redirect_policy",
                                       AsyncRedirectPolicy(**kwargs))
     self.transport = kwargs.get("transport", AioHttpTransport())
    def __init__(
            self,
            account_id: str,
            account_domain: str,
            credential: Union[AzureKeyCredential, "AsyncTokenCredential"],  #pylint: disable=unsubscriptable-object
            **kwargs) -> None:
        if not account_id:
            raise ValueError("account_id must be a non-empty string.")

        if not account_domain:
            raise ValueError("account_domain must be a non-empty string.")

        if not credential:
            raise ValueError("credential can not be None.")

        self._account_id = account_id
        self._account_domain = account_domain

        if isinstance(credential, AzureKeyCredential):
            credential = MixedRealityAccountKeyCredential(
                account_id, credential)

        self._credential = credential

        endpoint_url = kwargs.pop('custom_endpoint_url',
                                  construct_endpoint_url(account_domain))

        try:
            if not endpoint_url.lower().startswith('http'):
                endpoint_url = "https://" + endpoint_url
        except AttributeError as ex:
            raise ValueError("Host URL must be a string.") from ex

        parsed_url = urlparse(endpoint_url.rstrip('/'))
        if not parsed_url.netloc:
            raise ValueError("Invalid URL: {}".format(endpoint_url))

        self._endpoint_url = endpoint_url

        authentication_policy = AsyncBearerTokenCredentialPolicy(
            credential, [endpoint_url + '/.default'])

        self._client = MixedRealityStsRestClient(
            base_url=endpoint_url,
            authentication_policy=authentication_policy,
            sdk_moniker=SDK_MONIKER,
            **kwargs)
Exemple #18
0
 def _create_pipeline(self, credential, **kwargs):
     # type: (Any, **Any) -> Tuple[Configuration, Pipeline]
     self._credential_policy = None
     if hasattr(credential, 'get_token'):
         self._credential_policy = AsyncBearerTokenCredentialPolicy(
             credential, STORAGE_OAUTH_SCOPE)
     elif isinstance(credential, SharedKeyCredentialPolicy):
         self._credential_policy = credential
     elif isinstance(credential, AzureSasCredential):
         self._credential_policy = AzureSasCredentialPolicy(credential)
     elif credential is not None:
         raise TypeError("Unsupported credential: {}".format(credential))
     config = kwargs.get('_configuration') or create_configuration(**kwargs)
     if kwargs.get('_pipeline'):
         return config, kwargs['_pipeline']
     config.transport = kwargs.get('transport')  # type: ignore
     kwargs.setdefault("connection_timeout", CONNECTION_TIMEOUT)
     kwargs.setdefault("read_timeout", READ_TIMEOUT)
     if not config.transport:
         try:
             from azure.core.pipeline.transport import AioHttpTransport
         except ImportError:
             raise ImportError(
                 "Unable to create async transport. Please check aiohttp is installed."
             )
         config.transport = AioHttpTransport(**kwargs)
     policies = [
         QueueMessagePolicy(),
         config.headers_policy,
         config.proxy_policy,
         config.user_agent_policy,
         StorageContentValidation(),
         StorageRequestHook(**kwargs),
         self._credential_policy,
         ContentDecodePolicy(response_encoding="utf-8"),
         AsyncRedirectPolicy(**kwargs),
         StorageHosts(hosts=self._hosts, **kwargs),  # type: ignore
         config.retry_policy,
         config.logging_policy,
         AsyncStorageResponseHook(**kwargs),
         DistributedTracingPolicy(**kwargs),
         HttpLoggingPolicy(**kwargs),
     ]
     if kwargs.get("_additional_pipeline_policies"):
         policies = policies + kwargs.get("_additional_pipeline_policies")
     return config, AsyncPipeline(config.transport, policies=policies)
Exemple #19
0
async def test_preserves_enforce_https_opt_out():
    """The policy should use request context to preserve an opt out from https enforcement"""
    class ContextValidator(SansIOHTTPPolicy):
        def on_request(self, request):
            assert "enforce_https" in request.context, "'enforce_https' is not in the request's context"

    get_token = get_completed_future(AccessToken("***", 42))
    credential = Mock(get_token=lambda *_, **__: get_token)
    policies = [
        AsyncBearerTokenCredentialPolicy(credential, "scope"),
        ContextValidator()
    ]
    pipeline = AsyncPipeline(
        transport=Mock(send=lambda *_, **__: get_completed_future()),
        policies=policies)

    await pipeline.run(HttpRequest("GET", "http://not.secure"),
                       enforce_https=False)
Exemple #20
0
async def test_context_unmodified_by_default():
    """When no options for the policy accompany a request, the policy shouldn't add anything to the request context"""
    class ContextValidator(SansIOHTTPPolicy):
        def on_request(self, request):
            assert not any(
                request.context
            ), "the policy shouldn't add to the request's context"

    get_token = get_completed_future(AccessToken("***", 42))
    credential = Mock(get_token=lambda *_, **__: get_token)
    policies = [
        AsyncBearerTokenCredentialPolicy(credential, "scope"),
        ContextValidator()
    ]
    pipeline = AsyncPipeline(
        transport=Mock(send=lambda *_, **__: get_completed_future()),
        policies=policies)

    await pipeline.run(HttpRequest("GET", "https://secure"))
    def _create_pipeline(self,
                         credential,
                         endpoint=None,
                         aad_mode=False,
                         **kwargs):
        transport = kwargs.get('transport')
        policies = kwargs.get('policies')

        if policies is None:  # [] is a valid policy list
            if aad_mode:
                scope = endpoint.strip("/") + "/.default"
                if hasattr(credential, "get_token"):
                    credential_policy = AsyncBearerTokenCredentialPolicy(
                        credential, scope)
                else:
                    raise TypeError(
                        "Please provide an instance from azure-identity "
                        "or a class that implement the 'get_token protocol")
            else:
                credential_policy = MetricsAdvisorKeyCredentialPolicy(
                    credential)
            policies = [
                RequestIdPolicy(**kwargs),
                self._config.headers_policy,
                self._config.user_agent_policy,
                self._config.proxy_policy,
                ContentDecodePolicy(**kwargs),
                self._config.redirect_policy,
                self._config.retry_policy,
                credential_policy,
                self._config.logging_policy,  # HTTP request/response log
                DistributedTracingPolicy(**kwargs),
                self._config.http_logging_policy or HttpLoggingPolicy(**kwargs)
            ]

        if not transport:
            transport = AioHttpTransport(**kwargs)

        return AsyncPipeline(transport, policies)
async def test_bearer_policy_send():
    """The bearer token policy should invoke the next policy's send method and return the result"""
    expected_request = HttpRequest("GET", "https://spam.eggs")
    expected_response = Mock(spec=PipelineResponse)

    async def verify_request(request):
        assert request.http_request is expected_request
        return expected_response

    async def get_token(_):
        return ""

    fake_credential = Mock(get_token=get_token)
    policies = [
        AsyncBearerTokenCredentialPolicy(fake_credential, "scope"),
        Mock(spec=HTTPPolicy, send=verify_request),
    ]
    pipeline = AsyncPipeline(transport=Mock(spec=AsyncHttpTransport),
                             policies=policies)

    response = await pipeline.run(expected_request)

    assert response is expected_response
Exemple #23
0
    def __init__(self, arguments):
        super().__init__(arguments)

        token = AccessToken("**", int(time.time() + 3600))

        self.request = HttpRequest("GET", "https://localhost")

        credential = Mock(get_token=Mock(return_value=token))
        self.pipeline = Pipeline(
            transport=Mock(),
            policies=[BearerTokenCredentialPolicy(credential=credential)])

        completed_future = asyncio.Future()
        completed_future.set_result(token)
        async_credential = Mock(get_token=Mock(return_value=completed_future))

        # returning a token is okay because the policy does nothing with the transport's response
        async_transport = Mock(send=Mock(return_value=completed_future))
        self.async_pipeline = AsyncPipeline(
            async_transport,
            policies=[
                AsyncBearerTokenCredentialPolicy(credential=async_credential)
            ])
Exemple #24
0
 def _create_pipeline(self, credential, **kwargs):
     # type: (Any, **Any) -> Tuple[Configuration, Pipeline]
     credential_policy = None
     if hasattr(credential, 'get_token'):
         credential_policy = AsyncBearerTokenCredentialPolicy(credential, STORAGE_OAUTH_SCOPE)
     elif isinstance(credential, SharedKeyCredentialPolicy):
         credential_policy = credential
     elif credential is not None:
         raise TypeError("Unsupported credential: {}".format(credential))
     config = kwargs.get('_configuration') or create_configuration(**kwargs)
     if kwargs.get('_pipeline'):
         return config, kwargs['_pipeline']
     config.transport = kwargs.get('transport')  # type: ignore
     if 'connection_timeout' not in kwargs:
         kwargs['connection_timeout'] = DEFAULT_SOCKET_TIMEOUT[0] # type: ignore
     if not config.transport:
         try:
             from azure.core.pipeline.transport import AioHttpTransport
         except ImportError:
             raise ImportError("Unable to create async transport. Please check aiohttp is installed.")
         config.transport = AioHttpTransport(**kwargs)
     policies = [
         QueueMessagePolicy(),
         config.headers_policy,
         config.user_agent_policy,
         StorageContentValidation(),
         StorageRequestHook(**kwargs),
         credential_policy,
         ContentDecodePolicy(),
         AsyncRedirectPolicy(**kwargs),
         StorageHosts(hosts=self._hosts, **kwargs), # type: ignore
         config.retry_policy,
         config.logging_policy,
         AsyncStorageResponseHook(**kwargs),
         DistributedTracingPolicy(),
     ]
     return config, AsyncPipeline(config.transport, policies=policies)
Exemple #25
0
    def __init__(self, endpoint, credential, **kwargs):
        # type: (str, MetricsAdvisorKeyCredential, Any) -> None
        try:
            if not endpoint.lower().startswith('http'):
                endpoint = "https://" + endpoint
        except AttributeError:
            raise ValueError("Base URL must be a string.")

        if not credential:
            raise ValueError("Missing credential")

        self._endpoint = endpoint

        if isinstance(credential, MetricsAdvisorKeyCredential):
            self._client = AzureCognitiveServiceMetricsAdvisorRESTAPIOpenAPIV2(
                endpoint=endpoint,
                sdk_moniker=SDK_MONIKER,
                authentication_policy=MetricsAdvisorKeyCredentialPolicy(
                    credential),
                **kwargs)
        else:
            if hasattr(credential, "get_token"):
                credential_scopes = kwargs.pop(
                    'credential_scopes',
                    ['https://cognitiveservices.azure.com/.default'])
                credential_policy = AsyncBearerTokenCredentialPolicy(
                    credential, *credential_scopes)
            else:
                raise TypeError(
                    "Please provide an instance from azure-identity "
                    "or a class that implement the 'get_token protocol")
            self._client = AzureCognitiveServiceMetricsAdvisorRESTAPIOpenAPIV2(
                endpoint=endpoint,
                sdk_moniker=SDK_MONIKER,
                authentication_policy=credential_policy,
                **kwargs)
Exemple #26
0
    def __init__(self, arguments):
        super().__init__(arguments)

        token = AccessToken("**", int(time.time() + 3600))

        self.request = HttpRequest("GET", "https://localhost")

        credential = Mock(get_token=Mock(return_value=token))
        self.pipeline = Pipeline(
            transport=Mock(),
            policies=[BearerTokenCredentialPolicy(credential=credential)])

        get_token_future = asyncio.Future()
        get_token_future.set_result(token)
        async_credential = Mock(get_token=Mock(return_value=get_token_future))

        send_future = asyncio.Future()
        send_future.set_result(Mock())
        async_transport = Mock(send=Mock(return_value=send_future))
        self.async_pipeline = AsyncPipeline(
            async_transport,
            policies=[
                AsyncBearerTokenCredentialPolicy(credential=async_credential)
            ])
async def test_bearer_policy_enforces_tls():
    credential = Mock()
    pipeline = AsyncPipeline(transport=Mock(), policies=[AsyncBearerTokenCredentialPolicy(credential, "scope")])
    with pytest.raises(ServiceRequestError):
        await pipeline.run(HttpRequest("GET", "http://not.secure"))
    def __init__(
        self,
        *,
        endpoint: str,
        credential: Union[ConfidentialLedgerCertificateCredential, "TokenCredential"],
        ledger_certificate_path: str,
        **kwargs: Any
    ) -> None:

        client = kwargs.get("generated_client")
        if client:
            # caller provided a configured client -> nothing left to initialize
            self._client = client
            return

        if not endpoint:
            raise ValueError("Expected endpoint to be a non-empty string")

        if not credential:
            raise ValueError("Expected credential to not be None")

        if not isinstance(ledger_certificate_path, str):
            raise TypeError("ledger_certificate_path must be a string")

        if ledger_certificate_path == "":
            raise ValueError(
                "If not None, ledger_certificate_path must be a non-empty string"
            )

        endpoint = endpoint.strip(" /")
        try:
            if not endpoint.startswith("https://"):
                self._endpoint = "https://" + endpoint
            else:
                self._endpoint = endpoint
        except AttributeError:
            raise ValueError("Confidential Ledger URL must be a string.")

        self.api_version = kwargs.pop("api_version", DEFAULT_VERSION)

        if not kwargs.get("transport", None):
            # Customize the transport layer to use client certificate authentication and validate
            # a self-signed TLS certificate.
            if isinstance(credential, ConfidentialLedgerCertificateCredential):
                # The async version of the client seems to expect a sequence of filenames.
                # azure/core/pipeline/transport/_aiohttp.py:163
                # > ssl_ctx.load_cert_chain(*cert)
                kwargs["connection_cert"] = (credential.certificate_path,)

            kwargs["connection_verify"] = ledger_certificate_path

        http_logging_policy = HttpLoggingPolicy(**kwargs)
        http_logging_policy.allowed_header_names.update(
            {
                "x-ms-keyvault-network-info",
                "x-ms-keyvault-region",
                "x-ms-keyvault-service-version",
            }
        )

        if not isinstance(credential, ConfidentialLedgerCertificateCredential):
            kwargs["authentication_policy"] = kwargs.pop(
                "authentication_policy",
                AsyncBearerTokenCredentialPolicy(
                    credential,
                    "https://confidential-ledger.azure.com/.default",
                    **kwargs
                ),
            )

        try:
            self._client = _ConfidentialLedgerClient(
                self._endpoint,
                api_version=self.api_version,
                http_logging_policy=http_logging_policy,
                sdk_moniker=USER_AGENT,
                **kwargs
            )
        except NotImplementedError:
            raise NotImplementedError(
                "This package doesn't support API version '{}'. ".format(
                    self.api_version
                )
                + "Supported versions: 0.1-preview"
            )