1# -------------------------------------------------------------------------- 
    2# 
    3# Copyright (c) Microsoft Corporation. All rights reserved. 
    4# 
    5# The MIT License (MIT) 
    6# 
    7# Permission is hereby granted, free of charge, to any person obtaining a copy 
    8# of this software and associated documentation files (the ""Software""), to 
    9# deal in the Software without restriction, including without limitation the 
    10# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or 
    11# sell copies of the Software, and to permit persons to whom the Software is 
    12# furnished to do so, subject to the following conditions: 
    13# 
    14# The above copyright notice and this permission notice shall be included in 
    15# all copies or substantial portions of the Software. 
    16# 
    17# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
    18# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
    19# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
    20# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
    21# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 
    22# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS 
    23# IN THE SOFTWARE. 
    24# 
    25# -------------------------------------------------------------------------- 
    26import json 
    27import logging 
    28import re 
    29import time 
    30import uuid 
    31from typing import Union, Optional, cast 
    32 
    33from azure.core.pipeline import PipelineContext, PipelineRequest, PipelineResponse 
    34from azure.core.pipeline.policies import HTTPPolicy 
    35from azure.core.pipeline.transport import ( 
    36    HttpRequest as LegacyHttpRequest, 
    37    HttpResponse as LegacyHttpResponse, 
    38    AsyncHttpResponse as LegacyAsyncHttpResponse, 
    39) 
    40from azure.core.rest import HttpRequest, HttpResponse, AsyncHttpResponse 
    41 
    42 
    43_LOGGER = logging.getLogger(__name__) 
    44 
    45HTTPRequestType = Union[LegacyHttpRequest, HttpRequest] 
    46HTTPResponseType = Union[LegacyHttpResponse, HttpResponse] 
    47AllHttpResponseType = Union[ 
    48    LegacyHttpResponse, HttpResponse, LegacyAsyncHttpResponse, AsyncHttpResponse 
    49]  # Sync or async 
    50 
    51 
    52class _SansIOARMAutoResourceProviderRegistrationPolicy: 
    53    @staticmethod 
    54    def _check_rp_not_registered_err(response: PipelineResponse[HTTPRequestType, AllHttpResponseType]) -> Optional[str]: 
    55        try: 
    56            response_as_json = json.loads(response.http_response.text()) 
    57            if response_as_json["error"]["code"] == "MissingSubscriptionRegistration": 
    58                # While "match" can in theory be None, if we saw "MissingSubscriptionRegistration" it won't happen 
    59                match = cast(re.Match, re.match(r".*'(.*)'", response_as_json["error"]["message"])) 
    60                return match.group(1) 
    61        except Exception:  # pylint: disable=broad-except 
    62            pass 
    63        return None 
    64 
    65    @staticmethod 
    66    def _extract_subscription_url(url: str) -> str: 
    67        """Extract the first part of the URL, just after subscription: 
    68        https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/ 
    69 
    70        :param str url: The URL to extract the subscription ID from 
    71        :return: The subscription ID 
    72        :rtype: str 
    73        """ 
    74        match = re.match(r".*/subscriptions/[a-f0-9-]+/", url, re.IGNORECASE) 
    75        if not match: 
    76            raise ValueError("Unable to extract subscription ID from URL") 
    77        return match.group(0) 
    78 
    79    @staticmethod 
    80    def _build_next_request( 
    81        initial_request: PipelineRequest[HTTPRequestType], method: str, url: str 
    82    ) -> PipelineRequest[HTTPRequestType]: 
    83        request = HttpRequest(method, url) 
    84        context = PipelineContext(initial_request.context.transport, **initial_request.context.options) 
    85        return PipelineRequest(request, context) 
    86 
    87 
    88class ARMAutoResourceProviderRegistrationPolicy( 
    89    _SansIOARMAutoResourceProviderRegistrationPolicy, HTTPPolicy[HTTPRequestType, HTTPResponseType] 
    90):  # pylint: disable=name-too-long 
    91    """Auto register an ARM resource provider if not done yet.""" 
    92 
    93    def send(self, request: PipelineRequest[HTTPRequestType]) -> PipelineResponse[HTTPRequestType, HTTPResponseType]: 
    94        http_request = request.http_request 
    95        response = self.next.send(request) 
    96        if response.http_response.status_code == 409: 
    97            rp_name = self._check_rp_not_registered_err(response) 
    98            if rp_name: 
    99                url_prefix = self._extract_subscription_url(http_request.url) 
    100                if not self._register_rp(request, url_prefix, rp_name): 
    101                    return response 
    102                # Change the 'x-ms-client-request-id' otherwise the Azure endpoint 
    103                # just returns the same 409 payload without looking at the actual query 
    104                if "x-ms-client-request-id" in http_request.headers: 
    105                    http_request.headers["x-ms-client-request-id"] = str(uuid.uuid4()) 
    106                response = self.next.send(request) 
    107        return response 
    108 
    109    def _register_rp(self, initial_request: PipelineRequest[HTTPRequestType], url_prefix: str, rp_name: str) -> bool: 
    110        """Synchronously register the RP is paremeter. 
    111 
    112        Return False if we have a reason to believe this didn't work 
    113 
    114        :param initial_request: The initial request 
    115        :type initial_request: ~azure.core.pipeline.PipelineRequest 
    116        :param str url_prefix: The url prefix 
    117        :param str rp_name: The resource provider name 
    118        :return: Return False if we have a reason to believe this didn't work 
    119        :rtype: bool 
    120        """ 
    121        post_url = "{}providers/{}/register?api-version=2016-02-01".format(url_prefix, rp_name) 
    122        get_url = "{}providers/{}?api-version=2016-02-01".format(url_prefix, rp_name) 
    123        _LOGGER.warning( 
    124            "Resource provider '%s' used by this operation is not registered. We are registering for you.", 
    125            rp_name, 
    126        ) 
    127        post_response = self.next.send(self._build_next_request(initial_request, "POST", post_url)) 
    128        if post_response.http_response.status_code != 200: 
    129            _LOGGER.warning("Registration failed. Please register manually.") 
    130            return False 
    131 
    132        while True: 
    133            time.sleep(10) 
    134            get_response = self.next.send(self._build_next_request(initial_request, "GET", get_url)) 
    135            rp_info = json.loads(get_response.http_response.text()) 
    136            if rp_info["registrationState"] == "Registered": 
    137                _LOGGER.warning("Registration succeeded.") 
    138                return True