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