diff --git a/packages/google-auth/google/auth/_cloud_sdk.py b/packages/google-auth/google/auth/_cloud_sdk.py index 05f0e9e72515..745eae0b987c 100644 --- a/packages/google-auth/google/auth/_cloud_sdk.py +++ b/packages/google-auth/google/auth/_cloud_sdk.py @@ -31,6 +31,14 @@ _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", + "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 +156,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(_UNIVERSE_DOMAIN_ENV_VAR) + 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.SubprocessError, OSError, ValueError): + return None diff --git a/packages/google-auth/google/oauth2/credentials.py b/packages/google-auth/google/oauth2/credentials.py index cff8647d3bd9..c09bea616e00 100644 --- a/packages/google-auth/google/oauth2/credentials.py +++ b/packages/google-auth/google/oauth2/credentials.py @@ -605,6 +605,36 @@ def __init__(self, account=None, quota_project_id=None): super(UserAccessTokenCredentials, self).__init__() self._account = account self._quota_project_id = quota_project_id + self._universe_domain_cached = False + + 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 + + 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 _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.""" + return self._resolve_universe_domain() def with_account(self, account): """Create a new instance with the given account. @@ -616,11 +646,15 @@ 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) + self._copy_cached_universe_domain(cred) + 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) + self._copy_cached_universe_domain(cred) + return cred def refresh(self, request): """Refreshes the access token. @@ -631,9 +665,12 @@ def refresh(self, request): so just set it to `None`. Raises: + google.auth.exceptions.InvalidValue: If the resolved universe domain + is invalid. google.auth.exceptions.UserAccessTokenError: If the access token refresh failed. """ + self._resolve_universe_domain() 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..b87d7efd46d0 100644 --- a/packages/google-auth/tests/oauth2/test_credentials.py +++ b/packages/google-auth/tests/oauth2/test_credentials.py @@ -1065,13 +1065,17 @@ def test_instance(self): @mock.patch("google.auth._cloud_sdk.get_auth_access_token", autospec=True) def test_refresh(self, get_auth_access_token): - with pytest.warns( - UserWarning, match="UserAccessTokenCredentials is deprecated" + 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" + 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( @@ -1097,3 +1101,141 @@ 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-custom" + ) + 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() + + # 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 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_auth_access_token") + 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" + ): + with pytest.warns( + UserWarning, match="UserAccessTokenCredentials is deprecated" + ): + 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) + + 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="custom-universe.goog", + ) + 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 + + @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 6865d0d9e76d..c812b4db5e64 100644 --- a/packages/google-auth/tests/test__cloud_sdk.py +++ b/packages/google-auth/tests/test__cloud_sdk.py @@ -175,3 +175,112 @@ def test_get_auth_access_token_with_exception(check_output): with pytest.raises(exceptions.UserAccessTokenError): _cloud_sdk.get_auth_access_token(account="account") + + +@mock.patch("os.name", new="posix") +@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(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 as check_output: + universe_domain = _cloud_sdk.get_universe_domain() + + assert universe_domain == expected_universe_domain + assert check_output.call_args[0][0] == ( + "gcloud", + "config", + "get", + "core/universe_domain", + ) + + +@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", + ) + + +@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, + return_value=b"\xff\xfe\x00\x00invalid-bytes", + ) + + 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() + + 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..f2d9246b4fe5 100644 --- a/packages/google-auth/tests_async/oauth2/test_credentials_async.py +++ b/packages/google-auth/tests_async/oauth2/test_credentials_async.py @@ -500,10 +500,14 @@ def test_instance(self): @mock.patch("google.auth._cloud_sdk.get_auth_access_token", autospec=True) def test_refresh(self, get_auth_access_token): - get_auth_access_token.return_value = "access_token" - cred = _credentials_async.UserAccessTokenCredentials() - cred.refresh(None) - assert cred.token == "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() @@ -525,3 +529,59 @@ 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): + with pytest.warns( + UserWarning, match="UserAccessTokenCredentials is deprecated" + ): + 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_auth_access_token") + 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" + ): + 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