Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
50 changes: 28 additions & 22 deletions packages/google-auth/google/auth/compute_engine/credentials.py
Original file line number Diff line number Diff line change
Expand Up @@ -271,41 +271,47 @@ def get_cred_info(self):
"principal": self.service_account_email,
}

def _make_copy(self):
creds = self.__class__(
service_account_email=self._service_account_email,
quota_project_id=self._quota_project_id,
scopes=self._scopes,
default_scopes=self._default_scopes,
universe_domain=self._universe_domain,
trust_boundary=self._trust_boundary,
)
creds._universe_domain_cached = self._universe_domain_cached
self._copy_regional_access_boundary_manager(creds)
def _copy_with(self, **overrides):
kwargs = {
"service_account_email": self._service_account_email,
"quota_project_id": self._quota_project_id,
"scopes": self._scopes,
"default_scopes": self._default_scopes,
"universe_domain": (
self._universe_domain if self._universe_domain_cached else None
),
"trust_boundary": self._trust_boundary,
}
kwargs.update(overrides)
creds = self.__class__(**kwargs)
# RAB state only applies to the default universe domain, so do not carry
# cached RAB data onto credentials targeting another universe.
if (
not creds._universe_domain_cached
or (creds._universe_domain or "").lower()
== credentials.DEFAULT_UNIVERSE_DOMAIN
):
self._copy_regional_access_boundary_manager(creds)
return creds

def _make_copy(self):
return self._copy_with()

@_helpers.copy_docstring(credentials.CredentialsWithQuotaProject)
def with_quota_project(self, quota_project_id):
creds = self._make_copy()
creds._quota_project_id = quota_project_id
return creds
return self._copy_with(quota_project_id=quota_project_id)

@_helpers.copy_docstring(credentials.Scoped)
def with_scopes(self, scopes, default_scopes=None):
# Compute Engine credentials can not be scoped (the metadata service
# ignores the scopes parameter). App Engine, Cloud Run and Flex support
# requesting scopes.
creds = self._make_copy()
creds._scopes = scopes
creds._default_scopes = default_scopes
return creds
return self._copy_with(scopes=scopes, default_scopes=default_scopes)

@_helpers.copy_docstring(credentials.CredentialsWithUniverseDomain)
def with_universe_domain(self, universe_domain):
creds = self._make_copy()
creds._universe_domain = universe_domain
creds._universe_domain_cached = True
return creds
_helpers.validate_universe_domain(universe_domain)
return self._copy_with(universe_domain=universe_domain)


_DEFAULT_TOKEN_LIFETIME_SECS = 3600 # 1 hour in seconds
Expand Down
45 changes: 41 additions & 4 deletions packages/google-auth/google/auth/downscoped.py
Original file line number Diff line number Diff line change
Expand Up @@ -423,7 +423,10 @@ def to_json(self):
return json


