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
28 changes: 22 additions & 6 deletions packages/google-auth/google/auth/compute_engine/_metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -429,6 +429,27 @@ def get_project_id(request):
return get(request, "project/project-id")


def _get_explicit_universe_domain(request):
"""Get the universe domain value from the metadata server if available.

Args:
request (google.auth.transport.Request): A callable used to make
HTTP requests.

Returns:
Optional[str]: The universe domain value, or None if the universe
domain endpoint returns 404 or an empty response.

Raises:
google.auth.exceptions.TransportError: if an error other than
404 occurs while retrieving metadata.
"""
universe_domain = get(
request, "universe/universe-domain", return_none_for_not_found_error=True
)
return universe_domain or None


def get_universe_domain(request):
"""Get the universe domain value from the metadata server.

Expand All @@ -444,12 +465,7 @@ def get_universe_domain(request):
google.auth.exceptions.TransportError: if an error other than
404 occurs while retrieving metadata.
"""
universe_domain = get(
request, "universe/universe-domain", return_none_for_not_found_error=True
)
if not universe_domain:
return "googleapis.com"
return universe_domain
return _get_explicit_universe_domain(request) or "googleapis.com"


def get_service_account_info(request, service_account="default"):
Expand Down
22 changes: 10 additions & 12 deletions packages/google-auth/google/auth/compute_engine/credentials.py
Original file line number Diff line number Diff line change
Expand Up @@ -247,21 +247,19 @@ def requires_scopes(self):

@property
def universe_domain(self):
if self._universe_domain_cached:
return self._universe_domain

try:
from google.auth.transport import requests as google_auth_requests
if not self._universe_domain_cached:
try:
from google.auth.transport import requests as google_auth_requests

request = google_auth_requests.Request()
except ImportError:
from google.auth.transport import _http_client
request = google_auth_requests.Request()
except ImportError:
from google.auth.transport import _http_client

request = _http_client.Request()
request = _http_client.Request()

self._universe_domain = _metadata.get_universe_domain(request)
self._universe_domain_cached = True
return self._universe_domain
self._universe_domain = _metadata._get_explicit_universe_domain(request)
self._universe_domain_cached = True
return self._universe_domain or credentials.DEFAULT_UNIVERSE_DOMAIN

@_helpers.copy_docstring(credentials.Credentials)
def get_cred_info(self):
Expand Down
27 changes: 23 additions & 4 deletions packages/google-auth/google/auth/credentials.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,19 @@

DEFAULT_UNIVERSE_DOMAIN = _helpers.DEFAULT_UNIVERSE_DOMAIN


def _get_explicit_universe_domain(creds):
"""Returns the explicitly configured universe domain from creds, or None."""
# Read public universe_domain first so lazy credentials (such as Compute
# Engine) resolve metadata before we inspect _universe_domain.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

nit: I feel like this could use some more elaboration. I missed at first that universe_domain and _universe_domain were different

Maybe something like:

    # Unlike `_universe_domain` (which is None when omitted), the public
    # `universe_domain` property always falls back to DEFAULT_UNIVERSE_DOMAIN.
    # Read `universe_domain` first so lazy credentials (such as Compute Engine)
    # resolve metadata and any non-default universe is returned directly; then
    # check `_universe_domain` to distinguish an explicit default universe from
    # an omitted one.

universe_domain = getattr(creds, "universe_domain", DEFAULT_UNIVERSE_DOMAIN)
if universe_domain and universe_domain != DEFAULT_UNIVERSE_DOMAIN:
return universe_domain
if isinstance(creds, Credentials):
return getattr(creds, "_universe_domain", None)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Can we do this, to avoid empty strings?

Suggested change
return getattr(creds, "_universe_domain", None)
return getattr(creds, "_universe_domain", None) or None

return None


