_cloud_sdk.py 5.1 KB

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