Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Pluggable auth support #995

Merged
merged 58 commits into from
May 10, 2022
Merged
Show file tree
Hide file tree
Changes from 37 commits
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
11 changes: 10 additions & 1 deletion google/auth/_default.py
Original file line number Diff line number Diff line change
Expand Up @@ -317,14 +317,23 @@ def _get_external_account_credentials(
google.auth.exceptions.DefaultCredentialsError: if the info dictionary
is in the wrong format or is missing required information.
"""
# There are currently 2 types of external_account credentials.
# There are currently 3 types of external_account credentials.
renkelvin marked this conversation as resolved.
Show resolved Hide resolved
if info.get("subject_token_type") == _AWS_SUBJECT_TOKEN_TYPE:
# Check if configuration corresponds to an AWS credentials.
from google.auth import aws

credentials = aws.Credentials.from_info(
info, scopes=scopes, default_scopes=default_scopes
)
elif (
info.get("credential_source") is not None
and info.get("credential_source").get("executable") is not None
):
from google.auth import pluggable

credentials = pluggable.Credentials.from_info(
info, scopes=scopes, default_scopes=default_scopes
)
else:
try:
# Check if configuration corresponds to an Identity Pool credentials.
Expand Down
319 changes: 319 additions & 0 deletions google/auth/pluggable.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,319 @@
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Pluggable Credentials.
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.

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:
from collections.abc import Mapping
# Python 2.7 compatibility
except ImportError: # pragma: NO COVER
from collections import Mapping
import io
import json
import os
import subprocess
import time

from google.auth import _helpers
from google.auth import exceptions
from google.auth import external_account

# The max supported executable spec version.
EXECUTABLE_SUPPORTED_MAX_VERSION = 1


renkelvin marked this conversation as resolved.
Show resolved Hide resolved
class Credentials(external_account.Credentials):
"""External account credentials sourced from executables."""

def __init__(
self,
audience,
subject_token_type,
token_url,
credential_source,
service_account_impersonation_url=None,
client_id=None,
client_secret=None,
quota_project_id=None,
scopes=None,
default_scopes=None,
workforce_pool_user_project=None,
renkelvin marked this conversation as resolved.
Show resolved Hide resolved
):
"""Instantiates an external account credentials object from a executables.

Args:
audience (str): The STS audience field.
subject_token_type (str): The subject token type.
token_url (str): The STS endpoint URL.
credential_source (Mapping): The credential source dictionary used to
provide instructions on how to retrieve external credential to be
exchanged 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"
}
}

service_account_impersonation_url (Optional[str]): The optional service account
impersonation getAccessToken URL.
client_id (Optional[str]): The optional client ID.
client_secret (Optional[str]): The optional client secret.
quota_project_id (Optional[str]): The optional quota project ID.
scopes (Optional[Sequence[str]]): Optional scopes to request during the
authorization grant.
default_scopes (Optional[Sequence[str]]): Default scopes passed by a
Google client library. Use 'scopes' for user-defined scopes.
workforce_pool_user_project (Optona[str]): The optional workforce pool user
project number when the credential corresponds to a workforce pool and not
a workload Pluggable. The underlying principal must still have
serviceusage.services.use IAM permission to use the project for
billing/quota.

Raises:
google.auth.exceptions.RefreshError: If an error is encountered during
access token retrieval logic.
ValueError: For invalid parameters.

