Skip to content
Merged
Changes from 1 commit
Commits
Show all changes
58 commits
Select commit Hold shift + click to select a range
63ad5e9
feat: Add Pluggable auth support (#988)
Mar 1, 2022
f36e5e8
feat: Add file caching (#990)
Mar 3, 2022
28cfefc
🦉 Updates from OwlBot post-processor
gcf-owl-bot[bot] Mar 17, 2022
4b1e956
Merge branch 'main' into pluggable
arithmetic1728 Mar 17, 2022
d7f4980
Update pluggable.py
Mar 18, 2022
7092170
🦉 Updates from OwlBot post-processor
gcf-owl-bot[bot] Mar 19, 2022
5246463
Update pluggable.py
Mar 23, 2022
62246d6
🦉 Updates from OwlBot post-processor
gcf-owl-bot[bot] Mar 23, 2022
d0e4294
Update setup.py
Mar 23, 2022
0ceda64
Merge branch 'pluggable' of https://github.com/googleapis/google-auth…
Mar 23, 2022
6618271
Update setup.py
Mar 23, 2022
1f38c45
Update setup.py
Mar 23, 2022
be1cfc9
pytest_subprocess
Mar 23, 2022
97bd209
timeout
Mar 24, 2022
139bac9
Update pluggable.py
Mar 24, 2022
33c7667
env
Mar 24, 2022
3894c25
🦉 Updates from OwlBot post-processor
gcf-owl-bot[bot] Mar 24, 2022
9c233dc
Update _default.py
Mar 24, 2022
72ae073
🦉 Updates from OwlBot post-processor
gcf-owl-bot[bot] Mar 24, 2022
d51fd90
Update requirements.txt
Mar 24, 2022
b0b9ad2
Update _default.py
Mar 24, 2022
6712710
Update pluggable.py
Mar 29, 2022
29ac755
Update pluggable.py
Apr 5, 2022
1abed38
Update pluggable.py
Apr 5, 2022
d276d52
Update test_pluggable.py
Apr 5, 2022
c9d304d
format validations
Apr 6, 2022
ac6c360
Update _default.py
Apr 19, 2022
c87b614
Merge branch 'main' into pluggable
Apr 20, 2022
decb412
🦉 Updates from OwlBot post-processor
gcf-owl-bot[bot] Apr 20, 2022
1c9b6db
Update requirements.txt
Apr 20, 2022
564c3a0
Merge branch 'pluggable' of https://github.com/googleapis/google-auth…
Apr 20, 2022
a7efb54
Revert "Update requirements.txt"
Apr 20, 2022
1c08483
Revert "Update _default.py"
Apr 20, 2022
adc6779
Revert "Revert "Update _default.py""
Apr 20, 2022
889bf32
Raise output format error but retry parsing token if `success` is 0
Apr 29, 2022
e9db21c
🦉 Updates from OwlBot post-processor
gcf-owl-bot[bot] Apr 29, 2022
a94b68b
Merge branch 'main' into pluggable
Apr 29, 2022
e1edbb6
Update requirements.txt
May 3, 2022
74beba9
Delete test_pluggable.py
May 3, 2022
ac697a2
Revert "Delete test_pluggable.py"
May 4, 2022
ca65d6b
Merge branch 'main' into pluggable
May 4, 2022
ce79682
Update pluggable.py
May 4, 2022
78b2f83
Update pluggable.py
May 4, 2022
74afd44
🦉 Updates from OwlBot post-processor
gcf-owl-bot[bot] May 4, 2022
9a4a518
pytest-subprocess
May 5, 2022
d6ab6f0
Merge branch 'pluggable' of https://github.com/googleapis/google-auth…
May 5, 2022
ac27e4a
🦉 Updates from OwlBot post-processor
gcf-owl-bot[bot] May 5, 2022
484d07f
Merge branch 'main' into pluggable
arithmetic1728 May 5, 2022
d71587e
lint
May 5, 2022
3d40268
Update pluggable.py
May 5, 2022
8bfae0a
nox cover
May 5, 2022
245b610
🦉 Updates from OwlBot post-processor
gcf-owl-bot[bot] May 8, 2022
25b5446
lint
May 8, 2022
34126ef
Update test_pluggable.py
May 8, 2022
15d7a79
🦉 Updates from OwlBot post-processor
gcf-owl-bot[bot] May 8, 2022
1e5a89a
Update test_pluggable.py
May 8, 2022
f423446
Merge branch 'pluggable' of https://github.com/googleapis/google-auth…
May 8, 2022
e0b966a
Merge branch 'main' into pluggable
arithmetic1728 May 10, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Update pluggable.py
  • Loading branch information
Chuan Ren committed Mar 18, 2022
commit d7f4980e3c7cf8cf5096405cdde5bcd308edbc17
97 changes: 47 additions & 50 deletions google/auth/pluggable.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,23 +13,22 @@
# limitations under the License.

"""Pluggable Credentials.

This module provides credentials to access Google Cloud resources from on-prem
or non-Google Cloud platforms which support external credentials (e.g. OIDC ID
tokens) retrieved from local file locations or local servers. This includes
Microsoft Azure and OIDC identity providers (e.g. K8s workloads registered with
Hub with Hub workload identity enabled).

These credentials are recommended over the use of service account credentials
in on-prem/non-Google Cloud platforms as they do not involve the management of
long-live service account private keys.

Pluggable Credentials are initialized using external_account arguments which
are typically loaded from third-party executables. Unlike other
credentials that can be initialized with a list of explicit arguments, secrets
or credentials, external account clients use the environment and hints/guidelines
provided by the external_account JSON file to retrieve credentials and exchange
them for Google access tokens.
them for Google access tokens.

Example credential_source for pluggable credential::

{
"executable": {
"command": "/path/to/get/credentials.sh --arg1=value1 --arg2=value2",
"timeout_millis": 5000,
"output_file": "/path/to/generated/cached/credentials"
}
}
"""

try:
Expand All @@ -47,10 +46,9 @@
from google.auth import exceptions
from google.auth import external_account

# External account JSON type identifier.
# The max supported executable spec version.
EXECUTABLE_SUPPORTED_MAX_VERSION = 1


class Credentials(external_account.Credentials):
"""External account credentials sourced from executables."""

Expand Down Expand Up @@ -78,7 +76,7 @@ def __init__(
provide instructions on how to retrieve external credential to be
exchanged for Google access tokens.

Example credential_source for pluggable credential::
Example credential_source for pluggable credential:

{
"executable": {
Expand Down Expand Up @@ -126,40 +124,36 @@ def __init__(
default_scopes=default_scopes,
workforce_pool_user_project=workforce_pool_user_project,
)
if workforce_pool_user_project is not None:
raise ValueError(
"Pluggable auth doesn't support Workforce poolyet."
)
if not isinstance(credential_source, Mapping):
self._credential_source_executable = None
raise ValueError(
"Missing credential_source. The credential_source is not a dict."
)
else:
self._credential_source_executable = credential_source.get("executable")
if not self._credential_source_executable:
raise ValueError(
"Missing credential_source. An 'executable' must be provided."
)
self._credential_source_executable_command = self._credential_source_executable.get(
"command"
)
self._credential_source_executable_timeout_millis = self._credential_source_executable.get(
"timeout_millis"
)
self._credential_source_executable_output_file = self._credential_source_executable.get(
"output_file"
self._credential_source_executable = credential_source.get("executable")
if not self._credential_source_executable:
raise ValueError(
"Missing credential_source. An 'executable' must be provided."
)

# environment_id is only supported in AWS or dedicated future external
# account credentials.
if "environment_id" in credential_source:
raise ValueError(
"Invalid Pluggable credential_source field 'environment_id'"
)
self._credential_source_executable_command = self._credential_source_executable.get(
"command"
)
self._credential_source_executable_timeout_millis = self._credential_source_executable.get(
"timeout_millis"
)
self._credential_source_executable_output_file = self._credential_source_executable.get(
"output_file"
)

if not self._credential_source_executable_command:
raise ValueError("Missing command. Executable command must be provided.")
if not self._credential_source_executable_timeout_millis:
raise ValueError(
"Missing timeout_millis. Executable timeout millis must be provided."
)
self._credential_source_executable_timeout_millis = 30 * 1000
elif self._credential_source_executable_timeout_millis < 0 or self._credential_source_executable_timeout_millis > 120:
raise ValueError("Timeout must be between 0 and 120 seconds.")

@_helpers.copy_docstring(external_account.Credentials)
def retrieve_subject_token(self, request):
Expand All @@ -171,20 +165,21 @@ def retrieve_subject_token(self, request):
"Executables need to be explicitly allowed (set GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES to '1') to run."
)

# Check output file
# Check output file.
if self._credential_source_executable_output_file is not None:
try:
with open(
self._credential_source_executable_output_file
) as output_file:
response = json.load(output_file)
# If the cached response is expired, _parse_subject_token will raise an error which will be ignored and we will call the executable again.
subject_token = self._parse_subject_token(response)
except:
pass
else:
return subject_token

# Inject env vars
# Inject env vars.
original_audience = os.getenv("GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE")
os.environ["GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE"] = self._audience
original_subject_token_type = os.getenv("GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE")
Expand All @@ -199,7 +194,7 @@ def retrieve_subject_token(self, request):
if self._service_account_impersonation_url is not None:
os.environ[
"GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL"
] = self._service_account_impersonation_url
] = self.service_account_email()
original_credential_source_executable_output_file = os.getenv(
"GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE"
)
Expand All @@ -215,7 +210,7 @@ def retrieve_subject_token(self, request):
stderr=subprocess.STDOUT,
)

# Reset env vars
# Reset env vars.
if original_audience is not None:
os.environ["GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE"] = original_audience
else:
Expand Down Expand Up @@ -302,21 +297,23 @@ def from_file(cls, filename, **kwargs):
return cls.from_info(data, **kwargs)

def _parse_subject_token(self, response):
if not response["success"]:
raise exceptions.RefreshError(
"Executable returned unsuccessful response: {}.".format(response)
)
elif response["version"] > EXECUTABLE_SUPPORTED_MAX_VERSION:
if response["version"] > EXECUTABLE_SUPPORTED_MAX_VERSION:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not too familiar with Python but what happens if there is no "version" field here?

Copy link
Contributor

@sai-sunder-s sai-sunder-s May 4, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am not very familiar with python either. I came across this syntax to get a default value if the version is not present.
lookupValue = somedict.get(someKey, someDefaultValue)

May this can be used to simplify your code in the places where you are checking for presence first?

@renkelvin: We did this intentionally to distinguish whether it's a format issue or a content issue, so we can inform the customer to fix the output accordingly.

raise exceptions.RefreshError(
"Executable returned unsupported version {}.".format(
response["version"]
)
)
elif response["expiration_time"] < time.time():
if not response["success"] or not response["success"]:
if not response["code"] or not response["message"]:
raise ValueError("Code and message are required in the response.")
raise exceptions.RefreshError(
"Executable returned unsuccessful response: code: {}, message: {}.".format(response["code"], response["message"])
)
if response["expiration_time"] < time.time():
raise exceptions.RefreshError(
"The token returned by the executable is expired."
)
elif (
if (
response["token_type"] == "urn:ietf:params:oauth:token-type:jwt"
or response["token_type"] == "urn:ietf:params:oauth:token-type:id_token"
): # OIDC
Expand Down