From 3eb145dd210912da477b071cab5ef2a1a48572f9 Mon Sep 17 00:00:00 2001 From: Daniel Sanche Date: Fri, 4 Dec 2026 12:39:16 -0700 Subject: [PATCH 01/12] fix: validate universes for custom http transports --- googleapiclient/_universe.py | 21 +- googleapiclient/discovery.py | 24 +- googleapiclient/http.py | 63 ++++- tests/test__universe.py | 31 ++- tests/test_discovery.py | 3 + tests/test_http.py | 491 ++++++++++++++++++++++++++++++++++- 6 files changed, 606 insertions(+), 27 deletions(-) diff --git a/googleapiclient/_universe.py b/googleapiclient/_universe.py index 52c8566259..7e27e7df8e 100644 --- a/googleapiclient/_universe.py +++ b/googleapiclient/_universe.py @@ -109,7 +109,9 @@ def check_api_core_compatible_with_credentials_universe(credentials): raise APICoreVersionError -def validate_request_credentials_universe(client_universe, credentials): +def validate_request_credentials_universe( + client_universe, credentials, allow_none=True +): """Validate credentials immediately before making a network request. Unlike ``google.api_core.universe.validate_credentials_universe`` (which @@ -119,12 +121,19 @@ def validate_request_credentials_universe(client_universe, credentials): """ if not HAS_UNIVERSE: # Without google.api_core.universe (< 2.18.0), the client can only - # target the default universe; reject non-default credentials. + # target the default universe; reject non-default credentials even when + # client_universe is None. check_api_core_compatible_with_credentials_universe(credentials) - return - if credentials is None or isinstance(credentials, _ANONYMOUS_CREDENTIAL_TYPES): - return + return True + if client_universe is None: + # Standalone HttpRequest / custom BatchHttpRequest without a Resource + # universe domain have no client universe to compare against. + return True + if isinstance(credentials, _ANONYMOUS_CREDENTIAL_TYPES) or ( + allow_none and credentials is None + ): + return True # 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) + return api_core_universe.compare_domains(client_universe, credentials) diff --git a/googleapiclient/discovery.py b/googleapiclient/discovery.py index 6819659968..82b1cf2a43 100644 --- a/googleapiclient/discovery.py +++ b/googleapiclient/discovery.py @@ -1274,7 +1274,7 @@ def method(self, **kwargs): url = _add_query_parameter(url, "uploadType", "multipart") logger.debug("URL being requested: %s %s" % (httpMethod, url)) - return self._requestBuilder( + request = self._requestBuilder( self._http, model.response, url, @@ -1284,6 +1284,9 @@ def method(self, **kwargs): methodId=methodId, resumable=resumable, ) + if isinstance(request, HttpRequest): + request._universe_domain = self._universe_domain + return request docs = [methodDesc.get("description", DEFAULT_METHOD_DOC), "\n\n"] if len(parameters.argmap) > 0: @@ -1534,7 +1537,9 @@ def new_batch_http_request(callback=None): Returns: A BatchHttpRequest object based on the discovery document. """ - return BatchHttpRequest(callback=callback, batch_uri=batch_uri) + batch = BatchHttpRequest(callback=callback, batch_uri=batch_uri) + batch._universe_domain = self._universe_domain + return batch self._set_dynamic_attr("new_batch_http_request", new_batch_http_request) @@ -1635,18 +1640,13 @@ def _validate_credentials(self): Raises: UniverseMismatchError: If the configured universe domain is not valid. """ - credentials = getattr(self._http, "credentials", None) - - self._credentials_validated = ( - ( - self._credentials_validated - or _universe.api_core_universe.compare_domains( - self._universe_domain, credentials + if not self._credentials_validated: + credentials = getattr(self._http, "credentials", None) + self._credentials_validated = ( + _universe.validate_request_credentials_universe( + self._universe_domain, credentials, allow_none=False ) ) - if _universe.HAS_UNIVERSE - else True - ) return self._credentials_validated diff --git a/googleapiclient/http.py b/googleapiclient/http.py index 5aad076854..5ea90528d7 100644 --- a/googleapiclient/http.py +++ b/googleapiclient/http.py @@ -52,6 +52,7 @@ from googleapiclient import _auth from googleapiclient import _helpers as util +from googleapiclient import _universe from googleapiclient.errors import ( BatchError, HttpError, @@ -817,6 +818,10 @@ def next_chunk(self, num_retries=0): self._progress + self._chunksize - 1, ) http = self._request.http + _universe.validate_request_credentials_universe( + getattr(self._request, "_universe_domain", None), + _auth.get_credentials_from_http(http), + ) resp, content = _retry_request( http, @@ -953,6 +958,10 @@ def __init__( self._rand = random.random self._sleep = time.sleep + # Universe domain of the Resource that created this request (or None for + # standalone HttpRequest instances). + self._universe_domain = None + @util.positional(1) def execute(self, http=None, num_retries=0): """Execute the request. @@ -972,10 +981,17 @@ def execute(self, http=None, num_retries=0): Raises: googleapiclient.errors.HttpError if the response was not a 2xx. httplib2.HttpLib2Error if a transport error has occurred. + google.api_core.universe.UniverseMismatchError if the credentials + attached to ``http`` belong to a different universe domain than the + client. """ if http is None: http = self.http + _universe.validate_request_credentials_universe( + self._universe_domain, _auth.get_credentials_from_http(http) + ) + if self.resumable: body = None while body is None: @@ -1072,6 +1088,10 @@ def next_chunk(self, http=None, num_retries=0): if http is None: http = self.http + _universe.validate_request_credentials_universe( + self._universe_domain, _auth.get_credentials_from_http(http) + ) + if self.resumable.size() is None: size = "*" else: @@ -1226,7 +1246,7 @@ def from_json(s, http, postproc): d = json.loads(s) if d["resumable"] is not None: d["resumable"] = MediaUpload.new_from_json(d["resumable"]) - return HttpRequest( + req = HttpRequest( http, postproc, uri=d["uri"], @@ -1236,6 +1256,8 @@ def from_json(s, http, postproc): methodId=d["methodId"], resumable=d["resumable"], ) + req._universe_domain = d.get("_universe_domain") + return req @staticmethod def null_postproc(resp, contents): @@ -1326,6 +1348,43 @@ def __init__(self, callback=None, batch_uri=None): # A map of id(Credentials) that have been refreshed. self._refreshed_credentials = {} + # Track the batch's universe domain. Resource.new_batch_http_request() + # stamps its resolved universe domain here; the legacy default batch URI + # always targets googleapis.com. + self._universe_domain = ( + _universe.DEFAULT_UNIVERSE if batch_uri == _LEGACY_BATCH_URI else None + ) + + def _validate_http_credentials(self, http): + """Validate outer and per-request credentials before sending the batch.""" + # Collect unique credentials (outer http and per-subrequest http) and + # unique target universes (the batch endpoint and each subrequest) so + # cross-universe batches and mismatched overrides fail before any token + # refresh or network send. + creds_by_id = {} + for transport in (http, *(self._requests[i].http for i in self._order)): + creds = _auth.get_credentials_from_http(transport) + if creds is not None: + creds_by_id[id(creds)] = creds + + universes = dict.fromkeys( + u + for u in ( + self._universe_domain, + *( + getattr(self._requests[i], "_universe_domain", None) + for i in self._order + ), + ) + if u + ) + # Fall back to (None,) when no universe is stamped so + # validate_request_credentials_universe still checks credentials on + # google-api-core < 2.18.0. + for target_universe in universes or (None,): + for creds in creds_by_id.values(): + _universe.validate_request_credentials_universe(target_universe, creds) + def _refresh_and_apply_credentials(self, request, http): """Refresh the credentials and apply to the request. @@ -1635,6 +1694,8 @@ def execute(self, http=None): if http is None: raise ValueError("Missing a valid http object.") + self._validate_http_credentials(http) + # Special case for OAuth2Credentials-style objects which have not yet been # refreshed with an initial access_token. creds = _auth.get_credentials_from_http(http) diff --git a/tests/test__universe.py b/tests/test__universe.py index 1891c0d1be..fc47c0e777 100644 --- a/tests/test__universe.py +++ b/tests/test__universe.py @@ -197,18 +197,31 @@ def test_resolve_client_universe_invalid_type_raises(self): 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() + self.assertTrue( + _universe.validate_request_credentials_universe(self.FAKE_UNIVERSE, None) ) - _universe.validate_request_credentials_universe( - self.FAKE_UNIVERSE, _make_credentials(self.FAKE_UNIVERSE) + self.assertTrue( + _universe.validate_request_credentials_universe( + None, _make_credentials(self.FAKE_UNIVERSE) + ) + ) + self.assertTrue( + _universe.validate_request_credentials_universe( + self.FAKE_UNIVERSE, google.auth.credentials.AnonymousCredentials() + ) + ) + self.assertTrue( + _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() + self.assertTrue( + _universe.validate_request_credentials_universe( + self.FAKE_UNIVERSE, aio_credentials.AnonymousCredentials() + ) ) def test_validate_request_credentials_universe_mismatch_raises(self): @@ -216,6 +229,10 @@ def test_validate_request_credentials_universe_mismatch_raises(self): _universe.validate_request_credentials_universe( self.FAKE_UNIVERSE, _make_credentials("googleapis.com") ) + with self.assertRaises(universe.UniverseMismatchError): + _universe.validate_request_credentials_universe( + self.FAKE_UNIVERSE, None, allow_none=False + ) @unittest.skipUnless( hasattr(google.auth.compute_engine.Credentials, "universe_domain"), diff --git a/tests/test_discovery.py b/tests/test_discovery.py index d2b71e38ce..cf7bb2cbe5 100644 --- a/tests/test_discovery.py +++ b/tests/test_discovery.py @@ -1640,6 +1640,9 @@ def test_http_anonymous_credentials_in_universe(self): ) self.assertEqual(_requested_uris(http_mock), [self.V2_URI]) self.assertEqual(zoo._universe_domain, self.FAKE_UNIVERSE) + self.assertTrue(zoo._validate_credentials()) + request = zoo.animals().list() + self.assertEqual(request._universe_domain, self.FAKE_UNIVERSE) @unittest.skipUnless( hasattr(google.auth.compute_engine.Credentials, "universe_domain"), diff --git a/tests/test_http.py b/tests/test_http.py index 91f2c7ae52..0a5631140c 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -22,6 +22,7 @@ __author__ = "jcgregorio@google.com (Joe Gregorio)" +import importlib.util import io from io import FileIO @@ -38,9 +39,22 @@ from unittest import mock import urllib +import google.api_core +import google.auth.compute_engine +import google.auth.credentials +import google_auth_httplib2 import httplib2 +from parameterized import parameterized -from googleapiclient.discovery import build +try: + from google.api_core import universe + + HAS_UNIVERSE = True +except ImportError: + HAS_UNIVERSE = False + +from googleapiclient import _universe +from googleapiclient.discovery import APICoreVersionError, build, build_from_document from googleapiclient.errors import BatchError, HttpError, InvalidChunkSizeError from googleapiclient.http import ( DEFAULT_CHUNK_SIZE, @@ -1889,6 +1903,481 @@ def test_deserialize_non_dict_payload_raises_value_error(self): MediaFileUpload.from_json(payload) +def _make_universe_credentials(universe_domain): + credentials = mock.Mock(spec=google.auth.credentials.Credentials) + credentials.universe_domain = universe_domain + credentials.valid = True + credentials.expired = False + return credentials + + +def _read_datafile(filename): + with open(datafile(filename), "r") as f: + return f.read() + + +@unittest.skipUnless(HAS_UNIVERSE, "google-api-core >= 2.18.0 is required") +class TestExecuteUniverseValidation(unittest.TestCase): + """Per-request execute(http=...) and batch overrides validate universe_domain.""" + + FAKE_UNIVERSE = "foo.com" + OTHER_UNIVERSE = "bar.com" + + 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 _build_zoo(self, universe_domain=None, credentials_universe=None): + if credentials_universe is None: + credentials_universe = universe_domain or universe.DEFAULT_UNIVERSE + client_options = ( + {"universe_domain": universe_domain} + if universe_domain is not None + else None + ) + http = google_auth_httplib2.AuthorizedHttp( + _make_universe_credentials(credentials_universe), + http=HttpMockSequence([]), + ) + return build_from_document( + _read_datafile("zoo.json"), + http=http, + client_options=client_options, + ) + + def _make_authorized_http(self, universe_domain, responses=(), valid=True): + creds = _make_universe_credentials(universe_domain) + creds.valid = valid + http_mock = HttpMockSequence(list(responses)) + http = google_auth_httplib2.AuthorizedHttp(creds, http=http_mock) + return http, creds, http_mock + + def _assert_mismatch_raises(self, fn, creds, http_mock, check_refresh=False): + with self.assertRaises(universe.UniverseMismatchError): + fn() + self.assertEqual(http_mock.request_sequence, []) + creds.before_request.assert_not_called() + if check_refresh: + creds.refresh.assert_not_called() + + @parameterized.expand( + [ + ("custom_creds_on_default_resource", None, "foo.com"), + ("default_creds_on_custom_resource", "foo.com", "googleapis.com"), + ("other_universe_creds_on_custom_resource", "foo.com", "bar.com"), + ] + ) + def test_http_request_execute_http_override_mismatch_raises( + self, _, resource_universe, override_universe + ): + request = self._build_zoo(universe_domain=resource_universe).animals().list() + override_http, override_creds, http_mock = self._make_authorized_http( + override_universe + ) + self._assert_mismatch_raises( + lambda: request.execute(http=override_http), override_creds, http_mock + ) + + def test_http_request_execute_http_override_matching_universe_succeeds(self): + request = self._build_zoo(universe_domain=self.FAKE_UNIVERSE).animals().list() + override_http, _, http_mock = self._make_authorized_http( + self.FAKE_UNIVERSE, responses=[({"status": "200"}, '{"items": []}')] + ) + + self.assertEqual(request.execute(http=override_http), {"items": []}) + self.assertEqual(len(http_mock.request_sequence), 1) + self.assertIn(self.FAKE_UNIVERSE, http_mock.request_sequence[0][0]) + + def test_http_request_execute_http_override_anonymous_and_unauthenticated_succeed( + self, + ): + request = self._build_zoo(universe_domain=self.FAKE_UNIVERSE).animals().list() + + anon_mock = HttpMockSequence([({"status": "200"}, "{}")]) + anon_http = google_auth_httplib2.AuthorizedHttp( + google.auth.credentials.AnonymousCredentials(), http=anon_mock + ) + self.assertEqual(request.execute(http=anon_http), {}) + self.assertEqual(len(anon_mock.request_sequence), 1) + + plain_mock = HttpMockSequence([({"status": "200"}, "{}")]) + self.assertEqual(request.execute(http=plain_mock), {}) + self.assertEqual(len(plain_mock.request_sequence), 1) + + @unittest.skipUnless( + hasattr(google.auth.compute_engine.Credentials, "universe_domain"), + "google-auth >= 2.28.0 is required", + ) + def test_http_request_execute_http_override_uncached_compute_engine_mismatch(self): + request = self._build_zoo().animals().list() + + gce_creds = google.auth.compute_engine.Credentials() + gce_creds._universe_domain_cached = False + gce_creds.before_request = mock.Mock() + http_mock = HttpMockSequence([]) + override_http = google_auth_httplib2.AuthorizedHttp(gce_creds, 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: + self._assert_mismatch_raises( + lambda: request.execute(http=override_http), gce_creds, http_mock + ) + + mock_universe_domain.assert_called_once_with() + + def test_http_request_mutated_http_attribute_mismatch_raises(self): + request = self._build_zoo().animals().list() + request.http, creds, http_mock = self._make_authorized_http(self.FAKE_UNIVERSE) + self._assert_mismatch_raises(request.execute, creds, http_mock) + + def test_http_request_next_page_preserves_universe_validation(self): + gdu_http, _, _ = self._make_authorized_http(universe.DEFAULT_UNIVERSE) + drive = build_from_document(_read_datafile("drive.json"), http=gdu_http) + request = drive.changes().list(pageToken="1") + next_request = drive.changes().list_next( + request, {"nextPageToken": "next-token"} + ) + + override_http, creds, http_mock = self._make_authorized_http(self.FAKE_UNIVERSE) + self._assert_mismatch_raises( + lambda: next_request.execute(http=override_http), creds, http_mock + ) + + def test_http_request_to_from_json_preserves_universe_validation(self): + request = self._build_zoo().animals().list() + mismatched_http, creds, http_mock = self._make_authorized_http( + self.FAKE_UNIVERSE + ) + restored = HttpRequest.from_json( + request.to_json(), mismatched_http, request.postproc + ) + self._assert_mismatch_raises(restored.execute, creds, http_mock) + + def test_http_request_next_chunk_http_override_mismatch_raises(self): + upload = MediaInMemoryUpload( + b"hello world", mimetype="text/plain", resumable=True + ) + request = self._build_zoo().animals().insert(body={}, media_body=upload) + override_http, creds, http_mock = self._make_authorized_http(self.FAKE_UNIVERSE) + self._assert_mismatch_raises( + lambda: request.next_chunk(http=override_http), creds, http_mock + ) + + def test_media_download_next_chunk_mutated_http_mismatch_raises(self): + request = self._build_zoo().animals().get_media(name="Lion") + request.http, creds, http_mock = self._make_authorized_http(self.FAKE_UNIVERSE) + download = MediaIoBaseDownload(io.BytesIO(), request) + self._assert_mismatch_raises(download.next_chunk, creds, http_mock) + + def test_standalone_http_request_without_universe_allows_custom_credentials(self): + http, _, http_mock = self._make_authorized_http( + self.FAKE_UNIVERSE, responses=[({"status": "200"}, "{}")] + ) + request = HttpRequest( + http, JsonModel().response, "https://custom.example.com/resource" + ) + self.assertEqual(request.execute(), {}) + self.assertEqual(len(http_mock.request_sequence), 1) + + @parameterized.expand( + [ + ("custom_creds_on_default_batch", None, "foo.com"), + ("default_creds_on_custom_batch", "foo.com", "googleapis.com"), + ("other_universe_creds_on_custom_batch", "foo.com", "bar.com"), + ] + ) + def test_batch_execute_http_override_mismatch_raises( + self, _, resource_universe, override_universe + ): + zoo = self._build_zoo(universe_domain=resource_universe) + batch = zoo.new_batch_http_request() + batch.add(zoo.animals().list()) + + override_http, creds, http_mock = self._make_authorized_http( + override_universe, valid=False + ) + self._assert_mismatch_raises( + lambda: batch.execute(http=override_http), + creds, + http_mock, + check_refresh=True, + ) + + def test_batch_execute_http_override_matching_universe_succeeds(self): + zoo = self._build_zoo(universe_domain=self.FAKE_UNIVERSE) + batch = zoo.new_batch_http_request() + callbacks = Callbacks() + batch.add(zoo.animals().list(), callback=callbacks.f) + + batch_response = ( + { + "status": "200", + "content-type": 'multipart/mixed; boundary="batch_foobarbaz"', + }, + BATCH_SINGLE_RESPONSE, + ) + override_http, _, http_mock = self._make_authorized_http( + self.FAKE_UNIVERSE, responses=[batch_response] + ) + + batch.execute(http=override_http) + + self.assertEqual(callbacks.responses["1"], {"foo": 42}) + self.assertEqual(len(http_mock.request_sequence), 1) + self.assertIn(self.FAKE_UNIVERSE, http_mock.request_sequence[0][0]) + + def test_batch_execute_http_override_anonymous_succeeds(self): + zoo = self._build_zoo(universe_domain=self.FAKE_UNIVERSE) + batch = zoo.new_batch_http_request() + callbacks = Callbacks() + batch.add(zoo.animals().list(), callback=callbacks.f) + + anon_mock = HttpMockSequence( + [ + ( + { + "status": "200", + "content-type": 'multipart/mixed; boundary="batch_foobarbaz"', + }, + BATCH_SINGLE_RESPONSE, + ) + ] + ) + anon_http = google_auth_httplib2.AuthorizedHttp( + google.auth.credentials.AnonymousCredentials(), http=anon_mock + ) + + batch.execute(http=anon_http) + + self.assertEqual(callbacks.responses["1"], {"foo": 42}) + self.assertEqual(len(anon_mock.request_sequence), 1) + + @unittest.skipUnless( + hasattr(google.auth.compute_engine.Credentials, "universe_domain"), + "google-auth >= 2.28.0 is required", + ) + def test_batch_execute_http_override_uncached_compute_engine_mismatch(self): + zoo = self._build_zoo() + batch = zoo.new_batch_http_request() + batch.add(zoo.animals().list()) + + gce_creds = google.auth.compute_engine.Credentials() + gce_creds._universe_domain_cached = False + gce_creds.before_request = mock.Mock() + gce_creds.refresh = mock.Mock() + http_mock = HttpMockSequence([]) + override_http = google_auth_httplib2.AuthorizedHttp(gce_creds, 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: + self._assert_mismatch_raises( + lambda: batch.execute(http=override_http), + gce_creds, + http_mock, + check_refresh=True, + ) + + mock_universe_domain.assert_called_once_with() + + def test_batch_execute_cross_universe_subrequest_raises(self): + batch = self._build_zoo().new_batch_http_request() + batch.add(self._build_zoo(universe_domain=self.FAKE_UNIVERSE).animals().list()) + + gdu_http, creds, http_mock = self._make_authorized_http( + universe.DEFAULT_UNIVERSE + ) + self._assert_mismatch_raises( + lambda: batch.execute(http=gdu_http), creds, http_mock + ) + + def test_batch_execute_legacy_batch_with_custom_universe_override_raises(self): + batch = BatchHttpRequest() + batch.add( + HttpRequest( + None, JsonModel().response, "https://www.googleapis.com/zoo/v1/animals" + ) + ) + tpc_http, creds, http_mock = self._make_authorized_http(self.FAKE_UNIVERSE) + self._assert_mismatch_raises( + lambda: batch.execute(http=tpc_http), creds, http_mock + ) + + def test_batch_execute_custom_uri_uses_subrequest_universe(self): + batch = BatchHttpRequest(batch_uri="https://custom.example.com/batch") + batch.add(self._build_zoo().animals().list()) + + tpc_http, creds, http_mock = self._make_authorized_http(self.FAKE_UNIVERSE) + self._assert_mismatch_raises( + lambda: batch.execute(http=tpc_http), creds, http_mock + ) + + +class TestExecuteWithoutUniverseSupport(unittest.TestCase): + """Per-request execute(http=...) on google-api-core < 2.18.0.""" + + FAKE_UNIVERSE = "foo.com" + + @classmethod + def setUpClass(cls): + spec = importlib.util.spec_from_file_location( + "_universe_no_universe_http_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) + + discovery_patcher = mock.patch( + "googleapiclient.discovery._universe", self.legacy_universe + ) + http_patcher = mock.patch( + "googleapiclient.http._universe", self.legacy_universe + ) + discovery_patcher.start() + http_patcher.start() + self.addCleanup(discovery_patcher.stop) + self.addCleanup(http_patcher.stop) + + def test_http_request_execute_http_override_custom_universe_raises(self): + zoo = build_from_document(_read_datafile("zoo.json"), http=HttpMockSequence([])) + request = zoo.animals().list() + + tpc_creds = _make_universe_credentials(self.FAKE_UNIVERSE) + http_mock = HttpMockSequence([]) + override_http = google_auth_httplib2.AuthorizedHttp(tpc_creds, http=http_mock) + + with self.assertRaises(APICoreVersionError): + request.execute(http=override_http) + + self.assertEqual(http_mock.request_sequence, []) + tpc_creds.before_request.assert_not_called() + + def test_http_request_next_chunk_http_override_custom_universe_raises(self): + zoo = build_from_document(_read_datafile("zoo.json"), http=HttpMockSequence([])) + upload = MediaInMemoryUpload(b"hello", mimetype="text/plain", resumable=True) + request = zoo.animals().insert(body={}, media_body=upload) + + tpc_creds = _make_universe_credentials(self.FAKE_UNIVERSE) + http_mock = HttpMockSequence([]) + override_http = google_auth_httplib2.AuthorizedHttp(tpc_creds, http=http_mock) + + with self.assertRaises(APICoreVersionError): + request.next_chunk(http=override_http) + + self.assertEqual(http_mock.request_sequence, []) + tpc_creds.before_request.assert_not_called() + + def test_batch_execute_http_override_custom_universe_raises(self): + zoo = build_from_document(_read_datafile("zoo.json"), http=HttpMockSequence([])) + batch = zoo.new_batch_http_request() + batch.add(zoo.animals().list()) + + tpc_creds = _make_universe_credentials(self.FAKE_UNIVERSE) + http_mock = HttpMockSequence([]) + override_http = google_auth_httplib2.AuthorizedHttp(tpc_creds, http=http_mock) + + with self.assertRaises(APICoreVersionError): + batch.execute(http=override_http) + + self.assertEqual(http_mock.request_sequence, []) + tpc_creds.before_request.assert_not_called() + + def test_batch_execute_subrequest_custom_universe_raises(self): + zoo = build_from_document(_read_datafile("zoo.json"), http=HttpMockSequence([])) + batch = zoo.new_batch_http_request() + req = zoo.animals().list() + + tpc_creds = _make_universe_credentials(self.FAKE_UNIVERSE) + req.http = google_auth_httplib2.AuthorizedHttp( + tpc_creds, http=HttpMockSequence([]) + ) + batch.add(req) + + gdu_http_mock = HttpMockSequence([]) + gdu_http = google_auth_httplib2.AuthorizedHttp( + _make_universe_credentials("googleapis.com"), http=gdu_http_mock + ) + + with self.assertRaises(APICoreVersionError): + batch.execute(http=gdu_http) + + self.assertEqual(gdu_http_mock.request_sequence, []) + tpc_creds.before_request.assert_not_called() + + def test_http_request_execute_default_universe_succeeds(self): + zoo = build_from_document(_read_datafile("zoo.json"), http=HttpMockSequence([])) + request = zoo.animals().list() + + gdu_creds = _make_universe_credentials("googleapis.com") + http_mock = HttpMockSequence([({"status": "200"}, "{}")]) + override_http = google_auth_httplib2.AuthorizedHttp(gdu_creds, http=http_mock) + + self.assertEqual(request.execute(http=override_http), {}) + self.assertEqual(len(http_mock.request_sequence), 1) + + def test_batch_execute_default_universe_succeeds(self): + zoo = build_from_document(_read_datafile("zoo.json"), http=HttpMockSequence([])) + batch = zoo.new_batch_http_request() + callbacks = Callbacks() + batch.add(zoo.animals().list(), callback=callbacks.f) + + gdu_creds = _make_universe_credentials("googleapis.com") + http_mock = HttpMockSequence( + [ + ( + { + "status": "200", + "content-type": 'multipart/mixed; boundary="batch_foobarbaz"', + }, + BATCH_SINGLE_RESPONSE, + ) + ] + ) + override_http = google_auth_httplib2.AuthorizedHttp(gdu_creds, http=http_mock) + + batch.execute(http=override_http) + + self.assertEqual(callbacks.responses["1"], {"foo": 42}) + self.assertEqual(len(http_mock.request_sequence), 1) + + def test_media_download_next_chunk_custom_universe_raises(self): + zoo = build_from_document(_read_datafile("zoo.json"), http=HttpMockSequence([])) + request = zoo.animals().get_media(name="Lion") + + tpc_creds = _make_universe_credentials(self.FAKE_UNIVERSE) + http_mock = HttpMockSequence([]) + request.http = google_auth_httplib2.AuthorizedHttp(tpc_creds, http=http_mock) + download = MediaIoBaseDownload(io.BytesIO(), request) + + with self.assertRaises(APICoreVersionError): + download.next_chunk() + + self.assertEqual(http_mock.request_sequence, []) + tpc_creds.before_request.assert_not_called() + + if __name__ == "__main__": logging.getLogger().setLevel(logging.ERROR) unittest.main() From ff076d45fd9aad6a62d653616d462cd53828d0b9 Mon Sep 17 00:00:00 2001 From: Daniel Sanche Date: Fri, 4 Dec 2026 12:48:33 -0700 Subject: [PATCH 02/12] improve method docstrings --- googleapiclient/_universe.py | 36 +++++++++++++++++++++++++++++++----- googleapiclient/discovery.py | 4 +++- tests/test__universe.py | 2 +- 3 files changed, 35 insertions(+), 7 deletions(-) diff --git a/googleapiclient/_universe.py b/googleapiclient/_universe.py index 7e27e7df8e..f4e0551dd9 100644 --- a/googleapiclient/_universe.py +++ b/googleapiclient/_universe.py @@ -110,7 +110,7 @@ def check_api_core_compatible_with_credentials_universe(credentials): def validate_request_credentials_universe( - client_universe, credentials, allow_none=True + client_universe, credentials, allow_none_credentials=True ): """Validate credentials immediately before making a network request. @@ -118,11 +118,37 @@ def validate_request_credentials_universe( 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. + + Args: + client_universe (Optional[str]): The resolved client universe domain + (for example, ``"googleapis.com"``). When ``HAS_UNIVERSE`` is + ``True``, ``None`` indicates a standalone request or custom batch + not created by a ``Resource`` and skips validation. When + ``HAS_UNIVERSE`` is ``False`` (``google-api-core < 2.18.0``), + ``Resource._universe_domain`` is ``None`` while requests still + target the default universe, so non-default credentials are still + rejected. + credentials (Optional[google.auth.credentials.Credentials]): The + credentials attached to the request or transport, or ``None`` for + an unauthenticated transport. + allow_none_credentials (bool): If ``True`` (default), ``credentials`` + being ``None`` is treated as unauthenticated and allowed. If + ``False``, ``None`` is passed to ``compare_domains`` (preserving + ``Resource._validate_credentials()`` behavior). + + Returns: + bool: ``True`` if the credentials are valid for ``client_universe``. + + Raises: + APICoreVersionError: If ``google-api-core < 2.18.0`` and + ``credentials`` belong to a non-default universe. + google.api_core.universe.UniverseMismatchError: If ``credentials`` + belong to a different universe than ``client_universe``. """ if not HAS_UNIVERSE: - # Without google.api_core.universe (< 2.18.0), the client can only - # target the default universe; reject non-default credentials even when - # client_universe is None. + # Without google.api_core.universe (< 2.18.0), Resource._universe_domain + # is None while requests still target the default universe; reject + # non-default credentials before checking `client_universe is None`. check_api_core_compatible_with_credentials_universe(credentials) return True if client_universe is None: @@ -130,7 +156,7 @@ def validate_request_credentials_universe( # universe domain have no client universe to compare against. return True if isinstance(credentials, _ANONYMOUS_CREDENTIAL_TYPES) or ( - allow_none and credentials is None + allow_none_credentials and credentials is None ): return True # Intentionally call compare_domains directly rather than diff --git a/googleapiclient/discovery.py b/googleapiclient/discovery.py index 82b1cf2a43..2c6de6ba62 100644 --- a/googleapiclient/discovery.py +++ b/googleapiclient/discovery.py @@ -1644,7 +1644,9 @@ def _validate_credentials(self): credentials = getattr(self._http, "credentials", None) self._credentials_validated = ( _universe.validate_request_credentials_universe( - self._universe_domain, credentials, allow_none=False + self._universe_domain, + credentials, + allow_none_credentials=False, ) ) return self._credentials_validated diff --git a/tests/test__universe.py b/tests/test__universe.py index fc47c0e777..5d0cc8a57b 100644 --- a/tests/test__universe.py +++ b/tests/test__universe.py @@ -231,7 +231,7 @@ def test_validate_request_credentials_universe_mismatch_raises(self): ) with self.assertRaises(universe.UniverseMismatchError): _universe.validate_request_credentials_universe( - self.FAKE_UNIVERSE, None, allow_none=False + self.FAKE_UNIVERSE, None, allow_none_credentials=False ) @unittest.skipUnless( From 2459a32595563d9faa4f814a725df1e6236b6b2c Mon Sep 17 00:00:00 2001 From: Daniel Sanche Date: Fri, 4 Dec 2026 13:08:50 -0700 Subject: [PATCH 03/12] split up validate_request_credentials_universe --- googleapiclient/_universe.py | 98 +++++++++++++++++------------------- 1 file changed, 46 insertions(+), 52 deletions(-) diff --git a/googleapiclient/_universe.py b/googleapiclient/_universe.py index f4e0551dd9..c78d621e24 100644 --- a/googleapiclient/_universe.py +++ b/googleapiclient/_universe.py @@ -109,57 +109,51 @@ def check_api_core_compatible_with_credentials_universe(credentials): raise APICoreVersionError -def validate_request_credentials_universe( - client_universe, credentials, allow_none_credentials=True -): - """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. - - Args: - client_universe (Optional[str]): The resolved client universe domain - (for example, ``"googleapis.com"``). When ``HAS_UNIVERSE`` is - ``True``, ``None`` indicates a standalone request or custom batch - not created by a ``Resource`` and skips validation. When - ``HAS_UNIVERSE`` is ``False`` (``google-api-core < 2.18.0``), - ``Resource._universe_domain`` is ``None`` while requests still - target the default universe, so non-default credentials are still - rejected. - credentials (Optional[google.auth.credentials.Credentials]): The - credentials attached to the request or transport, or ``None`` for - an unauthenticated transport. - allow_none_credentials (bool): If ``True`` (default), ``credentials`` - being ``None`` is treated as unauthenticated and allowed. If - ``False``, ``None`` is passed to ``compare_domains`` (preserving - ``Resource._validate_credentials()`` behavior). - - Returns: - bool: ``True`` if the credentials are valid for ``client_universe``. - - Raises: - APICoreVersionError: If ``google-api-core < 2.18.0`` and - ``credentials`` belong to a non-default universe. - google.api_core.universe.UniverseMismatchError: If ``credentials`` - belong to a different universe than ``client_universe``. - """ - if not HAS_UNIVERSE: - # Without google.api_core.universe (< 2.18.0), Resource._universe_domain - # is None while requests still target the default universe; reject - # non-default credentials before checking `client_universe is None`. - check_api_core_compatible_with_credentials_universe(credentials) - return True - if client_universe is None: - # Standalone HttpRequest / custom BatchHttpRequest without a Resource - # universe domain have no client universe to compare against. - return True - if isinstance(credentials, _ANONYMOUS_CREDENTIAL_TYPES) or ( - allow_none_credentials and credentials is None +if HAS_UNIVERSE: + + def validate_request_credentials_universe( + client_universe, credentials, allow_none_credentials=True ): + """Check that credentials match ``client_universe`` before a request. + + Unlike ``google.api_core.universe.validate_credentials_universe``, this + also checks uncached Compute Engine credentials, because a token is + about to be sent. + + Args: + client_universe: The client's universe domain. ``None`` (a request + or batch not created by a ``Resource``) skips the check. + credentials: The transport's credentials, or ``None``. + allow_none_credentials: If ``False``, ``None`` credentials are + compared as the default universe instead of being allowed. + + Returns: + bool: ``True`` if the credentials are valid. + + Raises: + UniverseMismatchError: If the universes differ. + """ + if client_universe is None: + return True + if isinstance(credentials, _ANONYMOUS_CREDENTIAL_TYPES) or ( + allow_none_credentials and credentials is None + ): + return True + return api_core_universe.compare_domains(client_universe, credentials) + +else: + + # google-api-core < 2.18.0 has no universe support: Resource._universe_domain is + # None and every request targets googleapis.com + def validate_request_credentials_universe( + client_universe, credentials, allow_none_credentials=True + ): + """Reject credentials that belong to a non-default universe. + + ``client_universe`` and ``allow_none_credentials`` are unused. + + Raises: + APICoreVersionError: If the credentials need universe support. + """ + check_api_core_compatible_with_credentials_universe(credentials) return True - # 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. - return api_core_universe.compare_domains(client_universe, credentials) From 4b34e71b1a6d6f935a79e7ee06fc6d4222f0b271 Mon Sep 17 00:00:00 2001 From: Daniel Sanche Date: Fri, 4 Dec 2026 13:31:48 -0700 Subject: [PATCH 04/12] improve how empty universes are handled --- googleapiclient/_universe.py | 6 +-- googleapiclient/discovery.py | 7 +++- googleapiclient/http.py | 41 ++++++++++---------- tests/test__universe.py | 5 --- tests/test_http.py | 73 ++++++++++++++++++++++++++++++++++++ 5 files changed, 101 insertions(+), 31 deletions(-) diff --git a/googleapiclient/_universe.py b/googleapiclient/_universe.py index c78d621e24..5f39b1f9d8 100644 --- a/googleapiclient/_universe.py +++ b/googleapiclient/_universe.py @@ -121,8 +121,7 @@ def validate_request_credentials_universe( about to be sent. Args: - client_universe: The client's universe domain. ``None`` (a request - or batch not created by a ``Resource``) skips the check. + client_universe: The universe domain the request targets. credentials: The transport's credentials, or ``None``. allow_none_credentials: If ``False``, ``None`` credentials are compared as the default universe instead of being allowed. @@ -133,8 +132,6 @@ def validate_request_credentials_universe( Raises: UniverseMismatchError: If the universes differ. """ - if client_universe is None: - return True if isinstance(credentials, _ANONYMOUS_CREDENTIAL_TYPES) or ( allow_none_credentials and credentials is None ): @@ -142,7 +139,6 @@ def validate_request_credentials_universe( return api_core_universe.compare_domains(client_universe, credentials) else: - # google-api-core < 2.18.0 has no universe support: Resource._universe_domain is # None and every request targets googleapis.com def validate_request_credentials_universe( diff --git a/googleapiclient/discovery.py b/googleapiclient/discovery.py index 2c6de6ba62..9752b0b1fd 100644 --- a/googleapiclient/discovery.py +++ b/googleapiclient/discovery.py @@ -1285,7 +1285,10 @@ def method(self, **kwargs): resumable=resumable, ) if isinstance(request, HttpRequest): - request._universe_domain = self._universe_domain + # self._universe_domain is unset on google-api-core < 2.18.0, where + # requests always target the default universe. Stamp a real value + # so that None only ever means "not built by a Resource". + request._universe_domain = self._universe_domain or DEFAULT_UNIVERSE return request docs = [methodDesc.get("description", DEFAULT_METHOD_DOC), "\n\n"] @@ -1538,7 +1541,7 @@ def new_batch_http_request(callback=None): A BatchHttpRequest object based on the discovery document. """ batch = BatchHttpRequest(callback=callback, batch_uri=batch_uri) - batch._universe_domain = self._universe_domain + batch._universe_domain = self._universe_domain or DEFAULT_UNIVERSE return batch self._set_dynamic_attr("new_batch_http_request", new_batch_http_request) diff --git a/googleapiclient/http.py b/googleapiclient/http.py index 5ea90528d7..135aba5765 100644 --- a/googleapiclient/http.py +++ b/googleapiclient/http.py @@ -818,10 +818,11 @@ def next_chunk(self, num_retries=0): self._progress + self._chunksize - 1, ) http = self._request.http - _universe.validate_request_credentials_universe( - getattr(self._request, "_universe_domain", None), - _auth.get_credentials_from_http(http), - ) + request_universe = getattr(self._request, "_universe_domain", None) + if request_universe is not None: + _universe.validate_request_credentials_universe( + request_universe, _auth.get_credentials_from_http(http) + ) resp, content = _retry_request( http, @@ -958,8 +959,9 @@ def __init__( self._rand = random.random self._sleep = time.sleep - # Universe domain of the Resource that created this request (or None for - # standalone HttpRequest instances). + # Universe domain of the Resource that created this request. None means + # the request was not built by a Resource, so there is no universe to + # check its credentials against. self._universe_domain = None @util.positional(1) @@ -988,9 +990,10 @@ def execute(self, http=None, num_retries=0): if http is None: http = self.http - _universe.validate_request_credentials_universe( - self._universe_domain, _auth.get_credentials_from_http(http) - ) + if self._universe_domain is not None: + _universe.validate_request_credentials_universe( + self._universe_domain, _auth.get_credentials_from_http(http) + ) if self.resumable: body = None @@ -1088,9 +1091,10 @@ def next_chunk(self, http=None, num_retries=0): if http is None: http = self.http - _universe.validate_request_credentials_universe( - self._universe_domain, _auth.get_credentials_from_http(http) - ) + if self._universe_domain is not None: + _universe.validate_request_credentials_universe( + self._universe_domain, _auth.get_credentials_from_http(http) + ) if self.resumable.size() is None: size = "*" @@ -1349,8 +1353,8 @@ def __init__(self, callback=None, batch_uri=None): self._refreshed_credentials = {} # Track the batch's universe domain. Resource.new_batch_http_request() - # stamps its resolved universe domain here; the legacy default batch URI - # always targets googleapis.com. + # stamps its universe domain here; the legacy default batch URI always + # targets googleapis.com. None means the universe is unknown. self._universe_domain = ( _universe.DEFAULT_UNIVERSE if batch_uri == _LEGACY_BATCH_URI else None ) @@ -1367,6 +1371,8 @@ def _validate_http_credentials(self, http): if creds is not None: creds_by_id[id(creds)] = creds + # Skip None: a batch or request that was not built by a Resource has no + # universe to check against. universes = dict.fromkeys( u for u in ( @@ -1376,12 +1382,9 @@ def _validate_http_credentials(self, http): for i in self._order ), ) - if u + if u is not None ) - # Fall back to (None,) when no universe is stamped so - # validate_request_credentials_universe still checks credentials on - # google-api-core < 2.18.0. - for target_universe in universes or (None,): + for target_universe in universes: for creds in creds_by_id.values(): _universe.validate_request_credentials_universe(target_universe, creds) diff --git a/tests/test__universe.py b/tests/test__universe.py index 5d0cc8a57b..76595bdcbf 100644 --- a/tests/test__universe.py +++ b/tests/test__universe.py @@ -200,11 +200,6 @@ def test_validate_request_credentials_universe_accepts_matching_and_exempt(self) self.assertTrue( _universe.validate_request_credentials_universe(self.FAKE_UNIVERSE, None) ) - self.assertTrue( - _universe.validate_request_credentials_universe( - None, _make_credentials(self.FAKE_UNIVERSE) - ) - ) self.assertTrue( _universe.validate_request_credentials_universe( self.FAKE_UNIVERSE, google.auth.credentials.AnonymousCredentials() diff --git a/tests/test_http.py b/tests/test_http.py index 0a5631140c..cf8e6dc14f 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -2222,6 +2222,31 @@ def test_batch_execute_custom_uri_uses_subrequest_universe(self): lambda: batch.execute(http=tpc_http), creds, http_mock ) + def test_standalone_batch_allows_custom_credentials(self): + batch = BatchHttpRequest(batch_uri="https://custom.example.com/batch") + callbacks = Callbacks() + batch.add( + HttpRequest( + None, JsonModel().response, "https://custom.example.com/resource" + ), + callback=callbacks.f, + ) + batch_response = ( + { + "status": "200", + "content-type": 'multipart/mixed; boundary="batch_foobarbaz"', + }, + BATCH_SINGLE_RESPONSE, + ) + tpc_http, _, http_mock = self._make_authorized_http( + self.FAKE_UNIVERSE, responses=[batch_response] + ) + + batch.execute(http=tpc_http) + + self.assertEqual(callbacks.responses["1"], {"foo": 42}) + self.assertEqual(len(http_mock.request_sequence), 1) + class TestExecuteWithoutUniverseSupport(unittest.TestCase): """Per-request execute(http=...) on google-api-core < 2.18.0.""" @@ -2377,6 +2402,54 @@ def test_media_download_next_chunk_custom_universe_raises(self): self.assertEqual(http_mock.request_sequence, []) tpc_creds.before_request.assert_not_called() + def test_resource_stamps_default_universe(self): + zoo = build_from_document(_read_datafile("zoo.json"), http=HttpMockSequence([])) + + self.assertIsNone(zoo._universe_domain) + self.assertEqual(zoo.animals().list()._universe_domain, "googleapis.com") + self.assertEqual( + zoo.new_batch_http_request()._universe_domain, "googleapis.com" + ) + + def test_standalone_http_request_allows_custom_credentials(self): + tpc_creds = _make_universe_credentials(self.FAKE_UNIVERSE) + http_mock = HttpMockSequence([({"status": "200"}, "{}")]) + http = google_auth_httplib2.AuthorizedHttp(tpc_creds, http=http_mock) + request = HttpRequest( + http, JsonModel().response, "https://custom.example.com/resource" + ) + + self.assertEqual(request.execute(), {}) + self.assertEqual(len(http_mock.request_sequence), 1) + + def test_standalone_batch_allows_custom_credentials(self): + batch = BatchHttpRequest(batch_uri="https://custom.example.com/batch") + callbacks = Callbacks() + batch.add( + HttpRequest( + None, JsonModel().response, "https://custom.example.com/resource" + ), + callback=callbacks.f, + ) + tpc_creds = _make_universe_credentials(self.FAKE_UNIVERSE) + http_mock = HttpMockSequence( + [ + ( + { + "status": "200", + "content-type": 'multipart/mixed; boundary="batch_foobarbaz"', + }, + BATCH_SINGLE_RESPONSE, + ) + ] + ) + http = google_auth_httplib2.AuthorizedHttp(tpc_creds, http=http_mock) + + batch.execute(http=http) + + self.assertEqual(callbacks.responses["1"], {"foo": 42}) + self.assertEqual(len(http_mock.request_sequence), 1) + if __name__ == "__main__": logging.getLogger().setLevel(logging.ERROR) From 898c0839caa399569138c8028636adda57745067 Mon Sep 17 00:00:00 2001 From: Daniel Sanche Date: Fri, 4 Dec 2026 13:38:09 -0700 Subject: [PATCH 05/12] reverted validation to look more like base branch --- googleapiclient/_universe.py | 67 ++++++++++++++---------------------- 1 file changed, 25 insertions(+), 42 deletions(-) diff --git a/googleapiclient/_universe.py b/googleapiclient/_universe.py index 5f39b1f9d8..ad8ce47ebd 100644 --- a/googleapiclient/_universe.py +++ b/googleapiclient/_universe.py @@ -109,47 +109,30 @@ def check_api_core_compatible_with_credentials_universe(credentials): raise APICoreVersionError -if HAS_UNIVERSE: - - def validate_request_credentials_universe( - client_universe, credentials, allow_none_credentials=True - ): - """Check that credentials match ``client_universe`` before a request. - - Unlike ``google.api_core.universe.validate_credentials_universe``, this - also checks uncached Compute Engine credentials, because a token is - about to be sent. - - Args: - client_universe: The universe domain the request targets. - credentials: The transport's credentials, or ``None``. - allow_none_credentials: If ``False``, ``None`` credentials are - compared as the default universe instead of being allowed. - - Returns: - bool: ``True`` if the credentials are valid. - - Raises: - UniverseMismatchError: If the universes differ. - """ - if isinstance(credentials, _ANONYMOUS_CREDENTIAL_TYPES) or ( - allow_none_credentials and credentials is None - ): - return True - return api_core_universe.compare_domains(client_universe, credentials) - -else: - # google-api-core < 2.18.0 has no universe support: Resource._universe_domain is - # None and every request targets googleapis.com - def validate_request_credentials_universe( - client_universe, credentials, allow_none_credentials=True - ): - """Reject credentials that belong to a non-default universe. - - ``client_universe`` and ``allow_none_credentials`` are unused. - - Raises: - APICoreVersionError: If the credentials need universe support. - """ +def validate_request_credentials_universe( + client_universe, credentials, allow_none_credentials=True +): + """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. + + ``None`` credentials are allowed unless ``allow_none_credentials`` is + ``False``, in which case they are compared as the default universe. + Returns ``True`` if the credentials are valid. + """ + 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 True + if isinstance(credentials, _ANONYMOUS_CREDENTIAL_TYPES) or ( + allow_none_credentials and credentials is None + ): + return True + # 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. + return api_core_universe.compare_domains(client_universe, credentials) From 43f22e19d628461d2eb707b2b6d2881f4b06a1f8 Mon Sep 17 00:00:00 2001 From: Daniel Sanche Date: Fri, 4 Dec 2026 13:46:41 -0700 Subject: [PATCH 06/12] updated docstring --- googleapiclient/_universe.py | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/googleapiclient/_universe.py b/googleapiclient/_universe.py index ad8ce47ebd..8bd6c7331d 100644 --- a/googleapiclient/_universe.py +++ b/googleapiclient/_universe.py @@ -119,9 +119,21 @@ def validate_request_credentials_universe( during offline client initialization), this validates uncached Compute Engine credentials as well before the outbound request is sent. - ``None`` credentials are allowed unless ``allow_none_credentials`` is - ``False``, in which case they are compared as the default universe. - Returns ``True`` if the credentials are valid. + Args: + client_universe: The universe domain the request targets. + credentials: The credentials to check, or ``None`` if none are set. + allow_none_credentials: If ``True`` (default), ``None`` credentials + are treated as valid. If ``False``, they are checked as + default-universe credentials, so validation fails unless + ``client_universe`` is the default universe. + + Returns: + bool: ``True`` if the request may be sent with these credentials. + + Raises: + UniverseMismatchError: If the credentials belong to another universe. + APICoreVersionError: If google-api-core < 2.18.0 and the credentials + belong to a non-default universe. """ if not HAS_UNIVERSE: # Without google.api_core.universe (< 2.18.0), the client can only From c192774ee5f1592ca6de7423d44c20a8b2975105 Mon Sep 17 00:00:00 2001 From: Daniel Sanche Date: Fri, 4 Dec 2026 14:16:45 -0700 Subject: [PATCH 07/12] support previously pickled versions --- googleapiclient/http.py | 10 ++++++++++ tests/test_http.py | 43 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+) diff --git a/googleapiclient/http.py b/googleapiclient/http.py index 135aba5765..99f8732ba1 100644 --- a/googleapiclient/http.py +++ b/googleapiclient/http.py @@ -964,6 +964,11 @@ def __init__( # check its credentials against. self._universe_domain = None + def __setstate__(self, state): + self.__dict__.update(state) + # Objects pickled by an earlier release have no _universe_domain. + self.__dict__.setdefault("_universe_domain", None) + @util.positional(1) def execute(self, http=None, num_retries=0): """Execute the request. @@ -1359,6 +1364,11 @@ def __init__(self, callback=None, batch_uri=None): _universe.DEFAULT_UNIVERSE if batch_uri == _LEGACY_BATCH_URI else None ) + def __setstate__(self, state): + self.__dict__.update(state) + # Objects pickled by an earlier release have no _universe_domain. + self.__dict__.setdefault("_universe_domain", None) + def _validate_http_credentials(self, http): """Validate outer and per-request credentials before sending the batch.""" # Collect unique credentials (outer http and per-subrequest http) and diff --git a/tests/test_http.py b/tests/test_http.py index cf8e6dc14f..b6d3f7b4da 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -30,6 +30,7 @@ import json import logging import os +import pickle import random import socket import ssl @@ -2451,6 +2452,48 @@ def test_standalone_batch_allows_custom_credentials(self): self.assertEqual(len(http_mock.request_sequence), 1) +class TestExecuteWithoutUniverseAttribute(unittest.TestCase): + """Requests and batches created by an earlier release keep working.""" + + BATCH_HEADERS = { + "status": "200", + "content-type": 'multipart/mixed; boundary="batch_foobarbaz"', + } + + def test_request_created_before_universe_tracking(self): + request = HttpRequest( + HttpMockSequence([({"status": "200"}, "{}")]), + JsonModel().response, + "https://custom.example.com/resource", + ) + # A request pickled by an earlier release has no _universe_domain. + del request.__dict__["_universe_domain"] + request = pickle.loads(pickle.dumps(request)) + + self.assertIsNone(request._universe_domain) + self.assertEqual(request.execute(), {}) + + def test_batch_created_before_universe_tracking(self): + batch = BatchHttpRequest(batch_uri="https://custom.example.com/batch") + # A batch pickled by an earlier release has no _universe_domain. + del batch.__dict__["_universe_domain"] + batch = pickle.loads(pickle.dumps(batch)) + self.assertIsNone(batch._universe_domain) + callbacks = Callbacks() + batch.add( + HttpRequest( + None, JsonModel().response, "https://custom.example.com/resource" + ), + callback=callbacks.f, + ) + + batch.execute( + http=HttpMockSequence([(self.BATCH_HEADERS, BATCH_SINGLE_RESPONSE)]) + ) + + self.assertEqual(callbacks.responses["1"], {"foo": 42}) + + if __name__ == "__main__": logging.getLogger().setLevel(logging.ERROR) unittest.main() From 2f3a8ef39ccab9b6ba0f90441a74ef9b3e44c97d Mon Sep 17 00:00:00 2001 From: Daniel Sanche Date: Fri, 4 Dec 2026 14:26:45 -0700 Subject: [PATCH 08/12] credential-less clients now support non-default universes --- googleapiclient/_universe.py | 12 ++---------- googleapiclient/discovery.py | 5 ++--- tests/test__universe.py | 4 ---- tests/test_discovery.py | 31 +++++++++++++++++++++++++++++-- 4 files changed, 33 insertions(+), 19 deletions(-) diff --git a/googleapiclient/_universe.py b/googleapiclient/_universe.py index 8bd6c7331d..e1ae0ca9ef 100644 --- a/googleapiclient/_universe.py +++ b/googleapiclient/_universe.py @@ -109,9 +109,7 @@ def check_api_core_compatible_with_credentials_universe(credentials): raise APICoreVersionError -def validate_request_credentials_universe( - client_universe, credentials, allow_none_credentials=True -): +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 @@ -122,10 +120,6 @@ def validate_request_credentials_universe( Args: client_universe: The universe domain the request targets. credentials: The credentials to check, or ``None`` if none are set. - allow_none_credentials: If ``True`` (default), ``None`` credentials - are treated as valid. If ``False``, they are checked as - default-universe credentials, so validation fails unless - ``client_universe`` is the default universe. Returns: bool: ``True`` if the request may be sent with these credentials. @@ -140,9 +134,7 @@ def validate_request_credentials_universe( # target the default universe; reject non-default credentials. check_api_core_compatible_with_credentials_universe(credentials) return True - if isinstance(credentials, _ANONYMOUS_CREDENTIAL_TYPES) or ( - allow_none_credentials and credentials is None - ): + if credentials is None or isinstance(credentials, _ANONYMOUS_CREDENTIAL_TYPES): return True # Intentionally call compare_domains directly rather than # google.api_core.universe.validate_credentials_universe so uncached diff --git a/googleapiclient/discovery.py b/googleapiclient/discovery.py index 9752b0b1fd..40c05d7643 100644 --- a/googleapiclient/discovery.py +++ b/googleapiclient/discovery.py @@ -299,7 +299,7 @@ def build( # 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 + _auth.get_credentials_from_http(http) if http is not None else credentials ) _universe.validate_request_credentials_universe( universe_domain, credentials_to_validate @@ -1644,12 +1644,11 @@ def _validate_credentials(self): UniverseMismatchError: If the configured universe domain is not valid. """ if not self._credentials_validated: - credentials = getattr(self._http, "credentials", None) + credentials = _auth.get_credentials_from_http(self._http) self._credentials_validated = ( _universe.validate_request_credentials_universe( self._universe_domain, credentials, - allow_none_credentials=False, ) ) return self._credentials_validated diff --git a/tests/test__universe.py b/tests/test__universe.py index 76595bdcbf..428e6c1984 100644 --- a/tests/test__universe.py +++ b/tests/test__universe.py @@ -224,10 +224,6 @@ def test_validate_request_credentials_universe_mismatch_raises(self): _universe.validate_request_credentials_universe( self.FAKE_UNIVERSE, _make_credentials("googleapis.com") ) - with self.assertRaises(universe.UniverseMismatchError): - _universe.validate_request_credentials_universe( - self.FAKE_UNIVERSE, None, allow_none_credentials=False - ) @unittest.skipUnless( hasattr(google.auth.compute_engine.Credentials, "universe_domain"), diff --git a/tests/test_discovery.py b/tests/test_discovery.py index cf7bb2cbe5..e9fdd43af9 100644 --- a/tests/test_discovery.py +++ b/tests/test_discovery.py @@ -3074,9 +3074,10 @@ def test_validate_credentials_with_client_options_without_universe(self): def test_validate_credentials_with_no_universe(self): fake_universe = "foo.com" + creds_without_universe = mock.Mock(spec=[]) http = google_auth_httplib2.AuthorizedHttp( - credentials=None, http=build_http() + credentials=creds_without_universe, http=build_http() ) discovery = read_datafile("zoo.json") service = build_from_document( @@ -3090,7 +3091,7 @@ def test_validate_credentials_with_no_universe(self): assert service._validate_credentials() http = google_auth_httplib2.AuthorizedHttp( - credentials=None, http=build_http() + credentials=creds_without_universe, http=build_http() ) discovery = read_datafile("zoo.json") service = build_from_document( @@ -3104,6 +3105,32 @@ def test_validate_credentials_with_no_universe(self): with self.assertRaises(universe.UniverseMismatchError): service._validate_credentials() + def test_validate_credentials_without_credentials_in_custom_universe(self): + fake_universe = "foo.com" + discovery = read_datafile("zoo.json") + client_options = google.api_core.client_options.ClientOptions( + universe_domain=fake_universe + ) + + service = build_from_document( + discovery, + developerKey="fake-key", + client_options=client_options, + ) + assert service._validate_credentials() + request = service.animals().list() + assert request._universe_domain == fake_universe + + http = google_auth_httplib2.AuthorizedHttp( + credentials=None, http=build_http() + ) + service = build_from_document( + discovery, + http=http, + client_options=client_options, + ) + assert service._validate_credentials() + def test_validate_credentials_with_default_universe(self): fake_universe = "foo.com" From 03642c3f323a5c133165bed42326c3a74b361557 Mon Sep 17 00:00:00 2001 From: Daniel Sanche Date: Fri, 4 Dec 2026 15:03:21 -0700 Subject: [PATCH 09/12] updated comments --- googleapiclient/discovery.py | 3 --- googleapiclient/http.py | 5 ++--- 2 files changed, 2 insertions(+), 6 deletions(-) diff --git a/googleapiclient/discovery.py b/googleapiclient/discovery.py index 40c05d7643..feb6c66f9c 100644 --- a/googleapiclient/discovery.py +++ b/googleapiclient/discovery.py @@ -1285,9 +1285,6 @@ def method(self, **kwargs): resumable=resumable, ) if isinstance(request, HttpRequest): - # self._universe_domain is unset on google-api-core < 2.18.0, where - # requests always target the default universe. Stamp a real value - # so that None only ever means "not built by a Resource". request._universe_domain = self._universe_domain or DEFAULT_UNIVERSE return request diff --git a/googleapiclient/http.py b/googleapiclient/http.py index 99f8732ba1..b9703e4a65 100644 --- a/googleapiclient/http.py +++ b/googleapiclient/http.py @@ -959,9 +959,8 @@ def __init__( self._rand = random.random self._sleep = time.sleep - # Universe domain of the Resource that created this request. None means - # the request was not built by a Resource, so there is no universe to - # check its credentials against. + # Universe domain attached by the Resource that created this request; + # manually created requests have no universe attached. self._universe_domain = None def __setstate__(self, state): From 754c9d08ebf30ad6ee1fb640ce0c9da8399d3836 Mon Sep 17 00:00:00 2001 From: Daniel Sanche Date: Fri, 4 Dec 2026 15:53:04 -0700 Subject: [PATCH 10/12] handle alle googleapis urls, not just hard-coded endpoint --- googleapiclient/_universe.py | 46 +++++++++++++++++++++++++++-- googleapiclient/http.py | 8 ++++-- tests/test__universe.py | 56 ++++++++++++++++++++++++++++++++++++ tests/test_http.py | 44 ++++++++++++++++++++++++++++ 4 files changed, 148 insertions(+), 6 deletions(-) diff --git a/googleapiclient/_universe.py b/googleapiclient/_universe.py index e1ae0ca9ef..aa3e452c56 100644 --- a/googleapiclient/_universe.py +++ b/googleapiclient/_universe.py @@ -14,13 +14,14 @@ """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. +Prefers ``google.api_core.universe`` helpers when available (>= 2.45.0) and +falls back to local copies for older ``google-api-core`` releases. """ import collections.abc import os +import re +import urllib.parse from google.api_core import client_options as client_options_lib from google.auth import credentials as google_auth_credentials @@ -101,6 +102,45 @@ def resolve_client_universe(client_options=None): ) +try: + from google.api_core.universe import is_googleapis_host +except ImportError: + # TODO(https://github.com/googleapis/google-cloud-python/issues/19297): Replace with + # google.api_core.universe.is_googleapis_host once minimum allowed + # google-api-core version exceeds 2.44.0. + _GOOGLEAPIS_HOST_PATTERN = re.compile( + rf"^(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)*{re.escape(DEFAULT_UNIVERSE)}$", + re.IGNORECASE, + ) + + def is_googleapis_host(url): + """Return True if an HTTP(S) URL targets ``googleapis.com`` or a subdomain.""" + if ( + not isinstance(url, str) + or not url + or "#" in url + or "\\" in url + or not url.isprintable() + or any(ch.isspace() for ch in url) + ): + return False + try: + parsed = urllib.parse.urlsplit(url) + if parsed.scheme not in ("http", "https") or not url[ + len(parsed.scheme) : + ].startswith("://"): + return False + if "@" in parsed.netloc: + return False + _ = parsed.port + host = parsed.hostname or "" + return bool( + host and host.isascii() and _GOOGLEAPIS_HOST_PATTERN.fullmatch(host) + ) + except ValueError: + return False + + def check_api_core_compatible_with_credentials_universe(credentials): """Raise APICoreVersionError if credentials require universe support.""" if not HAS_UNIVERSE: diff --git a/googleapiclient/http.py b/googleapiclient/http.py index b9703e4a65..9e8249764d 100644 --- a/googleapiclient/http.py +++ b/googleapiclient/http.py @@ -1357,10 +1357,12 @@ def __init__(self, callback=None, batch_uri=None): self._refreshed_credentials = {} # Track the batch's universe domain. Resource.new_batch_http_request() - # stamps its universe domain here; the legacy default batch URI always - # targets googleapis.com. None means the universe is unknown. + # stamps its universe domain here; any googleapis.com batch URI targets + # the default universe. Other custom URIs leave this as None. self._universe_domain = ( - _universe.DEFAULT_UNIVERSE if batch_uri == _LEGACY_BATCH_URI else None + _universe.DEFAULT_UNIVERSE + if _universe.is_googleapis_host(batch_uri) + else None ) def __setstate__(self, state): diff --git a/tests/test__universe.py b/tests/test__universe.py index 428e6c1984..f88ed1e4ea 100644 --- a/tests/test__universe.py +++ b/tests/test__universe.py @@ -97,6 +97,38 @@ def test_prefers_upstream_resolve_client_universe_when_available(self): self.assertIs( _universe.resolve_client_universe, universe.resolve_client_universe ) + if hasattr(universe, "is_googleapis_host"): + self.assertIs(_universe.is_googleapis_host, universe.is_googleapis_host) + + def test_is_googleapis_host(self): + matching = ( + "https://www.googleapis.com/batch", + "https://www.googleapis.com/batch/zoo/v1", + "https://storage.googleapis.com/batch/storage/v1", + "https://googleapis.com/batch", + "http://www.googleapis.com/batch", + ) + non_matching = ( + "https://www.foo.com/batch", + "https://notgoogleapis.com/batch", + "https://www.googleapis.com@evil.com/batch", + "https://www.googleapis.com\\@evil.com/batch", + "https://www.googleapis.com/batch#frag", + "https://www.googleapis.com:99999/batch", + "ftp://www.googleapis.com/batch", + "https:www.googleapis.com/batch", + "https://www.googleapis.com /batch", + "", + None, + ) + for fn in ( + _universe.is_googleapis_host, + self.fallback_universe.is_googleapis_host, + ): + for url in matching: + self.assertTrue(fn(url), msg=url) + for url in non_matching: + self.assertFalse(fn(url), msg=url) @parameterized.expand( [ @@ -328,6 +360,30 @@ def test_validate_request_credentials_universe_delegates_without_universe_suppor None, _make_credentials(self.FAKE_UNIVERSE) ) + def test_is_googleapis_host_without_universe_support(self): + self.assertTrue( + self.legacy_universe.is_googleapis_host( + "https://www.googleapis.com/batch/zoo/v1" + ) + ) + self.assertFalse( + self.legacy_universe.is_googleapis_host("https://www.foo.com/batch") + ) + self.assertFalse( + self.legacy_universe.is_googleapis_host( + "https://www.googleapis.com@evil.com/batch" + ) + ) + self.assertFalse( + self.legacy_universe.is_googleapis_host( + "https://www.googleapis.com:99999/batch" + ) + ) + self.assertFalse(self.legacy_universe.is_googleapis_host("")) + self.assertFalse( + self.legacy_universe.is_googleapis_host("ftp://www.googleapis.com/batch") + ) + if __name__ == "__main__": unittest.main() diff --git a/tests/test_http.py b/tests/test_http.py index b6d3f7b4da..c5f2490395 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -2214,6 +2214,32 @@ def test_batch_execute_legacy_batch_with_custom_universe_override_raises(self): lambda: batch.execute(http=tpc_http), creds, http_mock ) + def test_batch_execute_api_specific_googleapis_uri_with_tpc_subrequest_raises(self): + tpc_http, creds, http_mock = self._make_authorized_http(self.FAKE_UNIVERSE) + tpc_zoo = build_from_document( + _read_datafile("zoo.json"), + http=tpc_http, + client_options={"universe_domain": self.FAKE_UNIVERSE}, + ) + batch = BatchHttpRequest(batch_uri="https://www.googleapis.com/batch/zoo/v1") + batch.add(tpc_zoo.animals().list()) + + self._assert_mismatch_raises(batch.execute, creds, http_mock) + + def test_batch_execute_api_specific_googleapis_uri_standalone_tpc_override_raises( + self, + ): + batch = BatchHttpRequest( + batch_uri="https://storage.googleapis.com/batch/storage/v1" + ) + batch.add( + HttpRequest(None, JsonModel().response, "https://storage.googleapis.com/x") + ) + tpc_http, creds, http_mock = self._make_authorized_http(self.FAKE_UNIVERSE) + self._assert_mismatch_raises( + lambda: batch.execute(http=tpc_http), creds, http_mock + ) + def test_batch_execute_custom_uri_uses_subrequest_universe(self): batch = BatchHttpRequest(batch_uri="https://custom.example.com/batch") batch.add(self._build_zoo().animals().list()) @@ -2330,6 +2356,24 @@ def test_batch_execute_http_override_custom_universe_raises(self): self.assertEqual(http_mock.request_sequence, []) tpc_creds.before_request.assert_not_called() + def test_batch_execute_api_specific_googleapis_uri_custom_universe_raises(self): + batch = BatchHttpRequest(batch_uri="https://www.googleapis.com/batch/zoo/v1") + batch.add( + HttpRequest( + None, JsonModel().response, "https://www.googleapis.com/zoo/v1/animals" + ) + ) + + tpc_creds = _make_universe_credentials(self.FAKE_UNIVERSE) + http_mock = HttpMockSequence([]) + override_http = google_auth_httplib2.AuthorizedHttp(tpc_creds, http=http_mock) + + with self.assertRaises(APICoreVersionError): + batch.execute(http=override_http) + + self.assertEqual(http_mock.request_sequence, []) + tpc_creds.before_request.assert_not_called() + def test_batch_execute_subrequest_custom_universe_raises(self): zoo = build_from_document(_read_datafile("zoo.json"), http=HttpMockSequence([])) batch = zoo.new_batch_http_request() From b00fd313b42da7b5141726fe646022d1876a53f7 Mon Sep 17 00:00:00 2001 From: Daniel Sanche Date: Fri, 4 Dec 2026 16:24:20 -0700 Subject: [PATCH 11/12] fix crash for stub transports --- googleapiclient/_auth.py | 2 +- googleapiclient/discovery.py | 2 +- tests/test__auth.py | 5 +++++ 3 files changed, 7 insertions(+), 2 deletions(-) diff --git a/googleapiclient/_auth.py b/googleapiclient/_auth.py index 065b2ecd30..7cf58e40e7 100644 --- a/googleapiclient/_auth.py +++ b/googleapiclient/_auth.py @@ -157,7 +157,7 @@ def is_valid(credentials): def get_credentials_from_http(http): if http is None: return None - elif hasattr(http.request, "credentials"): + elif hasattr(getattr(http, "request", None), "credentials"): return http.request.credentials elif hasattr(http, "credentials") and not isinstance( http.credentials, httplib2.Credentials diff --git a/googleapiclient/discovery.py b/googleapiclient/discovery.py index feb6c66f9c..3a88feae62 100644 --- a/googleapiclient/discovery.py +++ b/googleapiclient/discovery.py @@ -730,7 +730,7 @@ def build_from_document( base = mtls_endpoint else: # Check google-api-core >= 2.18.0 if credentials' universe != "googleapis.com". - http_credentials = getattr(http, "credentials", None) + http_credentials = _auth.get_credentials_from_http(http) _universe.check_api_core_compatible_with_credentials_universe(http_credentials) if model is None: diff --git a/tests/test__auth.py b/tests/test__auth.py index cb70ff3deb..ebeb2b5629 100644 --- a/tests/test__auth.py +++ b/tests/test__auth.py @@ -198,3 +198,8 @@ def test_default_credentials(self): credentials = mock.Mock(spec=google.auth.credentials.Credentials) with self.assertRaises(ValueError): _auth.authorized_http(credentials) + + +class TestGetCredentialsFromHttp(unittest.TestCase): + def test_missing_request_attribute_returns_none(self): + self.assertIsNone(_auth.get_credentials_from_http(object())) From ca69645786391e144e6652bdb5d2db7965171ab9 Mon Sep 17 00:00:00 2001 From: Daniel Sanche Date: Fri, 4 Dec 2026 16:28:40 -0700 Subject: [PATCH 12/12] added tests --- tests/test_http.py | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/tests/test_http.py b/tests/test_http.py index c5f2490395..d7cd7910cd 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -2274,6 +2274,20 @@ def test_standalone_batch_allows_custom_credentials(self): self.assertEqual(callbacks.responses["1"], {"foo": 42}) self.assertEqual(len(http_mock.request_sequence), 1) + def test_batch_execute_mutated_subrequest_http_mismatch_raises(self): + zoo = self._build_zoo() + batch = zoo.new_batch_http_request() + req = zoo.animals().list() + req.http, tpc_creds, _ = self._make_authorized_http(self.FAKE_UNIVERSE) + batch.add(req) + + gdu_http, _, gdu_http_mock = self._make_authorized_http( + universe.DEFAULT_UNIVERSE + ) + self._assert_mismatch_raises( + lambda: batch.execute(http=gdu_http), tpc_creds, gdu_http_mock + ) + class TestExecuteWithoutUniverseSupport(unittest.TestCase): """Per-request execute(http=...) on google-api-core < 2.18.0.""" @@ -2537,6 +2551,22 @@ def test_batch_created_before_universe_tracking(self): self.assertEqual(callbacks.responses["1"], {"foo": 42}) + def test_from_json_without_universe_domain_key(self): + request = HttpRequest( + None, JsonModel().response, "https://custom.example.com/resource" + ) + payload = json.loads(request.to_json()) + payload.pop("_universe_domain", None) + + http_mock = HttpMockSequence([({"status": "200"}, "{}")]) + restored = HttpRequest.from_json( + json.dumps(payload), http_mock, request.postproc + ) + + self.assertIsNone(restored._universe_domain) + self.assertEqual(restored.execute(), {}) + self.assertEqual(len(http_mock.request_sequence), 1) + if __name__ == "__main__": logging.getLogger().setLevel(logging.ERROR)