fix: retrieve the live discovery document from the client's universe domain (#2862)

* fix: retrieve the live discovery document from the client's universe domain

* improved comment and edge case

* use template strings

* added tests

* moved universe domain helpers into own file

* changed fallback structure

* updated fallback method

* dropped NO COVER check

* address feedback

* validate compute engine credentials

* drop v1 endpoint in external universes

* applied PR feedback
diff --git a/googleapiclient/_universe.py b/googleapiclient/_universe.py
new file mode 100644
index 0000000..52c8566
--- /dev/null
+++ b/googleapiclient/_universe.py
@@ -0,0 +1,130 @@
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Universe domain compatibility helpers.
+
+Prefers ``google.api_core.universe.resolve_client_universe`` when available
+(>= 2.45.0) and falls back to a local copy for older ``google-api-core``
+releases.
+"""
+
+import collections.abc
+import os
+
+from google.api_core import client_options as client_options_lib
+from google.auth import credentials as google_auth_credentials
+
+GOOGLE_CLOUD_UNIVERSE_DOMAIN = "GOOGLE_CLOUD_UNIVERSE_DOMAIN"
+DEFAULT_UNIVERSE = "googleapis.com"
+
+
+class APICoreVersionError(ValueError):
+    def __init__(self):
+        message = (
+            "google-api-core >= 2.18.0 is required to use the universe domain feature."
+        )
+        super().__init__(message)
+
+
+try:
+    from google.api_core import universe as api_core_universe
+
+    HAS_UNIVERSE = True
+except ImportError:
+    api_core_universe = None
+    HAS_UNIVERSE = False
+
+try:
+    from google.auth.aio import credentials as _aio_credentials
+
+    _ANONYMOUS_CREDENTIAL_TYPES = (
+        google_auth_credentials.AnonymousCredentials,
+        _aio_credentials.AnonymousCredentials,
+    )
+except ImportError:  # pragma: NO COVER
+    _ANONYMOUS_CREDENTIAL_TYPES = (google_auth_credentials.AnonymousCredentials,)
+
+try:
+    from google.api_core.universe import resolve_client_universe
+except ImportError:
+    # TODO(https://github.com/googleapis/google-cloud-python/issues/19297): Replace with
+    # google.api_core.universe.resolve_client_universe once minimum allowed
+    # google-api-core version exceeds 2.44.0.
+    def resolve_client_universe(client_options=None):
+        """Resolve a client's universe domain from ``client_options`` or the environment."""
+        if client_options is None:
+            options_universe = None
+        elif isinstance(client_options, collections.abc.Mapping):
+            options_universe = client_options.get("universe_domain")
+        elif isinstance(client_options, client_options_lib.ClientOptions):
+            # Versions of google-api-core that predate universe domains (< 2.18.0)
+            # have no `universe_domain` attribute on ClientOptions.
+            options_universe = getattr(client_options, "universe_domain", None)
+        else:
+            raise TypeError(
+                "client_options must be a ClientOptions instance, Mapping, or None; "
+                f"got {type(client_options).__name__}"
+            )
+        # Strip before checking/determine_domain so surrounding whitespace is
+        # removed from non-empty values even on older google-api-core releases.
+        stripped_options = (
+            options_universe.strip()
+            if isinstance(options_universe, str)
+            else options_universe
+        )
+        env_universe = os.getenv(GOOGLE_CLOUD_UNIVERSE_DOMAIN)
+        stripped_env = (
+            env_universe.strip() if isinstance(env_universe, str) else env_universe
+        )
+        if not HAS_UNIVERSE:
+            # Older google-api-core (< 2.18.0) cannot route to non-default
+            # universes; fail before any request if a universe is configured.
+            if stripped_options is not None or (
+                stripped_env is not None and stripped_env != DEFAULT_UNIVERSE
+            ):
+                raise APICoreVersionError
+            return None
+        return api_core_universe.determine_domain(
+            stripped_options,
+            stripped_env,
+        )
+
+
+def check_api_core_compatible_with_credentials_universe(credentials):
+    """Raise APICoreVersionError if credentials require universe support."""
+    if not HAS_UNIVERSE:
+        credentials_universe = getattr(credentials, "universe_domain", None)
+        if credentials_universe and credentials_universe != DEFAULT_UNIVERSE:
+            raise APICoreVersionError
+
+
+def validate_request_credentials_universe(client_universe, credentials):
+    """Validate credentials immediately before making a network request.
+
+    Unlike ``google.api_core.universe.validate_credentials_universe`` (which
+    skips uncached Compute Engine credentials to avoid metadata server calls
+    during offline client initialization), this validates uncached Compute
+    Engine credentials as well before the outbound request is sent.
+    """
+    if not HAS_UNIVERSE:
+        # Without google.api_core.universe (< 2.18.0), the client can only
+        # target the default universe; reject non-default credentials.
+        check_api_core_compatible_with_credentials_universe(credentials)
+        return
+    if credentials is None or isinstance(credentials, _ANONYMOUS_CREDENTIAL_TYPES):
+        return
+    # Intentionally call compare_domains directly rather than
+    # google.api_core.universe.validate_credentials_universe so uncached
+    # Compute Engine credentials are checked before attaching a token.
+    api_core_universe.compare_domains(client_universe, credentials)
diff --git a/googleapiclient/discovery.py b/googleapiclient/discovery.py
index 83978f7..6819659 100644
--- a/googleapiclient/discovery.py
+++ b/googleapiclient/discovery.py
@@ -53,16 +53,15 @@
 except ImportError:  # pragma: NO COVER
     google_auth_httplib2 = None
 
-try:
-    from google.api_core import universe
-
-    HAS_UNIVERSE = True
-except ImportError:
-    HAS_UNIVERSE = False
-
 # Local imports
-from googleapiclient import _auth, mimeparse
+from googleapiclient import _auth, _universe, mimeparse
 from googleapiclient._helpers import _add_query_parameter, positional
