From fb9b5f7c072cbd95b94647282755a2f6953a8eaa Mon Sep 17 00:00:00 2001 From: ohmayr Date: Wed, 25 Nov 2026 12:31:58 +0000 Subject: [PATCH 1/2] fix(auth): require explicit googleapis.com for RAB lookups When universe_domain is omitted in a credential config, constructor call, or Compute Engine metadata response (404 or empty), google-auth previously filled in "googleapis.com" in _universe_domain. That made an omitted universe look identical to an explicitly configured default universe, so Regional Access Boundary (RAB) lookups could send tokens for other universes to iamcredentials.googleapis.com. Store None in _universe_domain when universe_domain is omitted while keeping the public universe_domain property returning "googleapis.com" for backwards compatibility. Only allow RAB lookups when _universe_domain is explicitly "googleapis.com" (after resolving lazy metadata on Compute Engine). b/588990592 --- .../google/auth/compute_engine/_metadata.py | 28 ++++- .../google/auth/compute_engine/credentials.py | 22 ++-- .../google-auth/google/auth/credentials.py | 27 +++- .../google-auth/google/auth/downscoped.py | 4 +- .../google/auth/external_account.py | 13 +- .../auth/external_account_authorized_user.py | 13 +- .../google/auth/impersonated_credentials.py | 4 +- packages/google-auth/google/auth/jwt.py | 32 ++--- .../google-auth/google/oauth2/credentials.py | 14 +-- .../google/oauth2/service_account.py | 31 ++--- .../tests/compute_engine/test__metadata.py | 11 ++ .../tests/compute_engine/test_credentials.py | 61 +++++++-- .../tests/oauth2/test_credentials.py | 10 +- .../tests/oauth2/test_service_account.py | 49 +++++++- .../test__regional_access_boundary_utils.py | 4 +- packages/google-auth/tests/test_aws.py | 8 +- .../google-auth/tests/test_credentials.py | 34 +++++ .../tests/test_external_account.py | 37 ++++++ .../test_external_account_authorized_user.py | 38 +++++- .../google-auth/tests/test_identity_pool.py | 14 +-- .../tests/test_impersonated_credentials.py | 116 +++++++++++++++++- packages/google-auth/tests/test_jwt.py | 63 +++++++++- packages/google-auth/tests/test_pluggable.py | 8 +- .../google-auth/tests_async/test_jwt_async.py | 7 +- 24 files changed, 526 insertions(+), 122 deletions(-) diff --git a/packages/google-auth/google/auth/compute_engine/_metadata.py b/packages/google-auth/google/auth/compute_engine/_metadata.py index 7404cf2896e1..85d8f44b24be 100644 --- a/packages/google-auth/google/auth/compute_engine/_metadata.py +++ b/packages/google-auth/google/auth/compute_engine/_metadata.py @@ -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. @@ -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"): diff --git a/packages/google-auth/google/auth/compute_engine/credentials.py b/packages/google-auth/google/auth/compute_engine/credentials.py index f4882a96c36c..161f600030b5 100644 --- a/packages/google-auth/google/auth/compute_engine/credentials.py +++ b/packages/google-auth/google/auth/compute_engine/credentials.py @@ -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): diff --git a/packages/google-auth/google/auth/credentials.py b/packages/google-auth/google/auth/credentials.py index 607d56654b45..40d62aee7fbf 100644 --- a/packages/google-auth/google/auth/credentials.py +++ b/packages/google-auth/google/auth/credentials.py @@ -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. + 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) + 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] = [] @@ -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 @@ -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. @@ -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: + return False return True diff --git a/packages/google-auth/google/auth/downscoped.py b/packages/google-auth/google/auth/downscoped.py index 06a9ba5f771f..5d52badbd037 100644 --- a/packages/google-auth/google/auth/downscoped.py +++ b/packages/google-auth/google/auth/downscoped.py @@ -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. @@ -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) ) diff --git a/packages/google-auth/google/auth/external_account.py b/packages/google-auth/google/auth/external_account.py index 8832abbce29b..10cb8256be05 100644 --- a/packages/google-auth/google/auth/external_account.py +++ b/packages/google-auth/google/auth/external_account.py @@ -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. @@ -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 @@ -240,6 +240,7 @@ def info(self): service_account_impersonation=config_info.pop( "service_account_impersonation_options", None ), + universe_domain=self.universe_domain, ) config_info.pop("scopes", None) config_info.pop("default_scopes", None) @@ -746,9 +747,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, ) diff --git a/packages/google-auth/google/auth/external_account_authorized_user.py b/packages/google-auth/google/auth/external_account_authorized_user.py index 0b387053baa9..f965272a912a 100644 --- a/packages/google-auth/google/auth/external_account_authorized_user.py +++ b/packages/google-auth/google/auth/external_account_authorized_user.py @@ -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. @@ -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 @@ -170,7 +170,10 @@ def info(self): later. """ config_info = self.constructor_args() - config_info.update(type=_EXTERNAL_ACCOUNT_AUTHORIZED_USER_JSON_TYPE) + config_info.update( + type=_EXTERNAL_ACCOUNT_AUTHORIZED_USER_JSON_TYPE, + universe_domain=self.universe_domain, + ) if config_info["expiry"]: config_info["expiry"] = config_info["expiry"].isoformat() + "Z" @@ -439,9 +442,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, ) diff --git a/packages/google-auth/google/auth/impersonated_credentials.py b/packages/google-auth/google/auth/impersonated_credentials.py index f9faab5e7336..8e06b005ece8 100644 --- a/packages/google-auth/google/auth/impersonated_credentials.py +++ b/packages/google-auth/google/auth/impersonated_credentials.py @@ -263,7 +263,9 @@ def __init__( ): self._source_credentials._create_self_signed_jwt(None) - self._universe_domain = source_credentials.universe_domain + self._universe_domain = credentials._get_explicit_universe_domain( + source_credentials + ) self._target_principal = target_principal self._target_scopes = target_scopes self._delegates = delegates diff --git a/packages/google-auth/google/auth/jwt.py b/packages/google-auth/google/auth/jwt.py index 827d893bd14f..7d3619c0a6a1 100644 --- a/packages/google-auth/google/auth/jwt.py +++ b/packages/google-auth/google/auth/jwt.py @@ -405,7 +405,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: @@ -430,9 +430,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 = {} @@ -458,9 +456,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 @@ -529,10 +525,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) @@ -727,7 +721,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: @@ -752,9 +746,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 = {} @@ -781,9 +773,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 @@ -848,10 +838,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) diff --git a/packages/google-auth/google/oauth2/credentials.py b/packages/google-auth/google/oauth2/credentials.py index cff8647d3bd9..d13ce0d85ffe 100644 --- a/packages/google-auth/google/oauth2/credentials.py +++ b/packages/google-auth/google/oauth2/credentials.py @@ -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, ): """ @@ -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 @@ -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 @@ -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 ) ) @@ -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, "account": self._account, } if self.expiry: # flatten expiry timestamp diff --git a/packages/google-auth/google/oauth2/service_account.py b/packages/google-auth/google/oauth2/service_account.py index 6744e6f14d9b..d4caa2086ca6 100644 --- a/packages/google-auth/google/oauth2/service_account.py +++ b/packages/google-auth/google/oauth2/service_account.py @@ -150,7 +150,7 @@ def __init__( quota_project_id=None, additional_claims=None, always_use_jwt_access=False, - universe_domain=credentials.DEFAULT_UNIVERSE_DOMAIN, + universe_domain=None, trust_boundary=None, ): """ @@ -194,9 +194,9 @@ def __init__( self._quota_project_id = quota_project_id self._token_uri = token_uri self._always_use_jwt_access = always_use_jwt_access - self._universe_domain = universe_domain or credentials.DEFAULT_UNIVERSE_DOMAIN + self._universe_domain = universe_domain or None - if universe_domain != credentials.DEFAULT_UNIVERSE_DOMAIN: + if self.universe_domain != credentials.DEFAULT_UNIVERSE_DOMAIN: self._always_use_jwt_access = True self._jwt_credentials = None @@ -229,9 +229,7 @@ def _from_signer_and_info(cls, signer, info, **kwargs): service_account_email=info["client_email"], token_uri=info["token_uri"], project_id=info.get("project_id"), - universe_domain=info.get( - "universe_domain", credentials.DEFAULT_UNIVERSE_DOMAIN - ), + universe_domain=info.get("universe_domain"), trust_boundary=info.get("trust_boundary"), **kwargs, ) @@ -334,7 +332,7 @@ def with_always_use_jwt_access(self, always_use_jwt_access): """ cred = self._make_copy() if ( - cred._universe_domain != credentials.DEFAULT_UNIVERSE_DOMAIN + cred.universe_domain != credentials.DEFAULT_UNIVERSE_DOMAIN and not always_use_jwt_access ): raise exceptions.InvalidValue( @@ -347,7 +345,7 @@ def with_always_use_jwt_access(self, always_use_jwt_access): def with_universe_domain(self, universe_domain): cred = self._make_copy() cred._universe_domain = universe_domain - if universe_domain != credentials.DEFAULT_UNIVERSE_DOMAIN: + if cred.universe_domain != credentials.DEFAULT_UNIVERSE_DOMAIN: cred._always_use_jwt_access = True return cred @@ -446,7 +444,7 @@ def _perform_refresh_token(self, request): self._create_self_signed_jwt(None) if ( - self._universe_domain != credentials.DEFAULT_UNIVERSE_DOMAIN + self.universe_domain != credentials.DEFAULT_UNIVERSE_DOMAIN and self._subject ): raise exceptions.RefreshError( @@ -613,7 +611,7 @@ def __init__( target_audience, additional_claims=None, quota_project_id=None, - universe_domain=credentials.DEFAULT_UNIVERSE_DOMAIN, + universe_domain=None, ): """ Args: @@ -645,15 +643,12 @@ def __init__( self._quota_project_id = quota_project_id self._use_iam_endpoint = False - if not universe_domain: - self._universe_domain = credentials.DEFAULT_UNIVERSE_DOMAIN - else: - self._universe_domain = universe_domain + self._universe_domain = universe_domain or None self._iam_id_token_endpoint = iam._IAM_IDTOKEN_ENDPOINT.replace( - "googleapis.com", self._universe_domain + "googleapis.com", self.universe_domain ) - if self._universe_domain != credentials.DEFAULT_UNIVERSE_DOMAIN: + if self.universe_domain != credentials.DEFAULT_UNIVERSE_DOMAIN: self._use_iam_endpoint = True if additional_claims is not None: @@ -770,7 +765,7 @@ def _with_use_iam_endpoint(self, use_iam_endpoint): """ cred = self._make_copy() if ( - cred._universe_domain != credentials.DEFAULT_UNIVERSE_DOMAIN + cred.universe_domain != credentials.DEFAULT_UNIVERSE_DOMAIN and not use_iam_endpoint ): raise exceptions.InvalidValue( @@ -854,7 +849,7 @@ def _refresh_with_iam_endpoint(self, request): self.signer_email, self._target_audience, jwt_credentials.token.decode(), - self._universe_domain, + self.universe_domain, ) @_helpers.copy_docstring(credentials.Credentials) diff --git a/packages/google-auth/tests/compute_engine/test__metadata.py b/packages/google-auth/tests/compute_engine/test__metadata.py index af8573a80c66..2dbcfe770f30 100644 --- a/packages/google-auth/tests/compute_engine/test__metadata.py +++ b/packages/google-auth/tests/compute_engine/test__metadata.py @@ -596,6 +596,17 @@ def test_get_universe_domain_not_found(): assert universe_domain == "googleapis.com" +def test_get_explicit_universe_domain(): + ok_request = make_request("googleapis.com", headers={"content-type": "text/plain"}) + assert _metadata._get_explicit_universe_domain(ok_request) == "googleapis.com" + + empty_request = make_request("", headers={"content-type": "text/plain"}) + assert _metadata._get_explicit_universe_domain(empty_request) is None + + not_found_request = make_request("not found", status=http_client.NOT_FOUND) + assert _metadata._get_explicit_universe_domain(not_found_request) is None + + @mock.patch("time.sleep", return_value=None) def test_get_universe_domain_retryable_error_failure(_mock_sleep): # Test that if the universe domain endpoint returns a retryable error diff --git a/packages/google-auth/tests/compute_engine/test_credentials.py b/packages/google-auth/tests/compute_engine/test_credentials.py index 8334d9b1dddc..00c77efe0698 100644 --- a/packages/google-auth/tests/compute_engine/test_credentials.py +++ b/packages/google-auth/tests/compute_engine/test_credentials.py @@ -90,8 +90,8 @@ def test_default_state(self): assert self.credentials.service_account_email == "default" # No quota project assert not self.credentials._quota_project_id - # Universe domain is the default and not cached - assert self.credentials._universe_domain == "googleapis.com" + # Universe domain is unset and not cached + assert self.credentials._universe_domain is None assert not self.credentials._universe_domain_cached @mock.patch( @@ -262,7 +262,7 @@ def test_with_universe_domain(self): assert creds._universe_domain_cached @mock.patch( - "google.auth.compute_engine._metadata.get_universe_domain", + "google.auth.compute_engine._metadata._get_explicit_universe_domain", return_value="googleapis.com", ) def test_token_usage_metrics(self, mock_get_universe_domain): @@ -275,13 +275,13 @@ def test_token_usage_metrics(self, mock_get_universe_domain): assert headers["x-goog-api-client"] == "cred-type/mds" @mock.patch( - "google.auth.compute_engine._metadata.get_universe_domain", + "google.auth.compute_engine._metadata._get_explicit_universe_domain", return_value="fake_universe_domain", ) def test_universe_domain(self, get_universe_domain): # Check the default state assert not self.credentials._universe_domain_cached - assert self.credentials._universe_domain == "googleapis.com" + assert self.credentials._universe_domain is None # calling the universe_domain property should trigger a call to # get_universe_domain to fetch the value. The value should be cached. @@ -295,7 +295,7 @@ def test_universe_domain(self, get_universe_domain): assert self.credentials.universe_domain == "fake_universe_domain" get_universe_domain.assert_called_once() - @mock.patch("google.auth.compute_engine._metadata.get_universe_domain") + @mock.patch("google.auth.compute_engine._metadata._get_explicit_universe_domain") def test_user_provided_universe_domain(self, get_universe_domain): assert self.credentials_with_all_fields.universe_domain == FAKE_UNIVERSE_DOMAIN assert self.credentials_with_all_fields._universe_domain_cached @@ -347,7 +347,8 @@ def test_build_regional_access_boundary_lookup_url_http_client_request( "google.auth.compute_engine._metadata.get_service_account_info", autospec=True ) @mock.patch( - "google.auth.compute_engine._metadata.get_universe_domain", autospec=True + "google.auth.compute_engine._metadata._get_explicit_universe_domain", + autospec=True, ) def test_build_regional_access_boundary_lookup_url_explicit_email_standard( self, mock_get_universe_domain, mock_get_service_account_info, monkeypatch @@ -372,7 +373,8 @@ def test_build_regional_access_boundary_lookup_url_explicit_email_standard( "google.auth.compute_engine._metadata.get_service_account_info", autospec=True ) @mock.patch( - "google.auth.compute_engine._metadata.get_universe_domain", autospec=True + "google.auth.compute_engine._metadata._get_explicit_universe_domain", + autospec=True, ) def test_build_regional_access_boundary_lookup_url_explicit_email_mtls( self, mock_get_universe_domain, mock_get_service_account_info, monkeypatch @@ -394,7 +396,8 @@ def test_build_regional_access_boundary_lookup_url_explicit_email_mtls( assert url == expected_url @mock.patch( - "google.auth.compute_engine._metadata.get_universe_domain", autospec=True + "google.auth.compute_engine._metadata._get_explicit_universe_domain", + autospec=True, ) @mock.patch( "google.auth.compute_engine._metadata.get_service_account_info", autospec=True @@ -431,6 +434,7 @@ def test_is_regional_access_boundary_lookup_required(self, monkeypatch): "true", ) creds = self.credentials + creds._universe_domain = "googleapis.com" creds._universe_domain_cached = True # Valid email formats should pass. @@ -448,6 +452,44 @@ def test_is_regional_access_boundary_lookup_required(self, monkeypatch): creds._service_account_email = "principal://iam.googleapis.com/projects/1234567890/locations/global/workloadIdentityPools/my-project.svc.id.goog/subject/ns/my-namespace/sa/my-kubernetes-sa" assert creds._is_regional_access_boundary_lookup_required() is False + @mock.patch( + "google.auth.compute_engine._metadata._get_explicit_universe_domain", + autospec=True, + ) + def test_rab_lookup_skipped_when_metadata_universe_domain_missing( + self, mock_get_universe_domain, monkeypatch + ): + monkeypatch.setenv( + environment_vars.GOOGLE_SDK_EXPERIMENTAL_PYTHON_REGIONAL_ACCESS_BOUNDARY_LOOKUP_ENABLED, + "true", + ) + mock_get_universe_domain.return_value = None + creds = credentials.Credentials() + + assert creds._is_regional_access_boundary_lookup_required() is False + assert creds.universe_domain == "googleapis.com" + assert ( + creds.with_scopes(["scope"])._is_regional_access_boundary_lookup_required() + is False + ) + + @mock.patch( + "google.auth.compute_engine._metadata._get_explicit_universe_domain", + autospec=True, + ) + def test_rab_lookup_allowed_when_metadata_confirms_default_universe( + self, mock_get_universe_domain, monkeypatch + ): + monkeypatch.setenv( + environment_vars.GOOGLE_SDK_EXPERIMENTAL_PYTHON_REGIONAL_ACCESS_BOUNDARY_LOOKUP_ENABLED, + "true", + ) + mock_get_universe_domain.return_value = "googleapis.com" + creds = credentials.Credentials() + + assert creds._is_regional_access_boundary_lookup_required() is True + mock_get_universe_domain.assert_called_once() + def test_build_regional_access_boundary_lookup_url_with_invalid_email(self): creds = self.credentials creds._universe_domain_cached = True @@ -472,6 +514,7 @@ def test_regional_access_boundary_disabled_state_transitions( "scopes": ["one", "two"], } creds = self.credentials + creds._universe_domain = "googleapis.com" creds._universe_domain_cached = True creds._service_account_email = "default" diff --git a/packages/google-auth/tests/oauth2/test_credentials.py b/packages/google-auth/tests/oauth2/test_credentials.py index fc36f911bad9..d3e5141ca96e 100644 --- a/packages/google-auth/tests/oauth2/test_credentials.py +++ b/packages/google-auth/tests/oauth2/test_credentials.py @@ -993,8 +993,16 @@ def test_pickle_and_unpickle_universe_domain(self): unpickled = pickle.loads(pickle.dumps(creds)) - # make sure the unpickled cred sets _universe_domain to default. + # make sure the unpickled cred returns default universe_domain without + # backfilling _universe_domain. assert unpickled.universe_domain == "googleapis.com" + assert unpickled._universe_domain is None + + def test_pickle_and_unpickle_custom_universe_domain(self): + custom_creds = self.make_credentials().with_universe_domain("example.com") + unpickled_custom = pickle.loads(pickle.dumps(custom_creds)) + assert unpickled_custom.universe_domain == "example.com" + assert unpickled_custom._universe_domain == "example.com" def test_pickle_and_unpickle_with_refresh_handler(self): expected_expiry = _helpers.utcnow() + datetime.timedelta(seconds=2800) diff --git a/packages/google-auth/tests/oauth2/test_service_account.py b/packages/google-auth/tests/oauth2/test_service_account.py index 84074ec37b9a..7cd4642016cd 100644 --- a/packages/google-auth/tests/oauth2/test_service_account.py +++ b/packages/google-auth/tests/oauth2/test_service_account.py @@ -19,7 +19,15 @@ import pytest # type: ignore -from google.auth import _helpers, crypt, exceptions, iam, jwt, transport +from google.auth import ( + _helpers, + crypt, + environment_vars, + exceptions, + iam, + jwt, + transport, +) from google.auth.credentials import DEFAULT_UNIVERSE_DOMAIN from google.oauth2 import service_account @@ -104,7 +112,8 @@ def test_from_service_account_info(self): assert credentials._signer.key_id == SERVICE_ACCOUNT_INFO["private_key_id"] assert credentials.service_account_email == SERVICE_ACCOUNT_INFO["client_email"] assert credentials._token_uri == SERVICE_ACCOUNT_INFO["token_uri"] - assert credentials._universe_domain == DEFAULT_UNIVERSE_DOMAIN + assert credentials.universe_domain == DEFAULT_UNIVERSE_DOMAIN + assert credentials._universe_domain is None assert not credentials._always_use_jwt_access def test_from_service_account_info_non_gdu(self): @@ -288,6 +297,39 @@ def test_build_regional_access_boundary_lookup_url_with_subject(self): credentials = self.make_credentials().with_subject("user@example.com") assert credentials._build_regional_access_boundary_lookup_url() is None + def test_rab_lookup_requires_explicit_default_universe_domain(self, monkeypatch): + monkeypatch.setenv( + environment_vars.GOOGLE_SDK_EXPERIMENTAL_PYTHON_REGIONAL_ACCESS_BOUNDARY_LOOKUP_ENABLED, + "true", + ) + info_without_universe = SERVICE_ACCOUNT_INFO.copy() + info_without_universe.pop("universe_domain", None) + omitted_creds = service_account.Credentials.from_service_account_info( + info_without_universe + ) + + assert omitted_creds.universe_domain == DEFAULT_UNIVERSE_DOMAIN + assert omitted_creds._is_regional_access_boundary_lookup_required() is False + assert ( + omitted_creds.with_scopes( + ["email"] + )._is_regional_access_boundary_lookup_required() + is False + ) + assert ( + omitted_creds.with_quota_project( + "p" + )._is_regional_access_boundary_lookup_required() + is False + ) + + info_with_universe = info_without_universe.copy() + info_with_universe["universe_domain"] = DEFAULT_UNIVERSE_DOMAIN + explicit_creds = service_account.Credentials.from_service_account_info( + info_with_universe + ) + assert explicit_creds._is_regional_access_boundary_lookup_required() is True + def test_with_token_uri(self): credentials = self.make_credentials() new_token_uri = "https://example2.com/oauth2/token" @@ -701,7 +743,8 @@ def test_constructor_no_universe_domain(self): self.TARGET_AUDIENCE, universe_domain=None, ) - assert credentials._universe_domain == DEFAULT_UNIVERSE_DOMAIN + assert credentials.universe_domain == DEFAULT_UNIVERSE_DOMAIN + assert credentials._universe_domain is None def test_from_service_account_info(self): credentials = service_account.IDTokenCredentials.from_service_account_info( diff --git a/packages/google-auth/tests/test__regional_access_boundary_utils.py b/packages/google-auth/tests/test__regional_access_boundary_utils.py index 534ca0fe11c8..e6309a9ce4c7 100644 --- a/packages/google-auth/tests/test__regional_access_boundary_utils.py +++ b/packages/google-auth/tests/test__regional_access_boundary_utils.py @@ -46,7 +46,7 @@ def rab_caplog(caplog): class CredentialsImpl(credentials.CredentialsWithRegionalAccessBoundary): - def __init__(self, universe_domain=None): + def __init__(self, universe_domain=credentials.DEFAULT_UNIVERSE_DOMAIN): super(CredentialsImpl, self).__init__() if universe_domain: self._universe_domain = universe_domain @@ -621,7 +621,7 @@ def test_regional_access_boundary_refresh_manager_start_refresh_safety_lock(self class AsyncCredentialsImpl(_credentials_async.CredentialsWithRegionalAccessBoundary): - def __init__(self, universe_domain=None): + def __init__(self, universe_domain=credentials.DEFAULT_UNIVERSE_DOMAIN): super().__init__() if universe_domain: self._universe_domain = universe_domain diff --git a/packages/google-auth/tests/test_aws.py b/packages/google-auth/tests/test_aws.py index 04c7b2db7280..996a128419b5 100644 --- a/packages/google-auth/tests/test_aws.py +++ b/packages/google-auth/tests/test_aws.py @@ -1001,7 +1001,7 @@ def test_from_info_full_options(self, mock_init): aws_security_credentials_supplier=None, quota_project_id=QUOTA_PROJECT_ID, workforce_pool_user_project=None, - universe_domain=DEFAULT_UNIVERSE_DOMAIN, + universe_domain=None, trust_boundary=None, ) @@ -1031,7 +1031,7 @@ def test_from_info_required_options_only(self, mock_init): aws_security_credentials_supplier=None, quota_project_id=None, workforce_pool_user_project=None, - universe_domain=DEFAULT_UNIVERSE_DOMAIN, + universe_domain=None, trust_boundary=None, ) @@ -1063,7 +1063,7 @@ def test_from_info_supplier(self, mock_init): aws_security_credentials_supplier=supplier, quota_project_id=None, workforce_pool_user_project=None, - universe_domain=DEFAULT_UNIVERSE_DOMAIN, + universe_domain=None, trust_boundary=None, ) @@ -1147,7 +1147,7 @@ def test_from_file_required_options_only(self, mock_init, tmpdir): aws_security_credentials_supplier=None, quota_project_id=None, workforce_pool_user_project=None, - universe_domain=DEFAULT_UNIVERSE_DOMAIN, + universe_domain=None, trust_boundary=None, ) diff --git a/packages/google-auth/tests/test_credentials.py b/packages/google-auth/tests/test_credentials.py index e9497e291527..d479086c8786 100644 --- a/packages/google-auth/tests/test_credentials.py +++ b/packages/google-auth/tests/test_credentials.py @@ -418,6 +418,7 @@ def test_before_request_triggers_rab_refresh(monkeypatch): lookup.return_value = {"encodedLocations": "0xA30"} creds = CredentialsImpl() + creds._universe_domain = credentials.DEFAULT_UNIVERSE_DOMAIN creds = creds._set_blocking_regional_access_boundary_lookup() request = mock.Mock() @@ -453,3 +454,36 @@ def test_maybe_start_regional_access_boundary_refresh_invalid_url(): credentials_instance._maybe_start_regional_access_boundary_refresh( request, url=object() ) + + +def test_rab_lookup_skipped_when_universe_domain_omitted(monkeypatch): + monkeypatch.setenv( + environment_vars.GOOGLE_SDK_EXPERIMENTAL_PYTHON_REGIONAL_ACCESS_BOUNDARY_LOOKUP_ENABLED, + "true", + ) + with mock.patch("google.oauth2._client._lookup_regional_access_boundary") as lookup: + creds = CredentialsImpl() + creds = creds._set_blocking_regional_access_boundary_lookup() + + assert creds.universe_domain == credentials.DEFAULT_UNIVERSE_DOMAIN + assert creds._is_regional_access_boundary_lookup_required() is False + + headers = {} + creds.before_request(mock.Mock(), "GET", "http://example.com", headers) + + lookup.assert_not_called() + assert "x-allowed-locations" not in headers + + +def test_rab_lookup_skipped_for_unpickled_credentials_without_universe_domain( + monkeypatch, +): + monkeypatch.setenv( + environment_vars.GOOGLE_SDK_EXPERIMENTAL_PYTHON_REGIONAL_ACCESS_BOUNDARY_LOOKUP_ENABLED, + "true", + ) + creds = CredentialsImpl.__new__(CredentialsImpl) + creds.__setstate__({}) + + assert creds.universe_domain == credentials.DEFAULT_UNIVERSE_DOMAIN + assert creds._is_regional_access_boundary_lookup_required() is False diff --git a/packages/google-auth/tests/test_external_account.py b/packages/google-auth/tests/test_external_account.py index 73993fd76e50..6b945fb7488b 100644 --- a/packages/google-auth/tests/test_external_account.py +++ b/packages/google-auth/tests/test_external_account.py @@ -2470,6 +2470,43 @@ def worker(): assert init_mock.call_count == 1 assert creds._impersonated_credentials == mock_impersonated + def test_rab_lookup_requires_explicit_default_universe_domain(self, monkeypatch): + monkeypatch.setenv( + environment_vars.GOOGLE_SDK_EXPERIMENTAL_PYTHON_REGIONAL_ACCESS_BOUNDARY_LOOKUP_ENABLED, + "true", + ) + info = { + "type": "external_account", + "audience": self.AUDIENCE, + "subject_token_type": self.SUBJECT_TOKEN_TYPE, + "token_url": self.TOKEN_URL, + "credential_source": self.CREDENTIAL_SOURCE, + "service_account_impersonation_url": self.SERVICE_ACCOUNT_IMPERSONATION_URL, + } + omitted_creds = CredentialsImpl.from_info(info, scopes=self.SCOPES) + + assert omitted_creds.universe_domain == DEFAULT_UNIVERSE_DOMAIN + assert omitted_creds._is_regional_access_boundary_lookup_required() is False + assert ( + omitted_creds.with_scopes( + self.SCOPES + )._is_regional_access_boundary_lookup_required() + is False + ) + assert ( + omitted_creds._initialize_impersonated_credentials()._is_regional_access_boundary_lookup_required() + is False + ) + + explicit_info = info.copy() + explicit_info["universe_domain"] = DEFAULT_UNIVERSE_DOMAIN + explicit_creds = CredentialsImpl.from_info(explicit_info, scopes=self.SCOPES) + assert explicit_creds._is_regional_access_boundary_lookup_required() is True + assert ( + explicit_creds._initialize_impersonated_credentials()._is_regional_access_boundary_lookup_required() + is True + ) + def test_supplier_context(): context = external_account.SupplierContext("TestTokenType", "TestAudience") diff --git a/packages/google-auth/tests/test_external_account_authorized_user.py b/packages/google-auth/tests/test_external_account_authorized_user.py index 774485bec443..c3a703ffa1b4 100644 --- a/packages/google-auth/tests/test_external_account_authorized_user.py +++ b/packages/google-auth/tests/test_external_account_authorized_user.py @@ -19,7 +19,12 @@ import pytest # type: ignore -from google.auth import exceptions, external_account_authorized_user, transport +from google.auth import ( + environment_vars, + exceptions, + external_account_authorized_user, + transport, +) from google.auth.credentials import DEFAULT_UNIVERSE_DOMAIN TOKEN_URL = "https://sts.googleapis.com/v1/token" @@ -629,3 +634,34 @@ def test_build_regional_access_boundary_lookup_url_mtls(self, monkeypatch): def test_build_regional_access_boundary_lookup_url_invalid_audience(self, audience): credentials = self.make_credentials(audience=audience) assert credentials._build_regional_access_boundary_lookup_url() is None + + def test_rab_lookup_requires_explicit_default_universe_domain(self, monkeypatch): + monkeypatch.setenv( + environment_vars.GOOGLE_SDK_EXPERIMENTAL_PYTHON_REGIONAL_ACCESS_BOUNDARY_LOOKUP_ENABLED, + "true", + ) + info = { + "audience": AUDIENCE, + "refresh_token": REFRESH_TOKEN, + "token_url": TOKEN_URL, + "token_info_url": TOKEN_INFO_URL, + "client_id": CLIENT_ID, + "client_secret": CLIENT_SECRET, + } + omitted_creds = external_account_authorized_user.Credentials.from_info(info) + + assert omitted_creds.universe_domain == DEFAULT_UNIVERSE_DOMAIN + assert omitted_creds._is_regional_access_boundary_lookup_required() is False + assert ( + omitted_creds.with_quota_project( + QUOTA_PROJECT_ID + )._is_regional_access_boundary_lookup_required() + is False + ) + + explicit_info = info.copy() + explicit_info["universe_domain"] = DEFAULT_UNIVERSE_DOMAIN + explicit_creds = external_account_authorized_user.Credentials.from_info( + explicit_info + ) + assert explicit_creds._is_regional_access_boundary_lookup_required() is True diff --git a/packages/google-auth/tests/test_identity_pool.py b/packages/google-auth/tests/test_identity_pool.py index a6b59ef4552a..dedf2596d816 100644 --- a/packages/google-auth/tests/test_identity_pool.py +++ b/packages/google-auth/tests/test_identity_pool.py @@ -507,7 +507,7 @@ def test_from_info_full_options(self, mock_init): subject_token_supplier=None, quota_project_id=QUOTA_PROJECT_ID, workforce_pool_user_project=None, - universe_domain=DEFAULT_UNIVERSE_DOMAIN, + universe_domain=None, trust_boundary=None, ) @@ -537,7 +537,7 @@ def test_from_info_required_options_only(self, mock_init): subject_token_supplier=None, quota_project_id=None, workforce_pool_user_project=None, - universe_domain=DEFAULT_UNIVERSE_DOMAIN, + universe_domain=None, trust_boundary=None, ) @@ -569,7 +569,7 @@ def test_from_info_supplier(self, mock_init): subject_token_supplier=supplier, quota_project_id=None, workforce_pool_user_project=None, - universe_domain=DEFAULT_UNIVERSE_DOMAIN, + universe_domain=None, trust_boundary=None, ) @@ -600,7 +600,7 @@ def test_from_info_workforce_pool(self, mock_init): subject_token_supplier=None, quota_project_id=None, workforce_pool_user_project=WORKFORCE_POOL_USER_PROJECT, - universe_domain=DEFAULT_UNIVERSE_DOMAIN, + universe_domain=None, trust_boundary=None, ) @@ -652,7 +652,7 @@ def test_from_file_full_options(self, mock_init, tmpdir): subject_token_supplier=None, quota_project_id=QUOTA_PROJECT_ID, workforce_pool_user_project=None, - universe_domain=DEFAULT_UNIVERSE_DOMAIN, + universe_domain=None, trust_boundary=None, ) @@ -683,7 +683,7 @@ def test_from_file_required_options_only(self, mock_init, tmpdir): subject_token_supplier=None, quota_project_id=None, workforce_pool_user_project=None, - universe_domain=DEFAULT_UNIVERSE_DOMAIN, + universe_domain=None, trust_boundary=None, ) @@ -715,7 +715,7 @@ def test_from_file_workforce_pool(self, mock_init, tmpdir): subject_token_supplier=None, quota_project_id=None, workforce_pool_user_project=WORKFORCE_POOL_USER_PROJECT, - universe_domain=DEFAULT_UNIVERSE_DOMAIN, + universe_domain=None, trust_boundary=None, ) diff --git a/packages/google-auth/tests/test_impersonated_credentials.py b/packages/google-auth/tests/test_impersonated_credentials.py index 2cfcbf150f86..bf7887ff5c32 100644 --- a/packages/google-auth/tests/test_impersonated_credentials.py +++ b/packages/google-auth/tests/test_impersonated_credentials.py @@ -21,7 +21,15 @@ import pytest # type: ignore -from google.auth import _helpers, crypt, exceptions, impersonated_credentials, transport +from google.auth import ( + _helpers, + crypt, + environment_vars, + exceptions, + impersonated_credentials, + transport, +) +from google.auth.credentials import DEFAULT_UNIVERSE_DOMAIN from google.auth.impersonated_credentials import Credentials from google.oauth2 import credentials, service_account @@ -1079,3 +1087,109 @@ def test_sign_jwt_request_invalid_response_error(self): == "Unable to acquire impersonated credentials: No signed JWT in response." ) assert excinfo.value.args[1] == "invalid_data" + + def test_rab_lookup_inherits_explicit_universe_domain_from_source( + self, monkeypatch + ): + monkeypatch.setenv( + environment_vars.GOOGLE_SDK_EXPERIMENTAL_PYTHON_REGIONAL_ACCESS_BOUNDARY_LOOKUP_ENABLED, + "true", + ) + with open(SERVICE_ACCOUNT_JSON_FILE, "r") as fh: + sa_info = json.load(fh) + sa_info.pop("universe_domain", None) + + omitted_source = service_account.Credentials.from_service_account_info(sa_info) + omitted_impersonated = Credentials( + source_credentials=omitted_source, + target_principal="target@example.iam.gserviceaccount.com", + target_scopes=["https://www.googleapis.com/auth/devstorage.read_only"], + ) + assert omitted_impersonated.universe_domain == DEFAULT_UNIVERSE_DOMAIN + assert ( + omitted_impersonated._is_regional_access_boundary_lookup_required() is False + ) + + explicit_source = omitted_source.with_universe_domain(DEFAULT_UNIVERSE_DOMAIN) + explicit_impersonated = Credentials( + source_credentials=explicit_source, + target_principal="target@example.iam.gserviceaccount.com", + target_scopes=["https://www.googleapis.com/auth/devstorage.read_only"], + ) + assert ( + explicit_impersonated._is_regional_access_boundary_lookup_required() is True + ) + + @mock.patch( + "google.auth.compute_engine._metadata._get_explicit_universe_domain", + autospec=True, + ) + def test_rab_lookup_resolves_lazy_compute_engine_source_universe_domain( + self, mock_get_universe_domain, monkeypatch + ): + from google.auth import compute_engine + + monkeypatch.setenv( + environment_vars.GOOGLE_SDK_EXPERIMENTAL_PYTHON_REGIONAL_ACCESS_BOUNDARY_LOOKUP_ENABLED, + "true", + ) + + mock_get_universe_domain.return_value = None + missing_impersonated = Credentials( + source_credentials=compute_engine.Credentials(), + target_principal="target@example.iam.gserviceaccount.com", + target_scopes=["https://www.googleapis.com/auth/devstorage.read_only"], + ) + assert missing_impersonated.universe_domain == DEFAULT_UNIVERSE_DOMAIN + assert ( + missing_impersonated._is_regional_access_boundary_lookup_required() is False + ) + + mock_get_universe_domain.return_value = DEFAULT_UNIVERSE_DOMAIN + confirmed_impersonated = Credentials( + source_credentials=compute_engine.Credentials(), + target_principal="target@example.iam.gserviceaccount.com", + target_scopes=["https://www.googleapis.com/auth/devstorage.read_only"], + ) + assert ( + confirmed_impersonated._is_regional_access_boundary_lookup_required() + is True + ) + + def test_rab_lookup_skips_omitted_non_rab_and_custom_sources(self, monkeypatch): + from google.auth import downscoped + + monkeypatch.setenv( + environment_vars.GOOGLE_SDK_EXPERIMENTAL_PYTHON_REGIONAL_ACCESS_BOUNDARY_LOOKUP_ENABLED, + "true", + ) + oauth_source = credentials.Credentials(token="access-token") + downscoped_source = downscoped.Credentials( + source_credentials=oauth_source, + credential_access_boundary=downscoped.CredentialAccessBoundary( + rules=[ + downscoped.AccessBoundaryRule( + available_resource="//storage.googleapis.com/projects/_/buckets/b", + available_permissions=["inRole:roles/storage.objectViewer"], + ) + ] + ), + ) + custom_default_source = mock.Mock(universe_domain=DEFAULT_UNIVERSE_DOMAIN) + custom_empty_source = mock.Mock(universe_domain="") + custom_other_source = mock.Mock(universe_domain="example.com") + + for source, expected_universe in [ + (oauth_source, DEFAULT_UNIVERSE_DOMAIN), + (downscoped_source, DEFAULT_UNIVERSE_DOMAIN), + (custom_default_source, DEFAULT_UNIVERSE_DOMAIN), + (custom_empty_source, DEFAULT_UNIVERSE_DOMAIN), + (custom_other_source, "example.com"), + ]: + impersonated = Credentials( + source_credentials=source, + target_principal="target@example.iam.gserviceaccount.com", + target_scopes=["https://www.googleapis.com/auth/devstorage.read_only"], + ) + assert impersonated.universe_domain == expected_universe + assert impersonated._is_regional_access_boundary_lookup_required() is False diff --git a/packages/google-auth/tests/test_jwt.py b/packages/google-auth/tests/test_jwt.py index 7347dab47818..7f917a4bbb14 100644 --- a/packages/google-auth/tests/test_jwt.py +++ b/packages/google-auth/tests/test_jwt.py @@ -960,7 +960,10 @@ def test_before_request_default_universe_performs_rab_lookup(self, monkeypatch): "true", ) monkeypatch.setattr(_mtls_helper, "check_use_client_cert", lambda: False) - self.credentials._set_blocking_regional_access_boundary_lookup() + creds = self.credentials.with_universe_domain( + auth_credentials.DEFAULT_UNIVERSE_DOMAIN + ) + creds._set_blocking_regional_access_boundary_lookup() response = mock.create_autospec(transport.Response, instance=True) response.status = http_client.OK @@ -972,7 +975,7 @@ def test_before_request_default_universe_performs_rab_lookup(self, monkeypatch): ) headers = {} - self.credentials.before_request( + creds.before_request( request, "GET", "https://pubsub.googleapis.com/v1/projects/p/topics", @@ -983,6 +986,62 @@ def test_before_request_default_universe_performs_rab_lookup(self, monkeypatch): assert headers["x-allowed-locations"] == "0xA30" request.assert_called_once() + def test_before_request_omitted_universe_skips_rab_lookup(self, monkeypatch): + monkeypatch.setenv( + environment_vars.GOOGLE_SDK_EXPERIMENTAL_PYTHON_REGIONAL_ACCESS_BOUNDARY_LOOKUP_ENABLED, + "true", + ) + self.credentials._set_blocking_regional_access_boundary_lookup() + request = mock.create_autospec(transport.Request, instance=True) + + headers = {} + self.credentials.before_request( + request, + "GET", + "https://pubsub.googleapis.com/v1/projects/p/topics", + headers, + ) + + assert "authorization" in headers + assert "x-allowed-locations" not in headers + request.assert_not_called() + assert ( + self.credentials.with_claims( + audience="https://other.googleapis.com/" + )._is_regional_access_boundary_lookup_required() + is False + ) + assert ( + self.credentials.with_quota_project( + "project-id" + )._is_regional_access_boundary_lookup_required() + is False + ) + + def test_from_signing_credentials_preserves_explicit_universe_for_rab( + self, monkeypatch + ): + monkeypatch.setenv( + environment_vars.GOOGLE_SDK_EXPERIMENTAL_PYTHON_REGIONAL_ACCESS_BOUNDARY_LOOKUP_ENABLED, + "true", + ) + info = SERVICE_ACCOUNT_INFO.copy() + info.pop("universe_domain", None) + omitted_sa = service_account.Credentials.from_service_account_info(info) + omitted_jwt = jwt.Credentials.from_signing_credentials( + omitted_sa, "https://pubsub.googleapis.com/" + ) + assert omitted_jwt.universe_domain == auth_credentials.DEFAULT_UNIVERSE_DOMAIN + assert omitted_jwt._is_regional_access_boundary_lookup_required() is False + + explicit_sa = omitted_sa.with_universe_domain( + auth_credentials.DEFAULT_UNIVERSE_DOMAIN + ) + explicit_jwt = jwt.Credentials.from_signing_credentials( + explicit_sa, "https://pubsub.googleapis.com/" + ) + assert explicit_jwt._is_regional_access_boundary_lookup_required() is True + def test_impersonated_credentials_with_non_default_jwt_source( self, signer, monkeypatch ): diff --git a/packages/google-auth/tests/test_pluggable.py b/packages/google-auth/tests/test_pluggable.py index f02b48dc71d2..a52959d55839 100644 --- a/packages/google-auth/tests/test_pluggable.py +++ b/packages/google-auth/tests/test_pluggable.py @@ -272,7 +272,7 @@ def test_from_info_full_options(self, mock_init): credential_source=self.CREDENTIAL_SOURCE, quota_project_id=QUOTA_PROJECT_ID, workforce_pool_user_project=None, - universe_domain=DEFAULT_UNIVERSE_DOMAIN, + universe_domain=None, trust_boundary=None, ) @@ -301,7 +301,7 @@ def test_from_info_required_options_only(self, mock_init): credential_source=self.CREDENTIAL_SOURCE, quota_project_id=None, workforce_pool_user_project=None, - universe_domain=DEFAULT_UNIVERSE_DOMAIN, + universe_domain=None, trust_boundary=None, ) @@ -337,7 +337,7 @@ def test_from_file_full_options(self, mock_init, tmpdir): credential_source=self.CREDENTIAL_SOURCE, quota_project_id=QUOTA_PROJECT_ID, workforce_pool_user_project=None, - universe_domain=DEFAULT_UNIVERSE_DOMAIN, + universe_domain=None, trust_boundary=None, ) @@ -367,7 +367,7 @@ def test_from_file_required_options_only(self, mock_init, tmpdir): credential_source=self.CREDENTIAL_SOURCE, quota_project_id=None, workforce_pool_user_project=None, - universe_domain=DEFAULT_UNIVERSE_DOMAIN, + universe_domain=None, trust_boundary=None, ) diff --git a/packages/google-auth/tests_async/test_jwt_async.py b/packages/google-auth/tests_async/test_jwt_async.py index 287d688c9443..50960e719e37 100644 --- a/packages/google-auth/tests_async/test_jwt_async.py +++ b/packages/google-auth/tests_async/test_jwt_async.py @@ -336,7 +336,10 @@ async def test_before_request_default_universe_performs_rab_lookup( "true", ) monkeypatch.setattr(_mtls_helper, "check_use_client_cert", lambda: False) - self.credentials._set_blocking_regional_access_boundary_lookup() + creds = self.credentials.with_universe_domain( + auth_credentials.DEFAULT_UNIVERSE_DOMAIN + ) + creds._set_blocking_regional_access_boundary_lookup() response = mock.AsyncMock(spec=aio_transport.Response) response.status_code = http_client.OK @@ -348,7 +351,7 @@ async def test_before_request_default_universe_performs_rab_lookup( request = mock.AsyncMock(spec=aio_transport.Request, return_value=response) headers = {} - await self.credentials.before_request( + await creds.before_request( request, "GET", "https://pubsub.googleapis.com/v1/projects/p/topics", From 44719c8364a7de46a3bdd5861c9d4d8c0742c043 Mon Sep 17 00:00:00 2001 From: ohmayr Date: Wed, 25 Nov 2026 12:50:27 +0000 Subject: [PATCH 2/2] fix(auth): preserve omitted universe_domain in external account info Stop writing self.universe_domain ("googleapis.com") into external_account.Credentials.info and external_account_authorized_user.Credentials.info when universe_domain was omitted. Otherwise, round-tripping through from_info(creds.info) would turn an omitted universe_domain into an explicit "googleapis.com" and enable Regional Access Boundary (RAB) lookups. Keep self.universe_domain in oauth2.credentials.Credentials.to_json() so existing authorized-user ADC serialization (which does not support refreshing outside googleapis.com) remains backwards-compatible. b/588990592 --- .../google/auth/external_account.py | 1 - .../auth/external_account_authorized_user.py | 5 +--- packages/google-auth/tests/test_aws.py | 2 -- .../tests/test_external_account.py | 15 +++++++++++- .../test_external_account_authorized_user.py | 24 +++++++++++++++++-- .../google-auth/tests/test_identity_pool.py | 7 ------ packages/google-auth/tests/test_pluggable.py | 2 -- 7 files changed, 37 insertions(+), 19 deletions(-) diff --git a/packages/google-auth/google/auth/external_account.py b/packages/google-auth/google/auth/external_account.py index 10cb8256be05..6923f83b01ad 100644 --- a/packages/google-auth/google/auth/external_account.py +++ b/packages/google-auth/google/auth/external_account.py @@ -240,7 +240,6 @@ def info(self): service_account_impersonation=config_info.pop( "service_account_impersonation_options", None ), - universe_domain=self.universe_domain, ) config_info.pop("scopes", None) config_info.pop("default_scopes", None) diff --git a/packages/google-auth/google/auth/external_account_authorized_user.py b/packages/google-auth/google/auth/external_account_authorized_user.py index f965272a912a..bddfbd4d4577 100644 --- a/packages/google-auth/google/auth/external_account_authorized_user.py +++ b/packages/google-auth/google/auth/external_account_authorized_user.py @@ -170,10 +170,7 @@ def info(self): later. """ config_info = self.constructor_args() - config_info.update( - type=_EXTERNAL_ACCOUNT_AUTHORIZED_USER_JSON_TYPE, - universe_domain=self.universe_domain, - ) + config_info.update(type=_EXTERNAL_ACCOUNT_AUTHORIZED_USER_JSON_TYPE) if config_info["expiry"]: config_info["expiry"] = config_info["expiry"].isoformat() + "Z" diff --git a/packages/google-auth/tests/test_aws.py b/packages/google-auth/tests/test_aws.py index 996a128419b5..8f6cfe89cc35 100644 --- a/packages/google-auth/tests/test_aws.py +++ b/packages/google-auth/tests/test_aws.py @@ -1223,7 +1223,6 @@ def test_info(self): "token_url": TOKEN_URL, "token_info_url": TOKEN_INFO_URL, "credential_source": self.CREDENTIAL_SOURCE, - "universe_domain": DEFAULT_UNIVERSE_DOMAIN, } def test_token_info_url(self): @@ -1284,7 +1283,6 @@ def test_info_with_default_token_url(self): "subject_token_type": SUBJECT_TOKEN_TYPE, "token_url": TOKEN_URL, "credential_source": self.CREDENTIAL_SOURCE.copy(), - "universe_domain": DEFAULT_UNIVERSE_DOMAIN, } def test_info_with_default_token_url_with_universe_domain(self): diff --git a/packages/google-auth/tests/test_external_account.py b/packages/google-auth/tests/test_external_account.py index 6b945fb7488b..20ae52c97cd5 100644 --- a/packages/google-auth/tests/test_external_account.py +++ b/packages/google-auth/tests/test_external_account.py @@ -561,7 +561,6 @@ def test_info_workforce_pool(self): "token_url": self.TOKEN_URL, "credential_source": self.CREDENTIAL_SOURCE.copy(), "workforce_pool_user_project": self.WORKFORCE_POOL_USER_PROJECT, - "universe_domain": DEFAULT_UNIVERSE_DOMAIN, } def test_info_with_full_options(self): @@ -2487,6 +2486,13 @@ def test_rab_lookup_requires_explicit_default_universe_domain(self, monkeypatch) assert omitted_creds.universe_domain == DEFAULT_UNIVERSE_DOMAIN assert omitted_creds._is_regional_access_boundary_lookup_required() is False + assert "universe_domain" not in omitted_creds.info + assert ( + CredentialsImpl.from_info( + omitted_creds.info, scopes=self.SCOPES + )._is_regional_access_boundary_lookup_required() + is False + ) assert ( omitted_creds.with_scopes( self.SCOPES @@ -2502,6 +2508,13 @@ def test_rab_lookup_requires_explicit_default_universe_domain(self, monkeypatch) explicit_info["universe_domain"] = DEFAULT_UNIVERSE_DOMAIN explicit_creds = CredentialsImpl.from_info(explicit_info, scopes=self.SCOPES) assert explicit_creds._is_regional_access_boundary_lookup_required() is True + assert explicit_creds.info["universe_domain"] == DEFAULT_UNIVERSE_DOMAIN + assert ( + CredentialsImpl.from_info( + explicit_creds.info, scopes=self.SCOPES + )._is_regional_access_boundary_lookup_required() + is True + ) assert ( explicit_creds._initialize_impersonated_credentials()._is_regional_access_boundary_lookup_required() is True diff --git a/packages/google-auth/tests/test_external_account_authorized_user.py b/packages/google-auth/tests/test_external_account_authorized_user.py index c3a703ffa1b4..fdd6814e9939 100644 --- a/packages/google-auth/tests/test_external_account_authorized_user.py +++ b/packages/google-auth/tests/test_external_account_authorized_user.py @@ -406,7 +406,7 @@ def test_info(self): assert info["token_info_url"] == TOKEN_INFO_URL assert info["client_id"] == CLIENT_ID assert info["client_secret"] == CLIENT_SECRET - assert info["universe_domain"] == DEFAULT_UNIVERSE_DOMAIN + assert "universe_domain" not in info assert "token" not in info assert "expiry" not in info assert "revoke_url" not in info @@ -445,7 +445,7 @@ def test_to_json(self): assert info["token_info_url"] == TOKEN_INFO_URL assert info["client_id"] == CLIENT_ID assert info["client_secret"] == CLIENT_SECRET - assert info["universe_domain"] == DEFAULT_UNIVERSE_DOMAIN + assert "universe_domain" not in info assert "token" not in info assert "expiry" not in info assert "revoke_url" not in info @@ -652,6 +652,19 @@ def test_rab_lookup_requires_explicit_default_universe_domain(self, monkeypatch) assert omitted_creds.universe_domain == DEFAULT_UNIVERSE_DOMAIN assert omitted_creds._is_regional_access_boundary_lookup_required() is False + assert "universe_domain" not in omitted_creds.info + assert ( + external_account_authorized_user.Credentials.from_info( + omitted_creds.info + )._is_regional_access_boundary_lookup_required() + is False + ) + assert ( + external_account_authorized_user.Credentials.from_info( + json.loads(omitted_creds.to_json()) + )._is_regional_access_boundary_lookup_required() + is False + ) assert ( omitted_creds.with_quota_project( QUOTA_PROJECT_ID @@ -665,3 +678,10 @@ def test_rab_lookup_requires_explicit_default_universe_domain(self, monkeypatch) explicit_info ) assert explicit_creds._is_regional_access_boundary_lookup_required() is True + assert explicit_creds.info["universe_domain"] == DEFAULT_UNIVERSE_DOMAIN + assert ( + external_account_authorized_user.Credentials.from_info( + explicit_creds.info + )._is_regional_access_boundary_lookup_required() + is True + ) diff --git a/packages/google-auth/tests/test_identity_pool.py b/packages/google-auth/tests/test_identity_pool.py index dedf2596d816..0732cbed179e 100644 --- a/packages/google-auth/tests/test_identity_pool.py +++ b/packages/google-auth/tests/test_identity_pool.py @@ -32,7 +32,6 @@ metrics, transport, ) -from google.auth.credentials import DEFAULT_UNIVERSE_DOMAIN CLIENT_ID = "username" CLIENT_SECRET = "password" @@ -877,7 +876,6 @@ def test_info_with_workforce_pool_user_project(self): "token_info_url": TOKEN_INFO_URL, "credential_source": self.CREDENTIAL_SOURCE_TEXT_URL, "workforce_pool_user_project": WORKFORCE_POOL_USER_PROJECT, - "universe_domain": DEFAULT_UNIVERSE_DOMAIN, } def test_info_with_file_credential_source(self): @@ -892,7 +890,6 @@ def test_info_with_file_credential_source(self): "token_url": TOKEN_URL, "token_info_url": TOKEN_INFO_URL, "credential_source": self.CREDENTIAL_SOURCE_TEXT_URL, - "universe_domain": DEFAULT_UNIVERSE_DOMAIN, } def test_info_with_url_credential_source(self): @@ -907,7 +904,6 @@ def test_info_with_url_credential_source(self): "token_url": TOKEN_URL, "token_info_url": TOKEN_INFO_URL, "credential_source": self.CREDENTIAL_SOURCE_JSON_URL, - "universe_domain": DEFAULT_UNIVERSE_DOMAIN, } def test_info_with_certificate_credential_source(self): @@ -922,7 +918,6 @@ def test_info_with_certificate_credential_source(self): "token_url": TOKEN_URL, "token_info_url": TOKEN_INFO_URL, "credential_source": self.CREDENTIAL_SOURCE_CERTIFICATE, - "universe_domain": DEFAULT_UNIVERSE_DOMAIN, } def test_info_with_non_default_certificate_credential_source(self): @@ -937,7 +932,6 @@ def test_info_with_non_default_certificate_credential_source(self): "token_url": TOKEN_URL, "token_info_url": TOKEN_INFO_URL, "credential_source": self.CREDENTIAL_SOURCE_CERTIFICATE_NOT_DEFAULT, - "universe_domain": DEFAULT_UNIVERSE_DOMAIN, } def test_info_with_default_token_url(self): @@ -953,7 +947,6 @@ def test_info_with_default_token_url(self): "subject_token_type": SUBJECT_TOKEN_TYPE, "token_url": TOKEN_URL, "credential_source": self.CREDENTIAL_SOURCE_TEXT_URL, - "universe_domain": DEFAULT_UNIVERSE_DOMAIN, } def test_info_with_default_token_url_with_universe_domain(self): diff --git a/packages/google-auth/tests/test_pluggable.py b/packages/google-auth/tests/test_pluggable.py index a52959d55839..2fb3f8a62965 100644 --- a/packages/google-auth/tests/test_pluggable.py +++ b/packages/google-auth/tests/test_pluggable.py @@ -20,7 +20,6 @@ import pytest # type: ignore from google.auth import exceptions, pluggable -from google.auth.credentials import DEFAULT_UNIVERSE_DOMAIN from tests.test__default import WORKFORCE_AUDIENCE CLIENT_ID = "username" @@ -397,7 +396,6 @@ def test_info_with_credential_source(self): "token_url": TOKEN_URL, "token_info_url": TOKEN_INFO_URL, "credential_source": self.CREDENTIAL_SOURCE, - "universe_domain": DEFAULT_UNIVERSE_DOMAIN, } def test_token_info_url(self):