From 9d5581a0bff89cd429b2d4a7522604408b59599f Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Fri, 27 Nov 2026 16:15:09 +0000 Subject: [PATCH 1/5] fix(oauth2): verify universe domain for UserAccessTokenCredentials --- .../google-auth/google/auth/_cloud_sdk.py | 34 ++++++++++++++ .../google-auth/google/oauth2/credentials.py | 22 ++++++++++ .../tests/oauth2/test_credentials.py | 44 +++++++++++++++++++ packages/google-auth/tests/test__cloud_sdk.py | 39 ++++++++++++++++ 4 files changed, 139 insertions(+) diff --git a/packages/google-auth/google/auth/_cloud_sdk.py b/packages/google-auth/google/auth/_cloud_sdk.py index 05f0e9e72515..bb55a7ab210b 100644 --- a/packages/google-auth/google/auth/_cloud_sdk.py +++ b/packages/google-auth/google/auth/_cloud_sdk.py @@ -31,6 +31,12 @@ _CLOUD_SDK_WINDOWS_COMMAND = "gcloud.cmd" # The command to get the Cloud SDK configuration _CLOUD_SDK_CONFIG_GET_PROJECT_COMMAND = ("config", "get", "project") +# The command to get the active Cloud SDK universe domain +_CLOUD_SDK_CONFIG_GET_UNIVERSE_DOMAIN_COMMAND = ( + "config", + "get", + "core/universe_domain", +) # The command to get google user access token _CLOUD_SDK_USER_ACCESS_TOKEN_COMMAND = ("auth", "print-access-token") # Cloud SDK's application-default client ID @@ -148,3 +154,31 @@ def get_auth_access_token(account=None): "Failed to obtain access token", caught_exc ) raise new_exc from caught_exc + + +def get_universe_domain(): + """Gets the universe domain from the environment or Cloud SDK configuration. + + Returns: + Optional[str]: The universe domain if set, otherwise None. + """ + # Check standard environment variable first + env_universe = os.environ.get("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + if env_universe and env_universe.strip(): + return env_universe.strip() + + # Fall back to active gcloud CLI configuration + if os.name == "nt": + command = _CLOUD_SDK_WINDOWS_COMMAND + else: + command = _CLOUD_SDK_POSIX_COMMAND + + try: + # Safely run the command ignoring stderr to keep results clean + universe_domain = _run_subprocess_ignore_stderr( + (command,) + _CLOUD_SDK_CONFIG_GET_UNIVERSE_DOMAIN_COMMAND + ) + universe_domain = _helpers.from_bytes(universe_domain).strip() + return universe_domain if universe_domain else None + except (subprocess.CalledProcessError, OSError, IOError): + return None diff --git a/packages/google-auth/google/oauth2/credentials.py b/packages/google-auth/google/oauth2/credentials.py index cff8647d3bd9..4cae82b8eb79 100644 --- a/packages/google-auth/google/oauth2/credentials.py +++ b/packages/google-auth/google/oauth2/credentials.py @@ -605,6 +605,7 @@ def __init__(self, account=None, quota_project_id=None): super(UserAccessTokenCredentials, self).__init__() self._account = account self._quota_project_id = quota_project_id + self._verified_universe_domain = None def with_account(self, account): """Create a new instance with the given account. @@ -631,9 +632,30 @@ def refresh(self, request): so just set it to `None`. Raises: + google.auth.exceptions.InvalidValue: If the resolved universe domain + is invalid or does not match the default universe domain. google.auth.exceptions.UserAccessTokenError: If the access token refresh failed. """ + # Cache the verified universe domain to prevent repeated subprocess calls on subsequent refreshes + if not self._verified_universe_domain: + # Since this credential retrieves tokens dynamically from the active gcloud CLI session, + # we must check the active gcloud universe domain configuration to ensure it matches + # standard GDU boundaries before obtaining the token. + sdk_universe = ( + _cloud_sdk.get_universe_domain() or credentials.DEFAULT_UNIVERSE_DOMAIN + ) + + # 1. Validate the syntax of the resolved universe domain + _helpers.validate_universe_domain(sdk_universe) + + # 2. Verify that it matches the expected default universe (googleapis.com) + _helpers.compare_universe_domains( + sdk_universe, credentials.DEFAULT_UNIVERSE_DOMAIN + ) + + self._verified_universe_domain = sdk_universe + self.token = _cloud_sdk.get_auth_access_token(self._account) @_helpers.copy_docstring(credentials.Credentials) diff --git a/packages/google-auth/tests/oauth2/test_credentials.py b/packages/google-auth/tests/oauth2/test_credentials.py index fc36f911bad9..9d96215f42af 100644 --- a/packages/google-auth/tests/oauth2/test_credentials.py +++ b/packages/google-auth/tests/oauth2/test_credentials.py @@ -1097,3 +1097,47 @@ def test_before_request(self, refresh, apply): cred.before_request(mock.Mock(), "GET", "https://example.com", {}) refresh.assert_called() apply.assert_called() + + @mock.patch( + "google.auth._cloud_sdk.get_universe_domain", + return_value="non-default.universe.domain", + ) + @mock.patch( + "google.auth._cloud_sdk.get_auth_access_token", return_value="mock-token-tpc" + ) + def test_refresh_blocks_non_default_universe(self, mock_get_token, mock_get_ud): + """Verifies that refreshing fails when pointing to a non-default universe domain.""" + creds = credentials.UserAccessTokenCredentials() + + with pytest.raises(exceptions.InvalidValue) as exc_info: + creds.refresh(None) + + assert "does not match the expected universe domain" in str(exc_info.value) + # Ensure the token retrieve subprocess was never called + mock_get_token.assert_not_called() + + @mock.patch( + "google.auth._cloud_sdk.get_universe_domain", return_value="invalid@domain" + ) + @mock.patch("google.auth._cloud_sdk.get_auth_access_token") + def test_refresh_blocks_invalid_universe_format(self, mock_get_token, mock_get_ud): + """Verifies that refreshing fails on syntactically invalid universe domains.""" + creds = credentials.UserAccessTokenCredentials() + + with pytest.raises(exceptions.InvalidValue) as exc_info: + creds.refresh(None) + + assert "Universe domain must be a valid non-empty domain string" in str( + exc_info.value + ) + mock_get_token.assert_not_called() + + @mock.patch("google.auth._cloud_sdk.get_universe_domain", return_value=None) + @mock.patch( + "google.auth._cloud_sdk.get_auth_access_token", return_value="mock-token-gdu" + ) + def test_gdu_universe_succeeds(self, mock_get_token, mock_get_ud): + """Verifies that default universe domain setups refresh successfully.""" + creds = credentials.UserAccessTokenCredentials() + creds.refresh(None) + assert creds.token == "mock-token-gdu" diff --git a/packages/google-auth/tests/test__cloud_sdk.py b/packages/google-auth/tests/test__cloud_sdk.py index 6865d0d9e76d..88f5aba5e5ed 100644 --- a/packages/google-auth/tests/test__cloud_sdk.py +++ b/packages/google-auth/tests/test__cloud_sdk.py @@ -175,3 +175,42 @@ def test_get_auth_access_token_with_exception(check_output): with pytest.raises(exceptions.UserAccessTokenError): _cloud_sdk.get_auth_access_token(account="account") + + +@pytest.mark.parametrize( + "data, expected_universe_domain", + [ + (b"custom-universe.goog\n", "custom-universe.goog"), + (b" another-universe.domain.com \n", "another-universe.domain.com"), + (b"", None), + (b"\n", None), + ], +) +def test_get_universe_domain_success(data, expected_universe_domain): + # Mocking subprocess output to simulate different gcloud configurations + check_output_patch = mock.patch("subprocess.check_output", return_value=data) + + with check_output_patch: + universe_domain = _cloud_sdk.get_universe_domain() + + assert universe_domain == expected_universe_domain + + +def test_get_universe_domain_error(): + # Simulate gcloud failing (e.g. not installed or returns non-zero code) + check_output_patch = mock.patch( + "subprocess.check_output", + side_effect=subprocess.CalledProcessError(1, "gcloud"), + ) + + with check_output_patch: + universe_domain = _cloud_sdk.get_universe_domain() + + assert universe_domain is None + + +@mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "env.universe.goog"}) +def test_get_universe_domain_from_env(): + # If standard environment variable is present, it bypasses subprocess check entirely + universe_domain = _cloud_sdk.get_universe_domain() + assert universe_domain == "env.universe.goog" From 2ed62694215ce7d1be04220a190d496a8f24bf57 Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Tue, 1 Dec 2026 18:03:34 +0000 Subject: [PATCH 2/5] fix(oauth2): lazily resolve and cache UserAccessTokenCredentials.universe_domain --- .../google-auth/google/oauth2/credentials.py | 51 ++++---- .../tests/oauth2/test_credentials.py | 109 +++++++++++++++--- packages/google-auth/tests/test__cloud_sdk.py | 63 ++++++++-- .../oauth2/test_credentials_async.py | 35 +++++- 4 files changed, 205 insertions(+), 53 deletions(-) diff --git a/packages/google-auth/google/oauth2/credentials.py b/packages/google-auth/google/oauth2/credentials.py index 4cae82b8eb79..536b12a26ba8 100644 --- a/packages/google-auth/google/oauth2/credentials.py +++ b/packages/google-auth/google/oauth2/credentials.py @@ -605,7 +605,21 @@ def __init__(self, account=None, quota_project_id=None): super(UserAccessTokenCredentials, self).__init__() self._account = account self._quota_project_id = quota_project_id - self._verified_universe_domain = None + self._universe_domain_cached = False + + @property + def universe_domain(self): + """str: The universe domain resolved from the environment or Cloud SDK.""" + if getattr(self, "_universe_domain_cached", False): + return self._universe_domain + + sdk_universe = ( + _cloud_sdk.get_universe_domain() or credentials.DEFAULT_UNIVERSE_DOMAIN + ) + _helpers.validate_universe_domain(sdk_universe) + self._universe_domain = sdk_universe + self._universe_domain_cached = True + return self._universe_domain def with_account(self, account): """Create a new instance with the given account. @@ -617,11 +631,19 @@ def with_account(self, account): google.oauth2.credentials.UserAccessTokenCredentials: The created credentials with the given account. """ - return self.__class__(account=account, quota_project_id=self._quota_project_id) + cred = self.__class__(account=account, quota_project_id=self._quota_project_id) + if self._universe_domain_cached: + cred._universe_domain = self._universe_domain + cred._universe_domain_cached = True + return cred @_helpers.copy_docstring(credentials.CredentialsWithQuotaProject) def with_quota_project(self, quota_project_id): - return self.__class__(account=self._account, quota_project_id=quota_project_id) + cred = self.__class__(account=self._account, quota_project_id=quota_project_id) + if self._universe_domain_cached: + cred._universe_domain = self._universe_domain + cred._universe_domain_cached = True + return cred def refresh(self, request): """Refreshes the access token. @@ -633,28 +655,13 @@ def refresh(self, request): Raises: google.auth.exceptions.InvalidValue: If the resolved universe domain - is invalid or does not match the default universe domain. + is invalid. google.auth.exceptions.UserAccessTokenError: If the access token refresh failed. """ - # Cache the verified universe domain to prevent repeated subprocess calls on subsequent refreshes - if not self._verified_universe_domain: - # Since this credential retrieves tokens dynamically from the active gcloud CLI session, - # we must check the active gcloud universe domain configuration to ensure it matches - # standard GDU boundaries before obtaining the token. - sdk_universe = ( - _cloud_sdk.get_universe_domain() or credentials.DEFAULT_UNIVERSE_DOMAIN - ) - - # 1. Validate the syntax of the resolved universe domain - _helpers.validate_universe_domain(sdk_universe) - - # 2. Verify that it matches the expected default universe (googleapis.com) - _helpers.compare_universe_domains( - sdk_universe, credentials.DEFAULT_UNIVERSE_DOMAIN - ) - - self._verified_universe_domain = sdk_universe + # Resolve and validate the active Cloud SDK universe domain once before + # fetching a token; subsequent calls reuse the cached value. + _ = self.universe_domain self.token = _cloud_sdk.get_auth_access_token(self._account) diff --git a/packages/google-auth/tests/oauth2/test_credentials.py b/packages/google-auth/tests/oauth2/test_credentials.py index 9d96215f42af..3bb23967e03f 100644 --- a/packages/google-auth/tests/oauth2/test_credentials.py +++ b/packages/google-auth/tests/oauth2/test_credentials.py @@ -1063,8 +1063,9 @@ def test_instance(self): cred = cred.with_account("account") assert cred._account == "account" + @mock.patch("google.auth._cloud_sdk.get_universe_domain", return_value=None) @mock.patch("google.auth._cloud_sdk.get_auth_access_token", autospec=True) - def test_refresh(self, get_auth_access_token): + def test_refresh(self, get_auth_access_token, unused_get_universe_domain): with pytest.warns( UserWarning, match="UserAccessTokenCredentials is deprecated" ): @@ -1072,6 +1073,7 @@ def test_refresh(self, get_auth_access_token): cred = credentials.UserAccessTokenCredentials() cred.refresh(None) assert cred.token == "access_token" + assert cred.universe_domain == "googleapis.com" def test_with_quota_project(self): with pytest.warns( @@ -1100,29 +1102,89 @@ def test_before_request(self, refresh, apply): @mock.patch( "google.auth._cloud_sdk.get_universe_domain", - return_value="non-default.universe.domain", + return_value="custom-universe.goog", ) @mock.patch( - "google.auth._cloud_sdk.get_auth_access_token", return_value="mock-token-tpc" + "google.auth._cloud_sdk.get_auth_access_token", return_value="mock-token-custom" ) - def test_refresh_blocks_non_default_universe(self, mock_get_token, mock_get_ud): - """Verifies that refreshing fails when pointing to a non-default universe domain.""" - creds = credentials.UserAccessTokenCredentials() + def test_universe_domain_resolves_lazily_and_updates_property( + self, mock_get_token, mock_get_ud + ): + with pytest.warns( + UserWarning, match="UserAccessTokenCredentials is deprecated" + ): + creds = credentials.UserAccessTokenCredentials() - with pytest.raises(exceptions.InvalidValue) as exc_info: + # Accessing universe_domain before refresh resolves and caches it + assert creds.universe_domain == "custom-universe.goog" + assert mock_get_ud.call_count == 1 + + # Refresh reuses the cached universe domain without another lookup + creds.refresh(None) + assert creds.token == "mock-token-custom" + assert creds.universe_domain == "custom-universe.goog" + assert mock_get_ud.call_count == 1 + + @mock.patch( + "google.auth._cloud_sdk.get_universe_domain", + return_value="custom-universe.goog", + ) + @mock.patch( + "google.auth._cloud_sdk.get_auth_access_token", return_value="mock-token" + ) + def test_refresh_updates_public_universe_property( + self, mock_get_token, mock_get_ud + ): + with pytest.warns( + UserWarning, match="UserAccessTokenCredentials is deprecated" + ): + creds = credentials.UserAccessTokenCredentials() + + creds.refresh(None) + + assert creds.token == "mock-token" + assert creds.universe_domain == "custom-universe.goog" + assert mock_get_ud.call_count == 1 + + @pytest.mark.parametrize( + "resolved_universe,expected_universe", + [ + ("googleapis.com", "googleapis.com"), + (None, "googleapis.com"), + ("custom-universe.goog", "custom-universe.goog"), + ], + ) + @mock.patch( + "google.auth._cloud_sdk.get_auth_access_token", return_value="mock-token" + ) + def test_refresh_caches_resolved_universe_domain( + self, mock_get_token, resolved_universe, expected_universe + ): + with mock.patch( + "google.auth._cloud_sdk.get_universe_domain", + return_value=resolved_universe, + ) as mock_get_ud: + with pytest.warns( + UserWarning, match="UserAccessTokenCredentials is deprecated" + ): + creds = credentials.UserAccessTokenCredentials() + + creds.refresh(None) creds.refresh(None) - assert "does not match the expected universe domain" in str(exc_info.value) - # Ensure the token retrieve subprocess was never called - mock_get_token.assert_not_called() + assert creds.universe_domain == expected_universe + assert mock_get_ud.call_count == 1 + assert mock_get_token.call_count == 2 @mock.patch( "google.auth._cloud_sdk.get_universe_domain", return_value="invalid@domain" ) @mock.patch("google.auth._cloud_sdk.get_auth_access_token") def test_refresh_blocks_invalid_universe_format(self, mock_get_token, mock_get_ud): - """Verifies that refreshing fails on syntactically invalid universe domains.""" - creds = credentials.UserAccessTokenCredentials() + with pytest.warns( + UserWarning, match="UserAccessTokenCredentials is deprecated" + ): + creds = credentials.UserAccessTokenCredentials() with pytest.raises(exceptions.InvalidValue) as exc_info: creds.refresh(None) @@ -1130,14 +1192,23 @@ def test_refresh_blocks_invalid_universe_format(self, mock_get_token, mock_get_u assert "Universe domain must be a valid non-empty domain string" in str( exc_info.value ) + assert not creds._universe_domain_cached mock_get_token.assert_not_called() - @mock.patch("google.auth._cloud_sdk.get_universe_domain", return_value=None) @mock.patch( - "google.auth._cloud_sdk.get_auth_access_token", return_value="mock-token-gdu" + "google.auth._cloud_sdk.get_universe_domain", + return_value="custom-universe.goog", ) - def test_gdu_universe_succeeds(self, mock_get_token, mock_get_ud): - """Verifies that default universe domain setups refresh successfully.""" - creds = credentials.UserAccessTokenCredentials() - creds.refresh(None) - assert creds.token == "mock-token-gdu" + def test_with_account_and_quota_project_preserve_cached_universe(self, mock_get_ud): + with pytest.warns( + UserWarning, match="UserAccessTokenCredentials is deprecated" + ): + creds = credentials.UserAccessTokenCredentials() + assert creds.universe_domain == "custom-universe.goog" + + with_acct = creds.with_account("user@example.com") + with_quota = creds.with_quota_project("project-foo") + + assert with_acct.universe_domain == "custom-universe.goog" + assert with_quota.universe_domain == "custom-universe.goog" + assert mock_get_ud.call_count == 1 diff --git a/packages/google-auth/tests/test__cloud_sdk.py b/packages/google-auth/tests/test__cloud_sdk.py index 88f5aba5e5ed..f504783fd942 100644 --- a/packages/google-auth/tests/test__cloud_sdk.py +++ b/packages/google-auth/tests/test__cloud_sdk.py @@ -186,31 +186,72 @@ def test_get_auth_access_token_with_exception(check_output): (b"\n", None), ], ) -def test_get_universe_domain_success(data, expected_universe_domain): - # Mocking subprocess output to simulate different gcloud configurations - check_output_patch = mock.patch("subprocess.check_output", return_value=data) +def test_get_universe_domain_success(monkeypatch, data, expected_universe_domain): + monkeypatch.delenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN", raising=False) + check_output_patch = mock.patch( + "subprocess.check_output", autospec=True, return_value=data + ) - with check_output_patch: + with check_output_patch as check_output: universe_domain = _cloud_sdk.get_universe_domain() assert universe_domain == expected_universe_domain + assert check_output.called -def test_get_universe_domain_error(): - # Simulate gcloud failing (e.g. not installed or returns non-zero code) +@mock.patch("os.name", new="nt") +def test_get_universe_domain_windows(monkeypatch): + monkeypatch.delenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN", raising=False) check_output_patch = mock.patch( "subprocess.check_output", + autospec=True, + return_value=b"custom-universe.goog\n", + ) + + with check_output_patch as check_output: + universe_domain = _cloud_sdk.get_universe_domain() + + assert universe_domain == "custom-universe.goog" + assert check_output.call_args[0][0] == ( + "gcloud.cmd", + "config", + "get", + "core/universe_domain", + ) + + +def test_get_universe_domain_error(monkeypatch): + monkeypatch.delenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN", raising=False) + check_output_patch = mock.patch( + "subprocess.check_output", + autospec=True, side_effect=subprocess.CalledProcessError(1, "gcloud"), ) - with check_output_patch: + with check_output_patch as check_output: universe_domain = _cloud_sdk.get_universe_domain() assert universe_domain is None + assert check_output.called + +def test_get_universe_domain_from_env(monkeypatch): + monkeypatch.setenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN", " env.universe.goog ") + with mock.patch("subprocess.check_output", autospec=True) as check_output: + universe_domain = _cloud_sdk.get_universe_domain() -@mock.patch.dict(os.environ, {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "env.universe.goog"}) -def test_get_universe_domain_from_env(): - # If standard environment variable is present, it bypasses subprocess check entirely - universe_domain = _cloud_sdk.get_universe_domain() assert universe_domain == "env.universe.goog" + check_output.assert_not_called() + + +def test_get_universe_domain_whitespace_env_falls_back_to_gcloud(monkeypatch): + monkeypatch.setenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN", " ") + with mock.patch( + "subprocess.check_output", + autospec=True, + return_value=b"gcloud.universe.goog\n", + ) as check_output: + universe_domain = _cloud_sdk.get_universe_domain() + + assert universe_domain == "gcloud.universe.goog" + check_output.assert_called_once() diff --git a/packages/google-auth/tests_async/oauth2/test_credentials_async.py b/packages/google-auth/tests_async/oauth2/test_credentials_async.py index 7fbe76c02867..725e6607c3bb 100644 --- a/packages/google-auth/tests_async/oauth2/test_credentials_async.py +++ b/packages/google-auth/tests_async/oauth2/test_credentials_async.py @@ -498,12 +498,14 @@ def test_instance(self): cred = cred.with_account("account") assert cred._account == "account" + @mock.patch("google.auth._cloud_sdk.get_universe_domain", return_value=None) @mock.patch("google.auth._cloud_sdk.get_auth_access_token", autospec=True) - def test_refresh(self, get_auth_access_token): + def test_refresh(self, get_auth_access_token, unused_get_universe_domain): get_auth_access_token.return_value = "access_token" cred = _credentials_async.UserAccessTokenCredentials() cred.refresh(None) assert cred.token == "access_token" + assert cred.universe_domain == "googleapis.com" def test_with_quota_project(self): cred = _credentials_async.UserAccessTokenCredentials() @@ -525,3 +527,34 @@ def test_before_request(self, refresh, apply): cred.before_request(mock.Mock(), "GET", "https://example.com", {}) refresh.assert_called() apply.assert_called() + + @mock.patch( + "google.auth._cloud_sdk.get_universe_domain", + return_value="custom-universe.goog", + ) + @mock.patch( + "google.auth._cloud_sdk.get_auth_access_token", return_value="mock-token" + ) + def test_refresh_caches_resolved_universe_domain(self, mock_get_token, mock_get_ud): + cred = _credentials_async.UserAccessTokenCredentials() + assert cred.universe_domain == "custom-universe.goog" + + cred.refresh(None) + cred.refresh(None) + + assert cred.token == "mock-token" + assert cred.universe_domain == "custom-universe.goog" + assert mock_get_ud.call_count == 1 + assert mock_get_token.call_count == 2 + + @mock.patch( + "google.auth._cloud_sdk.get_universe_domain", return_value="invalid@domain" + ) + @mock.patch("google.auth._cloud_sdk.get_auth_access_token") + def test_refresh_blocks_invalid_universe_format(self, mock_get_token, mock_get_ud): + cred = _credentials_async.UserAccessTokenCredentials() + + with pytest.raises(exceptions.InvalidValue): + cred.refresh(None) + + mock_get_token.assert_not_called() From 95fd169c28fe4aa45f74543c224bd4f085a0e3e9 Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Tue, 1 Dec 2026 18:06:43 +0000 Subject: [PATCH 3/5] work in progress --- packages/google-auth/google/oauth2/credentials.py | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/packages/google-auth/google/oauth2/credentials.py b/packages/google-auth/google/oauth2/credentials.py index 536b12a26ba8..91683d2551d5 100644 --- a/packages/google-auth/google/oauth2/credentials.py +++ b/packages/google-auth/google/oauth2/credentials.py @@ -607,9 +607,8 @@ def __init__(self, account=None, quota_project_id=None): self._quota_project_id = quota_project_id self._universe_domain_cached = False - @property - def universe_domain(self): - """str: The universe domain resolved from the environment or Cloud SDK.""" + def _resolve_universe_domain(self): + """Resolves, validates, and caches the active Cloud SDK universe domain.""" if getattr(self, "_universe_domain_cached", False): return self._universe_domain @@ -621,6 +620,11 @@ def universe_domain(self): self._universe_domain_cached = True return self._universe_domain + @property + def universe_domain(self): + """str: The universe domain resolved from the environment or Cloud SDK.""" + return self._resolve_universe_domain() + def with_account(self, account): """Create a new instance with the given account. @@ -659,10 +663,7 @@ def refresh(self, request): google.auth.exceptions.UserAccessTokenError: If the access token refresh failed. """ - # Resolve and validate the active Cloud SDK universe domain once before - # fetching a token; subsequent calls reuse the cached value. - _ = self.universe_domain - + self._resolve_universe_domain() self.token = _cloud_sdk.get_auth_access_token(self._account) @_helpers.copy_docstring(credentials.Credentials) From 8fa6bf25b43950cb391fb9bd78e848b5cca7c5d4 Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Tue, 1 Dec 2026 18:12:13 +0000 Subject: [PATCH 4/5] refactor(oauth2): extract _resolve_universe_domain and expand universe tests --- .../google-auth/google/auth/_cloud_sdk.py | 6 ++-- .../google-auth/google/oauth2/credentials.py | 19 ++++++---- .../tests/oauth2/test_credentials.py | 25 +++++++++++++ packages/google-auth/tests/test__cloud_sdk.py | 35 +++++++++++++++++-- .../oauth2/test_credentials_async.py | 29 +++++++++++++-- 5 files changed, 101 insertions(+), 13 deletions(-) diff --git a/packages/google-auth/google/auth/_cloud_sdk.py b/packages/google-auth/google/auth/_cloud_sdk.py index bb55a7ab210b..745eae0b987c 100644 --- a/packages/google-auth/google/auth/_cloud_sdk.py +++ b/packages/google-auth/google/auth/_cloud_sdk.py @@ -31,6 +31,8 @@ _CLOUD_SDK_WINDOWS_COMMAND = "gcloud.cmd" # The command to get the Cloud SDK configuration _CLOUD_SDK_CONFIG_GET_PROJECT_COMMAND = ("config", "get", "project") +# The environment variable overriding the universe domain +_UNIVERSE_DOMAIN_ENV_VAR = "GOOGLE_CLOUD_UNIVERSE_DOMAIN" # The command to get the active Cloud SDK universe domain _CLOUD_SDK_CONFIG_GET_UNIVERSE_DOMAIN_COMMAND = ( "config", @@ -163,7 +165,7 @@ def get_universe_domain(): Optional[str]: The universe domain if set, otherwise None. """ # Check standard environment variable first - env_universe = os.environ.get("GOOGLE_CLOUD_UNIVERSE_DOMAIN") + env_universe = os.environ.get(_UNIVERSE_DOMAIN_ENV_VAR) if env_universe and env_universe.strip(): return env_universe.strip() @@ -180,5 +182,5 @@ def get_universe_domain(): ) universe_domain = _helpers.from_bytes(universe_domain).strip() return universe_domain if universe_domain else None - except (subprocess.CalledProcessError, OSError, IOError): + except (subprocess.SubprocessError, OSError, ValueError): return None diff --git a/packages/google-auth/google/oauth2/credentials.py b/packages/google-auth/google/oauth2/credentials.py index 91683d2551d5..c09bea616e00 100644 --- a/packages/google-auth/google/oauth2/credentials.py +++ b/packages/google-auth/google/oauth2/credentials.py @@ -609,6 +609,8 @@ def __init__(self, account=None, quota_project_id=None): def _resolve_universe_domain(self): """Resolves, validates, and caches the active Cloud SDK universe domain.""" + # Use getattr for compatibility with unpickled instances or subclasses + # that did not initialize _universe_domain_cached. if getattr(self, "_universe_domain_cached", False): return self._universe_domain @@ -620,6 +622,15 @@ def _resolve_universe_domain(self): self._universe_domain_cached = True return self._universe_domain + def _copy_cached_universe_domain(self, target): + # Use getattr for compatibility with unpickled instances or subclasses + # that did not initialize _universe_domain_cached or _universe_domain. + if getattr(self, "_universe_domain_cached", False): + target._universe_domain = getattr( + self, "_universe_domain", credentials.DEFAULT_UNIVERSE_DOMAIN + ) + target._universe_domain_cached = True + @property def universe_domain(self): """str: The universe domain resolved from the environment or Cloud SDK.""" @@ -636,17 +647,13 @@ def with_account(self, account): credentials with the given account. """ cred = self.__class__(account=account, quota_project_id=self._quota_project_id) - if self._universe_domain_cached: - cred._universe_domain = self._universe_domain - cred._universe_domain_cached = True + self._copy_cached_universe_domain(cred) return cred @_helpers.copy_docstring(credentials.CredentialsWithQuotaProject) def with_quota_project(self, quota_project_id): cred = self.__class__(account=self._account, quota_project_id=quota_project_id) - if self._universe_domain_cached: - cred._universe_domain = self._universe_domain - cred._universe_domain_cached = True + self._copy_cached_universe_domain(cred) return cred def refresh(self, request): diff --git a/packages/google-auth/tests/oauth2/test_credentials.py b/packages/google-auth/tests/oauth2/test_credentials.py index 3bb23967e03f..f73000b40229 100644 --- a/packages/google-auth/tests/oauth2/test_credentials.py +++ b/packages/google-auth/tests/oauth2/test_credentials.py @@ -1186,6 +1186,14 @@ def test_refresh_blocks_invalid_universe_format(self, mock_get_token, mock_get_u ): creds = credentials.UserAccessTokenCredentials() + with pytest.raises(exceptions.InvalidValue) as exc_info: + _ = creds.universe_domain + + assert "Universe domain must be a valid non-empty domain string" in str( + exc_info.value + ) + assert not creds._universe_domain_cached + with pytest.raises(exceptions.InvalidValue) as exc_info: creds.refresh(None) @@ -1212,3 +1220,20 @@ def test_with_account_and_quota_project_preserve_cached_universe(self, mock_get_ assert with_acct.universe_domain == "custom-universe.goog" assert with_quota.universe_domain == "custom-universe.goog" assert mock_get_ud.call_count == 1 + + @mock.patch( + "google.auth._cloud_sdk.get_universe_domain", + return_value="custom-universe.goog", + ) + def test_with_account_and_quota_project_uncached_resolve_lazily(self, mock_get_ud): + with pytest.warns( + UserWarning, match="UserAccessTokenCredentials is deprecated" + ): + creds = credentials.UserAccessTokenCredentials() + with_acct = creds.with_account("user@example.com") + with_quota = creds.with_quota_project("project-foo") + + assert mock_get_ud.call_count == 0 + assert with_acct.universe_domain == "custom-universe.goog" + assert with_quota.universe_domain == "custom-universe.goog" + assert mock_get_ud.call_count == 2 diff --git a/packages/google-auth/tests/test__cloud_sdk.py b/packages/google-auth/tests/test__cloud_sdk.py index f504783fd942..c812b4db5e64 100644 --- a/packages/google-auth/tests/test__cloud_sdk.py +++ b/packages/google-auth/tests/test__cloud_sdk.py @@ -177,6 +177,7 @@ def test_get_auth_access_token_with_exception(check_output): _cloud_sdk.get_auth_access_token(account="account") +@mock.patch("os.name", new="posix") @pytest.mark.parametrize( "data, expected_universe_domain", [ @@ -196,7 +197,12 @@ def test_get_universe_domain_success(monkeypatch, data, expected_universe_domain universe_domain = _cloud_sdk.get_universe_domain() assert universe_domain == expected_universe_domain - assert check_output.called + assert check_output.call_args[0][0] == ( + "gcloud", + "config", + "get", + "core/universe_domain", + ) @mock.patch("os.name", new="nt") @@ -220,12 +226,35 @@ def test_get_universe_domain_windows(monkeypatch): ) -def test_get_universe_domain_error(monkeypatch): +@pytest.mark.parametrize( + "error", + [ + subprocess.CalledProcessError(1, "gcloud"), + OSError("gcloud not found"), + subprocess.TimeoutExpired("gcloud", 10), + ], +) +def test_get_universe_domain_error(monkeypatch, error): + monkeypatch.delenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN", raising=False) + check_output_patch = mock.patch( + "subprocess.check_output", + autospec=True, + side_effect=error, + ) + + with check_output_patch as check_output: + universe_domain = _cloud_sdk.get_universe_domain() + + assert universe_domain is None + assert check_output.called + + +def test_get_universe_domain_decoding_error(monkeypatch): monkeypatch.delenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN", raising=False) check_output_patch = mock.patch( "subprocess.check_output", autospec=True, - side_effect=subprocess.CalledProcessError(1, "gcloud"), + return_value=b"\xff\xfe\x00\x00invalid-bytes", ) with check_output_patch as check_output: diff --git a/packages/google-auth/tests_async/oauth2/test_credentials_async.py b/packages/google-auth/tests_async/oauth2/test_credentials_async.py index 725e6607c3bb..b910b9660def 100644 --- a/packages/google-auth/tests_async/oauth2/test_credentials_async.py +++ b/packages/google-auth/tests_async/oauth2/test_credentials_async.py @@ -536,7 +536,10 @@ def test_before_request(self, refresh, apply): "google.auth._cloud_sdk.get_auth_access_token", return_value="mock-token" ) def test_refresh_caches_resolved_universe_domain(self, mock_get_token, mock_get_ud): - cred = _credentials_async.UserAccessTokenCredentials() + with pytest.warns( + UserWarning, match="UserAccessTokenCredentials is deprecated" + ): + cred = _credentials_async.UserAccessTokenCredentials() assert cred.universe_domain == "custom-universe.goog" cred.refresh(None) @@ -552,9 +555,31 @@ def test_refresh_caches_resolved_universe_domain(self, mock_get_token, mock_get_ ) @mock.patch("google.auth._cloud_sdk.get_auth_access_token") def test_refresh_blocks_invalid_universe_format(self, mock_get_token, mock_get_ud): - cred = _credentials_async.UserAccessTokenCredentials() + with pytest.warns( + UserWarning, match="UserAccessTokenCredentials is deprecated" + ): + cred = _credentials_async.UserAccessTokenCredentials() with pytest.raises(exceptions.InvalidValue): cred.refresh(None) mock_get_token.assert_not_called() + + @mock.patch( + "google.auth._cloud_sdk.get_universe_domain", + return_value="custom-universe.goog", + ) + def test_with_account_and_quota_project_universe_caching(self, mock_get_ud): + with pytest.warns( + UserWarning, match="UserAccessTokenCredentials is deprecated" + ): + cred = _credentials_async.UserAccessTokenCredentials() + uncached_clone = cred.with_account("user@example.com") + assert mock_get_ud.call_count == 0 + assert cred.universe_domain == "custom-universe.goog" + cached_clone = cred.with_quota_project("project-foo") + + assert cached_clone.universe_domain == "custom-universe.goog" + assert mock_get_ud.call_count == 1 + assert uncached_clone.universe_domain == "custom-universe.goog" + assert mock_get_ud.call_count == 2 From 691a7fb999e78aa12cf68582e0dac979e874f901 Mon Sep 17 00:00:00 2001 From: Anthonios Partheniou Date: Tue, 1 Dec 2026 18:22:12 +0000 Subject: [PATCH 5/5] test(oauth2): use with mock.patch for get_universe_domain in refresh tests --- .../tests/oauth2/test_credentials.py | 60 ++++++++++--------- .../oauth2/test_credentials_async.py | 36 +++++------ 2 files changed, 50 insertions(+), 46 deletions(-) diff --git a/packages/google-auth/tests/oauth2/test_credentials.py b/packages/google-auth/tests/oauth2/test_credentials.py index f73000b40229..b87d7efd46d0 100644 --- a/packages/google-auth/tests/oauth2/test_credentials.py +++ b/packages/google-auth/tests/oauth2/test_credentials.py @@ -1063,17 +1063,19 @@ def test_instance(self): cred = cred.with_account("account") assert cred._account == "account" - @mock.patch("google.auth._cloud_sdk.get_universe_domain", return_value=None) @mock.patch("google.auth._cloud_sdk.get_auth_access_token", autospec=True) - def test_refresh(self, get_auth_access_token, unused_get_universe_domain): - with pytest.warns( - UserWarning, match="UserAccessTokenCredentials is deprecated" + def test_refresh(self, get_auth_access_token): + with mock.patch( + "google.auth._cloud_sdk.get_universe_domain", return_value=None ): - get_auth_access_token.return_value = "access_token" - cred = credentials.UserAccessTokenCredentials() - cred.refresh(None) - assert cred.token == "access_token" - assert cred.universe_domain == "googleapis.com" + with pytest.warns( + UserWarning, match="UserAccessTokenCredentials is deprecated" + ): + get_auth_access_token.return_value = "access_token" + cred = credentials.UserAccessTokenCredentials() + cred.refresh(None) + assert cred.token == "access_token" + assert cred.universe_domain == "googleapis.com" def test_with_quota_project(self): with pytest.warns( @@ -1176,32 +1178,32 @@ def test_refresh_caches_resolved_universe_domain( assert mock_get_ud.call_count == 1 assert mock_get_token.call_count == 2 - @mock.patch( - "google.auth._cloud_sdk.get_universe_domain", return_value="invalid@domain" - ) @mock.patch("google.auth._cloud_sdk.get_auth_access_token") - def test_refresh_blocks_invalid_universe_format(self, mock_get_token, mock_get_ud): - with pytest.warns( - UserWarning, match="UserAccessTokenCredentials is deprecated" + def test_refresh_blocks_invalid_universe_format(self, mock_get_token): + with mock.patch( + "google.auth._cloud_sdk.get_universe_domain", return_value="invalid@domain" ): - creds = credentials.UserAccessTokenCredentials() + with pytest.warns( + UserWarning, match="UserAccessTokenCredentials is deprecated" + ): + creds = credentials.UserAccessTokenCredentials() - with pytest.raises(exceptions.InvalidValue) as exc_info: - _ = creds.universe_domain + with pytest.raises(exceptions.InvalidValue) as exc_info: + _ = creds.universe_domain - assert "Universe domain must be a valid non-empty domain string" in str( - exc_info.value - ) - assert not creds._universe_domain_cached + assert "Universe domain must be a valid non-empty domain string" in str( + exc_info.value + ) + assert not creds._universe_domain_cached - with pytest.raises(exceptions.InvalidValue) as exc_info: - creds.refresh(None) + with pytest.raises(exceptions.InvalidValue) as exc_info: + creds.refresh(None) - assert "Universe domain must be a valid non-empty domain string" in str( - exc_info.value - ) - assert not creds._universe_domain_cached - mock_get_token.assert_not_called() + assert "Universe domain must be a valid non-empty domain string" in str( + exc_info.value + ) + assert not creds._universe_domain_cached + mock_get_token.assert_not_called() @mock.patch( "google.auth._cloud_sdk.get_universe_domain", diff --git a/packages/google-auth/tests_async/oauth2/test_credentials_async.py b/packages/google-auth/tests_async/oauth2/test_credentials_async.py index b910b9660def..f2d9246b4fe5 100644 --- a/packages/google-auth/tests_async/oauth2/test_credentials_async.py +++ b/packages/google-auth/tests_async/oauth2/test_credentials_async.py @@ -498,14 +498,16 @@ def test_instance(self): cred = cred.with_account("account") assert cred._account == "account" - @mock.patch("google.auth._cloud_sdk.get_universe_domain", return_value=None) @mock.patch("google.auth._cloud_sdk.get_auth_access_token", autospec=True) - def test_refresh(self, get_auth_access_token, unused_get_universe_domain): - get_auth_access_token.return_value = "access_token" - cred = _credentials_async.UserAccessTokenCredentials() - cred.refresh(None) - assert cred.token == "access_token" - assert cred.universe_domain == "googleapis.com" + def test_refresh(self, get_auth_access_token): + with mock.patch( + "google.auth._cloud_sdk.get_universe_domain", return_value=None + ): + get_auth_access_token.return_value = "access_token" + cred = _credentials_async.UserAccessTokenCredentials() + cred.refresh(None) + assert cred.token == "access_token" + assert cred.universe_domain == "googleapis.com" def test_with_quota_project(self): cred = _credentials_async.UserAccessTokenCredentials() @@ -550,20 +552,20 @@ def test_refresh_caches_resolved_universe_domain(self, mock_get_token, mock_get_ assert mock_get_ud.call_count == 1 assert mock_get_token.call_count == 2 - @mock.patch( - "google.auth._cloud_sdk.get_universe_domain", return_value="invalid@domain" - ) @mock.patch("google.auth._cloud_sdk.get_auth_access_token") - def test_refresh_blocks_invalid_universe_format(self, mock_get_token, mock_get_ud): - with pytest.warns( - UserWarning, match="UserAccessTokenCredentials is deprecated" + def test_refresh_blocks_invalid_universe_format(self, mock_get_token): + with mock.patch( + "google.auth._cloud_sdk.get_universe_domain", return_value="invalid@domain" ): - cred = _credentials_async.UserAccessTokenCredentials() + with pytest.warns( + UserWarning, match="UserAccessTokenCredentials is deprecated" + ): + cred = _credentials_async.UserAccessTokenCredentials() - with pytest.raises(exceptions.InvalidValue): - cred.refresh(None) + with pytest.raises(exceptions.InvalidValue): + cred.refresh(None) - mock_get_token.assert_not_called() + mock_get_token.assert_not_called() @mock.patch( "google.auth._cloud_sdk.get_universe_domain",