diff --git a/packages/google-auth/google/auth/compute_engine/credentials.py b/packages/google-auth/google/auth/compute_engine/credentials.py index f4882a96c36c..df115ed8dcf3 100644 --- a/packages/google-auth/google/auth/compute_engine/credentials.py +++ b/packages/google-auth/google/auth/compute_engine/credentials.py @@ -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 diff --git a/packages/google-auth/google/auth/downscoped.py b/packages/google-auth/google/auth/downscoped.py index 06a9ba5f771f..8f56c04e958b 100644 --- a/packages/google-auth/google/auth/downscoped.py +++ b/packages/google-auth/google/auth/downscoped.py @@ -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. @@ -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. @@ -458,8 +461,13 @@ 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 @@ -467,10 +475,24 @@ def __init__( """ 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) ) @@ -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, ) diff --git a/packages/google-auth/google/auth/external_account.py b/packages/google-auth/google/auth/external_account.py index 505f013a793e..8195656d369f 100644 --- a/packages/google-auth/google/auth/external_account.py +++ b/packages/google-auth/google/auth/external_account.py @@ -91,6 +91,7 @@ class Credentials( credentials.Scoped, credentials.CredentialsWithQuotaProject, credentials.CredentialsWithTokenUri, + credentials.CredentialsWithUniverseDomain, credentials.CredentialsWithRegionalAccessBoundary, metaclass=abc.ABCMeta, ): @@ -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 ) @@ -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): @@ -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.""" 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..be72f9d4c518 100644 --- a/packages/google-auth/google/auth/external_account_authorized_user.py +++ b/packages/google-auth/google/auth/external_account_authorized_user.py @@ -60,6 +60,7 @@ class Credentials( credentials.CredentialsWithQuotaProject, credentials.ReadOnlyScoped, credentials.CredentialsWithTokenUri, + credentials.CredentialsWithUniverseDomain, credentials.CredentialsWithRegionalAccessBoundary, ): """Credentials for External Account Authorized Users. @@ -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 @@ -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): diff --git a/packages/google-auth/tests/compute_engine/test_credentials.py b/packages/google-auth/tests/compute_engine/test_credentials.py index 8334d9b1dddc..e80818d0fa4d 100644 --- a/packages/google-auth/tests/compute_engine/test_credentials.py +++ b/packages/google-auth/tests/compute_engine/test_credentials.py @@ -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", diff --git a/packages/google-auth/tests/test_downscoped.py b/packages/google-auth/tests/test_downscoped.py index 0607f65b028a..04568ae61254 100644 --- a/packages/google-auth/tests/test_downscoped.py +++ b/packages/google-auth/tests/test_downscoped.py @@ -76,11 +76,17 @@ class SourceCredentials(credentials.Credentials): - def __init__(self, raise_error=False, expires_in=3600): + def __init__( + self, + raise_error=False, + expires_in=3600, + universe_domain=DEFAULT_UNIVERSE_DOMAIN, + ): super(SourceCredentials, self).__init__() self._counter = 0 self._raise_error = raise_error self._expires_in = expires_in + self._universe_domain = universe_domain def refresh(self, request): if self._raise_error: @@ -93,6 +99,26 @@ def refresh(self, request): self.expiry = now + datetime.timedelta(seconds=self._expires_in) +class UniverseSourceCredentials( + SourceCredentials, credentials.CredentialsWithUniverseDomain +): + def with_universe_domain(self, universe_domain): + return self.__class__( + raise_error=self._raise_error, + expires_in=self._expires_in, + universe_domain=universe_domain, + ) + + +class DuckTypedUniverseSourceCredentials(SourceCredentials): + def with_universe_domain(self, universe_domain): + return self.__class__( + raise_error=self._raise_error, + expires_in=self._expires_in, + universe_domain=universe_domain, + ) + + def make_availability_condition(expression, title=None, description=None): return downscoped.AvailabilityCondition(expression, title, description) @@ -516,26 +542,159 @@ def test_default_state_with_explicit_none_value(self): def test_create_with_customized_universe_domain(self): test_universe_domain = "foo.com" - credentials = self.make_credentials(universe_domain=test_universe_domain) + source_credentials = SourceCredentials(universe_domain=test_universe_domain) + creds = self.make_credentials( + source_credentials=source_credentials, universe_domain=test_universe_domain + ) + assert isinstance(creds, credentials.CredentialsWithUniverseDomain) # No token acquired yet. - assert not credentials.token - assert not credentials.valid + assert not creds.token + assert not creds.valid # Expiration hasn't been set yet. - assert not credentials.expiry - assert not credentials.expired + assert not creds.expiry + assert not creds.expired # No quota project ID set. - assert not credentials.quota_project_id - assert credentials.universe_domain == test_universe_domain + assert not creds.quota_project_id + assert creds.universe_domain == test_universe_domain + + def test_inherits_source_credentials_universe_domain(self): + test_universe_domain = "custom.example.com" + source_credentials = SourceCredentials(universe_domain=test_universe_domain) + availability_condition = make_availability_condition( + EXPRESSION, TITLE, DESCRIPTION + ) + cab = make_credential_access_boundary( + [ + make_access_boundary_rule( + AVAILABLE_RESOURCE, AVAILABLE_PERMISSIONS, availability_condition + ) + ] + ) + creds = downscoped.Credentials(source_credentials, cab) + + assert creds.universe_domain == test_universe_domain + assert creds._sts_client._token_exchange_endpoint == ( + downscoped._STS_TOKEN_URL_PATTERN.format(test_universe_domain) + ) + + request = self.make_mock_request( + status=http_client.OK, data=SUCCESS_RESPONSE.copy() + ) + creds.refresh(request) + assert request.call_args[1]["url"] == ( + downscoped._STS_TOKEN_URL_PATTERN.format(test_universe_domain) + ) + + def test_source_credentials_with_none_universe_domain_defaults_to_default_universe( + self, + ): + source_credentials = SourceCredentials(universe_domain=None) + creds = self.make_credentials(source_credentials=source_credentials) + assert creds.universe_domain == DEFAULT_UNIVERSE_DOMAIN + + def test_universe_domain_mismatch_raises(self): + source_credentials = SourceCredentials(universe_domain="example.com") + with pytest.raises( + exceptions.InvalidValue, + match="does not match the expected universe domain", + ): + self.make_credentials( + source_credentials=source_credentials, + universe_domain=DEFAULT_UNIVERSE_DOMAIN, + ) + + @pytest.mark.parametrize("bad_universe", ["", " ", "example.com/path"]) + def test_invalid_universe_domain_raises(self, bad_universe): + with pytest.raises( + exceptions.InvalidValue, + match="Universe domain must be a valid non-empty domain string.", + ): + self.make_credentials(universe_domain=bad_universe) def test_with_quota_project(self): - credentials = self.make_credentials() + creds = self.make_credentials() - assert not credentials.quota_project_id + assert not creds.quota_project_id - quota_project_creds = credentials.with_quota_project("project-foo") + quota_project_creds = creds.with_quota_project("project-foo") assert quota_project_creds.quota_project_id == "project-foo" + def test_with_quota_project_preserves_universe_domain(self): + test_universe_domain = "custom.example.com" + source_credentials = SourceCredentials(universe_domain=test_universe_domain) + creds = self.make_credentials(source_credentials=source_credentials) + + quota_project_creds = creds.with_quota_project("project-foo") + + assert quota_project_creds.quota_project_id == "project-foo" + assert quota_project_creds.universe_domain == test_universe_domain + assert quota_project_creds._sts_client._token_exchange_endpoint == ( + downscoped._STS_TOKEN_URL_PATTERN.format(test_universe_domain) + ) + + request = self.make_mock_request( + status=http_client.OK, data=SUCCESS_RESPONSE.copy() + ) + quota_project_creds.refresh(request) + assert request.call_args[1]["url"] == ( + downscoped._STS_TOKEN_URL_PATTERN.format(test_universe_domain) + ) + + @pytest.mark.parametrize( + "source_cls", + [UniverseSourceCredentials, DuckTypedUniverseSourceCredentials], + ) + def test_with_universe_domain_propagates_to_source_credentials(self, source_cls): + source_credentials = source_cls() + creds = self.make_credentials( + source_credentials=source_credentials, quota_project_id="project-foo" + ) + + custom = creds.with_universe_domain("example.com") + + assert custom.universe_domain == "example.com" + assert custom._source_credentials.universe_domain == "example.com" + assert custom.quota_project_id == "project-foo" + assert custom._sts_client._token_exchange_endpoint == ( + "https://sts.example.com/v1/token" + ) + + request = self.make_mock_request( + status=http_client.OK, data=SUCCESS_RESPONSE.copy() + ) + custom.refresh(request) + assert request.call_args[1]["url"] == "https://sts.example.com/v1/token" + + def test_explicit_universe_domain_preserves_caller_value(self): + source_credentials = SourceCredentials(universe_domain="example.com") + creds = self.make_credentials( + source_credentials=source_credentials, universe_domain="Example.Com" + ) + assert creds.universe_domain == "Example.Com" + + def test_with_universe_domain_non_cloneable_source_credentials(self): + source_credentials = SourceCredentials(universe_domain="example.com") + creds = self.make_credentials(source_credentials=source_credentials) + + # Matching universe succeeds. + same = creds.with_universe_domain("example.com") + assert same.universe_domain == "example.com" + + # Mismatched universe raises InvalidValue. + with pytest.raises( + exceptions.InvalidValue, + match="does not match the expected universe domain", + ): + creds.with_universe_domain("other.example.com") + + # Invalid universe raises InvalidValue. + with pytest.raises( + exceptions.InvalidValue, + match="Universe domain must be a valid non-empty domain string.", + ): + creds.with_universe_domain("") + @mock.patch("google.auth._helpers.utcnow", return_value=datetime.datetime.min) def test_refresh_on_custom_universe(self, unused_utcnow): test_universe_domain = "foo.com" @@ -554,8 +713,8 @@ def test_refresh_on_custom_universe(self, unused_utcnow): "options": urllib.parse.quote(json.dumps(CREDENTIAL_ACCESS_BOUNDARY_JSON)), } request = self.make_mock_request(status=http_client.OK, data=response) - source_credentials = SourceCredentials() - credentials = self.make_credentials( + source_credentials = SourceCredentials(universe_domain=test_universe_domain) + creds = self.make_credentials( source_credentials=source_credentials, universe_domain=test_universe_domain ) token_exchange_endpoint = downscoped._STS_TOKEN_URL_PATTERN.format( @@ -567,15 +726,15 @@ def test_refresh_on_custom_universe(self, unused_utcnow): with mock.patch.object( source_credentials, "refresh", wraps=source_credentials.refresh ) as wrapped_souce_cred_refresh: - credentials.refresh(request) + creds.refresh(request) self.assert_request_kwargs( request.call_args[1], headers, request_data, token_exchange_endpoint ) - assert credentials.valid - assert credentials.expiry == expected_expiry - assert not credentials.expired - assert credentials.token == response["access_token"] + assert creds.valid + assert creds.expiry == expected_expiry + assert not creds.expired + assert creds.token == response["access_token"] # Confirm source credentials called with the same request instance. wrapped_souce_cred_refresh.assert_called_with(request) diff --git a/packages/google-auth/tests/test_external_account.py b/packages/google-auth/tests/test_external_account.py index c0c494e12562..6b43b8d64eb7 100644 --- a/packages/google-auth/tests/test_external_account.py +++ b/packages/google-auth/tests/test_external_account.py @@ -27,7 +27,11 @@ external_account, transport, ) -from google.auth.credentials import DEFAULT_UNIVERSE_DOMAIN, TokenState +from google.auth.credentials import ( + DEFAULT_UNIVERSE_DOMAIN, + CredentialsWithUniverseDomain, + TokenState, +) IMPERSONATE_ACCESS_TOKEN_REQUEST_METRICS_HEADER_VALUE = "gl-python/ auth/ auth-request-type/at cred-type/imp" LANG_LIBRARY_METRICS_HEADER_VALUE = "gl-python/ auth/" @@ -429,6 +433,16 @@ def test_with_token_uri(self): creds_with_new_token_uri = credentials.with_token_uri(new_token_uri) assert creds_with_new_token_uri._token_url == new_token_uri + assert ( + creds_with_new_token_uri._sts_client._token_exchange_endpoint + == new_token_uri + ) + + request = self.make_mock_request( + status=http_client.OK, data=self.SUCCESS_RESPONSE.copy() + ) + creds_with_new_token_uri.refresh(request) + assert request.call_args[1]["url"] == new_token_uri def test_with_token_uri_workforce_pool(self): credentials = self.make_workforce_pool_credentials( @@ -527,27 +541,115 @@ def test_universe_domain(self): credentials = self.make_credentials() assert credentials.universe_domain == DEFAULT_UNIVERSE_DOMAIN + credentials = CredentialsImpl( + audience=self.AUDIENCE, + subject_token_type=self.SUBJECT_TOKEN_TYPE, + token_url=external_account._DEFAULT_TOKEN_URL, + credential_source=self.CREDENTIAL_SOURCE, + universe_domain=None, + ) + assert credentials.universe_domain == DEFAULT_UNIVERSE_DOMAIN + assert credentials._token_url == "https://sts.googleapis.com/v1/token" + assert ( + credentials._cloud_resource_manager_url + == "https://cloudresourcemanager.googleapis.com/v1/projects/" + ) + def test_with_universe_domain(self): credentials = self.make_credentials() + assert isinstance(credentials, CredentialsWithUniverseDomain) + new_credentials = credentials.with_universe_domain("dummy_universe.com") assert new_credentials.universe_domain == "dummy_universe.com" + assert ( + new_credentials._cloud_resource_manager_url + == "https://cloudresourcemanager.dummy_universe.com/v1/projects/" + ) + + def test_with_universe_domain_rebuilds_template_token_url_and_sts_client(self): + credentials = CredentialsImpl( + audience=self.AUDIENCE, + subject_token_type=self.SUBJECT_TOKEN_TYPE, + token_url=external_account._DEFAULT_TOKEN_URL, + credential_source=self.CREDENTIAL_SOURCE, + ) + assert credentials._token_url == "https://sts.googleapis.com/v1/token" + assert ( + credentials._sts_client._token_exchange_endpoint + == "https://sts.googleapis.com/v1/token" + ) + + # Cloning via with_scopes and with_quota_project preserves _raw_token_url. + scoped = credentials.with_scopes(self.SCOPES).with_quota_project("project-foo") + assert scoped.info["token_url"] == "https://sts.googleapis.com/v1/token" + + custom = scoped.with_universe_domain("example.com") + assert custom.universe_domain == "example.com" + assert custom._token_url == "https://sts.example.com/v1/token" + assert ( + custom._sts_client._token_exchange_endpoint + == "https://sts.example.com/v1/token" + ) + assert ( + custom._cloud_resource_manager_url + == "https://cloudresourcemanager.example.com/v1/projects/" + ) + assert custom.info["token_url"] == "https://sts.example.com/v1/token" + + request = self.make_mock_request( + status=http_client.OK, data=self.SUCCESS_RESPONSE.copy() + ) + custom.refresh(request) + assert request.call_args[1]["url"] == "https://sts.example.com/v1/token" + + # Chaining with_universe_domain again re-formats from _raw_token_url. + other = custom.with_universe_domain("other.example.com") + assert other._token_url == "https://sts.other.example.com/v1/token" + assert ( + other._sts_client._token_exchange_endpoint + == "https://sts.other.example.com/v1/token" + ) + assert ( + other._cloud_resource_manager_url + == "https://cloudresourcemanager.other.example.com/v1/projects/" + ) + + @pytest.mark.parametrize("bad_universe", [None, "", " ", "example.com/path"]) + def test_with_universe_domain_invalid(self, bad_universe): + credentials = self.make_credentials() + with pytest.raises( + exceptions.InvalidValue, + match="Universe domain must be a valid non-empty domain string.", + ): + credentials.with_universe_domain(bad_universe) def test_copy_regional_access_boundary_manager_state_and_config(self): credentials = self.make_credentials() credentials._rab_manager._data = mock.sentinel.rab_data credentials._rab_manager._use_blocking_regional_access_boundary_lookup = True - new_credentials = credentials.with_universe_domain("dummy_universe.com") + # Staying in the default universe preserves RAB state and blocking config. + for cloned in ( + credentials.with_quota_project("project-foo"), + credentials.with_scopes(self.SCOPES), + credentials.with_universe_domain(DEFAULT_UNIVERSE_DOMAIN), + ): + 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 credentials._rab_manager - # Verify references to boundary data are shared - assert new_credentials._rab_manager._data == mock.sentinel.rab_data - # Verify blocking config flag is preserved + # Switching to a non-default universe starts with empty RAB state. + non_default = credentials.with_universe_domain("dummy_universe.com") + assert non_default._rab_manager is not credentials._rab_manager + assert non_default._rab_manager._data.encoded_locations is None + assert non_default._rab_manager._data.expiry is None assert ( - new_credentials._rab_manager._use_blocking_regional_access_boundary_lookup - is True + non_default._rab_manager._use_blocking_regional_access_boundary_lookup + is False ) - # Verify target manager object is not replaced - assert new_credentials._rab_manager is not credentials._rab_manager def test_info_workforce_pool(self): credentials = self.make_workforce_pool_credentials( @@ -2382,16 +2484,36 @@ def test_get_project_id_skips_non_default_universe_endpoints( assert project_id is None request.assert_not_called() - @pytest.mark.parametrize( - "universe_domain", - [ - pytest.param("example.com", id="custom_universe"), - pytest.param(None, id="none_universe"), - pytest.param("", id="empty_universe"), - ], - ) - def test_get_project_id_skips_default_crm_url_after_with_universe_domain( - self, universe_domain + def test_get_project_id_uses_updated_crm_url_after_with_universe_domain(self): + request = self.make_mock_request( + status=http_client.OK, + data=self.SUCCESS_RESPONSE.copy(), + cloud_resource_manager_status=http_client.OK, + cloud_resource_manager_data=self.CLOUD_RESOURCE_MANAGER_SUCCESS_RESPONSE, + ) + credentials = CredentialsImpl.from_info( + { + "type": "external_account", + "audience": self.AUDIENCE, + "subject_token_type": self.SUBJECT_TOKEN_TYPE, + "token_url": "https://sts.example.com/v1/token", + "credential_source": self.CREDENTIAL_SOURCE, + }, + scopes=self.SCOPES, + ).with_universe_domain("example.com") + + project_id = credentials.get_project_id(request) + + assert project_id == self.PROJECT_ID + crm_request_kwargs = request.call_args_list[-1][1] + assert crm_request_kwargs[ + "url" + ] == "https://cloudresourcemanager.example.com/v1/projects/{}".format( + self.PROJECT_NUMBER + ) + + def test_get_project_id_skips_default_crm_url_for_non_default_token_url_after_with_universe_domain( + self, ): request = mock.create_autospec(transport.Request) credentials = CredentialsImpl.from_info( @@ -2403,7 +2525,7 @@ def test_get_project_id_skips_default_crm_url_after_with_universe_domain( "credential_source": self.CREDENTIAL_SOURCE, }, scopes=self.SCOPES, - ).with_universe_domain(universe_domain) + ).with_universe_domain(DEFAULT_UNIVERSE_DOMAIN) project_id = credentials.get_project_id(request) 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..69366fe67701 100644 --- a/packages/google-auth/tests/test_external_account_authorized_user.py +++ b/packages/google-auth/tests/test_external_account_authorized_user.py @@ -20,7 +20,10 @@ import pytest # type: ignore from google.auth import exceptions, external_account_authorized_user, transport -from google.auth.credentials import DEFAULT_UNIVERSE_DOMAIN +from google.auth.credentials import ( + DEFAULT_UNIVERSE_DOMAIN, + CredentialsWithUniverseDomain, +) TOKEN_URL = "https://sts.googleapis.com/v1/token" TOKEN_INFO_URL = "https://sts.googleapis.com/v1/introspect" @@ -527,6 +530,7 @@ def test_with_token_uri(self): assert new_creds._audience == creds._audience assert new_creds._refresh_token == creds.refresh_token assert new_creds._token_url == "https://google.com" + assert new_creds._sts_client._token_exchange_endpoint == "https://google.com" assert new_creds._token_info_url == creds._token_info_url assert new_creds._client_id == creds._client_id assert new_creds._client_secret == creds._client_secret @@ -535,6 +539,12 @@ def test_with_token_uri(self): assert new_creds._revoke_url == creds._revoke_url assert new_creds._quota_project_id == creds._quota_project_id + request = self.make_mock_request( + data={"access_token": "NEW_TOKEN", "expires_in": 3600} + ) + new_creds.refresh(request) + assert request.call_args[1]["url"] == "https://google.com" + def test_with_universe_domain(self): creds = self.make_credentials( token=ACCESS_TOKEN, @@ -542,6 +552,8 @@ def test_with_universe_domain(self): revoke_url=REVOKE_URL, quota_project_id=QUOTA_PROJECT_ID, ) + assert isinstance(creds, CredentialsWithUniverseDomain) + new_creds = creds.with_universe_domain(FAKE_UNIVERSE_DOMAIN) assert new_creds._audience == creds._audience assert new_creds._refresh_token == creds.refresh_token @@ -549,12 +561,104 @@ def test_with_universe_domain(self): assert new_creds._token_info_url == creds._token_info_url assert new_creds._client_id == creds._client_id assert new_creds._client_secret == creds._client_secret - assert new_creds.token == creds.token - assert new_creds.expiry == creds.expiry + assert new_creds.token is None + assert new_creds.expiry is None + assert not new_creds.valid assert new_creds._revoke_url == creds._revoke_url assert new_creds._quota_project_id == QUOTA_PROJECT_ID assert new_creds.universe_domain == FAKE_UNIVERSE_DOMAIN + # Staying in the same universe preserves cached token and expiry. + same_universe = creds.with_universe_domain(DEFAULT_UNIVERSE_DOMAIN) + assert same_universe.token == ACCESS_TOKEN + assert same_universe.expiry == NOW + + def test_with_universe_domain_token_only_raises(self): + future_expiry = datetime.datetime.now(datetime.timezone.utc).replace( + tzinfo=None + ) + datetime.timedelta(hours=1) + creds = external_account_authorized_user.Credentials( + token=ACCESS_TOKEN, + expiry=future_expiry, + ) + with pytest.raises(exceptions.InvalidOperation): + creds.with_universe_domain(FAKE_UNIVERSE_DOMAIN) + + def test_with_universe_domain_rebuilds_template_token_url_and_sts_client(self): + creds = self.make_credentials( + token_url="https://sts.{universe_domain}/v1/oauth/token", + ) + assert creds.token_url == "https://sts.googleapis.com/v1/oauth/token" + assert ( + creds._sts_client._token_exchange_endpoint + == "https://sts.googleapis.com/v1/oauth/token" + ) + + # with_quota_project preserves _raw_token_url for subsequent universe changes. + with_quota = creds.with_quota_project(QUOTA_PROJECT_ID) + assert ( + with_quota.info["token_url"] == "https://sts.googleapis.com/v1/oauth/token" + ) + + custom = with_quota.with_universe_domain("example.com") + assert custom.universe_domain == "example.com" + assert custom.token_url == "https://sts.example.com/v1/oauth/token" + assert ( + custom._sts_client._token_exchange_endpoint + == "https://sts.example.com/v1/oauth/token" + ) + + request = self.make_mock_request( + data={"access_token": "NEW_TOKEN", "expires_in": 3600} + ) + custom.refresh(request) + assert request.call_args[1]["url"] == "https://sts.example.com/v1/oauth/token" + + # Chained with_universe_domain re-formats from _raw_token_url. + other = custom.with_universe_domain("other.example.com") + assert other.token_url == "https://sts.other.example.com/v1/oauth/token" + assert ( + other._sts_client._token_exchange_endpoint + == "https://sts.other.example.com/v1/oauth/token" + ) + + @pytest.mark.parametrize("bad_universe", [None, "", " ", "example.com/path"]) + def test_with_universe_domain_invalid(self, bad_universe): + creds = self.make_credentials() + with pytest.raises( + exceptions.InvalidValue, + match="Universe domain must be a valid non-empty domain string.", + ): + creds.with_universe_domain(bad_universe) + + def test_with_universe_domain_resets_rab_state(self): + creds = self.make_credentials() + creds._rab_manager._data = mock.sentinel.rab_data + creds._rab_manager._use_blocking_regional_access_boundary_lookup = True + + # Staying in default universe preserves RAB state and blocking config. + for cloned in ( + creds.with_quota_project(QUOTA_PROJECT_ID), + creds.with_token_uri("https://sts.googleapis.com/v1/oauth/token"), + creds.with_universe_domain(DEFAULT_UNIVERSE_DOMAIN), + ): + 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 creds._rab_manager + + # Switching to a non-default universe starts with fresh RAB state. + non_default = creds.with_universe_domain(FAKE_UNIVERSE_DOMAIN) + assert non_default._rab_manager is not 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 + ) + def test_from_file_required_options_only(self, tmpdir): from_creds = self.make_credentials() config_file = tmpdir.join("config.json")