|
| 1 | +# ------------------------------------ |
| 2 | +# Copyright (c) Microsoft Corporation. |
| 3 | +# Licensed under the MIT License. |
| 4 | +# ------------------------------------ |
| 5 | +import six |
| 6 | + |
| 7 | +from azure.core.configuration import Configuration |
| 8 | +from azure.core.exceptions import ClientAuthenticationError |
| 9 | +from azure.core.pipeline import Pipeline |
| 10 | +from azure.core.pipeline.policies import ( |
| 11 | + ContentDecodePolicy, |
| 12 | + DistributedTracingPolicy, |
| 13 | + HttpLoggingPolicy, |
| 14 | + NetworkTraceLoggingPolicy, |
| 15 | + ProxyPolicy, |
| 16 | + RetryPolicy, |
| 17 | + UserAgentPolicy, |
| 18 | +) |
| 19 | +from azure.core.pipeline.transport import HttpRequest, RequestsTransport |
| 20 | + |
| 21 | +from .user_agent import USER_AGENT |
| 22 | + |
| 23 | +try: |
| 24 | + from typing import TYPE_CHECKING |
| 25 | +except ImportError: |
| 26 | + TYPE_CHECKING = False |
| 27 | + |
| 28 | +if TYPE_CHECKING: |
| 29 | + # pylint:disable=unused-import,ungrouped-imports |
| 30 | + from typing import Any, Dict, List, Optional, Union |
| 31 | + from azure.core.pipeline import PipelineResponse |
| 32 | + from azure.core.pipeline.policies import HTTPPolicy, SansIOHTTPPolicy |
| 33 | + from azure.core.pipeline.transport import HttpTransport |
| 34 | + |
| 35 | + PolicyList = List[Union[HTTPPolicy, SansIOHTTPPolicy]] |
| 36 | + RequestData = Union[Dict[str, str], str] |
| 37 | + |
| 38 | + |
| 39 | +class MsalResponse(object): |
| 40 | + """Wraps HttpResponse according to msal.oauth2cli.http""" |
| 41 | + |
| 42 | + def __init__(self, response): |
| 43 | + # type: (PipelineResponse) -> None |
| 44 | + self._response = response |
| 45 | + |
| 46 | + @property |
| 47 | + def status_code(self): |
| 48 | + # type: () -> int |
| 49 | + return self._response.http_response.status_code |
| 50 | + |
| 51 | + @property |
| 52 | + def text(self): |
| 53 | + # type: () -> str |
| 54 | + return self._response.http_response.text(encoding="utf-8") |
| 55 | + |
| 56 | + def raise_for_status(self): |
| 57 | + if self.status_code < 400: |
| 58 | + return |
| 59 | + |
| 60 | + if ContentDecodePolicy.CONTEXT_NAME in self._response.context: |
| 61 | + content = self._response.context[ContentDecodePolicy.CONTEXT_NAME] |
| 62 | + if "error" in content or "error_description" in content: |
| 63 | + message = "Authentication failed: {}".format(content.get("error_description") or content.get("error")) |
| 64 | + else: |
| 65 | + for secret in ("access_token", "refresh_token"): |
| 66 | + if secret in content: |
| 67 | + content[secret] = "***" |
| 68 | + message = 'Unexpected response from Azure Active Directory: "{}"'.format(content) |
| 69 | + else: |
| 70 | + message = "Unexpected response from Azure Active Directory" |
| 71 | + |
| 72 | + raise ClientAuthenticationError(message=message, response=self._response.http_response) |
| 73 | + |
| 74 | + |
| 75 | +class MsalClient(object): |
| 76 | + """Wraps Pipeline according to msal.oauth2cli.http""" |
| 77 | + |
| 78 | + def __init__(self, **kwargs): # pylint:disable=missing-client-constructor-parameter-credential |
| 79 | + # type: (**Any) -> None |
| 80 | + self._pipeline = _build_pipeline(**kwargs) |
| 81 | + |
| 82 | + def post(self, url, params=None, data=None, headers=None, **kwargs): # pylint:disable=unused-argument |
| 83 | + # type: (str, Optional[Dict[str, str]], RequestData, Optional[Dict[str, str]], **Any) -> MsalResponse |
| 84 | + request = HttpRequest("POST", url, headers=headers) |
| 85 | + if params: |
| 86 | + request.format_parameters(params) |
| 87 | + if data: |
| 88 | + if isinstance(data, dict): |
| 89 | + request.headers["Content-Type"] = "application/x-www-form-urlencoded" |
| 90 | + request.set_formdata_body(data) |
| 91 | + elif isinstance(data, six.text_type): |
| 92 | + body_bytes = six.ensure_binary(data) |
| 93 | + request.set_bytes_body(body_bytes) |
| 94 | + else: |
| 95 | + raise ValueError('expected "data" to be text or a dict') |
| 96 | + |
| 97 | + response = self._pipeline.run(request) |
| 98 | + return MsalResponse(response) |
| 99 | + |
| 100 | + def get(self, url, params=None, headers=None, **kwargs): # pylint:disable=unused-argument |
| 101 | + # type: (str, Optional[Dict[str, str]], Optional[Dict[str, str]], **Any) -> MsalResponse |
| 102 | + request = HttpRequest("GET", url, headers=headers) |
| 103 | + if params: |
| 104 | + request.format_parameters(params) |
| 105 | + response = self._pipeline.run(request) |
| 106 | + return MsalResponse(response) |
| 107 | + |
| 108 | + |
| 109 | +def _create_config(**kwargs): |
| 110 | + # type: (Any) -> Configuration |
| 111 | + config = Configuration(**kwargs) |
| 112 | + config.logging_policy = NetworkTraceLoggingPolicy(**kwargs) |
| 113 | + config.retry_policy = RetryPolicy(**kwargs) |
| 114 | + config.proxy_policy = ProxyPolicy(**kwargs) |
| 115 | + config.user_agent_policy = UserAgentPolicy(base_user_agent=USER_AGENT, **kwargs) |
| 116 | + return config |
| 117 | + |
| 118 | + |
| 119 | +def _build_pipeline(config=None, policies=None, transport=None, **kwargs): |
| 120 | + # type: (Optional[Configuration], Optional[PolicyList], Optional[HttpTransport], **Any) -> Pipeline |
| 121 | + config = config or _create_config(**kwargs) |
| 122 | + |
| 123 | + if policies is None: # [] is a valid policy list |
| 124 | + policies = [ |
| 125 | + ContentDecodePolicy(), |
| 126 | + config.user_agent_policy, |
| 127 | + config.proxy_policy, |
| 128 | + config.retry_policy, |
| 129 | + config.logging_policy, |
| 130 | + DistributedTracingPolicy(**kwargs), |
| 131 | + HttpLoggingPolicy(**kwargs), |
| 132 | + ] |
| 133 | + |
| 134 | + if not transport: |
| 135 | + transport = RequestsTransport(**kwargs) |
| 136 | + |
| 137 | + return Pipeline(transport=transport, policies=policies) |
0 commit comments