+from googleapiclient._universe import (
+    DEFAULT_UNIVERSE,
+    GOOGLE_CLOUD_UNIVERSE_DOMAIN,
+    HAS_UNIVERSE,
+    APICoreVersionError,
+)
 from googleapiclient.errors import (
     HttpError,
     InvalidJsonError,
@@ -90,13 +89,15 @@
 
 URITEMPLATE = re.compile("{[^}]*}")
 VARNAME = re.compile("[a-zA-Z0-9_-]+")
+# Legacy V1 discovery is only supported in the default universe (googleapis.com).
 DISCOVERY_URI = (
     "https://www.googleapis.com/discovery/v1/apis/" "{api}/{apiVersion}/rest"
 )
 V1_DISCOVERY_URI = DISCOVERY_URI
-V2_DISCOVERY_URI = (
-    "https://{api}.googleapis.com/$discovery/rest?" "version={apiVersion}"
+_V2_DISCOVERY_URI_TEMPLATE = (
+    "https://{{api}}.{universe_domain}/$discovery/rest?version={{apiVersion}}"
 )
+V2_DISCOVERY_URI = _V2_DISCOVERY_URI_TEMPLATE.format(universe_domain=DEFAULT_UNIVERSE)
 DEFAULT_METHOD_DOC = "A description of how to use this function"
 HTTP_PAYLOAD_METHODS = frozenset(["PUT", "POST", "PATCH"])
 
@@ -123,22 +124,12 @@
 # Parameters controlling mTLS behavior. See https://google.aip.dev/auth/4114.
 GOOGLE_API_USE_CLIENT_CERTIFICATE = "GOOGLE_API_USE_CLIENT_CERTIFICATE"
 GOOGLE_API_USE_MTLS_ENDPOINT = "GOOGLE_API_USE_MTLS_ENDPOINT"
-GOOGLE_CLOUD_UNIVERSE_DOMAIN = "GOOGLE_CLOUD_UNIVERSE_DOMAIN"
-DEFAULT_UNIVERSE = "googleapis.com"
 # Parameters accepted by the stack, but not visible via discovery.
 # TODO(dhermes): Remove 'userip' in 'v2'.
 STACK_QUERY_PARAMETERS = frozenset(["trace", "pp", "userip", "strict"])
 STACK_QUERY_PARAMETER_DEFAULT_VALUE = {"type": "string", "location": "query"}
 
 
-class APICoreVersionError(ValueError):
-    def __init__(self):
-        message = (
-            "google-api-core >= 2.18.0 is required to use the universe domain feature."
-        )
-        super().__init__(message)
-
-
 # Library-specific reserved words beyond Python keywords.
 RESERVED_WORDS = frozenset(["body"])
 
@@ -222,7 +213,8 @@
       discoveryServiceUrl: string, a URI Template that points to the location of
         the discovery service. It should have two parameters {api} and
         {apiVersion} that when filled in produce an absolute URI to the discovery
-        document for that service.
+        document for that service. If not provided, the discovery service of the
+        client's universe domain is used.
       developerKey: string, key obtained from
         https://code.google.com/apis/console.
       model: googleapiclient.Model, converts to and from the wire format.
@@ -276,6 +268,13 @@
     Raises:
       google.auth.exceptions.MutualTLSChannelError: if there are any problems
         setting up mutual TLS channel.
+      google.api_core.universe.UniverseMismatchError: if `static_discovery` is
+        False and the credentials of `http` or `credentials` belong to a
+        different universe domain than the client.
+      google.api_core.universe.EmptyUniverseError: if the configured universe
+        domain is empty.
+      googleapiclient.discovery.APICoreVersionError: if universe features
+        are configured with `google-api-core < 2.18.0`.
     """
     params = {"api": serviceName, "apiVersion": version}
 
@@ -291,6 +290,21 @@
         else:
             static_discovery = False
 
+    # Resolve the universe domain before any request is made, so that the
+    # discovery document is retrieved from the same universe as the API.
+    universe_domain = _universe.resolve_client_universe(client_options)
+
+    if not static_discovery:
+        # Validate any in-memory credentials before retrieving the discovery
+        # document over the network (raises UniverseMismatchError, or
+        # APICoreVersionError when google-api-core < 2.18.0).
+        credentials_to_validate = (
+            getattr(http, "credentials", None) if http is not None else credentials
+        )
+        _universe.validate_request_credentials_universe(
+            universe_domain, credentials_to_validate
+        )
+
     if http is None:
         discovery_http = build_http()
     else:
@@ -298,7 +312,9 @@
 
     service = None
 
-    for discovery_url in _discovery_service_uri_options(discoveryServiceUrl, version):
+    for discovery_url in _discovery_service_uri_options(
+        discoveryServiceUrl, version, universe_domain
+    ):
         requested_url = uritemplate.expand(discovery_url, params)
 
         try:
@@ -344,7 +360,7 @@
         return service
 
 
-def _discovery_service_uri_options(discoveryServiceUrl, version):
+def _discovery_service_uri_options(discoveryServiceUrl, version, universe_domain=None):
     """
       Returns Discovery URIs to be used for attempting to build the API Resource.
 
@@ -353,6 +369,10 @@
           string, the Original Discovery Service URL preferred by the customer.
       version:
           string, API Version requested
+      universe_domain:
+          string, the universe domain of the client. The default Discovery URIs
+          are returned for this universe domain. A non-empty
+          `discoveryServiceUrl` is returned unchanged.
 
     Returns:
         A list of URIs to be tried for the Service Discovery, in order.
@@ -360,6 +380,11 @@
 
     if discoveryServiceUrl is not None:
         return [discoveryServiceUrl]
+    if universe_domain and universe_domain != DEFAULT_UNIVERSE:
+        # Legacy V1 discovery (www.<domain>/discovery/v1/...) is only supported
+        # in the default universe; non-default universes serve discovery from
+        # the per-service V2 endpoint.
+        return [_V2_DISCOVERY_URI_TEMPLATE.format(universe_domain=universe_domain)]
     if version is None:
         # V1 Discovery won't work if the requested version is None
         logger.warning(
@@ -454,13 +479,6 @@
     return content
 
 
-def _check_api_core_compatible_with_credentials_universe(credentials):
-    if not HAS_UNIVERSE:
-        credentials_universe = getattr(credentials, "universe_domain", None)
-        if credentials_universe and credentials_universe != DEFAULT_UNIVERSE:
-            raise APICoreVersionError
-
-
 @positional(1)
 def build_from_document(
     service,
@@ -569,17 +587,9 @@
 
     # If an API Endpoint is provided on client options, use that as the base URL
     base = urllib.parse.urljoin(service["rootUrl"], service["servicePath"])
-    universe_domain = None
-    if HAS_UNIVERSE:
-        universe_domain_env = os.getenv(GOOGLE_CLOUD_UNIVERSE_DOMAIN, None)
-        universe_domain = universe.determine_domain(
-            client_options.universe_domain, universe_domain_env
-        )
-        base = base.replace(universe.DEFAULT_UNIVERSE, universe_domain)
-    else:
-        client_universe = getattr(client_options, "universe_domain", None)
-        if client_universe:
-            raise APICoreVersionError
+    universe_domain = _universe.resolve_client_universe(client_options)
+    if _universe.HAS_UNIVERSE:
+        base = base.replace(DEFAULT_UNIVERSE, universe_domain)
 
     audience_for_self_signed_jwt = base
     if client_options.api_endpoint:
@@ -620,7 +630,7 @@
                 )
 
             # Check google-api-core >= 2.18.0 if credentials' universe != "googleapis.com".
-            _check_api_core_compatible_with_credentials_universe(credentials)
+            _universe.check_api_core_compatible_with_credentials_universe(credentials)
 
             # The credentials need to be scoped.
             # If the user provided scopes via client_options don't override them
@@ -713,15 +723,15 @@
             if use_mtls_endpoint == "always" or (
                 use_mtls_endpoint == "auto" and client_cert_to_use
             ):
-                if HAS_UNIVERSE and universe_domain != universe.DEFAULT_UNIVERSE:
+                if _universe.HAS_UNIVERSE and universe_domain != DEFAULT_UNIVERSE:
                     raise MutualTLSChannelError(
-                        f"mTLS is not supported in any universe other than {universe.DEFAULT_UNIVERSE}."
+                        f"mTLS is not supported in any universe other than {DEFAULT_UNIVERSE}."
                     )
                 base = mtls_endpoint
     else:
         # Check google-api-core >= 2.18.0 if credentials' universe != "googleapis.com".
         http_credentials = getattr(http, "credentials", None)
-        _check_api_core_compatible_with_credentials_universe(http_credentials)
+        _universe.check_api_core_compatible_with_credentials_universe(http_credentials)
 
     if model is None:
         features = service.get("features", [])
@@ -1413,7 +1423,7 @@
         resourceDesc,
         rootDesc,
         schema,
-        universe_domain=universe.DEFAULT_UNIVERSE if HAS_UNIVERSE else "",
+        universe_domain=DEFAULT_UNIVERSE if _universe.HAS_UNIVERSE else "",
     ):
         """Build a Resource from the API description.
 
@@ -1630,9 +1640,11 @@
         self._credentials_validated = (
             (
                 self._credentials_validated
-                or universe.compare_domains(self._universe_domain, credentials)
+                or _universe.api_core_universe.compare_domains(
+                    self._universe_domain, credentials
+                )
             )
-            if HAS_UNIVERSE
+            if _universe.HAS_UNIVERSE
             else True
         )
         return self._credentials_validated
diff --git a/tests/test__universe.py b/tests/test__universe.py
new file mode 100644
index 0000000..1891c0d
--- /dev/null
+++ b/tests/test__universe.py
@@ -0,0 +1,325 @@
+# Copyright 2026 Google LLC
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Unit tests for googleapiclient._universe."""
+
+import importlib.util
+import os
+import types
+import unittest
+from unittest import mock
+
+import google.api_core
+import google.api_core.client_options
+import google.auth.compute_engine
+import google.auth.credentials
+from parameterized import parameterized
+import pytest
+
+from googleapiclient import _universe
+
+try:
+    from google.api_core import universe
+
+    HAS_UNIVERSE = True
+except ImportError:
+    HAS_UNIVERSE = False
+
+
+def _make_credentials(universe_domain):
+    credentials = mock.Mock(spec=google.auth.credentials.Credentials)
+    credentials.universe_domain = universe_domain
+    return credentials
+
+
+def _load_universe_module_with_fallbacks():
+    """Load an isolated copy of ``_universe`` simulating ``google-api-core < 2.45.0``."""
+    spec = importlib.util.spec_from_file_location(
+        "_universe_fallback_test", _universe.__file__
+    )
+    module = importlib.util.module_from_spec(spec)
+    legacy_universe = types.SimpleNamespace(
+        DEFAULT_UNIVERSE=universe.DEFAULT_UNIVERSE,
+        determine_domain=universe.determine_domain,
+        compare_domains=universe.compare_domains,
+    )
+    with mock.patch.dict(
+        "sys.modules", {"google.api_core.universe": legacy_universe}
+    ), mock.patch.object(google.api_core, "universe", legacy_universe, create=True):
+        spec.loader.exec_module(module)
+    module.APICoreVersionError = _universe.APICoreVersionError
+    return module
+
+
+def _load_universe_module_without_universe():
+    """Load an isolated copy of ``_universe`` simulating ``google-api-core < 2.18.0``."""
+    spec = importlib.util.spec_from_file_location(
+        "_universe_no_universe_test", _universe.__file__
+    )
+    module = importlib.util.module_from_spec(spec)
+    with mock.patch.dict(
+        "sys.modules", {"google.api_core.universe": None}
+    ), mock.patch.dict(google.api_core.__dict__):
+        google.api_core.__dict__.pop("universe", None)
+        spec.loader.exec_module(module)
+    module.APICoreVersionError = _universe.APICoreVersionError
+    return module
+
+
+@unittest.skipUnless(HAS_UNIVERSE, "google-api-core >= 2.18.0 is required")
+class UniverseHelpersTest(unittest.TestCase):
+    FAKE_UNIVERSE = "foo.com"
+
+    @classmethod
+    def setUpClass(cls):
+        cls.fallback_universe = _load_universe_module_with_fallbacks()
+
+    def setUp(self):
+        environ_patcher = mock.patch.dict("os.environ")
+        environ_patcher.start()
+        self.addCleanup(environ_patcher.stop)
+        os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None)
+        os.environ.pop("GOOGLE_API_USE_MTLS_ENDPOINT", None)
+
+    def test_prefers_upstream_resolve_client_universe_when_available(self):
+        if hasattr(universe, "resolve_client_universe"):
+            self.assertIs(
+                _universe.resolve_client_universe, universe.resolve_client_universe
+            )
+
+    @parameterized.expand(
+        [
+            ("defaults_to_default_universe", lambda: None, None, "googleapis.com"),
+            ("env_var_fallback", lambda: None, "foo.com", "foo.com"),
+            (
+                "dict_options",
+                lambda: {"universe_domain": "foo.com"},
+                None,
+                "foo.com",
+            ),
+            (
+                "mapping_proxy_options",
+                lambda: types.MappingProxyType({"universe_domain": "foo.com"}),
+                None,
+                "foo.com",
+            ),
+            (
+                "client_options_instance",
+                lambda: google.api_core.client_options.ClientOptions(
+                    universe_domain="foo.com"
+                ),
+                None,
+                "foo.com",
+            ),
+            (
+                "explicit_default_universe_overrides_env",
+                lambda: {"universe_domain": "googleapis.com"},
+                "foo.com",
+                "googleapis.com",
+            ),
+            (
+                "empty_client_options_falls_back_to_env",
+                lambda: google.api_core.client_options.ClientOptions(),
+                "foo.com",
+                "foo.com",
+            ),
+            (
+                "strips_whitespace_in_dict_universe",
+                lambda: {"universe_domain": " foo.com "},
+                None,
+                "foo.com",
+            ),
+            (
+                "strips_whitespace_in_env_universe",
+                lambda: None,
+                " foo.com ",
+                "foo.com",
+            ),
+        ]
+    )
+    def test_resolve_client_universe_precedence(
+        self, _, make_client_options, env_value, expected
+    ):
+        if env_value is not None:
+            os.environ["GOOGLE_CLOUD_UNIVERSE_DOMAIN"] = env_value
+
+        for fn in (
+            _universe.resolve_client_universe,
+            self.fallback_universe.resolve_client_universe,
+        ):
+            self.assertEqual(fn(make_client_options()), expected)
+
+    @parameterized.expand(
+        [
+            ("empty_dict_universe", lambda: {"universe_domain": ""}, None),
+            (
+                "empty_client_options_universe",
+                lambda: google.api_core.client_options.ClientOptions(
+                    universe_domain=""
+                ),
+                None,
+            ),
+            ("empty_env_universe", lambda: None, ""),
+            ("whitespace_dict_universe", lambda: {"universe_domain": "   "}, None),
+            ("whitespace_env_universe", lambda: None, "   "),
+        ]
+    )
+    def test_resolve_client_universe_empty_raises(
+        self, _, make_client_options, env_value
+    ):
+        if env_value is not None:
+            os.environ["GOOGLE_CLOUD_UNIVERSE_DOMAIN"] = env_value
+
+        for fn in (
+            _universe.resolve_client_universe,
+            self.fallback_universe.resolve_client_universe,
+        ):
+            with self.assertRaises(universe.EmptyUniverseError):
+                fn(make_client_options())
+
+    def test_resolve_client_universe_invalid_type_raises(self):
+        for fn in (
+            _universe.resolve_client_universe,
+            self.fallback_universe.resolve_client_universe,
+        ):
+            with self.assertRaises(TypeError):
+                fn("invalid")
+
+    def test_validate_request_credentials_universe_accepts_matching_and_exempt(self):
+        _universe.validate_request_credentials_universe(self.FAKE_UNIVERSE, None)
+        _universe.validate_request_credentials_universe(
+            self.FAKE_UNIVERSE, google.auth.credentials.AnonymousCredentials()
+        )
+        _universe.validate_request_credentials_universe(
+            self.FAKE_UNIVERSE, _make_credentials(self.FAKE_UNIVERSE)
+        )
+
+    def test_validate_request_credentials_universe_exempts_aio_anonymous(self):
+        aio_credentials = pytest.importorskip("google.auth.aio.credentials")
+        _universe.validate_request_credentials_universe(
+            self.FAKE_UNIVERSE, aio_credentials.AnonymousCredentials()
+        )
+
+    def test_validate_request_credentials_universe_mismatch_raises(self):
+        with self.assertRaises(universe.UniverseMismatchError):
+            _universe.validate_request_credentials_universe(
+                self.FAKE_UNIVERSE, _make_credentials("googleapis.com")
+            )
+
+    @unittest.skipUnless(
+        hasattr(google.auth.compute_engine.Credentials, "universe_domain"),
+        "google-auth >= 2.28.0 is required",
+    )
+    def test_validate_request_credentials_universe_checks_uncached_compute_engine(self):
+        gce_credentials = google.auth.compute_engine.Credentials()
+        gce_credentials._universe_domain_cached = False
+        with mock.patch.object(
+            google.auth.compute_engine.Credentials,
+            "universe_domain",
+            new_callable=mock.PropertyMock,
+            return_value="googleapis.com",
+        ) as mock_universe_domain:
+            with self.assertRaises(universe.UniverseMismatchError):
+                _universe.validate_request_credentials_universe(
+                    self.FAKE_UNIVERSE, gce_credentials
+                )
+        mock_universe_domain.assert_called_once_with()
+
+
+class UniverseHelpersWithoutUniverseSupportTest(unittest.TestCase):
+    FAKE_UNIVERSE = "foo.com"
+
+    @classmethod
+    def setUpClass(cls):
+        cls.legacy_universe = _load_universe_module_without_universe()
+
+    def setUp(self):
+        environ_patcher = mock.patch.dict("os.environ")
+        environ_patcher.start()
+        self.addCleanup(environ_patcher.stop)
+        os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None)
+        os.environ.pop("GOOGLE_API_USE_MTLS_ENDPOINT", None)
+
+    def test_has_universe_is_false(self):
+        self.assertFalse(self.legacy_universe.HAS_UNIVERSE)
+
+    def test_resolve_client_universe_defaults_to_none(self):
+        self.assertIsNone(self.legacy_universe.resolve_client_universe())
+        self.assertIsNone(self.legacy_universe.resolve_client_universe({}))
+        self.assertIsNone(
+            self.legacy_universe.resolve_client_universe(
+                google.api_core.client_options.ClientOptions()
+            )
+        )
+        with mock.patch.dict(
+            "os.environ", {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "googleapis.com"}
+        ):
+            self.assertIsNone(self.legacy_universe.resolve_client_universe())
+        with mock.patch.dict(
+            "os.environ", {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": " googleapis.com "}
+        ):
+            self.assertIsNone(self.legacy_universe.resolve_client_universe())
+
+    def test_resolve_client_universe_raises_on_configured_universe(self):
+        with mock.patch.dict(
+            "os.environ", {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": self.FAKE_UNIVERSE}
+        ):
+            with self.assertRaises(_universe.APICoreVersionError):
+                self.legacy_universe.resolve_client_universe()
+        with mock.patch.dict("os.environ", {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": ""}):
+            with self.assertRaises(_universe.APICoreVersionError):
+                self.legacy_universe.resolve_client_universe()
+        with self.assertRaises(_universe.APICoreVersionError):
+            self.legacy_universe.resolve_client_universe(
+                {"universe_domain": self.FAKE_UNIVERSE}
+            )
+        with self.assertRaises(_universe.APICoreVersionError):
+            self.legacy_universe.resolve_client_universe({"universe_domain": ""})
+        if hasattr(google.api_core.client_options.ClientOptions, "universe_domain"):
+            with self.assertRaises(_universe.APICoreVersionError):
+                self.legacy_universe.resolve_client_universe(
+                    google.api_core.client_options.ClientOptions(
+                        universe_domain=self.FAKE_UNIVERSE
+                    )
+                )
+            with self.assertRaises(_universe.APICoreVersionError):
+                self.legacy_universe.resolve_client_universe(
+                    google.api_core.client_options.ClientOptions(universe_domain="")
+                )
+
+    def test_check_api_core_compatible_with_credentials_universe(self):
+        self.legacy_universe.check_api_core_compatible_with_credentials_universe(None)
+        self.legacy_universe.check_api_core_compatible_with_credentials_universe(
+            _make_credentials("googleapis.com")
+        )
+        with self.assertRaises(_universe.APICoreVersionError):
+            self.legacy_universe.check_api_core_compatible_with_credentials_universe(
+                _make_credentials(self.FAKE_UNIVERSE)
+            )
+
+    def test_validate_request_credentials_universe_delegates_without_universe_support(
+        self,
+    ):
+        self.legacy_universe.validate_request_credentials_universe(None, None)
+        self.legacy_universe.validate_request_credentials_universe(
+            None, _make_credentials("googleapis.com")
+        )
+        with self.assertRaises(_universe.APICoreVersionError):
+            self.legacy_universe.validate_request_credentials_universe(
+                None, _make_credentials(self.FAKE_UNIVERSE)
+            )
+
+
+if __name__ == "__main__":
+    unittest.main()
diff --git a/tests/test_discovery.py b/tests/test_discovery.py
index 6e9ba2c..d2b71e3 100644
--- a/tests/test_discovery.py
+++ b/tests/test_discovery.py
@@ -27,6 +27,7 @@
 from collections import defaultdict
 import copy
 import datetime
+import importlib.util
 import io
 import itertools
 import json
@@ -38,8 +39,10 @@
 from unittest import mock
 import urllib
 
+import google.api_core
 import google.api_core.exceptions
 from google.auth import __version__ as auth_version
+import google.auth.compute_engine
 import google.auth.credentials
 from google.auth.exceptions import MutualTLSChannelError
 import google_auth_httplib2
@@ -64,6 +67,7 @@
     HAS_UNIVERSE = False
 
 from googleapiclient import _helpers as util
+from googleapiclient import _universe
 from googleapiclient.discovery import (
     DISCOVERY_URI,
     MEDIA_BODY_PARAMETER_DEFAULT_VALUE,
@@ -1373,6 +1377,485 @@
         validate_discovery_requests(self, http, "zoo", "v123", V1_DISCOVERY_URI)
 
 
+def _make_universe_credentials(universe_domain):
+    credentials = mock.Mock(spec=google.auth.credentials.Credentials)
+    credentials.universe_domain = universe_domain
+    return credentials
+
+
+def _requested_uris(http_mock):
+    return [request[0] for request in http_mock.request_sequence]
+
+
+@unittest.skipUnless(HAS_UNIVERSE, "google-api-core >= 2.18.0 is required")
+class DiscoveryFromHttpUniverse(unittest.TestCase):
+    """The live discovery document is retrieved from the client's universe."""
+
+    FAKE_UNIVERSE = "foo.com"
+    V2_URI = "https://zoo.foo.com/$discovery/rest?version=v1"
+
+    def setUp(self):
+        environ_patcher = mock.patch.dict("os.environ")
+        environ_patcher.start()
+        self.addCleanup(environ_patcher.stop)
+        os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None)
+        os.environ.pop("GOOGLE_API_USE_MTLS_ENDPOINT", None)
+        os.environ.pop("REMOTE_ADDR", None)
+
+    @parameterized.expand(
+        [
+            ("dict", lambda universe_domain: {"universe_domain": universe_domain}),
+            (
+                "client_options",
+                lambda universe_domain: google.api_core.client_options.ClientOptions(
+                    universe_domain=universe_domain
+                ),
+            ),
+        ]
+    )
+    def test_client_options_universe(self, _, make_client_options):
+        http = HttpMockSequence([({"status": "200"}, read_datafile("zoo.json", "rb"))])
+        zoo = build(
+            "zoo",
+            "v1",
+            http=http,
+            cache_discovery=False,
+            client_options=make_client_options(self.FAKE_UNIVERSE),
+            static_discovery=False,
+        )
+        self.assertEqual(_requested_uris(http), [self.V2_URI])
+        self.assertEqual(zoo._universe_domain, self.FAKE_UNIVERSE)
+        self.assertEqual(zoo._baseUrl, "https://www.foo.com/zoo/v1/")
+
+    def test_universe_env_var(self):
+        http = HttpMockSequence([({"status": "200"}, read_datafile("zoo.json", "rb"))])
+        with mock.patch.dict(
+            "os.environ", {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": self.FAKE_UNIVERSE}
+        ):
+            zoo = build(
+                "zoo",
+                "v1",
+                http=http,
+                cache_discovery=False,
+                static_discovery=False,
+            )
+        self.assertEqual(_requested_uris(http), [self.V2_URI])
+        self.assertEqual(zoo._universe_domain, self.FAKE_UNIVERSE)
+
+    def test_client_options_universe_overrides_env_var(self):
+        http = HttpMockSequence([({"status": "200"}, read_datafile("zoo.json", "rb"))])
+        with mock.patch.dict(
+            "os.environ", {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": self.FAKE_UNIVERSE}
+        ):
+            build(
+                "zoo",
+                "v1",
+                http=http,
+                cache_discovery=False,
+                client_options={"universe_domain": universe.DEFAULT_UNIVERSE},
+                static_discovery=False,
+            )
+        validate_discovery_requests(self, http, "zoo", "v1", V1_DISCOVERY_URI)
+
+    def test_universe_with_empty_version_uses_v2(self):
+        http = HttpMockSequence([({"status": "200"}, read_datafile("zoo.json", "rb"))])
+        build(
+            "zoo",
+            version=None,
+            http=http,
+            cache_discovery=False,
+            client_options={"universe_domain": self.FAKE_UNIVERSE},
+            static_discovery=False,
+        )
+        validate_discovery_requests(
+            self,
+            http,
+            "zoo",
+            None,
+            "https://{api}.foo.com/$discovery/rest?version={apiVersion}",
+        )
+        self.assertEqual(len(http.request_sequence), 1)
+
+    def test_universe_preserves_custom_discovery_uri(self):
+        http = HttpMockSequence([({"status": "200"}, read_datafile("zoo.json", "rb"))])
+        custom_discovery_uri = "https://discovery.example.com/{api}/{apiVersion}"
+        build(
+            "zoo",
+            "v1",
+            http=http,
+            cache_discovery=False,
+            discoveryServiceUrl=custom_discovery_uri,
+            client_options={"universe_domain": self.FAKE_UNIVERSE},
+            static_discovery=False,
+        )
+        self.assertEqual(
+            _requested_uris(http), ["https://discovery.example.com/zoo/v1"]
+        )
+
+    def test_developer_key_is_sent_to_universe(self):
+        http = HttpMockSequence([({"status": "400"}, read_datafile("zoo.json", "rb"))])
+        with self.assertRaises(HttpError) as exc_info:
+            build(
+                "zoo",
+                "v1",
+                http=http,
+                developerKey="foo",
+                cache_discovery=False,
+                client_options={"universe_domain": self.FAKE_UNIVERSE},
+                static_discovery=False,
+            )
+        assertUrisEqual(self, self.V2_URI + "&key=foo", exc_info.exception.uri)
+        self.assertEqual(len(http.request_sequence), 1)
+        assertUrisEqual(self, self.V2_URI + "&key=foo", _requested_uris(http)[0])
+
+    def test_discovery_cache_is_keyed_by_universe(self):
+        cache = mock.Mock(spec=Cache)
+        cache.get.return_value = None
+        http = HttpMockSequence([({"status": "200"}, read_datafile("zoo.json", "rb"))])
+        build(
+            "zoo",
+            "v1",
+            http=http,
+            cache=cache,
+            client_options={"universe_domain": self.FAKE_UNIVERSE},
+            static_discovery=False,
+        )
+        cache.get.assert_called_once_with(self.V2_URI)
+        cache.set.assert_called_once_with(self.V2_URI, mock.ANY)
+
+    def test_empty_universe_raises_before_discovery(self):
+        http = HttpMockSequence([])
+        with self.assertRaises(universe.EmptyUniverseError):
+            build(
+                "zoo",
+                "v1",
+                http=http,
+                cache_discovery=False,
+                client_options={"universe_domain": ""},
+                static_discovery=False,
+            )
+        with mock.patch.dict("os.environ", {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": ""}):
+            with self.assertRaises(universe.EmptyUniverseError):
+                build(
+                    "zoo",
+                    "v1",
+                    http=http,
+                    cache_discovery=False,
+                    static_discovery=False,
+                )
+        self.assertEqual(http.request_sequence, [])
+
+    def test_http_credentials_in_client_universe(self):
+        credentials = _make_universe_credentials(self.FAKE_UNIVERSE)
+        http_mock = HttpMockSequence(
+            [({"status": "200"}, read_datafile("zoo.json", "rb"))]
+        )
+        http = google_auth_httplib2.AuthorizedHttp(credentials, http=http_mock)
+        zoo = build(
+            "zoo",
+            "v1",
+            http=http,
+            cache_discovery=False,
+            client_options={"universe_domain": self.FAKE_UNIVERSE},
+            static_discovery=False,
+        )
+        self.assertEqual(_requested_uris(http_mock), [self.V2_URI])
+        self.assertTrue(zoo._validate_credentials())
+
+    def test_http_credentials_in_default_universe(self):
+        credentials = _make_universe_credentials(universe.DEFAULT_UNIVERSE)
+        http_mock = HttpMockSequence(
+            [({"status": "200"}, read_datafile("zoo.json", "rb"))]
+        )
+        http = google_auth_httplib2.AuthorizedHttp(credentials, http=http_mock)
+        build("zoo", "v1", http=http, cache_discovery=False, static_discovery=False)
+        validate_discovery_requests(self, http_mock, "zoo", "v1", V1_DISCOVERY_URI)
+
+    @parameterized.expand(
+        [
+            ("credentials_universe_on_default_client", "foo.com", None),
+            (
+                "default_credentials_on_universe_client",
+                "googleapis.com",
+                {"universe_domain": "foo.com"},
+            ),
+            (
+                "credentials_universe_on_another_universe_client",
+                "foo.com",
+                {"universe_domain": "bar.com"},
+            ),
+        ]
+    )
+    def test_http_credentials_universe_mismatch_raises_before_discovery(
+        self, _, credentials_universe, client_options
+    ):
+        credentials = _make_universe_credentials(credentials_universe)
+        http_mock = HttpMockSequence([])
+        http = google_auth_httplib2.AuthorizedHttp(credentials, http=http_mock)
+        with self.assertRaises(universe.UniverseMismatchError):
+            build(
+                "zoo",
+                "v1",
+                http=http,
+                developerKey="foo",
+                cache_discovery=False,
+                client_options=client_options,
+                static_discovery=False,
+            )
+        self.assertEqual(http_mock.request_sequence, [])
+        credentials.before_request.assert_not_called()
+
+    def test_http_credentials_universe_mismatch_with_env_var(self):
+        credentials = _make_universe_credentials(universe.DEFAULT_UNIVERSE)
+        http_mock = HttpMockSequence([])
+        http = google_auth_httplib2.AuthorizedHttp(credentials, http=http_mock)
+        with mock.patch.dict(
+            "os.environ", {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": self.FAKE_UNIVERSE}
+        ):
+            with self.assertRaises(universe.UniverseMismatchError):
+                build(
+                    "zoo",
+                    "v1",
+                    http=http,
+                    cache_discovery=False,
+                    static_discovery=False,
+                )
+        self.assertEqual(http_mock.request_sequence, [])
+        credentials.before_request.assert_not_called()
+
+    def test_http_anonymous_credentials_in_universe(self):
+        http_mock = HttpMockSequence(
+            [({"status": "200"}, read_datafile("zoo.json", "rb"))]
+        )
+        http = google_auth_httplib2.AuthorizedHttp(
+            google.auth.credentials.AnonymousCredentials(), http=http_mock
+        )
+        zoo = build(
+            "zoo",
+            "v1",
+            http=http,
+            cache_discovery=False,
+            client_options={"universe_domain": self.FAKE_UNIVERSE},
+            static_discovery=False,
+        )
+        self.assertEqual(_requested_uris(http_mock), [self.V2_URI])
+        self.assertEqual(zoo._universe_domain, self.FAKE_UNIVERSE)
+
+    @unittest.skipUnless(
+        hasattr(google.auth.compute_engine.Credentials, "universe_domain"),
+        "google-auth >= 2.28.0 is required",
+    )
+    def test_http_uncached_compute_engine_credentials_mismatch_raises_before_discovery(
+        self,
+    ):
+        gce_credentials = google.auth.compute_engine.Credentials()
+        gce_credentials._universe_domain_cached = False
+        gce_credentials.before_request = mock.Mock()
+        http_mock = HttpMockSequence([])
+        http = google_auth_httplib2.AuthorizedHttp(gce_credentials, http=http_mock)
+        with mock.patch.object(
+            google.auth.compute_engine.Credentials,
+            "universe_domain",
+            new_callable=mock.PropertyMock,
+            return_value=self.FAKE_UNIVERSE,
+        ) as mock_universe_domain:
+            with self.assertRaises(universe.UniverseMismatchError):
+                build(
+                    "zoo",
+                    "v1",
+                    http=http,
+                    cache_discovery=False,
+                    static_discovery=False,
+                )
+        mock_universe_domain.assert_called_once_with()
+        self.assertEqual(http_mock.request_sequence, [])
+        gce_credentials.before_request.assert_not_called()
+
+    def test_credentials_argument_in_universe(self):
+        credentials = _make_universe_credentials(self.FAKE_UNIVERSE)
+        discovery_http = HttpMockSequence(
+            [({"status": "200"}, read_datafile("zoo.json", "rb"))]
+        )
+        discovery_http.close = mock.Mock()
+        with mock.patch(
+            "googleapiclient.discovery.build_http", return_value=discovery_http
+        ):
+            zoo = build(
+                "zoo",
+                "v1",
+                credentials=credentials,
+                cache_discovery=False,
+                client_options={"universe_domain": self.FAKE_UNIVERSE},
+                static_discovery=False,
+            )
+        self.assertEqual(_requested_uris(discovery_http), [self.V2_URI])
+        # The discovery document is retrieved without credentials.
+        credentials.before_request.assert_not_called()
+        discovery_http.close.assert_called_once_with()
+        self.assertTrue(zoo._validate_credentials())
+
+    @parameterized.expand(
+        [
+            ("credentials_universe_on_default_client", "foo.com", None),
+            (
+                "default_credentials_on_universe_client",
+                "googleapis.com",
+                {"universe_domain": "foo.com"},
+            ),
+            (
+                "credentials_universe_on_another_universe_client",
+                "foo.com",
+                {"universe_domain": "bar.com"},
+            ),
+        ]
+    )
+    def test_credentials_argument_universe_mismatch_raises_before_discovery(
+        self, _, credentials_universe, client_options
+    ):
+        credentials = _make_universe_credentials(credentials_universe)
+        with mock.patch("googleapiclient.discovery.build_http") as build_http_mock:
+            with self.assertRaises(universe.UniverseMismatchError):
+                build(
+                    "zoo",
+                    "v1",
+                    credentials=credentials,
+                    developerKey="foo",
+                    cache_discovery=False,
+                    client_options=client_options,
+                    static_discovery=False,
+                )
+        build_http_mock.assert_not_called()
+        credentials.before_request.assert_not_called()
+
+
+class DiscoveryFromHttpWithoutUniverseSupport(unittest.TestCase):
+    """Live discovery with a google-api-core version that predates universes."""
+
+    @classmethod
+    def setUpClass(cls):
+        spec = importlib.util.spec_from_file_location(
+            "_universe_no_universe_discovery_test", _universe.__file__
+        )
+        module = importlib.util.module_from_spec(spec)
+        with mock.patch.dict(
+            "sys.modules", {"google.api_core.universe": None}
+        ), mock.patch.dict(google.api_core.__dict__):
+            google.api_core.__dict__.pop("universe", None)
+            spec.loader.exec_module(module)
+        module.APICoreVersionError = APICoreVersionError
+        cls.legacy_universe = module
+
+    def setUp(self):
+        environ_patcher = mock.patch.dict("os.environ")
+        environ_patcher.start()
+        self.addCleanup(environ_patcher.stop)
+        os.environ.pop("GOOGLE_CLOUD_UNIVERSE_DOMAIN", None)
+        os.environ.pop("GOOGLE_API_USE_MTLS_ENDPOINT", None)
+
+        universe_patcher = mock.patch(
+            "googleapiclient.discovery._universe", self.legacy_universe
+        )
+        universe_patcher.start()
+        self.addCleanup(universe_patcher.stop)
+
+    def test_default_universe(self):
+        credentials = _make_universe_credentials("googleapis.com")
+        http_mock = HttpMockSequence(
+            [({"status": "200"}, read_datafile("zoo.json", "rb"))]
+        )
+        http = google_auth_httplib2.AuthorizedHttp(credentials, http=http_mock)
+        zoo = build(
+            "zoo", "v1", http=http, cache_discovery=False, static_discovery=False
+        )
+        validate_discovery_requests(self, http_mock, "zoo", "v1", V1_DISCOVERY_URI)
+        self.assertTrue(hasattr(zoo, "animals"))
+
+    def test_http_credentials_universe_raises_before_discovery(self):
+        credentials = _make_universe_credentials("foo.com")
+        http_mock = HttpMockSequence([])
+        http = google_auth_httplib2.AuthorizedHttp(credentials, http=http_mock)
+        with self.assertRaises(APICoreVersionError):
+            build("zoo", "v1", http=http, cache_discovery=False, static_discovery=False)
+        self.assertEqual(http_mock.request_sequence, [])
+        credentials.before_request.assert_not_called()
+
+    def test_credentials_argument_universe_raises_before_discovery(self):
+        credentials = _make_universe_credentials("foo.com")
+        with mock.patch("googleapiclient.discovery.build_http") as build_http_mock:
+            with self.assertRaises(APICoreVersionError):
+                build(
+                    "zoo",
+                    "v1",
+                    credentials=credentials,
+                    developerKey="foo",
+                    cache_discovery=False,
+                    static_discovery=False,
+                )
+        build_http_mock.assert_not_called()
+        credentials.before_request.assert_not_called()
+
+    def test_client_options_universe_raises_before_discovery(self):
+        http = HttpMockSequence([])
+        with self.assertRaises(APICoreVersionError):
+            build(
+                "zoo",
+                "v1",
+                http=http,
+                developerKey="foo",
+                cache_discovery=False,
+                client_options={"universe_domain": "foo.com"},
+                static_discovery=False,
+            )
+        self.assertEqual(http.request_sequence, [])
+
+    def test_empty_universe_raises_before_discovery(self):
+        http = HttpMockSequence([])
+        with self.assertRaises(APICoreVersionError):
+            build(
+                "zoo",
+                "v1",
+                http=http,
+                cache_discovery=False,
+                client_options={"universe_domain": ""},
+                static_discovery=False,
+            )
+        with mock.patch.dict("os.environ", {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": ""}):
+            with self.assertRaises(APICoreVersionError):
+                build(
+                    "zoo",
+                    "v1",
+                    http=http,
+                    cache_discovery=False,
+                    static_discovery=False,
+                )
+        self.assertEqual(http.request_sequence, [])
+
+    def test_universe_env_var_raises_before_discovery(self):
+        http = HttpMockSequence([])
+        with mock.patch.dict("os.environ", {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "foo.com"}):
+            with self.assertRaises(APICoreVersionError):
+                build(
+                    "zoo",
+                    "v1",
+                    http=http,
+                    developerKey="foo",
+                    cache_discovery=False,
+                    static_discovery=False,
+                )
+        self.assertEqual(http.request_sequence, [])
+
+    def test_universe_env_var_default_universe_succeeds(self):
+        http = HttpMockSequence([({"status": "200"}, read_datafile("zoo.json", "rb"))])
+        with mock.patch.dict(
+            "os.environ", {"GOOGLE_CLOUD_UNIVERSE_DOMAIN": "googleapis.com"}
+        ):
+            zoo = build(
+                "zoo", "v1", http=http, cache_discovery=False, static_discovery=False
+            )
+        validate_discovery_requests(self, http, "zoo", "v1", V1_DISCOVERY_URI)
+        self.assertTrue(hasattr(zoo, "animals"))
+
+
 class DiscoveryRetryFromHttp(unittest.TestCase):
     def test_repeated_500_retries_and_fails(self):
         http = HttpMockSequence(