.. note:: Typically one of the helper constructors
:meth:`from_file` or
:meth:`from_info` are used instead of calling the constructor directly.
"""

super(Credentials, self).__init__(
audience=audience,
subject_token_type=subject_token_type,
token_url=token_url,
credential_source=credential_source,
service_account_impersonation_url=service_account_impersonation_url,
client_id=client_id,
client_secret=client_secret,
quota_project_id=quota_project_id,
scopes=scopes,
default_scopes=default_scopes,
workforce_pool_user_project=workforce_pool_user_project,
)
if workforce_pool_user_project is not None:
raise ValueError(
"Workforce Pools are not yet supported with Pluggable Auth."
)
if not isinstance(credential_source, Mapping):
self._credential_source_executable = None
raise ValueError(
"Missing credential_source. The credential_source is not a dict."
)
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"
)

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

@_helpers.copy_docstring(external_account.Credentials)
def retrieve_subject_token(self, request):
env_allow_executables = os.environ.get(
"GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES"
)
if env_allow_executables != "1":
raise ValueError(
"Executables need to be explicitly allowed (set GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES to '1') to run."
)

# 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)
except:
pass
lsirac marked this conversation as resolved.
Show resolved Hide resolved
else:
try:
# 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 ValueError:
raise
except exceptions.RefreshError:
pass
else:
return subject_token

# Inject env vars.
renkelvin marked this conversation as resolved.
Show resolved Hide resolved
env = os.environ.copy()
env["GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE"] = self._audience
lsirac marked this conversation as resolved.
Show resolved Hide resolved
env["GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE"] = self._subject_token_type
env[
"GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE"
] = "0" # Always set to 0 until interactive mode is implemented.
if self._service_account_impersonation_url is not None:
env[
"GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL"
] = self.service_account_email()
if self._credential_source_executable_output_file is not None:
env[
"GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE"
] = self._credential_source_executable_output_file
result = subprocess.run(
lsirac marked this conversation as resolved.
Show resolved Hide resolved
renkelvin marked this conversation as resolved.
Show resolved Hide resolved
self._credential_source_executable_command.split(),
timeout=self._credential_source_executable_timeout_millis / 1000,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
env=env,
)

if result.returncode != 0:
raise exceptions.RefreshError(
"Executable exited with non-zero return code {}. Error: {}".format(
result.returncode, result.stdout
lsirac marked this conversation as resolved.
Show resolved Hide resolved
)
)
else:
try:
data = result.stdout.decode("utf-8")
response = json.loads(data)
lsirac marked this conversation as resolved.
Show resolved Hide resolved
subject_token = self._parse_subject_token(response)
except:
raise
else:
return subject_token

@classmethod
def from_info(cls, info, **kwargs):
"""Creates a Pluggable Credentials instance from parsed external account info.

Args:
info (Mapping[str, str]): The Pluggable external account info in Google
format.
kwargs: Additional arguments to pass to the constructor.

Returns:
google.auth.pluggable.Credentials: The constructed
credentials.

Raises:
ValueError: For invalid parameters.
"""
return cls(
audience=info.get("audience"),
subject_token_type=info.get("subject_token_type"),
token_url=info.get("token_url"),
service_account_impersonation_url=info.get(
"service_account_impersonation_url"
),
client_id=info.get("client_id"),
client_secret=info.get("client_secret"),
credential_source=info.get("credential_source"),
quota_project_id=info.get("quota_project_id"),
workforce_pool_user_project=info.get("workforce_pool_user_project"),
**kwargs
)

@classmethod
def from_file(cls, filename, **kwargs):
"""Creates an Pluggable Credentials instance from an external account json file.

Args:
filename (str): The path to the Pluggable external account json file.
kwargs: Additional arguments to pass to the constructor.

Returns:
google.auth.pluggable.Credentials: The constructed
credentials.
"""
with io.open(filename, "r", encoding="utf-8") as json_file:
data = json.load(json_file)
return cls.from_info(data, **kwargs)

def _parse_subject_token(self, response):
lsirac marked this conversation as resolved.
Show resolved Hide resolved
if not "version" in response:
lsirac marked this conversation as resolved.
Show resolved Hide resolved
raise ValueError("The executable response is missing the version field.")
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.

lsirac marked this conversation as resolved.
Show resolved Hide resolved
raise exceptions.RefreshError(
"Executable returned unsupported version {}.".format(
response["version"]
)
)
if not "success" in response:
raise ValueError("The executable response is missing the success field.")
if not response["success"]:
if "code" not in response or "message" not in response:
raise ValueError(
"Error code and message fields are required in the response."
)
raise exceptions.RefreshError(
"Executable returned unsuccessful response: code: {}, message: {}.".format(
response["code"], response["message"]
)
)
if not "expiration_time" in response:
raise ValueError(
"The executable response is missing the expiration_time field."
)
if response["expiration_time"] < time.time():
raise exceptions.RefreshError(
"The token returned by the executable is expired."
)
if not "token_type" in response:
raise ValueError("The executable response is missing the token_type field.")
if (
response["token_type"] == "urn:ietf:params:oauth:token-type:jwt"
or response["token_type"] == "urn:ietf:params:oauth:token-type:id_token"
): # OIDC
return response["id_token"]
elif response["token_type"] == "urn:ietf:params:oauth:token-type:saml2": # SAML
return response["saml_response"]
else:
raise exceptions.RefreshError("Executable returned unsupported token type.")
1 change: 1 addition & 0 deletions testing/requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ urllib3
cryptography
responses
grpcio
pytest-subprocess; python_version > '3.6'
# Async Dependencies
pytest-asyncio; python_version > '3.0'
aioresponses; python_version > '3.0'
Expand Down
Loading