# These constants are deprecated and no longer used.
# They are kept solely for backward compatibility with older implementations.
NO_OP_TRUST_BOUNDARY_LOCATIONS: List[str] = []
Expand Down Expand Up @@ -77,8 +90,9 @@ def __init__(self):
"""Optional[dict]: Cache of a trust boundary response which has a list
of allowed regions and an encoded string representation of credentials
trust boundary."""
self._universe_domain = DEFAULT_UNIVERSE_DOMAIN
"""Optional[str]: The universe domain value, default is googleapis.com
self._universe_domain = None
"""Optional[str]: The explicitly configured universe domain, or None
if omitted.
"""

self._use_non_blocking_refresh = False
Expand Down Expand Up @@ -144,7 +158,7 @@ def quota_project_id(self):
@property
def universe_domain(self):
"""The universe domain value."""
return self._universe_domain
return getattr(self, "_universe_domain", None) or DEFAULT_UNIVERSE_DOMAIN

def get_cred_info(self):
"""The credential information JSON.
Expand Down Expand Up @@ -503,9 +517,14 @@ def _is_regional_access_boundary_lookup_required(self):
if not _regional_access_boundary_utils.is_regional_access_boundary_lookup_enabled():
return False

# Skip for non-default universe domains.
# Skip unless the universe domain is explicitly confirmed to be
# googleapis.com. Checking self.universe_domain first lets lazy
# subclasses (such as Compute Engine) resolve metadata before we
# inspect _universe_domain.
if self.universe_domain != DEFAULT_UNIVERSE_DOMAIN:
return False
if getattr(self, "_universe_domain", None) != DEFAULT_UNIVERSE_DOMAIN:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

nit: It feels a little risky to have an under-documented, private attribute doing such an important job here. Subclasses could implement their own version of universe_domain, and not realize they're silently skipping RAB lookups

Maybe we should have a separate thin self._get_explicit_universe_domain(), or self._is_explicit_default_universe() method, to better document this?

return False

return True