class Credentials(credentials.CredentialsWithQuotaProject):
class Credentials(
credentials.CredentialsWithQuotaProject,
credentials.CredentialsWithUniverseDomain,
):
"""Defines a set of Google credentials that are downscoped from an existing set
of Google OAuth2 credentials. This is useful to restrict the Identity and Access
Management (IAM) permissions that a short-lived credential can use.
Expand All @@ -439,7 +442,7 @@ def __init__(
source_credentials,
credential_access_boundary,
quota_project_id=None,
universe_domain=credentials.DEFAULT_UNIVERSE_DOMAIN,
universe_domain=None,
):
"""Instantiates a downscoped credentials object using the provided source
credentials and credential access boundary rules.
Expand All @@ -458,19 +461,38 @@ def __init__(
the upper bound of the permissions that are available on that resource and an
optional condition to further restrict permissions.
quota_project_id (Optional[str]): The optional quota project ID.
universe_domain (Optional[str]): The universe domain value, default is googleapis.com
universe_domain (Optional[str]): The universe domain value. If omitted,
defaults to ``source_credentials.universe_domain`` (or
``googleapis.com`` if unset). If provided, it must match
``source_credentials.universe_domain``.
Raises:
google.auth.exceptions.InvalidValue: If ``universe_domain`` is
invalid or does not match ``source_credentials.universe_domain``.
google.auth.exceptions.RefreshError: If the source credentials
return an error on token refresh.
google.auth.exceptions.OAuthError: If the STS token exchange
endpoint returned an error during downscoped token generation.
"""

super(Credentials, self).__init__()
# Validate early to fail fast before triggering a lazy metadata lookup
# on uncached source credentials (such as compute_engine.Credentials).
if universe_domain is not None:
_helpers.validate_universe_domain(universe_domain)
source_universe = getattr(source_credentials, "universe_domain", None)
if source_universe is None:
source_universe = credentials.DEFAULT_UNIVERSE_DOMAIN
if universe_domain is not None:
_helpers.compare_universe_domains(universe_domain, source_universe)
else:
_helpers.validate_universe_domain(source_universe)

self._source_credentials = source_credentials
self._credential_access_boundary = credential_access_boundary
self._quota_project_id = quota_project_id
self._universe_domain = universe_domain or credentials.DEFAULT_UNIVERSE_DOMAIN
self._universe_domain = (
universe_domain if universe_domain is not None else source_universe
)
self._sts_client = sts.Client(
_STS_TOKEN_URL_PATTERN.format(self.universe_domain)
)
Expand Down Expand Up @@ -507,4 +529,19 @@ def with_quota_project(self, quota_project_id):
self._source_credentials,
self._credential_access_boundary,
quota_project_id=quota_project_id,
universe_domain=self._universe_domain,
)

@_helpers.copy_docstring(credentials.CredentialsWithUniverseDomain)
def with_universe_domain(self, universe_domain):
_helpers.validate_universe_domain(universe_domain)
source_credentials = self._source_credentials
with_universe_domain = getattr(source_credentials, "with_universe_domain", None)
if callable(with_universe_domain):
source_credentials = with_universe_domain(universe_domain)
return self.__class__(
source_credentials,
self._credential_access_boundary,
quota_project_id=self._quota_project_id,
universe_domain=universe_domain,
)
41 changes: 21 additions & 20 deletions packages/google-auth/google/auth/external_account.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ class Credentials(
credentials.Scoped,
credentials.CredentialsWithQuotaProject,
credentials.CredentialsWithTokenUri,
credentials.CredentialsWithUniverseDomain,
credentials.CredentialsWithRegionalAccessBoundary,
metaclass=abc.ABCMeta,
):
Expand Down Expand Up @@ -167,9 +168,10 @@ def __init__(
super(Credentials, self).__init__()
self._audience = audience
self._subject_token_type = subject_token_type
self._universe_domain = universe_domain
self._universe_domain = universe_domain or credentials.DEFAULT_UNIVERSE_DOMAIN
self._raw_token_url = token_url
self._token_url = token_url
if self._token_url == _DEFAULT_TOKEN_URL:
if self._token_url and "{universe_domain}" in self._token_url:
self._token_url = self._token_url.replace(
"{universe_domain}", self._universe_domain
Comment thread
parthea marked this conversation as resolved.
Resolved
)
Expand Down Expand Up @@ -366,13 +368,7 @@ def get_cred_info(self):

@_helpers.copy_docstring(credentials.Scoped)
def with_scopes(self, scopes, default_scopes=None):
kwargs = self._constructor_args()
kwargs.update(scopes=scopes, default_scopes=default_scopes)
scoped = self.__class__(**kwargs)
scoped._cred_file_path = self._cred_file_path
scoped._metrics_options = self._metrics_options
self._copy_regional_access_boundary_manager(scoped)
return scoped
return self._copy_with(scopes=scopes, default_scopes=default_scopes)

@abc.abstractmethod
def retrieve_subject_token(self, request):
Expand Down Expand Up @@ -600,32 +596,37 @@ def _build_regional_access_boundary_lookup_url(
)
return None

def _make_copy(self):
def _copy_with(self, **overrides):
kwargs = self._constructor_args()
# Preserve the unformatted token_url template so cloned credentials can
# re-format it when with_universe_domain() is called later.
kwargs["token_url"] = getattr(self, "_raw_token_url", self._token_url)
kwargs.update(overrides)
new_cred = self.__class__(**kwargs)
new_cred._cred_file_path = self._cred_file_path
new_cred._metrics_options = self._metrics_options
self._copy_regional_access_boundary_manager(new_cred)
# RAB state only applies to the default universe domain, so do not carry
# cached RAB data onto credentials targeting another universe.
if new_cred.universe_domain.lower() == credentials.DEFAULT_UNIVERSE_DOMAIN:
self._copy_regional_access_boundary_manager(new_cred)
return new_cred

def _make_copy(self):
return self._copy_with()

@_helpers.copy_docstring(credentials.CredentialsWithQuotaProject)
def with_quota_project(self, quota_project_id):
# Return copy of instance with the provided quota project ID.
cred = self._make_copy()
cred._quota_project_id = quota_project_id
return cred
return self._copy_with(quota_project_id=quota_project_id)

@_helpers.copy_docstring(credentials.CredentialsWithTokenUri)
def with_token_uri(self, token_uri):
cred = self._make_copy()
cred._token_url = token_uri
return cred
return self._copy_with(token_url=token_uri)

@_helpers.copy_docstring(credentials.CredentialsWithUniverseDomain)
def with_universe_domain(self, universe_domain):
cred = self._make_copy()
cred._universe_domain = universe_domain
return cred
_helpers.validate_universe_domain(universe_domain)
return self._copy_with(universe_domain=universe_domain)

def _should_initialize_impersonated_credentials(self):
"""Determines if the underlying Service Account credential should be initialized."""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ class Credentials(
credentials.CredentialsWithQuotaProject,
credentials.ReadOnlyScoped,
credentials.CredentialsWithTokenUri,
credentials.CredentialsWithUniverseDomain,
credentials.CredentialsWithRegionalAccessBoundary,
):
"""Credentials for External Account Authorized Users.
Expand Down Expand Up @@ -133,14 +134,19 @@ def __init__(
self.expiry = expiry
self._audience = audience
self._refresh_token = refresh_token
self._universe_domain = universe_domain or credentials.DEFAULT_UNIVERSE_DOMAIN
self._raw_token_url = token_url
self._token_url = token_url
if self._token_url and "{universe_domain}" in self._token_url:
self._token_url = self._token_url.replace(
"{universe_domain}", self._universe_domain
)
self._token_info_url = token_info_url
self._client_id = client_id
self._client_secret = client_secret
self._revoke_url = revoke_url
self._quota_project_id = quota_project_id
self._scopes = scopes
self._universe_domain = universe_domain or credentials.DEFAULT_UNIVERSE_DOMAIN
self._cred_file_path = None
self._trust_boundary = trust_boundary

Expand Down Expand Up @@ -373,30 +379,43 @@ def get_cred_info(self):
}
return None

def _make_copy(self):
def _copy_with(self, **overrides):
kwargs = self.constructor_args()
# Preserve the unformatted token_url template so cloned credentials can
# re-format it when with_universe_domain() is called later.
kwargs["token_url"] = getattr(self, "_raw_token_url", self._token_url)
kwargs.update(overrides)
# Clear cached access token state when switching universe domains so a
# token minted in one universe is not reused in another.
if (
"universe_domain" in overrides
and overrides["universe_domain"].lower() != self._universe_domain.lower()
):
kwargs["token"] = None
kwargs["expiry"] = None
cred = self.__class__(**kwargs)
cred._cred_file_path = self._cred_file_path
self._copy_regional_access_boundary_manager(cred)
# RAB state only applies to the default universe domain, so do not carry
# cached RAB data onto credentials targeting another universe.
if cred.universe_domain.lower() == credentials.DEFAULT_UNIVERSE_DOMAIN:
self._copy_regional_access_boundary_manager(cred)
return cred

def _make_copy(self):
return self._copy_with()

@_helpers.copy_docstring(credentials.CredentialsWithQuotaProject)
def with_quota_project(self, quota_project_id):
cred = self._make_copy()
cred._quota_project_id = quota_project_id
return cred
return self._copy_with(quota_project_id=quota_project_id)

@_helpers.copy_docstring(credentials.CredentialsWithTokenUri)
def with_token_uri(self, token_uri):
cred = self._make_copy()
cred._token_url = token_uri
return cred
return self._copy_with(token_url=token_uri)

@_helpers.copy_docstring(credentials.CredentialsWithUniverseDomain)
def with_universe_domain(self, universe_domain):
cred = self._make_copy()
cred._universe_domain = universe_domain
return cred
_helpers.validate_universe_domain(universe_domain)
return self._copy_with(universe_domain=universe_domain)

@classmethod
def from_info(cls, info, **kwargs):
Expand Down
49 changes: 49 additions & 0 deletions packages/google-auth/tests/compute_engine/test_credentials.py
Original file line number Diff line number Diff line change
Expand Up @@ -261,6 +261,55 @@ def test_with_universe_domain(self):
assert creds.universe_domain == "universe_domain"
assert creds._universe_domain_cached

@pytest.mark.parametrize("bad_universe", [None, "", " ", "example.com/path"])
def test_with_universe_domain_invalid(self, bad_universe):
with pytest.raises(
exceptions.InvalidValue,
match="Universe domain must be a valid non-empty domain string.",
):
self.credentials.with_universe_domain(bad_universe)

def test_with_universe_domain_resets_rab_state(self):
default_creds = credentials.Credentials(universe_domain="googleapis.com")
default_creds._rab_manager._data = mock.sentinel.rab_data
default_creds._rab_manager._use_blocking_regional_access_boundary_lookup = True

# Staying in the default universe preserves RAB state and blocking config.
for cloned in (
default_creds._make_copy(),
default_creds.with_quota_project("project-foo"),
default_creds.with_scopes(["one"]),
default_creds.with_universe_domain("googleapis.com"),
):
assert cloned._rab_manager._data == mock.sentinel.rab_data
assert (
cloned._rab_manager._use_blocking_regional_access_boundary_lookup
is True
)
assert cloned._rab_manager is not default_creds._rab_manager

# Switching to a non-default universe starts with fresh RAB state.
non_default = default_creds.with_universe_domain("example.com")
assert non_default._rab_manager is not default_creds._rab_manager
assert non_default._rab_manager._data.encoded_locations is None
assert non_default._rab_manager._data.expiry is None
assert (
non_default._rab_manager._use_blocking_regional_access_boundary_lookup
is False
)

# Uncached credentials preserve RAB config when cloned without changing universe.
uncached = credentials.Credentials()
uncached._rab_manager._data = mock.sentinel.rab_data
uncached._rab_manager._use_blocking_regional_access_boundary_lookup = True
uncached_copy = uncached.with_quota_project("project-foo")
assert uncached_copy._rab_manager._data == mock.sentinel.rab_data
assert (
uncached_copy._rab_manager._use_blocking_regional_access_boundary_lookup
is True
)
assert not uncached_copy._universe_domain_cached

@mock.patch(
"google.auth.compute_engine._metadata.get_universe_domain",
return_value="googleapis.com",
Expand Down
Loading
Loading