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# --------------------------------------------------------------------------
26from typing import Mapping, MutableMapping, Optional, Type, Union, cast, Dict, Any
27import re
28import logging
29from azure.core import AzureClouds
30
31
32_LOGGER = logging.getLogger(__name__)
33_ARMID_RE = re.compile(
34 "(?i)/subscriptions/(?P<subscription>[^/]+)(/resourceGroups/(?P<resource_group>[^/]+))?"
35 + "(/providers/(?P<namespace>[^/]+)/(?P<type>[^/]*)/(?P<name>[^/]+)(?P<children>.*))?"
36)
37
38_CHILDREN_RE = re.compile(
39 "(?i)(/providers/(?P<child_namespace>[^/]+))?/" + "(?P<child_type>[^/]*)/(?P<child_name>[^/]+)"
40)
41
42_ARMNAME_RE = re.compile("^[^<>%&:\\?/]{1,260}$")
43
44
45__all__ = [
46 "parse_resource_id",
47 "resource_id",
48 "is_valid_resource_id",
49 "is_valid_resource_name",
50 "get_arm_endpoints",
51]
52
53
54def parse_resource_id(rid: str) -> Mapping[str, Union[str, int]]:
55 """Parses a resource_id into its various parts.
56
57 Returns a dictionary with a single key-value pair, 'name': rid, if invalid resource id.
58
59 :param rid: The resource id being parsed
60 :type rid: str
61 :returns: A dictionary with with following key/value pairs (if found):
62
63 - subscription: Subscription id
64 - resource_group: Name of resource group
65 - namespace: Namespace for the resource provider (i.e. Microsoft.Compute)
66 - type: Type of the root resource (i.e. virtualMachines)
67 - name: Name of the root resource
68 - child_namespace_{level}: Namespace for the child resource of that level
69 - child_type_{level}: Type of the child resource of that level
70 - child_name_{level}: Name of the child resource of that level
71 - last_child_num: Level of the last child
72 - resource_parent: Computed parent in the following pattern: providers/{namespace}\
73 /{parent}/{type}/{name}
74 - resource_namespace: Same as namespace. Note that this may be different than the \
75 target resource's namespace.
76 - resource_type: Type of the target resource (not the parent)
77 - resource_name: Name of the target resource (not the parent)
78
79 :rtype: dict[str,str]
80 """
81 if not rid:
82 return {}
83 match = _ARMID_RE.match(rid)
84 if match:
85 result: MutableMapping[str, Union[None, str, int]] = match.groupdict()
86 children = _CHILDREN_RE.finditer(cast(Optional[str], result["children"]) or "")
87 count = None
88 for count, child in enumerate(children):
89 result.update({key + "_%d" % (count + 1): group for key, group in child.groupdict().items()})
90 result["last_child_num"] = count + 1 if isinstance(count, int) else None
91 final_result = _populate_alternate_kwargs(result)
92 else:
93 final_result = result = {"name": rid}
94 return {key: value for key, value in final_result.items() if value is not None}
95
96
97def _populate_alternate_kwargs(
98 kwargs: MutableMapping[str, Union[None, str, int]]
99) -> Mapping[str, Union[None, str, int]]:
100 """Translates the parsed arguments into a format used by generic ARM commands
101 such as the resource and lock commands.
102
103 :param any kwargs: The parsed arguments
104 :return: The translated arguments
105 :rtype: any
106 """
107
108 resource_namespace = kwargs["namespace"]
109 resource_type = kwargs.get("child_type_{}".format(kwargs["last_child_num"])) or kwargs["type"]
110 resource_name = kwargs.get("child_name_{}".format(kwargs["last_child_num"])) or kwargs["name"]
111
112 _get_parents_from_parts(kwargs)
113 kwargs["resource_namespace"] = resource_namespace
114 kwargs["resource_type"] = resource_type
115 kwargs["resource_name"] = resource_name
116 return kwargs
117
118
119def _get_parents_from_parts(kwargs: MutableMapping[str, Union[None, str, int]]) -> Mapping[str, Union[None, str, int]]:
120 """Get the parents given all the children parameters.
121
122 :param any kwargs: The children parameters
123 :return: The parents
124 :rtype: any
125 """
126 parent_builder = []
127 if kwargs["last_child_num"] is not None:
128 parent_builder.append("{type}/{name}/".format(**kwargs))
129 for index in range(1, cast(int, kwargs["last_child_num"])):
130 child_namespace = kwargs.get("child_namespace_{}".format(index))
131 if child_namespace is not None:
132 parent_builder.append("providers/{}/".format(child_namespace))
133 kwargs["child_parent_{}".format(index)] = "".join(parent_builder)
134 parent_builder.append("{{child_type_{0}}}/{{child_name_{0}}}/".format(index).format(**kwargs))
135 child_namespace = kwargs.get("child_namespace_{}".format(kwargs["last_child_num"]))
136 if child_namespace is not None:
137 parent_builder.append("providers/{}/".format(child_namespace))
138 kwargs["child_parent_{}".format(kwargs["last_child_num"])] = "".join(parent_builder)
139 kwargs["resource_parent"] = "".join(parent_builder) if kwargs["name"] else None
140 return kwargs
141
142
143def resource_id(**kwargs: Optional[str]) -> str: # pylint: disable=docstring-keyword-should-match-keyword-only
144 """Create a valid resource id string from the given parts.
145
146 This method builds the resource id from the left until the next required id parameter
147 to be appended is not found. It then returns the built up id.
148
149 :keyword str subscription: (required) Subscription id
150 :keyword str resource_group: Name of resource group
151 :keyword str namespace: Namespace for the resource provider (i.e. Microsoft.Compute)
152 :keyword str type: Type of the resource (i.e. virtualMachines)
153 :keyword str name: Name of the resource (or parent if child_name is also specified)
154 :keyword str child_namespace_{level}: Namespace for the child resource of that level (optional)
155 :keyword str child_type_{level}: Type of the child resource of that level
156 :keyword str child_name_{level}: Name of the child resource of that level
157
158 :returns: A resource id built from the given arguments.
159 :rtype: str
160 """
161 kwargs = {k: v for k, v in kwargs.items() if v is not None}
162 rid_builder = ["/subscriptions/{subscription}".format(**kwargs)]
163 try:
164 try:
165 rid_builder.append("resourceGroups/{resource_group}".format(**kwargs))
166 except KeyError:
167 pass
168 rid_builder.append("providers/{namespace}".format(**kwargs))
169 rid_builder.append("{type}/{name}".format(**kwargs))
170 count = 1
171 while True:
172 try:
173 rid_builder.append("providers/{{child_namespace_{}}}".format(count).format(**kwargs))
174 except KeyError:
175 pass
176 rid_builder.append("{{child_type_{0}}}/{{child_name_{0}}}".format(count).format(**kwargs))
177 count += 1
178 except KeyError:
179 pass
180 return "/".join(rid_builder)
181
182
183def is_valid_resource_id(rid: str, exception_type: Optional[Type[BaseException]] = None) -> bool:
184 """Validates the given resource id.
185
186 :param rid: The resource id being validated.
187 :type rid: str
188 :param exception_type: Raises this Exception if invalid.
189 :type exception_type: Exception
190 :returns: A boolean describing whether the id is valid.
191 :rtype: bool
192 """
193 is_valid: bool = False
194 try:
195 # Ideally, we would make a TypedDict here, but keeping this file simple for now.
196 is_valid = rid and resource_id(**parse_resource_id(rid)).lower() == rid.lower() # type: ignore
197 except KeyError:
198 pass
199 if not is_valid and exception_type:
200 raise exception_type()
201 return is_valid
202
203
204def is_valid_resource_name(rname: str, exception_type: Optional[Type[BaseException]] = None) -> bool:
205 """Validates the given resource name to ARM guidelines, individual services may be more restrictive.
206
207 :param rname: The resource name being validated.
208 :type rname: str
209 :param exception_type: Raises this Exception if invalid.
210 :type exception_type: Exception
211 :returns: A boolean describing whether the name is valid.
212 :rtype: bool
213 """
214
215 match = _ARMNAME_RE.match(rname)
216
217 if match:
218 return True
219 if exception_type:
220 raise exception_type()
221 return False
222
223
224def get_arm_endpoints(cloud_setting: AzureClouds) -> Dict[str, Any]:
225 """Get the ARM endpoint and ARM credential scopes for the given cloud setting.
226
227 :param cloud_setting: The cloud setting for which to get the ARM endpoint.
228 :type cloud_setting: AzureClouds
229 :return: The ARM endpoint and ARM credential scopes.
230 :rtype: dict[str, Any]
231 """
232 if cloud_setting == AzureClouds.AZURE_CHINA_CLOUD:
233 return {
234 "resource_manager": "https://management.chinacloudapi.cn/",
235 "credential_scopes": ["https://management.chinacloudapi.cn/.default"],
236 }
237 if cloud_setting == AzureClouds.AZURE_US_GOVERNMENT:
238 return {
239 "resource_manager": "https://management.usgovcloudapi.net/",
240 "credential_scopes": ["https://management.core.usgovcloudapi.net/.default"],
241 }
242 if cloud_setting == AzureClouds.AZURE_PUBLIC_CLOUD:
243 return {
244 "resource_manager": "https://management.azure.com/",
245 "credential_scopes": ["https://management.azure.com/.default"],
246 }
247 raise ValueError("Unknown cloud setting: {}".format(cloud_setting))