_metadata.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. # Copyright 2016 Google LLC
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """Provides helper methods for talking to the Compute Engine metadata server.
  15. See https://cloud.google.com/compute/docs/metadata for more details.
  16. """
  17. import datetime
  18. import http.client as http_client
  19. import json
  20. import logging
  21. import os
  22. from urllib.parse import urljoin
  23. from google.auth import _helpers
  24. from google.auth import environment_vars
  25. from google.auth import exceptions
  26. from google.auth import metrics
  27. _LOGGER = logging.getLogger(__name__)
  28. # Environment variable GCE_METADATA_HOST is originally named
  29. # GCE_METADATA_ROOT. For compatiblity reasons, here it checks
  30. # the new variable first; if not set, the system falls back
  31. # to the old variable.
  32. _GCE_METADATA_HOST = os.getenv(environment_vars.GCE_METADATA_HOST, None)
  33. if not _GCE_METADATA_HOST:
  34. _GCE_METADATA_HOST = os.getenv(
  35. environment_vars.GCE_METADATA_ROOT, "metadata.google.internal"
  36. )
  37. _METADATA_ROOT = "http://{}/computeMetadata/v1/".format(_GCE_METADATA_HOST)
  38. # This is used to ping the metadata server, it avoids the cost of a DNS
  39. # lookup.
  40. _METADATA_IP_ROOT = "http://{}".format(
  41. os.getenv(environment_vars.GCE_METADATA_IP, "169.254.169.254")
  42. )
  43. _METADATA_FLAVOR_HEADER = "metadata-flavor"
  44. _METADATA_FLAVOR_VALUE = "Google"
  45. _METADATA_HEADERS = {_METADATA_FLAVOR_HEADER: _METADATA_FLAVOR_VALUE}
  46. # Timeout in seconds to wait for the GCE metadata server when detecting the
  47. # GCE environment.
  48. try:
  49. _METADATA_DEFAULT_TIMEOUT = int(os.getenv("GCE_METADATA_TIMEOUT", 3))
  50. except ValueError: # pragma: NO COVER
  51. _METADATA_DEFAULT_TIMEOUT = 3
  52. # Detect GCE Residency
  53. _GOOGLE = "Google"
  54. _GCE_PRODUCT_NAME_FILE = "/sys/class/dmi/id/product_name"
  55. def is_on_gce(request):
  56. """Checks to see if the code runs on Google Compute Engine
  57. Args:
  58. request (google.auth.transport.Request): A callable used to make
  59. HTTP requests.
  60. Returns:
  61. bool: True if the code runs on Google Compute Engine, False otherwise.
  62. """
  63. if ping(request):
  64. return True
  65. if os.name == "nt":
  66. # TODO: implement GCE residency detection on Windows
  67. return False
  68. # Detect GCE residency on Linux
  69. return detect_gce_residency_linux()
  70. def detect_gce_residency_linux():
  71. """Detect Google Compute Engine residency by smbios check on Linux
  72. Returns:
  73. bool: True if the GCE product name file is detected, False otherwise.
  74. """
  75. try:
  76. with open(_GCE_PRODUCT_NAME_FILE, "r") as file_obj:
  77. content = file_obj.read().strip()
  78. except Exception:
  79. return False
  80. return content.startswith(_GOOGLE)
  81. def ping(request, timeout=_METADATA_DEFAULT_TIMEOUT, retry_count=3):
  82. """Checks to see if the metadata server is available.
  83. Args:
  84. request (google.auth.transport.Request): A callable used to make
  85. HTTP requests.
  86. timeout (int): How long to wait for the metadata server to respond.
  87. retry_count (int): How many times to attempt connecting to metadata
  88. server using above timeout.
  89. Returns:
  90. bool: True if the metadata server is reachable, False otherwise.
  91. """
  92. # NOTE: The explicit ``timeout`` is a workaround. The underlying
  93. # issue is that resolving an unknown host on some networks will take
  94. # 20-30 seconds; making this timeout short fixes the issue, but
  95. # could lead to false negatives in the event that we are on GCE, but
  96. # the metadata resolution was particularly slow. The latter case is
  97. # "unlikely".
  98. retries = 0
  99. headers = _METADATA_HEADERS.copy()
  100. headers[metrics.API_CLIENT_HEADER] = metrics.mds_ping()
  101. while retries < retry_count:
  102. try:
  103. response = request(
  104. url=_METADATA_IP_ROOT, method="GET", headers=headers, timeout=timeout
  105. )
  106. metadata_flavor = response.headers.get(_METADATA_FLAVOR_HEADER)
  107. return (
  108. response.status == http_client.OK
  109. and metadata_flavor == _METADATA_FLAVOR_VALUE
  110. )
  111. except exceptions.TransportError as e:
  112. _LOGGER.warning(
  113. "Compute Engine Metadata server unavailable on "
  114. "attempt %s of %s. Reason: %s",
  115. retries + 1,
  116. retry_count,
  117. e,
  118. )
  119. retries += 1
  120. return False
  121. def get(
  122. request,
  123. path,
  124. root=_METADATA_ROOT,
  125. params=None,
  126. recursive=False,
  127. retry_count=5,
  128. headers=None,
  129. return_none_for_not_found_error=False,
  130. ):
  131. """Fetch a resource from the metadata server.
  132. Args:
  133. request (google.auth.transport.Request): A callable used to make
  134. HTTP requests.
  135. path (str): The resource to retrieve. For example,
  136. ``'instance/service-accounts/default'``.
  137. root (str): The full path to the metadata server root.
  138. params (Optional[Mapping[str, str]]): A mapping of query parameter
  139. keys to values.
  140. recursive (bool): Whether to do a recursive query of metadata. See
  141. https://cloud.google.com/compute/docs/metadata#aggcontents for more
  142. details.
  143. retry_count (int): How many times to attempt connecting to metadata
  144. server using above timeout.
  145. headers (Optional[Mapping[str, str]]): Headers for the request.
  146. return_none_for_not_found_error (Optional[bool]): If True, returns None
  147. for 404 error instead of throwing an exception.
  148. Returns:
  149. Union[Mapping, str]: If the metadata server returns JSON, a mapping of
  150. the decoded JSON is return. Otherwise, the response content is
  151. returned as a string.
  152. Raises:
  153. google.auth.exceptions.TransportError: if an error occurred while
  154. retrieving metadata.
  155. """
  156. base_url = urljoin(root, path)
  157. query_params = {} if params is None else params
  158. headers_to_use = _METADATA_HEADERS.copy()
  159. if headers:
  160. headers_to_use.update(headers)
  161. if recursive:
  162. query_params["recursive"] = "true"
  163. url = _helpers.update_query(base_url, query_params)
  164. retries = 0
  165. while retries < retry_count:
  166. try:
  167. response = request(url=url, method="GET", headers=headers_to_use)
  168. break
  169. except exceptions.TransportError as e:
  170. _LOGGER.warning(
  171. "Compute Engine Metadata server unavailable on "
  172. "attempt %s of %s. Reason: %s",
  173. retries + 1,
  174. retry_count,
  175. e,
  176. )
  177. retries += 1
  178. else:
  179. raise exceptions.TransportError(
  180. "Failed to retrieve {} from the Google Compute Engine "
  181. "metadata service. Compute Engine Metadata server unavailable".format(url)
  182. )
  183. content = _helpers.from_bytes(response.data)
  184. if response.status == http_client.NOT_FOUND and return_none_for_not_found_error:
  185. return None
  186. if response.status == http_client.OK:
  187. if (
  188. _helpers.parse_content_type(response.headers["content-type"])
  189. == "application/json"
  190. ):
  191. try:
  192. return json.loads(content)
  193. except ValueError as caught_exc:
  194. new_exc = exceptions.TransportError(
  195. "Received invalid JSON from the Google Compute Engine "
  196. "metadata service: {:.20}".format(content)
  197. )
  198. raise new_exc from caught_exc
  199. else:
  200. return content
  201. raise exceptions.TransportError(
  202. "Failed to retrieve {} from the Google Compute Engine "
  203. "metadata service. Status: {} Response:\n{}".format(
  204. url, response.status, response.data
  205. ),
  206. response,
  207. )
  208. def get_project_id(request):
  209. """Get the Google Cloud Project ID from the metadata server.
  210. Args:
  211. request (google.auth.transport.Request): A callable used to make
  212. HTTP requests.
  213. Returns:
  214. str: The project ID
  215. Raises:
  216. google.auth.exceptions.TransportError: if an error occurred while
  217. retrieving metadata.
  218. """
  219. return get(request, "project/project-id")
  220. def get_universe_domain(request):
  221. """Get the universe domain value from the metadata server.
  222. Args:
  223. request (google.auth.transport.Request): A callable used to make
  224. HTTP requests.
  225. Returns:
  226. str: The universe domain value. If the universe domain endpoint is not
  227. not found, return the default value, which is googleapis.com
  228. Raises:
  229. google.auth.exceptions.TransportError: if an error other than
  230. 404 occurs while retrieving metadata.
  231. """
  232. universe_domain = get(
  233. request, "universe/universe_domain", return_none_for_not_found_error=True
  234. )
  235. if not universe_domain:
  236. return "googleapis.com"
  237. return universe_domain
  238. def get_service_account_info(request, service_account="default"):
  239. """Get information about a service account from the metadata server.
  240. Args:
  241. request (google.auth.transport.Request): A callable used to make
  242. HTTP requests.
  243. service_account (str): The string 'default' or a service account email
  244. address. The determines which service account for which to acquire
  245. information.
  246. Returns:
  247. Mapping: The service account's information, for example::
  248. {
  249. 'email': '...',
  250. 'scopes': ['scope', ...],
  251. 'aliases': ['default', '...']
  252. }
  253. Raises:
  254. google.auth.exceptions.TransportError: if an error occurred while
  255. retrieving metadata.
  256. """
  257. path = "instance/service-accounts/{0}/".format(service_account)
  258. # See https://cloud.google.com/compute/docs/metadata#aggcontents
  259. # for more on the use of 'recursive'.
  260. return get(request, path, params={"recursive": "true"})
  261. def get_service_account_token(request, service_account="default", scopes=None):
  262. """Get the OAuth 2.0 access token for a service account.
  263. Args:
  264. request (google.auth.transport.Request): A callable used to make
  265. HTTP requests.
  266. service_account (str): The string 'default' or a service account email
  267. address. The determines which service account for which to acquire
  268. an access token.
  269. scopes (Optional[Union[str, List[str]]]): Optional string or list of
  270. strings with auth scopes.
  271. Returns:
  272. Tuple[str, datetime]: The access token and its expiration.
  273. Raises:
  274. google.auth.exceptions.TransportError: if an error occurred while
  275. retrieving metadata.
  276. """
  277. if scopes:
  278. if not isinstance(scopes, str):
  279. scopes = ",".join(scopes)
  280. params = {"scopes": scopes}
  281. else:
  282. params = None
  283. metrics_header = {
  284. metrics.API_CLIENT_HEADER: metrics.token_request_access_token_mds()
  285. }
  286. path = "instance/service-accounts/{0}/token".format(service_account)
  287. token_json = get(request, path, params=params, headers=metrics_header)
  288. token_expiry = _helpers.utcnow() + datetime.timedelta(
  289. seconds=token_json["expires_in"]
  290. )
  291. return token_json["access_token"], token_expiry