_cloud_sdk.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. # Copyright 2015 Google Inc.
  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. """Helpers for reading the Google Cloud SDK's configuration."""
  15. import json
  16. import os
  17. import subprocess
  18. import six
  19. from google.auth import environment_vars
  20. from google.auth import exceptions
  21. # The ~/.config subdirectory containing gcloud credentials.
  22. _CONFIG_DIRECTORY = "gcloud"
  23. # Windows systems store config at %APPDATA%\gcloud
  24. _WINDOWS_CONFIG_ROOT_ENV_VAR = "APPDATA"
  25. # The name of the file in the Cloud SDK config that contains default
  26. # credentials.
  27. _CREDENTIALS_FILENAME = "application_default_credentials.json"
  28. # The name of the Cloud SDK shell script
  29. _CLOUD_SDK_POSIX_COMMAND = "gcloud"
  30. _CLOUD_SDK_WINDOWS_COMMAND = "gcloud.cmd"
  31. # The command to get the Cloud SDK configuration
  32. _CLOUD_SDK_CONFIG_COMMAND = ("config", "config-helper", "--format", "json")
  33. # The command to get google user access token
  34. _CLOUD_SDK_USER_ACCESS_TOKEN_COMMAND = ("auth", "print-access-token")
  35. # Cloud SDK's application-default client ID
  36. CLOUD_SDK_CLIENT_ID = (
  37. "764086051850-6qr4p6gpi6hn506pt8ejuq83di341hur.apps.googleusercontent.com"
  38. )
  39. def get_config_path():
  40. """Returns the absolute path the the Cloud SDK's configuration directory.
  41. Returns:
  42. str: The Cloud SDK config path.
  43. """
  44. # If the path is explicitly set, return that.
  45. try:
  46. return os.environ[environment_vars.CLOUD_SDK_CONFIG_DIR]
  47. except KeyError:
  48. pass
  49. # Non-windows systems store this at ~/.config/gcloud
  50. if os.name != "nt":
  51. return os.path.join(os.path.expanduser("~"), ".config", _CONFIG_DIRECTORY)
  52. # Windows systems store config at %APPDATA%\gcloud
  53. else:
  54. try:
  55. return os.path.join(
  56. os.environ[_WINDOWS_CONFIG_ROOT_ENV_VAR], _CONFIG_DIRECTORY
  57. )
  58. except KeyError:
  59. # This should never happen unless someone is really
  60. # messing with things, but we'll cover the case anyway.
  61. drive = os.environ.get("SystemDrive", "C:")
  62. return os.path.join(drive, "\\", _CONFIG_DIRECTORY)
  63. def get_application_default_credentials_path():
  64. """Gets the path to the application default credentials file.
  65. The path may or may not exist.
  66. Returns:
  67. str: The full path to application default credentials.
  68. """
  69. config_path = get_config_path()
  70. return os.path.join(config_path, _CREDENTIALS_FILENAME)
  71. def _run_subprocess_ignore_stderr(command):
  72. """ Return subprocess.check_output with the given command and ignores stderr."""
  73. with open(os.devnull, "w") as devnull:
  74. output = subprocess.check_output(command, stderr=devnull)
  75. return output
  76. def get_project_id():
  77. """Gets the project ID from the Cloud SDK.
  78. Returns:
  79. Optional[str]: The project ID.
  80. """
  81. if os.name == "nt":
  82. command = _CLOUD_SDK_WINDOWS_COMMAND
  83. else:
  84. command = _CLOUD_SDK_POSIX_COMMAND
  85. try:
  86. # Ignore the stderr coming from gcloud, so it won't be mixed into the output.
  87. # https://github.com/googleapis/google-auth-library-python/issues/673
  88. output = _run_subprocess_ignore_stderr((command,) + _CLOUD_SDK_CONFIG_COMMAND)
  89. except (subprocess.CalledProcessError, OSError, IOError):
  90. return None
  91. try:
  92. configuration = json.loads(output.decode("utf-8"))
  93. except ValueError:
  94. return None
  95. try:
  96. return configuration["configuration"]["properties"]["core"]["project"]
  97. except KeyError:
  98. return None
  99. def get_auth_access_token(account=None):
  100. """Load user access token with the ``gcloud auth print-access-token`` command.
  101. Args:
  102. account (Optional[str]): Account to get the access token for. If not
  103. specified, the current active account will be used.
  104. Returns:
  105. str: The user access token.
  106. Raises:
  107. google.auth.exceptions.UserAccessTokenError: if failed to get access
  108. token from gcloud.
  109. """
  110. if os.name == "nt":
  111. command = _CLOUD_SDK_WINDOWS_COMMAND
  112. else:
  113. command = _CLOUD_SDK_POSIX_COMMAND
  114. try:
  115. if account:
  116. command = (
  117. (command,)
  118. + _CLOUD_SDK_USER_ACCESS_TOKEN_COMMAND
  119. + ("--account=" + account,)
  120. )
  121. else:
  122. command = (command,) + _CLOUD_SDK_USER_ACCESS_TOKEN_COMMAND
  123. access_token = subprocess.check_output(command, stderr=subprocess.STDOUT)
  124. # remove the trailing "\n"
  125. return access_token.decode("utf-8").strip()
  126. except (subprocess.CalledProcessError, OSError, IOError) as caught_exc:
  127. new_exc = exceptions.UserAccessTokenError(
  128. "Failed to obtain access token", caught_exc
  129. )
  130. six.raise_from(new_exc, caught_exc)