diff --git a/packages/google-auth/google/oauth2/_service_account_async.py b/packages/google-auth/google/oauth2/_service_account_async.py index 50ba8e82530c..f2133bfe248d 100644 --- a/packages/google-auth/google/oauth2/_service_account_async.py +++ b/packages/google-auth/google/oauth2/_service_account_async.py @@ -77,6 +77,12 @@ def __setstate__(self, state): @_helpers.copy_docstring(credentials_async.Credentials) async def refresh(self, request): + # Use the same self-signed JWT refresh path as sync credentials before + # falling back to the OAuth 2.0 assertion grant. This is synchronous + # because jwt.Credentials.refresh() only signs locally and performs no I/O. + if self._try_refresh_self_signed_jwt(request): + return + assertion = self._make_authorization_grant_assertion() access_token, expiry, _ = await _client_async.jwt_grant( request, self._token_uri, assertion diff --git a/packages/google-auth/google/oauth2/service_account.py b/packages/google-auth/google/oauth2/service_account.py index 6744e6f14d9b..33146704f4b0 100644 --- a/packages/google-auth/google/oauth2/service_account.py +++ b/packages/google-auth/google/oauth2/service_account.py @@ -196,7 +196,7 @@ def __init__( self._always_use_jwt_access = always_use_jwt_access self._universe_domain = universe_domain or credentials.DEFAULT_UNIVERSE_DOMAIN - 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 @@ -438,32 +438,51 @@ def _metric_header_for_usage(self): return metrics.CRED_TYPE_SA_JWT return metrics.CRED_TYPE_SA_ASSERTION - @_helpers.copy_docstring(credentials.CredentialsWithRegionalAccessBoundary) - def _perform_refresh_token(self, request): + def _try_refresh_self_signed_jwt(self, request): + """Refreshes self-signed JWT credentials if applicable. + + Returns: + bool: ``True`` if a self-signed JWT was refreshed and stored on + ``self.token`` and ``self.expiry``; ``False`` if the caller + should fall back to the OAuth 2.0 assertion grant. + + Raises: + google.auth.exceptions.RefreshError: If a non-default universe + domain cannot use a self-signed JWT. + """ if self._always_use_jwt_access and not self._jwt_credentials: # If self signed jwt should be used but jwt credential is not # created, try to create one with scopes self._create_self_signed_jwt(None) - if ( - self._universe_domain != credentials.DEFAULT_UNIVERSE_DOMAIN - and self._subject - ): - raise exceptions.RefreshError( - "domain wide delegation is not supported for non-default universe domain" - ) + if self._universe_domain != credentials.DEFAULT_UNIVERSE_DOMAIN: + if self._subject: + raise exceptions.RefreshError( + "domain wide delegation is not supported for non-default universe domain" + ) + if not self._use_self_signed_jwt(): + raise exceptions.RefreshError( + "self-signed JWT credentials could not be created for " + "non-default universe domain without scopes or audience" + ) if self._use_self_signed_jwt(): self._jwt_credentials.refresh(request) self.token = self._jwt_credentials.token.decode() self.expiry = self._jwt_credentials.expiry - else: - assertion = self._make_authorization_grant_assertion() - access_token, expiry, _ = _client.jwt_grant( - request, self._token_uri, assertion - ) - self.token = access_token - self.expiry = expiry + return True + + return False + + @_helpers.copy_docstring(credentials.CredentialsWithRegionalAccessBoundary) + def _perform_refresh_token(self, request): + if self._try_refresh_self_signed_jwt(request): + return + + assertion = self._make_authorization_grant_assertion() + access_token, expiry, _ = _client.jwt_grant(request, self._token_uri, assertion) + self.token = access_token + self.expiry = expiry def _create_self_signed_jwt(self, audience): """Create a self-signed JWT from the credentials if requirements are met. diff --git a/packages/google-auth/tests/oauth2/test_service_account.py b/packages/google-auth/tests/oauth2/test_service_account.py index 84074ec37b9a..df0a52be2abc 100644 --- a/packages/google-auth/tests/oauth2/test_service_account.py +++ b/packages/google-auth/tests/oauth2/test_service_account.py @@ -95,6 +95,7 @@ def test_constructor_no_universe_domain(self): SIGNER, self.SERVICE_ACCOUNT_EMAIL, self.TOKEN_URI, universe_domain=None ) assert credentials.universe_domain == DEFAULT_UNIVERSE_DOMAIN + assert not credentials._always_use_jwt_access def test_from_service_account_info(self): credentials = service_account.Credentials.from_service_account_info( @@ -677,6 +678,41 @@ def test_refresh_non_gdu_domain_wide_delegation_not_supported(self): credentials.refresh(None) assert excinfo.match("domain wide delegation is not supported") + def test_refresh_unscoped_non_default_universe_domain_requires_self_signed_jwt( + self, + ): + """Unscoped non-default universe refresh raises RefreshError without audience.""" + credentials = service_account.Credentials( + SIGNER, + self.SERVICE_ACCOUNT_EMAIL, + service_account._GOOGLE_OAUTH2_TOKEN_ENDPOINT, + scopes=None, + default_scopes=None, + universe_domain=FAKE_UNIVERSE_DOMAIN, + ) + request = mock.create_autospec(transport.Request, instance=True) + response = mock.create_autospec(transport.Response, instance=True) + response.status = 200 + response.data = json.dumps( + { + "access_token": "token", + "expires_in": 3600, + "token_type": "Bearer", + } + ).encode("utf-8") + request.return_value = response + + assert credentials._always_use_jwt_access + assert credentials._jwt_credentials is None + + with pytest.raises( + exceptions.RefreshError, + match="self-signed JWT credentials could not be created", + ): + credentials.refresh(request) + + request.assert_not_called() + class TestIDTokenCredentials(object): SERVICE_ACCOUNT_EMAIL = "service-account@example.com" diff --git a/packages/google-auth/tests_async/oauth2/test_service_account_async.py b/packages/google-auth/tests_async/oauth2/test_service_account_async.py index d3606c9641e0..8cdee62c9178 100644 --- a/packages/google-auth/tests_async/oauth2/test_service_account_async.py +++ b/packages/google-auth/tests_async/oauth2/test_service_account_async.py @@ -17,7 +17,7 @@ import pytest # type: ignore -from google.auth import _helpers, crypt, environment_vars, jwt, transport +from google.auth import _helpers, crypt, environment_vars, exceptions, jwt, transport from google.oauth2 import _service_account_async as service_account from tests.oauth2 import test_service_account @@ -231,6 +231,157 @@ async def test_before_request_refreshes(self, jwt_grant): # Credentials should now be valid. assert credentials.valid + @mock.patch("google.oauth2._client_async.jwt_grant", autospec=True) + @pytest.mark.asyncio + async def test_refresh_unscoped_non_default_universe_domain_requires_self_signed_jwt( + self, jwt_grant + ): + """Async unscoped non-default universe refresh raises RefreshError.""" + jwt_grant.return_value = ( + "token", + _helpers.utcnow() + datetime.timedelta(seconds=500), + {}, + ) + credentials = service_account.Credentials( + test_service_account.SIGNER, + self.SERVICE_ACCOUNT_EMAIL, + self.TOKEN_URI, + universe_domain="universe.foo", + ) + request = mock.create_autospec(transport.Request, instance=True) + + with pytest.raises( + exceptions.RefreshError, + match="self-signed JWT credentials could not be created", + ): + await credentials.refresh(request) + + jwt_grant.assert_not_called() + + @mock.patch("google.oauth2._client_async.jwt_grant", autospec=True) + @pytest.mark.asyncio + async def test_before_request_unscoped_non_default_universe_domain_without_hostname( + self, jwt_grant + ): + """Async unscoped non-default universe fails if URL has no hostname.""" + jwt_grant.return_value = ( + "token", + _helpers.utcnow() + datetime.timedelta(seconds=500), + {}, + ) + credentials = service_account.Credentials( + test_service_account.SIGNER, + self.SERVICE_ACCOUNT_EMAIL, + self.TOKEN_URI, + universe_domain="universe.foo", + ) + request = mock.create_autospec(transport.Request, instance=True) + + with pytest.raises( + exceptions.RefreshError, + match="self-signed JWT credentials could not be created", + ): + await credentials.before_request(request, "GET", "/storage/v1/b", {}) + + jwt_grant.assert_not_called() + + @mock.patch("google.oauth2._client_async.jwt_grant", autospec=True) + @pytest.mark.asyncio + async def test_refresh_non_gdu_domain_wide_delegation_not_supported( + self, jwt_grant + ): + """Async non-default universe rejects domain-wide delegation.""" + jwt_grant.return_value = ( + "token", + _helpers.utcnow() + datetime.timedelta(seconds=500), + {}, + ) + credentials = service_account.Credentials( + test_service_account.SIGNER, + self.SERVICE_ACCOUNT_EMAIL, + self.TOKEN_URI, + subject="user@example.com", + universe_domain="universe.foo", + ) + request = mock.create_autospec(transport.Request, instance=True) + + with pytest.raises( + exceptions.RefreshError, + match="domain wide delegation is not supported", + ): + await credentials.refresh(request) + + jwt_grant.assert_not_called() + + @mock.patch("google.oauth2._client_async.jwt_grant", autospec=True) + @pytest.mark.asyncio + async def test_before_request_scoped_non_default_universe_domain_uses_scopes( + self, jwt_grant + ): + """Async scoped non-default universe before_request uses scope-based JWT.""" + jwt_grant.return_value = ( + "token", + _helpers.utcnow() + datetime.timedelta(seconds=500), + {}, + ) + credentials = service_account.Credentials( + test_service_account.SIGNER, + self.SERVICE_ACCOUNT_EMAIL, + self.TOKEN_URI, + scopes=["https://www.googleapis.com/auth/cloud-platform"], + universe_domain="universe.foo", + ) + request = mock.create_autospec(transport.Request, instance=True) + headers = {} + + await credentials.before_request( + request, "GET", "https://storage.universe.foo/storage/v1/b", headers + ) + + jwt_grant.assert_not_called() + assert headers["authorization"].startswith("Bearer ") + payload = jwt.decode( + headers["authorization"].split(" ", 1)[1], + test_service_account.PUBLIC_CERT_BYTES, + ) + assert payload["scope"] == "https://www.googleapis.com/auth/cloud-platform" + assert "aud" not in payload + + @mock.patch("google.oauth2._client_async.jwt_grant", autospec=True) + @pytest.mark.asyncio + async def test_before_request_preserves_explicit_jwt_audience(self, jwt_grant): + """Async before_request uses explicit self-signed JWT audience without jwt_grant.""" + jwt_grant.return_value = ( + "token", + _helpers.utcnow() + datetime.timedelta(seconds=500), + {}, + ) + credentials = service_account.Credentials( + test_service_account.SIGNER, + self.SERVICE_ACCOUNT_EMAIL, + self.TOKEN_URI, + universe_domain="universe.foo", + ) + explicit_audience = "https://compute.universe.foo/" + credentials._create_self_signed_jwt(explicit_audience) + request = mock.create_autospec(transport.Request, instance=True) + headers = {} + + await credentials.before_request( + request, + "GET", + "https://us-central1-compute.universe.foo/v1/projects", + headers, + ) + + jwt_grant.assert_not_called() + assert headers["authorization"].startswith("Bearer ") + payload = jwt.decode( + headers["authorization"].split(" ", 1)[1], + test_service_account.PUBLIC_CERT_BYTES, + ) + assert payload["aud"] == explicit_audience + @pytest.mark.asyncio async def test_before_request_triggers_rab_refresh(self, monkeypatch): monkeypatch.setenv(