Expand Down
4 changes: 2 additions & 2 deletions packages/google-auth/google/auth/downscoped.py
Original file line number Diff line number Diff line change
Expand Up @@ -439,7 +439,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 Down Expand Up @@ -470,7 +470,7 @@ def __init__(
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 or None
self._sts_client = sts.Client(
_STS_TOKEN_URL_PATTERN.format(self.universe_domain)
)
Expand Down
12 changes: 5 additions & 7 deletions packages/google-auth/google/auth/external_account.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ def __init__(
scopes=None,
default_scopes=None,
workforce_pool_user_project=None,
universe_domain=credentials.DEFAULT_UNIVERSE_DOMAIN,
universe_domain=None,
trust_boundary=None,
):
"""Instantiates an external account credentials object.
Expand Down Expand Up @@ -167,14 +167,14 @@ 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 None
self._token_url = token_url
if self._token_url == _DEFAULT_TOKEN_URL:
self._token_url = self._token_url.replace(
"{universe_domain}", self._universe_domain
"{universe_domain}", self.universe_domain
)
self._cloud_resource_manager_url = _CLOUD_RESOURCE_MANAGER.replace(
"{universe_domain}", self._universe_domain
"{universe_domain}", self.universe_domain
)
self._token_info_url = token_info_url
self._credential_source = credential_source
Expand Down Expand Up @@ -763,9 +763,7 @@ def from_info(cls, info, **kwargs):
credential_source=info.get("credential_source"),
quota_project_id=info.get("quota_project_id"),
workforce_pool_user_project=info.get("workforce_pool_user_project"),
universe_domain=info.get(
"universe_domain", credentials.DEFAULT_UNIVERSE_DOMAIN
),
universe_domain=info.get("universe_domain"),
trust_boundary=info.get("trust_boundary"),
**kwargs,
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ def __init__(
revoke_url=None,
scopes=None,
quota_project_id=None,
universe_domain=credentials.DEFAULT_UNIVERSE_DOMAIN,
universe_domain=None,
trust_boundary=None,
):
"""Instantiates a external account authorized user credentials object.
Expand Down Expand Up @@ -140,7 +140,7 @@ def __init__(
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._universe_domain = universe_domain or None
self._cred_file_path = None
self._trust_boundary = trust_boundary

Expand Down Expand Up @@ -439,9 +439,7 @@ def from_info(cls, info, **kwargs):
revoke_url=info.get("revoke_url"),
quota_project_id=info.get("quota_project_id"),
scopes=info.get("scopes"),
universe_domain=info.get(
"universe_domain", credentials.DEFAULT_UNIVERSE_DOMAIN
),
universe_domain=info.get("universe_domain"),
trust_boundary=info.get("trust_boundary"),
**kwargs,
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -280,9 +280,12 @@ def __init__(
source_universe = credentials.DEFAULT_UNIVERSE_DOMAIN
if universe_domain is not None:
_helpers.compare_universe_domains(universe_domain, source_universe)
self._universe_domain = universe_domain
else:
_helpers.validate_universe_domain(source_universe)
self._universe_domain = source_universe
self._universe_domain = credentials._get_explicit_universe_domain(
self._source_credentials
)
self._target_principal = target_principal
self._target_scopes = target_scopes
self._delegates = delegates
Expand Down
32 changes: 10 additions & 22 deletions packages/google-auth/google/auth/jwt.py
Original file line number Diff line number Diff line change
Expand Up @@ -394,7 +394,7 @@ def __init__(
additional_claims=None,
token_lifetime=_DEFAULT_TOKEN_LIFETIME_SECS,
quota_project_id=None,
universe_domain=google.auth.credentials.DEFAULT_UNIVERSE_DOMAIN,
universe_domain=None,
):
"""
Args:
Expand All @@ -419,9 +419,7 @@ def __init__(
self._audience = audience
self._token_lifetime = token_lifetime
self._quota_project_id = quota_project_id
self._universe_domain = (
universe_domain or google.auth.credentials.DEFAULT_UNIVERSE_DOMAIN
)
self._universe_domain = universe_domain or None

if additional_claims is None:
additional_claims = {}
Expand All @@ -447,9 +445,7 @@ def _from_signer_and_info(cls, signer, info, **kwargs):
kwargs.setdefault("subject", info["client_email"])
kwargs.setdefault("issuer", info["client_email"])
if not kwargs.get("universe_domain"):
kwargs["universe_domain"] = info.get(
"universe_domain", google.auth.credentials.DEFAULT_UNIVERSE_DOMAIN
)
kwargs["universe_domain"] = info.get("universe_domain")
return cls(signer, **kwargs)

@classmethod
Expand Down Expand Up @@ -518,10 +514,8 @@ def from_signing_credentials(cls, credentials, audience, **kwargs):
kwargs.setdefault("issuer", credentials.signer_email)
kwargs.setdefault("subject", credentials.signer_email)
if not kwargs.get("universe_domain"):
kwargs["universe_domain"] = getattr(
credentials,
"universe_domain",
google.auth.credentials.DEFAULT_UNIVERSE_DOMAIN,
kwargs["universe_domain"] = (
google.auth.credentials._get_explicit_universe_domain(credentials)
)
jwt_creds = cls(credentials.signer, audience=audience, **kwargs)

Expand Down Expand Up @@ -716,7 +710,7 @@ def __init__(
token_lifetime=_DEFAULT_TOKEN_LIFETIME_SECS,
max_cache_size=_DEFAULT_MAX_CACHE_SIZE,
quota_project_id=None,
universe_domain=google.auth.credentials.DEFAULT_UNIVERSE_DOMAIN,
universe_domain=None,
):
"""
Args:
Expand All @@ -741,9 +735,7 @@ def __init__(
self._subject = subject
self._token_lifetime = token_lifetime
self._quota_project_id = quota_project_id
self._universe_domain = (
universe_domain or google.auth.credentials.DEFAULT_UNIVERSE_DOMAIN
)
self._universe_domain = universe_domain or None

if additional_claims is None:
additional_claims = {}
Expand All @@ -770,9 +762,7 @@ def _from_signer_and_info(cls, signer, info, **kwargs):
kwargs.setdefault("subject", info["client_email"])
kwargs.setdefault("issuer", info["client_email"])
if not kwargs.get("universe_domain"):
kwargs["universe_domain"] = info.get(
"universe_domain", google.auth.credentials.DEFAULT_UNIVERSE_DOMAIN
)
kwargs["universe_domain"] = info.get("universe_domain")
return cls(signer, **kwargs)

@classmethod
Expand Down Expand Up @@ -837,10 +827,8 @@ def from_signing_credentials(cls, credentials, **kwargs):
kwargs.setdefault("issuer", credentials.signer_email)
kwargs.setdefault("subject", credentials.signer_email)
if not kwargs.get("universe_domain"):
kwargs["universe_domain"] = getattr(
credentials,
"universe_domain",
google.auth.credentials.DEFAULT_UNIVERSE_DOMAIN,
kwargs["universe_domain"] = (
google.auth.credentials._get_explicit_universe_domain(credentials)
)
return cls(credentials.signer, **kwargs)

Expand Down
14 changes: 6 additions & 8 deletions packages/google-auth/google/oauth2/credentials.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ def __init__(
enable_reauth_refresh=False,
granted_scopes=None,
trust_boundary=None,
universe_domain=credentials.DEFAULT_UNIVERSE_DOMAIN,
universe_domain=None,
account=None,
):
"""
Expand Down Expand Up @@ -162,7 +162,7 @@ def __init__(
self.refresh_handler = refresh_handler
self._enable_reauth_refresh = enable_reauth_refresh
self._trust_boundary = trust_boundary
self._universe_domain = universe_domain or credentials.DEFAULT_UNIVERSE_DOMAIN
self._universe_domain = universe_domain or None
self._account = account or ""
self._cred_file_path = None

Expand Down Expand Up @@ -200,9 +200,7 @@ def __setstate__(self, d):
self._rapt_token = d.get("_rapt_token")
self._enable_reauth_refresh = d.get("_enable_reauth_refresh")
self._trust_boundary = d.get("_trust_boundary")
self._universe_domain = (
d.get("_universe_domain") or credentials.DEFAULT_UNIVERSE_DOMAIN
)
self._universe_domain = d.get("_universe_domain") or None
self._cred_file_path = d.get("_cred_file_path")
# The refresh_handler setter should be used to repopulate this.
self._refresh_handler = None
Expand Down Expand Up @@ -380,14 +378,14 @@ def _is_regional_access_boundary_lookup_required(self):
return False

def _perform_refresh_token(self, request):
if self._universe_domain != credentials.DEFAULT_UNIVERSE_DOMAIN:
if self.universe_domain != credentials.DEFAULT_UNIVERSE_DOMAIN:
raise exceptions.RefreshError(
"User credential refresh is only supported in the default "
"googleapis.com universe domain, but the current universe "
"domain is {}. If you created the credential with an access "
"token, it's likely that the provided token is expired now, "
"please update your code with a valid token.".format(
self._universe_domain
self.universe_domain
)
)

Expand Down Expand Up @@ -565,7 +563,7 @@ def to_json(self, strip=None):
"client_secret": self.client_secret,
"scopes": self.scopes,
"rapt_token": self.rapt_token,
"universe_domain": self._universe_domain,
"universe_domain": self.universe_domain,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

high

Using self.universe_domain here will serialize the default "googleapis.com" even if the universe domain was originally omitted (i.e., self._universe_domain is None). When this serialized JSON is later loaded back, the recreated credential will have an explicit "googleapis.com" universe domain, which will enable Regional Access Boundary (RAB) lookup. To preserve the omitted state across serialization and deserialization, serialize self._universe_domain instead.

Suggested change
"universe_domain": self.universe_domain,
"universe_domain": self._universe_domain,

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Kept self.universe_domain intentionally here for backwards compatibility. google-auth-oauthlib / gcloud auth application-default login builds oauth2.credentials.Credentials without passing universe_domain and saves ADC via to_json(), expecting "universe_domain": "googleapis.com" in the output. User OAuth2 credentials also only support refreshing in googleapis.com (_perform_refresh_token raises RefreshError for other universes), so keeping self.universe_domain here avoids breaking ADC serialization without opening a non-default refresh path.

"account": self._account,
}
if self.expiry: # flatten expiry timestamp
Expand Down
Loading
Loading