def get_authentication_policy( endpoint, # type: str credential, # type: TokenCredential or str 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"): 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=is_async) 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): # type: (Any, **Any) -> Tuple[Configuration, Pipeline] self._credential_policy = None if hasattr(credential, "get_token"): self._credential_policy = BearerTokenCredentialPolicy( credential, STORAGE_OAUTH_SCOPE) elif isinstance(credential, SharedKeyCredentialPolicy): self._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 kwargs.setdefault("connection_timeout", CONNECTION_TIMEOUT) kwargs.setdefault("read_timeout", READ_TIMEOUT) if not config.transport: config.transport = RequestsTransport(**kwargs) policies = [ QueueMessagePolicy(), config.headers_policy, config.proxy_policy, config.user_agent_policy, StorageContentValidation(), StorageRequestHook(**kwargs), self._credential_policy, ContentDecodePolicy(response_encoding="utf-8"), RedirectPolicy(**kwargs), StorageHosts(hosts=self._hosts, **kwargs), config.retry_policy, config.logging_policy, StorageResponseHook(**kwargs), DistributedTracingPolicy(**kwargs), HttpLoggingPolicy(**kwargs) ] if kwargs.get("_additional_pipeline_policies"): policies = policies + kwargs.get("_additional_pipeline_policies") return config, Pipeline(config.transport, policies=policies)
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) def verify_authorization_header(request): assert request.http_request.headers[ "Authorization"] == "Bearer {}".format(expected_token.token) return Mock() fake_credential = Mock(get_token=Mock(return_value=expected_token)) policies = [ BearerTokenCredentialPolicy(fake_credential, "scope"), Mock(send=verify_authorization_header) ] pipeline = Pipeline(transport=Mock(), policies=policies) pipeline.run(HttpRequest("GET", "https://spam.eggs")) assert fake_credential.get_token.call_count == 1 pipeline.run(HttpRequest("GET", "https://spam.eggs")) # Didn't need a new token assert fake_credential.get_token.call_count == 1
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 = BearerTokenCredentialPolicy(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 )
def test_bearer_policy_optionally_enforces_https(): """HTTPS enforcement should be controlled by a keyword argument, and enabled by default""" def assert_option_popped(request, **kwargs): assert "enforce_https" not in kwargs, "BearerTokenCredentialPolicy didn't pop the 'enforce_https' option" return Mock() credential = Mock(get_token=lambda *_, **__: AccessToken("***", 42)) pipeline = Pipeline( transport=Mock(send=assert_option_popped), policies=[BearerTokenCredentialPolicy(credential, "scope")]) # by default and when enforce_https=True, the policy should raise when given an insecure request with pytest.raises(ServiceRequestError): pipeline.run(HttpRequest("GET", "http://not.secure")) with pytest.raises(ServiceRequestError): pipeline.run(HttpRequest("GET", "http://not.secure"), enforce_https=True) # when enforce_https=False, an insecure request should pass pipeline.run(HttpRequest("GET", "http://not.secure"), enforce_https=False) # https requests should always pass pipeline.run(HttpRequest("GET", "https://secure"), enforce_https=False) pipeline.run(HttpRequest("GET", "https://secure"), enforce_https=True) pipeline.run(HttpRequest("GET", "https://secure"))
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 = BearerTokenCredentialPolicy( credential, "https://cognitiveservices.azure.com/.default") elif isinstance(credential, AzureKeyCredential): credential_policy = AzureKeyCredentialPolicy( name="Ocp-Apim-Subscription-Key", credential=credential) elif credential is not None: raise TypeError( "Unsupported credential: {}. Use an instance of AzureKeyCredential " "or a token credential from azure.identity".format( type(credential))) config = self._create_configuration(**kwargs) config.transport = kwargs.get("transport") # type: ignore if not config.transport: config.transport = RequestsTransport(**kwargs) policies = [ config.headers_policy, config.user_agent_policy, RequestIdPolicy(**kwargs), config.proxy_policy, config.redirect_policy, config.retry_policy, credential_policy, config.logging_policy, TextAnalyticsResponseHookPolicy(**kwargs), DistributedTracingPolicy(**kwargs), HttpLoggingPolicy(**kwargs), ] return Pipeline(config.transport, policies=policies)
def __init__(self, endpoint: str, credential: CommunicationTokenCredential, **kwargs: Any) -> None: # type: (...) -> None 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._endpoint = endpoint self._credential = credential self._client = AzureCommunicationChatService( self._endpoint, authentication_policy=BearerTokenCredentialPolicy( self._credential), sdk_moniker=SDK_MONIKER, **kwargs)
def _create_pipeline(self, credential, **kwargs): # type: (Any, **Any) -> Tuple[Configuration, Pipeline] self._credential_policy = None if hasattr(credential, "get_token"): self._credential_policy = BearerTokenCredentialPolicy( credential, STORAGE_OAUTH_SCOPE) elif isinstance(credential, SharedKeyCredentialPolicy): self._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 if not config.transport: config.transport = RequestsTransport(**kwargs) policies = [ QueueMessagePolicy(), config.headers_policy, config.user_agent_policy, StorageContentValidation(), StorageRequestHook(**kwargs), self._credential_policy, ContentDecodePolicy(), RedirectPolicy(**kwargs), StorageHosts(hosts=self._hosts, **kwargs), config.retry_policy, config.logging_policy, StorageResponseHook(**kwargs), DistributedTracingPolicy(), ] return config, Pipeline(config.transport, policies=policies)
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 = BearerTokenCredentialPolicy( 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: config.transport = RequestsTransport(**kwargs) config.user_agent_policy.add_user_agent( "azsdk-python-azure-cognitiveservices-language-textanalytics/{}".format(VERSION) ) policies = [ config.headers_policy, config.user_agent_policy, RequestIdPolicy(**kwargs), config.proxy_policy, credential_policy, config.redirect_policy, config.retry_policy, config.logging_policy, TextAnalyticsResponseHook(**kwargs), DistributedTracingPolicy(**kwargs), HttpLoggingPolicy(**kwargs), ] return Pipeline(config.transport, policies=policies)
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 = BearerTokenCredentialPolicy(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, self._config.retry_policy, self._sync_token_policy, credential_policy, self._config.logging_policy, # HTTP request/response log DistributedTracingPolicy(**kwargs), HttpLoggingPolicy(**kwargs), ContentDecodePolicy(**kwargs), ] if not transport: transport = RequestsTransport(**kwargs) return Pipeline(transport, policies)
def _build_pipeline(self, **kwargs): # pylint: disable=no-self-use transport = kwargs.get("transport") policies = kwargs.get("policies") credential_policy = ( ServiceBusSharedKeyCredentialPolicy( self._endpoint, self._credential, "Authorization" ) if isinstance(self._credential, ServiceBusSharedKeyCredential) else BearerTokenCredentialPolicy(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 = RequestsTransport(**kwargs) return Pipeline(transport, policies)
def __init__(self, credential=None, resource_id="https://management.azure.com/.default", **kwargs): """Wrap any azure-identity credential to work with SDK that needs azure.common.credentials/msrestazure. Default resource is ARM (syntax of endpoint v2) :param credential: Any azure-identity credential (DefaultAzureCredential by default) :param str resource_id: The scope to use to get the token (default ARM) """ super(CredentialWrapper, self).__init__(None) if credential is None: credential = DefaultAzureCredential() self._policy = BearerTokenCredentialPolicy(credential, resource_id, **kwargs)
def _prepare_mgmt_client_kwargs_track2(cli_ctx, cred): """Prepare kwargs for Track 2 SDK mgmt client.""" client_kwargs = _prepare_client_kwargs_track2(cli_ctx) # Enable CAE support in mgmt SDK from azure.core.pipeline.policies import BearerTokenCredentialPolicy # Track 2 SDK maintains `scopes` and passes `scopes` to get_token. scopes = resource_to_scopes( cli_ctx.cloud.endpoints.active_directory_resource_id) policy = BearerTokenCredentialPolicy(cred, *scopes) client_kwargs['credential_scopes'] = scopes client_kwargs['authentication_policy'] = policy # Track 2 currently lacks the ability to take external credentials. # https://github.com/Azure/azure-sdk-for-python/issues/8313 # As a temporary workaround, manually add external tokens to 'x-ms-authorization-auxiliary' header. # https://docs.microsoft.com/en-us/azure/azure-resource-manager/management/authenticate-multi-tenant if hasattr(cred, "get_auxiliary_tokens"): aux_tokens = cred.get_auxiliary_tokens(*scopes) if aux_tokens: # Hard-code scheme to 'Bearer' as _BearerTokenCredentialPolicyBase._update_headers does. client_kwargs['headers']['x-ms-authorization-auxiliary'] = \ ', '.join("Bearer {}".format(token.token) for token in aux_tokens) return client_kwargs
def create_pipeline(credential, **kwargs): # type: (Any, **Any) -> Tuple[Configuration, Pipeline] credential_policy = None if hasattr(credential, 'get_token'): credential_policy = BearerTokenCredentialPolicy( 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'] transport = kwargs.get('transport') # type: HttpTransport if 'connection_timeout' not in kwargs: kwargs['connection_timeout'] = DEFAULT_SOCKET_TIMEOUT if not transport: transport = RequestsTransport(**kwargs) policies = [ QueueMessagePolicy(), config.headers_policy, config.user_agent_policy, StorageContentValidation(), StorageRequestHook(**kwargs), credential_policy, ContentDecodePolicy(), config.redirect_policy, StorageHosts(**kwargs), config.retry_policy, config.logging_policy, StorageResponseHook(**kwargs), ] return config, Pipeline(transport, policies=policies)
class CredentialWrapper(BasicTokenAuthentication): """Class for handling legacy auth conversion.""" def __init__( self, credential=None, resource_id="https://management.azure.com/.default", **kwargs, ): """ Wrap azure-identity credential to work with SDK that needs ADAL. Parameters ---------- credential : [type], optional Any azure-identity credential, by default DefaultAzureCredential resource_id : str, optional The scope to use to get the token, by default "https://management.azure.com/.default" """ super().__init__(None) self.token: Dict[str, Any] = {} if credential is None: credential = DefaultAzureCredential() self._policy = BearerTokenCredentialPolicy(credential, resource_id, **kwargs) def set_token(self): """ Ask the azure-core BearerTokenCredentialPolicy policy to get a token. Using the policy gives us for free the caching system of azure-core. We could make this code simpler by using private method, but by definition I can't assure they will be there forever, so mocking a fake call to the policy to extract the token, using 100% public API. """ request = _make_request() self._policy.on_request(request) # Read Authorization, and get the second part after Bearer token = request.http_request.headers["Authorization"].split(" ", 1)[1] self.token = {"access_token": token} def signed_session(self, session=None): """Wrap signed session object.""" self.set_token() return super().signed_session(session)
class CredentialWrapper(BasicTokenAuthentication): def __init__(self, credential, resource_id="https://management.azure.com/.default", **kwargs): """ Wrap any azure-identity credential to work with SDK that needs azure.common.credentials/msrestazure. Default resource is ARM (syntax of endpoint v2) :param credential: Any azure-identity credential :param str resource_id: The scope to use to get the token (default ARM) """ super(CredentialWrapper, self).__init__(None) self.credential = credential self._policy = BearerTokenCredentialPolicy(credential, resource_id, **kwargs) def _make_request(self): return PipelineRequest( HttpRequest("CredentialWrapper", "https://fakeurl"), PipelineContext(None)) def set_token(self): """ Ask the azure-core BearerTokenCredentialPolicy policy to get a token. Using the policy gives us for free the caching system of azure-core. We could make this code simpler by using private method, but by definition I can't assure they will be there forever, so mocking a fake call to the policy to extract the token, using 100% public API. """ request = self._make_request() self._policy.on_request(request) # Read Authorization, and get the second part after Bearer token = request.http_request.headers["Authorization"].split(" ", 1)[1] self.token = {"access_token": token} def get_token(self, *scopes, **kwargs): return self.credential.get_token(*scopes, **kwargs) def signed_session(self, session=None): self.set_token() return super(CredentialWrapper, self).signed_session(session)
class AzureIdentityCredentialAdapter(BasicTokenAuthentication): def __init__(self, credential: Any = None, resource_id: Any = "https://management.azure.com/.default", **kwargs: Any): """Adapt any azure-identity credential to work with SDK that needs azure.common.credentials or msrestazure. Default resource is ARM (syntax of endpoint v2) :param credential: Any azure-identity credential (DefaultAzureCredential by default) :param str resource_id: The scope to use to get the token (default ARM) """ super(AzureIdentityCredentialAdapter, self).__init__({}) if credential is None: credential = DefaultAzureCredential() self._policy = BearerTokenCredentialPolicy(credential, resource_id, **kwargs) def _make_request(self) -> Any: return PipelineRequest( HttpRequest( "AzureIdentityCredentialAdapter", # This URL is not actually used. We just create a phony request to get credentials using only public APIs. # Use a standard Microsoft-controlled example URL anyway. "https://contoso.com", ), PipelineContext(None), ) def set_token(self) -> Any: """Ask the azure-core BearerTokenCredentialPolicy policy to get a token. Using the policy gives us for free the caching system of azure-core. We could make this code simpler by using private method, but by definition I can't assure they will be there forever, so mocking a fake call to the policy to extract the token, using 100% public API.""" request = self._make_request() self._policy.on_request(request) # Read Authorization, and get the second part after Bearer token = request.http_request.headers["Authorization"].split(" ", 1)[1] self.token = {"access_token": token} def signed_session(self, session: Any = None) -> Any: self.set_token() return super(AzureIdentityCredentialAdapter, self).signed_session(session)
def create_config(credential, api_version=None, **kwargs): # type: (TokenCredential, Optional[str], Mapping[str, Any]) -> Configuration if api_version is None: api_version = KeyVaultClient.DEFAULT_API_VERSION config = KeyVaultClient.get_configuration_class(api_version, aio=False)(credential, **kwargs) config.authentication_policy = BearerTokenCredentialPolicy( credential, KEY_VAULT_SCOPE) return config
def _configure_credential(self, credential): # type: (Any, **Any) -> Tuple[Configuration, Pipeline] self._credential_policy = None if hasattr(credential, "get_token"): self._credential_policy = BearerTokenCredentialPolicy( credential, STORAGE_OAUTH_SCOPE) elif isinstance(credential, SharedKeyCredentialPolicy): self._credential_policy = credential elif credential is not None: raise TypeError("Unsupported credential: {}".format(credential))
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" policies = [BearerTokenCredentialPolicy(credential=Mock(), scope="scope"), ContextValidator()] pipeline = Pipeline(transport=Mock(), policies=policies) pipeline.run(HttpRequest("GET", "https://secure"))
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" policies = [BearerTokenCredentialPolicy(credential=Mock(), scope="scope"), ContextValidator()] pipeline = Pipeline(transport=Mock(), policies=policies) pipeline.run(HttpRequest("GET", "http://not.secure"), enforce_https=False)
def test_bearer_policy_default_context(http_request): """The policy should call get_token with the scopes given at construction, and no keyword arguments, by default""" expected_scope = "scope" token = AccessToken("", 0) credential = Mock(get_token=Mock(return_value=token)) policy = BearerTokenCredentialPolicy(credential, expected_scope) pipeline = Pipeline(transport=Mock(), policies=[policy]) pipeline.run(http_request("GET", "https://localhost")) credential.get_token.assert_called_once_with(expected_scope)
def __init__(self, endpoint, account_id, account_domain, credential, **kwargs): # type: (str, str, str, Union[TokenCredential, AccessToken], Any) -> None self._api_version = kwargs.pop("api_version", RemoteRenderingApiVersion.V2021_01_01) validate_api_version(self._api_version) 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") if isinstance(credential, AccessToken): cred = StaticAccessTokenCredential( credential) # type: TokenCredential elif isinstance(credential, AzureKeyCredential): cred = MixedRealityAccountKeyCredential(account_id=account_id, account_key=credential) else: cred = credential self.polling_interval = kwargs.pop("polling_interval", 5) endpoint_url = kwargs.pop('authentication_endpoint_url', construct_endpoint_url(account_domain)) # 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) if pipeline_credential is None: raise ValueError( "credential is not of type TokenCredential, AzureKeyCredential or AccessToken" ) authentication_policy = BearerTokenCredentialPolicy( 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)
def create_config(credential, scopes, **kwargs): # Here the SDK developer would define the default # config to interact with the service config = Configuration(**kwargs) config.headers_policy = HeadersPolicy({"CustomHeader": "Value"}, **kwargs) config.authentication_policy = BearerTokenCredentialPolicy(credential, scopes, **kwargs) config.user_agent_policy = UserAgentPolicy("ServiceUserAgentValue", **kwargs) config.retry_policy = RetryPolicy(**kwargs) config.redirect_policy = RedirectPolicy(**kwargs) config.logging_policy = NetworkTraceLoggingPolicy(**kwargs) config.proxy_policy = ProxyPolicy(**kwargs)
def test_bearer_policy_token_caching(): good_for_one_hour = AccessToken("token", time.time() + 3600) credential = Mock(get_token=Mock(return_value=good_for_one_hour)) pipeline = Pipeline(transport=Mock(), policies=[BearerTokenCredentialPolicy(credential, "scope")]) pipeline.run(HttpRequest("GET", "https://spam.eggs")) assert credential.get_token.call_count == 1 # policy has no token at first request -> it should call get_token pipeline.run(HttpRequest("GET", "https://spam.eggs")) assert credential.get_token.call_count == 1 # token is good for an hour -> policy should return it from cache expired_token = AccessToken("token", time.time()) credential.get_token.reset_mock() credential.get_token.return_value = expired_token pipeline = Pipeline(transport=Mock(), policies=[BearerTokenCredentialPolicy(credential, "scope")]) pipeline.run(HttpRequest("GET", "https://spam.eggs")) assert credential.get_token.call_count == 1 pipeline.run(HttpRequest("GET", "https://spam.eggs")) assert credential.get_token.call_count == 2 # token expired -> policy should call get_token
def _configure_credential(self, credential): # type: (Any) -> None if hasattr(credential, "get_token"): self._credential_policy = BearerTokenCredentialPolicy( credential, STORAGE_OAUTH_SCOPE) elif isinstance(credential, SharedKeyCredentialPolicy): self._credential_policy = credential elif isinstance(credential, AzureSasCredential): self._credential_policy = AzureSasCredentialPolicy(credential) elif isinstance(credential, AzureNamedKeyCredential): self._credential_policy = SharedKeyCredentialPolicy(credential) elif credential is not None: raise TypeError("Unsupported credential: {}".format(credential))
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() def verify_request(request): assert request.http_request is expected_request return expected_response fake_credential = Mock(get_token=lambda _: AccessToken("", 0)) policies = [BearerTokenCredentialPolicy(fake_credential, "scope"), Mock(send=verify_request)] response = Pipeline(transport=Mock(), policies=policies).run(expected_request) assert response is expected_response
def __init__(self, credential, **kwargs): # pylint:disable=super-init-not-called self._set_universal(**kwargs) # sync-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 = BearerTokenCredentialPolicy( credential, *scopes, **kwargs) self.retry_policy = kwargs.get("retry_policy", RetryPolicy(**kwargs)) self.redirect_policy = kwargs.get("redirect_policy", RedirectPolicy(**kwargs)) self.transport = kwargs.get("transport", RequestsTransport())
def get_metrics_authentication_policy( credential, # type: TokenCredential ): # type: (...) -> BearerTokenCredentialPolicy """Returns the correct authentication policy """ if credential is None: raise ValueError("Parameter 'credential' must not be None.") if hasattr(credential, "get_token"): return BearerTokenCredentialPolicy( credential, "https://management.azure.com/.default") raise TypeError("Unsupported credential")
def test_bearer_policy_preserves_enforce_https_opt_out(http_request): """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" return Mock() credential = Mock(get_token=Mock(return_value=AccessToken("***", 42))) policies = [ BearerTokenCredentialPolicy(credential, "scope"), ContextValidator() ] pipeline = Pipeline(transport=Mock(), policies=policies) pipeline.run(http_request("GET", "http://not.secure"), enforce_https=False)